__init__.py 14.1 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()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
3
from future.utils import with_metaclass
4

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
import os.path
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
6
import os
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
7
import re
8
import pickle
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
9
import logging
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
10
import copy
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
11
import pprint
12 13 14 15 16 17

import inspect
import sys
import subprocess
import importlib
import yaml
18
import threading
19

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
20
from .. import models, utils
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
21
from .. import api
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
22 23 24

logger = logging.getLogger(__name__)

25

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
26
class PluginMeta(models.BaseMeta):
27
    _classes = {}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
28 29 30 31 32 33

    def __new__(mcs, name, bases, attrs, **kwargs):
        plugin_type = []
        if hasattr(bases[0], 'plugin_type'):
            plugin_type += bases[0].plugin_type
        plugin_type.append(name)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
34
        alias = attrs.get('name', name)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
35
        attrs['plugin_type'] = plugin_type
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
36 37 38 39 40 41 42 43
        attrs['name'] = alias
        if 'description' not in attrs:
            doc = attrs.get('__doc__', None)
            if not doc:
                raise Exception(('Please, add a description or '
                                 'documentation to class {}').format(name))
            attrs['description'] = doc
            attrs['name'] = alias
44
        cls = super(PluginMeta, mcs).__new__(mcs, name, bases, attrs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
45 46 47 48 49 50 51 52

        if alias in mcs._classes:
            if os.environ.get('SENPY_TESTING', ""):
                raise Exception(('The type of plugin {} already exists. '
                                'Please, choose a different name').format(name))
            else:
                logger.warn('Overloading plugin class: {}'.format(alias))
        mcs._classes[alias] = cls
53 54 55 56 57
        return cls

    @classmethod
    def for_type(cls, ptype):
        return cls._classes[ptype]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
58 59 60


class Plugin(with_metaclass(PluginMeta, models.Plugin)):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
61 62 63 64 65 66 67 68 69 70 71
    '''
    Base class for all plugins in senpy.
    A plugin must provide at least these attributes:

        - version
        - description (or docstring)
        - author

    Additionally, they may provide a URL (url) of a repository or website.

    '''
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
72 73

    def __init__(self, info=None, data_folder=None, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
74 75 76 77
        """
        Provides a canonical name for plugins and serves as base for other
        kinds of plugins.
        """
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
78
        logger.debug("Initialising {}".format(info))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
79
        super(Plugin, self).__init__(**kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
80 81
        if info:
            self.update(info)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
82
        self.validate()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
83
        self.id = 'plugins/{}_{}'.format(self['name'], self['version'])
84
        self.is_activated = False
85
        self._lock = threading.Lock()
86
        self.data_folder = data_folder or os.getcwd()
87

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
88
    def validate(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
89 90 91 92 93 94
        missing = []
        for x in ['name', 'description', 'version']:
            if x not in self:
                missing.append(x)
        if missing:
            raise models.Error('Missing configuration parameters: {}'.format(missing))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
95

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
96 97 98
    def get_folder(self):
        return os.path.dirname(inspect.getfile(self.__class__))

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

    def deactivate(self):
        pass

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
105 106 107 108 109 110 111 112
    def test(self, test_cases=None):
        if not test_cases:
            if not hasattr(self, 'test_cases'):
                raise AttributeError(('Plugin {} [{}] does not have any defined '
                                      'test cases').format(self.id,
                                                           inspect.getfile(self.__class__)))
            test_cases = self.test_cases
        for case in test_cases:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
113
            try:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
114 115 116
                self.test_case(case)
            except Exception as ex:
                logger.warn('Test case failed:\n{}'.format(pprint.pformat(case)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
117 118
                raise

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    def test_case(self, case):
        entry = models.Entry(case['entry'])
        given_parameters = case.get('params', case.get('parameters', {}))
        expected = case['expected']
        try:
            params = api.parse_params(given_parameters, self.extra_params)
            res = list(self.analyse_entry(entry, params))
        except models.Error:
            if not expected:
                return
            raise
        if not expected:
            raise Exception('This test should have raised an exception.')

        if not isinstance(expected, list):
            expected = [expected]
        utils.check_template(res, expected)
        for r in res:
            r.validate()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
138

139 140 141
    def open(self, fpath, *args, **kwargs):
        if not os.path.isabs(fpath):
            fpath = os.path.join(self.data_folder, fpath)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
142 143
        return open(fpath, *args, **kwargs)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
144 145
    def serve(self, debug=True, **kwargs):
        utils.easy(plugin_list=[self, ], plugin_folder=None, debug=debug, **kwargs)
146

147

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
148
# For backwards compatibility
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
149 150 151
SenpyPlugin = Plugin


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
152 153 154 155
class Analysis(Plugin):
    '''
    A subclass of Plugin that analyses text and provides an annotation.
    '''
156

157
    def analyse(self, *args, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
158
        raise NotImplementedError(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
159
            'Your plugin should implement either analyse or analyse_entry')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
160 161 162 163 164 165 166 167

    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)
        """
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
168
        text = entry['nif:isString']
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
169 170 171 172 173
        params = copy.copy(parameters)
        params['input'] = text
        results = self.analyse(**params)
        for i in results.entries:
            yield i
174

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
175 176 177
    def analyse_entries(self, entries, parameters):
        for entry in entries:
            logger.debug('Analysing entry with plugin {}: {}'.format(self, entry))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
178 179 180 181 182 183 184 185 186 187 188 189 190
            results = self.analyse_entry(entry, parameters)
            if inspect.isgenerator(results):
                for result in results:
                    yield result
            else:
                yield results

    def test_case(self, case):
        if 'entry' not in case and 'input' in case:
            entry = models.Entry(_auto_id=False)
            entry.nif__isString = case['input']
            case['entry'] = entry
        super(Analysis, self).test_case(case)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
191

192

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
193 194 195 196 197 198 199 200
AnalysisPlugin = Analysis


class Conversion(Plugin):
    '''
    A subclass of Plugins that convert between different annotation models.
    e.g. a conversion of emotion models, or normalization of sentiment values.
    '''
201
    pass
202

203

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
204 205 206 207 208 209 210
ConversionPlugin = Conversion


class SentimentPlugin(Analysis, models.SentimentPlugin):
    '''
    Sentiment plugins provide sentiment annotation (using Marl)
    '''
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
211 212
    minPolarityValue = 0
    maxPolarityValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
213

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    def test_case(self, case):
        expected = case.get('expected', {})
        if 'polarity' in case:
            s = models.Sentiment(_auto_id=False)
            s.marl__hasPolarity = case['polarity']
            if 'sentiments' not in expected:
                expected['sentiments'] = []
            expected['sentiments'].append(s)
            case['expected'] = expected
        super(SentimentPlugin, self).test_case(case)


class EmotionPlugin(Analysis, models.EmotionPlugin):
    '''
    Emotion plugins provide emotion annotation (using Onyx)
    '''
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
230 231
    minEmotionValue = 0
    maxEmotionValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
232 233


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
234 235 236 237
class EmotionConversion(Conversion):
    '''
    A subclass of Conversion that converts emotion annotations using different models
    '''
238
    pass
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
239 240


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
241 242 243
EmotionConversionPlugin = EmotionConversion


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
244 245 246
class ShelfMixin(object):
    @property
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
247
        if not hasattr(self, '_sh') or self._sh is None:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
248
            self._sh = {}
249
            if os.path.isfile(self.shelf_file):
250
                try:
251
                    with self.open(self.shelf_file, 'rb') as p:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
252
                        self._sh = pickle.load(p)
253
                except (IndexError, EOFError, pickle.UnpicklingError):
254 255 256
                    logger.warning('{} has a corrupted shelf file!'.format(self.id))
                    if not self.get('force_shelf', False):
                        raise
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
257 258 259 260
        return self._sh

    @sh.deleter
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
261 262
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
263
            del self._sh
264
        self.save()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
265

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
266 267 268 269
    @sh.setter
    def sh(self, value):
        self._sh = value

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
270 271
    @property
    def shelf_file(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
272
        if 'shelf_file' not in self or not self['shelf_file']:
273
            self.shelf_file = os.path.join(self.data_folder, self.name + '.p')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
274
        return self['shelf_file']
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
275

276
    def save(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
277
        logger.debug('saving pickle')
278
        if hasattr(self, '_sh') and self._sh is not None:
279
            with self.open(self.shelf_file, 'wb') as f:
280
                pickle.dump(self._sh, f)
281 282 283 284 285 286 287 288


def pfilter(plugins, **kwargs):
    """ Filter plugins by different criteria """
    if isinstance(plugins, models.Plugins):
        plugins = plugins.plugins
    elif isinstance(plugins, dict):
        plugins = plugins.values()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
289
    ptype = kwargs.pop('plugin_type', Plugin)
290 291 292
    logger.debug('#' * 100)
    logger.debug('ptype {}'.format(ptype))
    if ptype:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
293 294
        if isinstance(ptype, PluginMeta):
            ptype = ptype.__name__
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        try:
            ptype = ptype[0].upper() + ptype[1:]
            pclass = globals()[ptype]
            logger.debug('Class: {}'.format(pclass))
            candidates = filter(lambda x: isinstance(x, pclass),
                                plugins)
        except KeyError:
            raise models.Error('{} is not a valid type'.format(ptype))
    else:
        candidates = plugins

    logger.debug(candidates)

    def matches(plug):
        res = all(getattr(plug, k, None) == v for (k, v) in kwargs.items())
        logger.debug(
            "matching {} with {}: {}".format(plug.name, kwargs, res))
        return res

    if kwargs:
        candidates = filter(matches, candidates)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
316
    return candidates
317 318


319 320 321
def load_module(name, root=None):
    if root:
        sys.path.append(root)
322
    tmp = importlib.import_module(name)
323 324
    if root:
        sys.path.remove(root)
325 326 327
    return tmp


328
def _log_subprocess_output(process):
329 330 331 332 333 334 335
    for line in iter(process.stdout.readline, b''):
        logger.info('%r', line)
    for line in iter(process.stderr.readline, b''):
        logger.error('%r', line)


def install_deps(*plugins):
336
    installed = False
337 338 339
    for info in plugins:
        requirements = info.get('requirements', [])
        if requirements:
340
            pip_args = [sys.executable, '-m', 'pip', 'install', '--use-wheel']
341 342 343 344 345 346
            for req in requirements:
                pip_args.append(req)
            logger.info('Installing requirements: ' + str(requirements))
            process = subprocess.Popen(pip_args,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
347
            _log_subprocess_output(process)
348
            exitcode = process.wait()
349
            installed = True
350 351
            if exitcode != 0:
                raise models.Error("Dependencies not properly installed")
352
    return installed
353 354


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
355
is_plugin_file = re.compile(r'.*\.senpy$|senpy_[a-zA-Z0-9_]+\.py$|[a-zA-Z0-9_]+_plugin.py$')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
356 357


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
def find_plugins(folders):
    for search_folder in folders:
        for root, dirnames, filenames in os.walk(search_folder):
            # Do not look for plugins in hidden or special folders
            dirnames[:] = [d for d in dirnames if d[0] not in ['.', '_']]
            for filename in filter(is_plugin_file.match, filenames):
                fpath = os.path.join(root, filename)
                yield fpath


def from_path(fpath, **kwargs):
    logger.debug("Loading plugin from {}".format(fpath))
    if fpath.endswith('.py'):
        # We asume root is the dir of the file, and module is the name of the file
        root = os.path.dirname(fpath)
        module = os.path.basename(fpath)[:-3]
        for instance in _from_module_name(module=module, root=root, **kwargs):
            yield instance
    else:
        info = parse_plugin_info(fpath)
        yield from_info(info, **kwargs)


def from_folder(folders, loader=from_path, **kwargs):
    plugins = []
    for fpath in find_plugins(folders):
        for plugin in loader(fpath, **kwargs):
            plugins.append(plugin)
    return plugins


def from_info(info, root=None, **kwargs):
    if any(x not in info for x in ('module',)):
391
        raise ValueError('Plugin info is not valid: {}'.format(info))
392 393
    module = info["module"]

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
394 395 396 397
    if not root and '_path' in info:
        root = os.path.dirname(info['_path'])

    return one_from_module(module, root=root, info=info, **kwargs)
398 399


400
def parse_plugin_info(fpath):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
401
    logger.debug("Parsing plugin info: {}".format(fpath))
402 403
    with open(fpath, 'r') as f:
        info = yaml.load(f)
404
    info['_path'] = fpath
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
405
    return info
406 407


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
408
def from_module(module, **kwargs):
409

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
410 411 412 413 414 415
    if inspect.ismodule(module):
        res = _from_loaded_module(module, **kwargs)
    else:
        res = _from_module_name(module, **kwargs)
    for p in res:
        yield p
416

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

def one_from_module(module, root, info, **kwargs):
    if '@type' in info:
        cls = PluginMeta.from_type(info['@type'])
        return cls(info=info, **kwargs)
    instance = next(from_module(module=module, root=root, info=info, **kwargs), None)
    if not instance:
        raise Exception("No valid plugin for: {}".format(module))
    return instance


def _classes_in_module(module):
    for _, obj in inspect.getmembers(module):
        if inspect.isclass(obj) and inspect.getmodule(obj) == module:
            logger.debug(("Found plugin class:"
                          " {}@{}").format(obj, inspect.getmodule(obj)))
            yield obj


def _instances_in_module(module):
    for _, obj in inspect.getmembers(module):
        if isinstance(obj, Plugin) and inspect.getmodule(obj) == module:
            logger.debug(("Found plugin instance:"
                          " {}@{}").format(obj, inspect.getmodule(obj)))
            yield obj


def _from_module_name(module, root, info=None, install=True, **kwargs):
    try:
        module = load_module(module, root)
    except ImportError:
        if not install or not info:
            raise
        install_deps(info)
        module = load_module(module, root)
    for plugin in _from_loaded_module(module=module, root=root, info=info, **kwargs):
        yield plugin


def _from_loaded_module(module, info=None, **kwargs):
    for cls in _classes_in_module(module):
        yield cls(info=info, **kwargs)
    for instance in _instances_in_module(module):
        yield instance