plugins.py 4.59 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
2
from future import standard_library
standard_library.install_aliases()
3

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
4
5
6
import inspect
import os.path
import shelve
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
7
import logging
8
from .models import Response, Leaf
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
9
10
11

logger = logging.getLogger(__name__)

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
PARAMS = {
    "input": {
        "@id": "input",
        "aliases": ["i", "input"],
        "required": True,
        "help": "Input text"
    },
    "informat": {
        "@id": "informat",
        "aliases": ["f", "informat"],
        "required": False,
        "default": "text",
        "options": ["turtle", "text"],
    },
    "intype": {
        "@id": "intype",
        "aliases": ["intype", "t"],
        "required": False,
        "default": "direct",
        "options": ["direct", "url", "file"],
    },
    "outformat": {
        "@id": "outformat",
        "aliases": ["outformat", "o"],
        "default": "json-ld",
        "required": False,
        "options": ["json-ld"],
    },
    "language": {
        "@id": "language",
        "aliases": ["language", "l"],
        "required": False,
    },
    "prefix": {
        "@id": "prefix",
        "aliases": ["prefix", "p"],
        "required": True,
        "default": "",
    },
    "urischeme": {
        "@id": "urischeme",
        "aliases": ["urischeme", "u"],
        "required": False,
        "default": "RFC5147String",
        "options": "RFC5147String"
    },
}
59

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
60

61
class SenpyPlugin(Leaf):
62
63
    _context = Leaf.get_context(Response._context)
    _frame = {"@context": _context,
64
              "name": {},
65
66
              "extra_params": {"@container": "@index"},
              "@explicit": True,
67
68
              "version": {},
              "repo": None,
69
70
              "is_activated": {},
              "params": None,
71
              }
72

73
74
    def __init__(self, info=None):
        if not info:
75
76
            raise ValueError(("You need to provide configuration"
                              "information for the plugin."))
77
        logger.debug("Initialising {}".format(info))
78
        super(SenpyPlugin, self).__init__()
79
80
        self.name = info["name"]
        self.version = info["version"]
81
        self.id = "{}_{}".format(self.name, self.version)
82
        self.params = info.get("params", PARAMS.copy())
83
84
        if "@id" not in self.params:
            self.params["@id"] = "params_%s" % self.id
85
        self.extra_params = info.get("extra_params", {})
86
87
88
        self.params.update(self.extra_params.copy())
        if "@id" not in self.extra_params:
            self.extra_params["@id"] = "extra_params_%s" % self.id
89
        self.is_activated = False
90
        self._info = info
91

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
92
93
94
    def get_folder(self):
        return os.path.dirname(inspect.getfile(self.__class__))

95
    def analyse(self, *args, **kwargs):
96
        logger.debug("Analysing with: {} {}".format(self.name, self.version))
97
98
        pass

99
100
101
102
103
    def activate(self):
        pass

    def deactivate(self):
        pass
104

105
106
107
108
109
110
    def jsonld(self, parameters=False, *args, **kwargs):
        nframe = kwargs.pop("frame", self._frame)
        if parameters:
            nframe = nframe.copy()
            nframe["params"] = {}
        return super(SenpyPlugin, self).jsonld(frame=nframe, *args, **kwargs)
111

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
112
113
114
115
    @property
    def id(self):
        return "{}_{}".format(self.name, self.version)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
116
117
118
    def __del__(self):
        ''' Destructor, to make sure all the resources are freed '''
        self.deactivate()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
119

120
class SentimentPlugin(SenpyPlugin):
121

122
123
124
125
    def __init__(self, info, *args, **kwargs):
        super(SentimentPlugin, self).__init__(info, *args, **kwargs)
        self.minPolarityValue = float(info.get("minPolarityValue", 0))
        self.maxPolarityValue = float(info.get("maxPolarityValue", 1))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
126

127

128
class EmotionPlugin(SenpyPlugin):
129

130
131
132
133
    def __init__(self, info, *args, **kwargs):
        resp = super(EmotionPlugin, self).__init__(info, *args, **kwargs)
        self.minEmotionValue = float(info.get("minEmotionValue", 0))
        self.maxEmotionValue = float(info.get("maxEmotionValue", 0))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
134
135
136
137
138
139
140
141
142
143
144
145


class ShelfMixin(object):

    @property
    def sh(self):
        if not hasattr(self, '_sh') or not self._sh:
            self._sh = shelve.open(self.shelf_file, writeback=True)
        return self._sh

    @sh.deleter
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
146
147
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
148
149
150
151
152
153
154
155
156
157
158

    @property
    def shelf_file(self):
        if not hasattr(self, '_shelf_file') or not self._shelf_file:
            if hasattr(self, '_info') and 'shelf_file' in self._info:
                self._shelf_file = self._info['shelf_file']
            else:
                self._shelf_file = os.path.join(self.get_folder(), self.name + '.db')
        return self._shelf_file 

    def close(self):
159
        self.sh.close()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
160
        del(self._sh)