__init__.py 3.36 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
import inspect
import os.path
6
import pickle
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
7
import logging
8
import tempfile
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
9
import copy
10
from .. import models
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
11
12
13

logger = logging.getLogger(__name__)

14

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
15
class SenpyPlugin(models.Plugin):
16
    def __init__(self, info=None):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
17
18
19
20
        """
        Provides a canonical name for plugins and serves as base for other
        kinds of plugins.
        """
21
        if not info:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
22
23
            raise models.Error(message=("You need to provide configuration"
                                        "information for the plugin."))
24
        logger.debug("Initialising {}".format(info))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
25
26
        id = 'plugins/{}_{}'.format(info['name'], info['version'])
        super(SenpyPlugin, self).__init__(id=id, **info)
27
        self.is_activated = False
28

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
29
30
31
    def get_folder(self):
        return os.path.dirname(inspect.getfile(self.__class__))

32
    def analyse(self, *args, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
        raise NotImplemented(
            'Your method should implement either analyse or analyse_entry')

    def analyse_entry(self, entry, parameters):
        """ An implemented plugin should override this method.
        This base method is here to adapt old style plugins which only
        implement the *analyse* function.
        Note that this method may yield an annotated entry or a list of
        entries (e.g. in a tokenizer)
        """
        text = entry['text']
        params = copy.copy(parameters)
        params['input'] = text
        results = self.analyse(**params)
        for i in results.entries:
            yield i
49

50
51
52
53
54
    def activate(self):
        pass

    def deactivate(self):
        pass
55

56

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
57
class SentimentPlugin(models.SentimentPlugin, SenpyPlugin):
58
59
60
61
    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
62

63

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
64
class EmotionPlugin(models.EmotionPlugin, SenpyPlugin):
65
    def __init__(self, info, *args, **kwargs):
66
        super(EmotionPlugin, self).__init__(info, *args, **kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
67
68
69
70
71
72
73
        self.minEmotionValue = float(info.get("minEmotionValue", -1))
        self.maxEmotionValue = float(info.get("maxEmotionValue", 1))


class EmotionConversionPlugin(models.EmotionConversionPlugin, SenpyPlugin):
    def __init__(self, info, *args, **kwargs):
        super(EmotionConversionPlugin, self).__init__(info, *args, **kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
74
75
76
77
78


class ShelfMixin(object):
    @property
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
79
        if not hasattr(self, '_sh') or self._sh is None:
80
81
82
            self.__dict__['_sh'] = {}
            if os.path.isfile(self.shelf_file):
                self.__dict__['_sh'] = pickle.load(open(self.shelf_file, 'rb'))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
83
84
85
86
        return self._sh

    @sh.deleter
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
87
88
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
89
90
            del self.__dict__['_sh']
        self.save()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
91

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
92
93
    @property
    def shelf_file(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
94
95
96
97
        if 'shelf_file' not in self or not self['shelf_file']:
            self.shelf_file = os.path.join(tempfile.gettempdir(),
                                           self.name + '.p')
        return self['shelf_file']
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
98

99
    def save(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
100
        logger.debug('saving pickle')
101
102
103
        if hasattr(self, '_sh') and self._sh is not None:
            with open(self.shelf_file, 'wb') as f:
                pickle.dump(self._sh, f)