Completed
Push — master ( d242d8...16b8b8 )
by Gus
01:27
created

Processor._annotate_message()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
# use data structures
5
from __future__ import unicode_literals
6
from .ds import Document, Sentence, Dependencies
7
from .utils import post_json
8
import json
9
10
11
class Processor(object):
12
13
    def __init__(self, address):
14
        self.service = "{}/annotate".format(address)
15
16
    def _message_to_json_dict(self, msg):
17
        return post_json(self.service, msg.to_JSON())
18
19
    def _annotate_message(self, msg):
20
        annotated_text = post_json(self.service, msg.to_JSON())
21
        return Document.load_from_JSON(annotated_text)
22
23
    def annotate(self, text):
24
        try:
25
            # load json and build Sentences and Document
26
            msg = Message(text)
27
            return self._annotate_message(msg)
28
29
        except Exception as e:
30
            #print(e)
31
            return None
32
33
    def annotate_from_sentences(self, sentences):
34
        """
35
        Annotate text that has already been segmented into sentences.
36
        """
37
        try:
38
            # load json from str interable and build Sentences and Document
39
            msg = SentencesMessage(sentences)
40
            return self._annotate_message(msg)
41
42
        except Exception as e:
43
            #print(e)
44
            return None
45
46
class FastNLPProcessor(Processor):
47
48
    def __init__(self, address):
49
        self.service = "{}/fastnlp/annotate".format(address)
50
51
    def annotate(self, text):
52
        return super(FastNLPProcessor, self).annotate(text)
53
54
55
class BioNLPProcessor(Processor):
56
57
    def __init__(self, address):
58
        self.service = "{}/bionlp/annotate".format(address)
59
60
    def annotate(self, text):
61
        return super(BioNLPProcessor, self).annotate(text)
62
63
64
class Message(object):
65
    def __init__(self, text):
66
        self.text = text
67
68
    def to_JSON_dict(self):
69
        jdict = dict()
70
        jdict["text"] = self.text
71
        return jdict
72
73
    def to_JSON(self):
74
        return json.dumps(self.to_JSON_dict(), sort_keys=True, indent=4)
75
76
77
class SentencesMessage(object):
78
    def __init__(self, sentences):
79
        self.sentences = sentences
80
81
    def to_JSON_dict(self):
82
        jdict = dict()
83
        jdict["sentences"] = self.sentences
84
        return jdict
85
86
    def to_JSON(self):
87
        return json.dumps(self.to_JSON_dict(), sort_keys=True, indent=4)
88