__init__.py 22.5 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
from future.utils import with_metaclass
J. Fernando Sánchez's avatar
WIP  
J. Fernando Sánchez committed
5
from functools import partial
6

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

import inspect
import sys
import subprocess
import importlib
import yaml
19
import threading
20
import nltk
21

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
22
from .. import models, utils
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
23
from .. import api
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
24
from .. import gsitk_compat
25
from .. import testing
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
26 27 28

logger = logging.getLogger(__name__)

29

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30
class PluginMeta(models.BaseMeta):
31
    _classes = {}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
32 33 34 35 36 37

    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
38
        alias = attrs.get('name', name)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
39
        attrs['plugin_type'] = plugin_type
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
40 41 42
        attrs['name'] = alias
        if 'description' not in attrs:
            doc = attrs.get('__doc__', None)
43 44 45
            if doc:
                attrs['description'] = doc
            else:
46 47 48 49
                logger.warning(
                    ('Plugin {} does not have a description. '
                     'Please, add a short summary to help other developers'
                     ).format(name))
50
        cls = super(PluginMeta, mcs).__new__(mcs, name, bases, attrs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
51 52 53

        if alias in mcs._classes:
            if os.environ.get('SENPY_TESTING', ""):
54 55 56
                raise Exception(
                    ('The type of plugin {} already exists. '
                     'Please, choose a different name').format(name))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
57
            else:
58
                logger.warning('Overloading plugin class: {}'.format(alias))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
59
        mcs._classes[alias] = cls
60 61 62 63 64
        return cls

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


class Plugin(with_metaclass(PluginMeta, models.Plugin)):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
68 69 70 71 72 73 74 75 76 77 78
    '''
    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
79 80

    def __init__(self, info=None, data_folder=None, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
81 82 83 84
        """
        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
85
        logger.debug("Initialising {}".format(info))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
86
        super(Plugin, self).__init__(**kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
87 88
        if info:
            self.update(info)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
89
        self.validate()
90 91
        self.id = 'endpoint:plugins/{}_{}'.format(self['name'],
                                                  self['version'])
92
        self.is_activated = False
93
        self._lock = threading.Lock()
94 95
        self._directory = os.path.abspath(
            os.path.dirname(inspect.getfile(self.__class__)))
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

        data_folder = data_folder or os.getcwd()
        subdir = os.path.join(data_folder, self.name)

        self._data_paths = [
            data_folder,
            subdir,
            self._directory,
            os.path.join(self._directory, 'data'),
        ]

        if os.path.exists(subdir):
            data_folder = subdir
        self.data_folder = data_folder

111 112 113 114 115
        self._log = logging.getLogger('{}.{}'.format(__name__, self.name))

    @property
    def log(self):
        return self._log
116

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
117
    def validate(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
118 119 120 121 122
        missing = []
        for x in ['name', 'description', 'version']:
            if x not in self:
                missing.append(x)
        if missing:
123 124
            raise models.Error(
                'Missing configuration parameters: {}'.format(missing))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
125

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
126 127 128
    def get_folder(self):
        return os.path.dirname(inspect.getfile(self.__class__))

129 130 131 132 133 134
    def activate(self):
        pass

    def deactivate(self):
        pass

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    def process(self, request, **kwargs):
        """
        An implemented plugin should override this method.
        Here, we assume that a process_entries method exists."""
        newentries = list(
            self.process_entries(request.entries, request.parameters))
        request.entries = newentries
        return request

    def process_entries(self, entries, parameters):
        for entry in entries:
            self.log.debug('Processing entry with plugin {}: {}'.format(
                self, entry))
            results = self.process_entry(entry, parameters)
            if inspect.isgenerator(results):
                for result in results:
                    yield result
            else:
                yield results

    def process_entry(self, entry, parameters):
        """
        This base method is here to adapt plugins which only
        implement the *process* function.
        Note that this method may yield an annotated entry or a list of
        entries (e.g. in a tokenizer)
        """
        raise NotImplementedError(
            'You need to implement process, process_entries or process_entry in your plugin'
        )

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
166 167 168
    def test(self, test_cases=None):
        if not test_cases:
            if not hasattr(self, 'test_cases'):
169 170 171 172
                raise AttributeError(
                    ('Plugin {} [{}] does not have any defined '
                     'test cases').format(self.id,
                                          inspect.getfile(self.__class__)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
173 174
            test_cases = self.test_cases
        for case in test_cases:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
175
            try:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
176
                self.test_case(case)
177 178
                self.log.debug('Test case passed:\n{}'.format(
                    pprint.pformat(case)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
179
            except Exception as ex:
180 181
                self.log.warning('Test case failed:\n{}'.format(
                    pprint.pformat(case)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
182 183
                raise

184
    def test_case(self, case, mock=testing.MOCK_REQUESTS):
185 186 187 188
        if 'entry' not in case and 'input' in case:
            entry = models.Entry(_auto_id=False)
            entry.nif__isString = case['input']
            case['entry'] = entry
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
189 190
        entry = models.Entry(case['entry'])
        given_parameters = case.get('params', case.get('parameters', {}))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
191
        expected = case.get('expected', None)
192
        should_fail = case.get('should_fail', False)
193 194
        responses = case.get('responses', [])

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
195
        try:
196 197 198 199 200 201
            request = models.Response()
            request.parameters = api.parse_params(given_parameters,
                                                  self.extra_params)
            request.entries = [
                entry,
            ]
202

203
            method = partial(self.process, request)
204 205

            if mock:
206
                res = method()
207 208
            else:
                with testing.patch_all_requests(responses):
209
                    res = method()
210 211 212

            if not isinstance(expected, list):
                expected = [expected]
213 214
            utils.check_template(res.entries, expected)
            res.validate()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
215
        except models.Error:
216
            if should_fail:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
217
                return
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
218
            raise
219
        assert not should_fail
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    def find_file(self, fname):
        for p in self._data_paths:
            alternative = os.path.join(p, fname)
            if os.path.exists(alternative):
                return alternative
        raise IOError('File does not exist: {}'.format(fname))

    def open(self, fpath, mode='r'):
        if 'w' in mode:
            # When writing, only use absolute paths or data_folder
            if not os.path.isabs(fpath):
                fpath = os.path.join(self.data_folder, fpath)
        else:
            fpath = self.find_file(fpath)

        return open(fpath, mode=mode)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
237

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

241

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
242
# For backwards compatibility
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
243 244 245
SenpyPlugin = Plugin


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
246 247 248 249
class Analysis(Plugin):
    '''
    A subclass of Plugin that analyses text and provides an annotation.
    '''
250

251 252
    def analyse(self, request, parameters):
        return super(Analysis, self).process(request)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
253

254 255
    def analyse_entries(self, entries, parameters):
        for i in super(Analysis, self).process_entries(entries, parameters):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
256
            yield i
257

258 259
    def process(self, request, **kwargs):
        return self.analyse(request, request.parameters)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
260

261 262 263 264 265 266 267 268 269 270
    def process_entries(self, entries, parameters):
        for i in self.analyse_entries(entries, parameters):
            yield i

    def process_entry(self, entry, parameters, **kwargs):
        if hasattr(self, 'analyse_entry'):
            for i in self.analyse_entry(entry, parameters):
                yield i
        else:
            super(Analysis, self).process_entry(entry, parameters, **kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
271

272

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
273 274 275 276 277 278 279 280
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.
    '''
281 282 283 284 285 286 287 288 289 290 291 292 293 294

    def process(self, response, plugins=None, **kwargs):
        plugins = plugins or []
        newentries = []
        for entry in response.entries:
            newentries.append(
                self.convert_entry(entry, response.parameters, plugins))
        response.entries = newentries
        return response

    def convert_entry(self, entry, parameters, conversions_applied):
        raise NotImplementedError(
            'You should implement a way to convert each entry, or a custom process method'
        )
295

296

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
297 298 299 300 301 302 303
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
304 305
    minPolarityValue = 0
    maxPolarityValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
306

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
307 308
    def test_case(self, case):
        if 'polarity' in case:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
309
            expected = case.get('expected', {})
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
310 311 312 313 314 315 316 317 318 319 320 321 322
            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
323 324
    minEmotionValue = 0
    maxEmotionValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
325 326


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
327 328 329 330
class EmotionConversion(Conversion):
    '''
    A subclass of Conversion that converts emotion annotations using different models
    '''
331 332 333 334 335 336 337 338 339 340 341

    def can_convert(self, fromModel, toModel):
        '''
        Whether this plugin can convert from fromModel to toModel.
        If fromModel is None, it is interpreted as "any Model"
        '''
        for pair in self.onyx__doesConversion:
            if (pair['onyx:conversionTo'] == toModel) and \
               ((fromModel is None) or (pair['onyx:conversionFrom'] == fromModel)):
                return True
        return False
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
342 343


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
344 345 346
EmotionConversionPlugin = EmotionConversion


347 348 349 350 351 352
class PostProcessing(Plugin):
    def check(self, request, plugins):
        '''Should this plugin be run for this request?'''
        return False


353 354 355 356 357 358 359
class Box(AnalysisPlugin):
    '''
    Black box plugins delegate analysis to a function.
    The flow is like so:

    .. code-block::

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
360
                   entry --> input() --> predict_one() --> output() --> entry'
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375


    In other words: their ``input`` method convers a query (entry and a set of parameters) into
    the input to the box method. The ``output`` method convers the results given by the box into
    an entry that senpy can handle.
    '''

    def input(self, entry, params=None):
        '''Transforms a query (entry+param) into an input for the black box'''
        return entry

    def output(self, output, entry=None, params=None):
        '''Transforms the results of the black box into an entry'''
        return output

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
376
    def predict_one(self, input):
377 378
        raise NotImplementedError(
            'You should define the behavior of this plugin')
379

380
    def process_entries(self, entries, params):
381 382
        for entry in entries:
            input = self.input(entry=entry, params=params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
383
            results = self.predict_one(input=input)
384 385
            yield self.output(output=results, entry=entry, params=params)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
386 387 388 389
    def fit(self, X=None, y=None):
        return self

    def transform(self, X):
390
        return [self.predict_one(x) for x in X]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
391 392 393 394 395 396 397 398 399

    def predict(self, X):
        return self.transform(X)

    def fit_transform(self, X, y):
        self.fit(X, y)
        return self.transform(X)

    def as_pipe(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
400
        pipe = gsitk_compat.Pipeline([('plugin', self)])
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
401 402 403
        pipe.name = self.name
        return pipe

404 405 406 407 408 409 410 411 412 413 414 415 416 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

class TextBox(Box):
    '''A black box plugin that takes only text as input'''

    def input(self, entry, params):
        entry = super(TextBox, self).input(entry, params)
        return entry['nif:isString']


class SentimentBox(TextBox, SentimentPlugin):
    '''
    A box plugin where the output is only a polarity label or a tuple (polarity, polarityValue)
    '''

    def output(self, output, entry, **kwargs):
        s = models.Sentiment()
        try:
            label, value = output
        except ValueError:
            label, value = output, None
        s.prov(self)
        s.polarity = label
        if value is not None:
            s.polarityValue = value
        entry.sentiments.append(s)
        return entry


class EmotionBox(TextBox, EmotionPlugin):
    '''
    A box plugin where the output is only an a tuple of emotion labels
    '''

    def output(self, output, entry, **kwargs):
        if not isinstance(output, list):
            output = [output]
        s = models.EmotionSet()
        entry.emotions.append(s)
        for label in output:
            e = models.Emotion(onyx__hasEmotionCategory=label)
            s.append(e)
        return entry


class MappingMixin(object):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
449 450 451 452 453 454 455 456
    @property
    def mappings(self):
        return self._mappings

    @mappings.setter
    def mappings(self, value):
        self._mappings = value

457
    def output(self, output, entry, params):
458 459 460 461
        output = self.mappings.get(output, self.mappings.get(
            'default', output))
        return super(MappingMixin, self).output(
            output=output, entry=entry, params=params)
462 463


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
464 465 466
class ShelfMixin(object):
    @property
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
467
        if not hasattr(self, '_sh') or self._sh is None:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
468
            self._sh = {}
469
            if os.path.isfile(self.shelf_file):
470
                try:
471
                    with self.open(self.shelf_file, 'rb') as p:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
472
                        self._sh = pickle.load(p)
473
                except (IndexError, EOFError, pickle.UnpicklingError):
474 475
                    self.log.warning('Corrupted shelf file: {}'.format(
                        self.shelf_file))
476 477
                    if not self.get('force_shelf', False):
                        raise
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
478 479 480 481
        return self._sh

    @sh.deleter
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
482 483
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
484
            del self._sh
485
        self.save()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
486

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
487 488 489 490
    @sh.setter
    def sh(self, value):
        self._sh = value

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
491 492
    @property
    def shelf_file(self):
493 494 495 496 497 498 499
        if not hasattr(self, '_shelf_file') or not self._shelf_file:
            self._shelf_file = os.path.join(self.data_folder, self.name + '.p')
        return self._shelf_file

    @shelf_file.setter
    def shelf_file(self, value):
        self._shelf_file = value
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
500

501
    def save(self):
502
        self.log.debug('Saving pickle')
503
        if hasattr(self, '_sh') and self._sh is not None:
504
            with self.open(self.shelf_file, 'wb') as f:
505
                pickle.dump(self._sh, f)
506 507


508
def pfilter(plugins, plugin_type=Analysis, **kwargs):
509 510 511 512 513 514
    """ Filter plugins by different criteria """
    if isinstance(plugins, models.Plugins):
        plugins = plugins.plugins
    elif isinstance(plugins, dict):
        plugins = plugins.values()
    logger.debug('#' * 100)
515 516 517 518
    logger.debug('plugin_type {}'.format(plugin_type))
    if plugin_type:
        if isinstance(plugin_type, PluginMeta):
            plugin_type = plugin_type.__name__
519
        try:
520 521
            plugin_type = plugin_type[0].upper() + plugin_type[1:]
            pclass = globals()[plugin_type]
522
            logger.debug('Class: {}'.format(pclass))
523
            candidates = filter(lambda x: isinstance(x, pclass), plugins)
524
        except KeyError:
525
            raise models.Error('{} is not a valid type'.format(plugin_type))
526 527 528 529 530 531 532
    else:
        candidates = plugins

    logger.debug(candidates)

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

    if kwargs:
        candidates = filter(matches, candidates)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
538
    return candidates
539 540


541 542 543
def load_module(name, root=None):
    if root:
        sys.path.append(root)
544
    tmp = importlib.import_module(name)
545 546
    if root:
        sys.path.remove(root)
547 548 549
    return tmp


550
def _log_subprocess_output(process):
551 552 553 554 555 556 557
    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):
558
    installed = False
559
    nltk_resources = set()
560 561 562
    for info in plugins:
        requirements = info.get('requirements', [])
        if requirements:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
563
            pip_args = [sys.executable, '-m', 'pip', 'install']
564 565 566
            for req in requirements:
                pip_args.append(req)
            logger.info('Installing requirements: ' + str(requirements))
567 568
            process = subprocess.Popen(
                pip_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
569
            _log_subprocess_output(process)
570
            exitcode = process.wait()
571
            installed = True
572
            if exitcode != 0:
573 574
                raise models.Error(
                    "Dependencies not properly installed: {}".format(pip_args))
575 576 577
        nltk_resources |= set(info.get('nltk_resources', []))

    installed |= nltk.download(list(nltk_resources))
578
    return installed
579 580


581 582
is_plugin_file = re.compile(r'.*\.senpy$|senpy_[a-zA-Z0-9_]+\.py$|'
                            '^(?!test_)[a-zA-Z0-9_]+_plugin.py$')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
583 584


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
585 586 587 588 589 590 591 592 593 594
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


J. Fernando Sánchez's avatar
WIP  
J. Fernando Sánchez committed
595
def from_path(fpath, install_on_fail=False, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
596 597 598 599 600 601 602 603 604
    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)
J. Fernando Sánchez's avatar
WIP  
J. Fernando Sánchez committed
605
        yield from_info(info, install_on_fail=install_on_fail, **kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
606 607 608 609 610 611 612 613 614 615


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


J. Fernando Sánchez's avatar
WIP  
J. Fernando Sánchez committed
616
def from_info(info, root=None, install_on_fail=True, **kwargs):
617
    if any(x not in info for x in ('module', )):
618
        raise ValueError('Plugin info is not valid: {}'.format(info))
619 620
    module = info["module"]

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
621 622 623
    if not root and '_path' in info:
        root = os.path.dirname(info['_path'])

J. Fernando Sánchez's avatar
WIP  
J. Fernando Sánchez committed
624 625 626 627 628 629
    fun = partial(one_from_module, module, root=root, info=info, **kwargs)
    try:
        return fun()
    except (ImportError, LookupError):
        install_deps(info)
        return fun()
630 631


632
def parse_plugin_info(fpath):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
633
    logger.debug("Parsing plugin info: {}".format(fpath))
634 635
    with open(fpath, 'r') as f:
        info = yaml.load(f)
636
    info['_path'] = fpath
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
637
    return info
638 639


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

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
642 643 644 645 646 647
    if inspect.ismodule(module):
        res = _from_loaded_module(module, **kwargs)
    else:
        res = _from_module_name(module, **kwargs)
    for p in res:
        yield p
648

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
649 650 651 652 653

def one_from_module(module, root, info, **kwargs):
    if '@type' in info:
        cls = PluginMeta.from_type(info['@type'])
        return cls(info=info, **kwargs)
654 655
    instance = next(
        from_module(module=module, root=root, info=info, **kwargs), None)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    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


J. Fernando Sánchez's avatar
WIP  
J. Fernando Sánchez committed
677 678
def _from_module_name(module, root, info=None, **kwargs):
    module = load_module(module, root)
679 680
    for plugin in _from_loaded_module(
            module=module, root=root, info=info, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
681 682 683 684 685 686 687 688
        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
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
689 690 691


def evaluate(plugins, datasets, **kwargs):
692 693 694 695
    ev = gsitk_compat.Eval(
        tuples=None,
        datasets=datasets,
        pipelines=[plugin.as_pipe() for plugin in plugins])
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
    ev.evaluate()
    results = ev.results
    evaluations = evaluations_to_JSONLD(results, **kwargs)
    return evaluations


def evaluations_to_JSONLD(results, flatten=False):
    '''
    Map the evaluation results to a JSONLD scheme
    '''

    evaluations = list()
    metric_names = ['accuracy', 'precision_macro', 'recall_macro',
                    'f1_macro', 'f1_weighted', 'f1_micro', 'f1_macro']

    for index, row in results.iterrows():
        evaluation = models.Evaluation()
        if row.get('CV', True):
            evaluation['@type'] = ['StaticCV', 'Evaluation']
        evaluation.evaluatesOn = row['Dataset']
        evaluation.evaluates = row['Model']
        i = 0
        if flatten:
            metric = models.Metric()
            for name in metric_names:
                metric[name] = row[name]
            evaluation.metrics.append(metric)
        else:
            # We should probably discontinue this representation
            for name in metric_names:
                metric = models.Metric()
                metric['@id'] = 'Metric' + str(i)
                metric['@type'] = name.capitalize()
                metric.value = row[name]
                evaluation.metrics.append(metric)
                i += 1
        evaluations.append(evaluation)
    return evaluations