__init__.py 20.4 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 4


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
from future.utils import with_metaclass
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 copy
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
13
import pprint
14 15 16 17 18 19

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

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

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

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
27 28
logger = logging.getLogger(__name__)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
29 30 31 32 33 34 35 36
try:
    from gsitk.evaluation.evaluation import Evaluation as Eval
    from sklearn.pipeline import Pipeline
    GSITK_AVAILABLE = True
except ImportError:
    logger.warn('GSITK is not installed. Some functions will be unavailable.')
    GSITK_AVAILABLE = False

37

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
38
class PluginMeta(models.BaseMeta):
39
    _classes = {}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
40 41 42 43 44 45

    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
46
        alias = attrs.get('name', name)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
47
        attrs['plugin_type'] = plugin_type
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
48 49 50
        attrs['name'] = alias
        if 'description' not in attrs:
            doc = attrs.get('__doc__', None)
51 52 53 54 55
            if doc:
                attrs['description'] = doc
            else:
                logger.warn(('Plugin {} does not have a description. '
                             'Please, add a short summary to help other developers').format(name))
56
        cls = super(PluginMeta, mcs).__new__(mcs, name, bases, attrs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
57 58 59 60 61 62 63 64

        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
65 66 67 68 69
        return cls

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


class Plugin(with_metaclass(PluginMeta, models.Plugin)):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
73 74 75 76 77 78 79 80 81 82 83
    '''
    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
84 85

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

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

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
110
    def validate(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
111 112 113 114 115 116
        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
117

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
118 119 120
    def get_folder(self):
        return os.path.dirname(inspect.getfile(self.__class__))

121 122 123 124 125 126
    def activate(self):
        pass

    def deactivate(self):
        pass

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
127 128 129 130 131 132 133 134
    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
135
            try:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
136
                self.test_case(case)
137
                self.log.debug('Test case passed:\n{}'.format(pprint.pformat(case)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
138
            except Exception as ex:
139
                self.log.warn('Test case failed:\n{}'.format(pprint.pformat(case)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
140 141
                raise

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
142 143 144
    def test_case(self, case):
        entry = models.Entry(case['entry'])
        given_parameters = case.get('params', case.get('parameters', {}))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
145
        expected = case.get('expected', None)
146
        should_fail = case.get('should_fail', False)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
147 148
        try:
            params = api.parse_params(given_parameters, self.extra_params)
149 150 151 152 153 154 155
            res = list(self.analyse_entries([entry, ], params))

            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
156
        except models.Error:
157
            if should_fail:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
158
                return
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
159
            raise
160
        assert not should_fail
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    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
178

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

182

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
183
# For backwards compatibility
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
184 185 186
SenpyPlugin = Plugin


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
187 188 189 190
class Analysis(Plugin):
    '''
    A subclass of Plugin that analyses text and provides an annotation.
    '''
191

192
    def analyse(self, *args, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
193
        raise NotImplementedError(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
194
            'Your plugin should implement either analyse or analyse_entry')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
195 196 197 198 199 200 201 202

    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
203
        text = entry['nif:isString']
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
204 205 206 207 208
        params = copy.copy(parameters)
        params['input'] = text
        results = self.analyse(**params)
        for i in results.entries:
            yield i
209

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
210 211
    def analyse_entries(self, entries, parameters):
        for entry in entries:
212
            self.log.debug('Analysing entry with plugin {}: {}'.format(self, entry))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
213 214 215 216 217 218 219 220 221 222 223 224 225
            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
226

227

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
228 229 230 231 232 233 234 235
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.
    '''
236
    pass
237

238

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
239 240 241 242 243 244 245
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
246 247
    minPolarityValue = 0
    maxPolarityValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
248

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
249 250
    def test_case(self, case):
        if 'polarity' in case:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
251
            expected = case.get('expected', {})
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
252 253 254 255 256 257 258 259 260 261 262 263 264
            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
265 266
    minEmotionValue = 0
    maxEmotionValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
267 268


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
269 270 271 272
class EmotionConversion(Conversion):
    '''
    A subclass of Conversion that converts emotion annotations using different models
    '''
273
    pass
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
274 275


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
276 277 278
EmotionConversionPlugin = EmotionConversion


279 280 281 282 283 284 285
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
286
                   entry --> input() --> predict_one() --> output() --> entry'
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301


    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
302
    def predict_one(self, input):
303 304 305 306 307
        raise NotImplementedError('You should define the behavior of this plugin')

    def analyse_entries(self, entries, params):
        for entry in entries:
            input = self.input(entry=entry, params=params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
308
            results = self.predict_one(input=input)
309 310
            yield self.output(output=results, entry=entry, params=params)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
311 312 313 314
    def fit(self, X=None, y=None):
        return self

    def transform(self, X):
315
        return [self.predict_one(x) for x in X]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
316 317 318 319 320 321 322 323 324 325 326 327 328

    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):
        pipe = Pipeline([('plugin', self)])
        pipe.name = self.name
        return pipe

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

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
375 376 377 378 379 380 381 382
    @property
    def mappings(self):
        return self._mappings

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

383 384 385 386 387 388 389 390
    def output(self, output, entry, params):
        output = self.mappings.get(output,
                                   self.mappings.get('default', output))
        return super(MappingMixin, self).output(output=output,
                                                entry=entry,
                                                params=params)


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
391 392 393
class ShelfMixin(object):
    @property
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
394
        if not hasattr(self, '_sh') or self._sh is None:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
395
            self._sh = {}
396
            if os.path.isfile(self.shelf_file):
397
                try:
398
                    with self.open(self.shelf_file, 'rb') as p:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
399
                        self._sh = pickle.load(p)
400
                except (IndexError, EOFError, pickle.UnpicklingError):
401
                    self.log.warning('Corrupted shelf file: {}'.format(self.shelf_file))
402 403
                    if not self.get('force_shelf', False):
                        raise
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
404 405 406 407
        return self._sh

    @sh.deleter
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
408 409
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
410
            del self._sh
411
        self.save()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
412

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
413 414 415 416
    @sh.setter
    def sh(self, value):
        self._sh = value

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
417 418
    @property
    def shelf_file(self):
419 420 421 422 423 424 425
        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
426

427
    def save(self):
428
        self.log.debug('Saving pickle')
429
        if hasattr(self, '_sh') and self._sh is not None:
430
            with self.open(self.shelf_file, 'wb') as f:
431
                pickle.dump(self._sh, f)
432 433


434
def pfilter(plugins, plugin_type=Analysis, **kwargs):
435 436 437 438 439 440
    """ Filter plugins by different criteria """
    if isinstance(plugins, models.Plugins):
        plugins = plugins.plugins
    elif isinstance(plugins, dict):
        plugins = plugins.values()
    logger.debug('#' * 100)
441 442 443 444
    logger.debug('plugin_type {}'.format(plugin_type))
    if plugin_type:
        if isinstance(plugin_type, PluginMeta):
            plugin_type = plugin_type.__name__
445
        try:
446 447
            plugin_type = plugin_type[0].upper() + plugin_type[1:]
            pclass = globals()[plugin_type]
448 449 450 451
            logger.debug('Class: {}'.format(pclass))
            candidates = filter(lambda x: isinstance(x, pclass),
                                plugins)
        except KeyError:
452
            raise models.Error('{} is not a valid type'.format(plugin_type))
453 454 455 456 457 458 459 460 461 462 463 464 465
    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
466
    return candidates
467 468


469 470 471
def load_module(name, root=None):
    if root:
        sys.path.append(root)
472
    tmp = importlib.import_module(name)
473 474
    if root:
        sys.path.remove(root)
475 476 477
    return tmp


478
def _log_subprocess_output(process):
479 480 481 482 483 484 485
    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):
486
    installed = False
487
    nltk_resources = set()
488 489 490
    for info in plugins:
        requirements = info.get('requirements', [])
        if requirements:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
491
            pip_args = [sys.executable, '-m', 'pip', 'install']
492 493 494 495 496 497
            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)
498
            _log_subprocess_output(process)
499
            exitcode = process.wait()
500
            installed = True
501 502
            if exitcode != 0:
                raise models.Error("Dependencies not properly installed")
503 504 505
        nltk_resources |= set(info.get('nltk_resources', []))

    installed |= nltk.download(list(nltk_resources))
506
    return installed
507 508


509 510
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
511 512


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
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',)):
546
        raise ValueError('Plugin info is not valid: {}'.format(info))
547 548
    module = info["module"]

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
549 550 551 552
    if not root and '_path' in info:
        root = os.path.dirname(info['_path'])

    return one_from_module(module, root=root, info=info, **kwargs)
553 554


555
def parse_plugin_info(fpath):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
556
    logger.debug("Parsing plugin info: {}".format(fpath))
557 558
    with open(fpath, 'r') as f:
        info = yaml.load(f)
559
    info['_path'] = fpath
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
560
    return info
561 562


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

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
565 566 567 568 569 570
    if inspect.ismodule(module):
        res = _from_loaded_module(module, **kwargs)
    else:
        res = _from_module_name(module, **kwargs)
    for p in res:
        yield p
571

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

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)
602
    except (ImportError, LookupError):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
603 604 605 606 607
        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):
608 609
        if install:
            install_deps(plugin)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
610 611 612 613 614 615 616 617
        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
618 619 620


def evaluate(plugins, datasets, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
621 622 623
    if not GSITK_AVAILABLE:
        raise Exception('GSITK is not available. Install it to use this function.')

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    ev = Eval(tuples=None,
              datasets=datasets,
              pipelines=[plugin.as_pipe() for plugin in plugins])
    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