plugins.py 4.54 KB
Newer Older
1

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

logger = logging.getLogger(__name__)

11
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
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"
    },
}
58

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

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

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

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

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

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

    def deactivate(self):
        pass
103

104
105
106
107
108
109
    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)
110

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

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
115
116
117
    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
118

119
class SentimentPlugin(SenpyPlugin):
120

121
122
123
124
    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
125

126

127
class EmotionPlugin(SenpyPlugin):
128

129
130
131
132
    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
133
134
135
136
137
138
139
140
141
142
143
144


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
145
146
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
147
148
149
150
151
152
153
154
155
156
157

    @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):
158
        self.sh.close()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
159
        del(self._sh)