__init__.py 18.6 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

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

25 26 27
from gsitk.evaluation.evaluation import Evaluation as Eval
from sklearn.pipeline import Pipeline

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

30

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

    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
39
        alias = attrs.get('name', name)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
40
        attrs['plugin_type'] = plugin_type
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
41 42 43 44 45 46 47 48
        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
49
        cls = super(PluginMeta, mcs).__new__(mcs, name, bases, attrs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
50 51 52 53 54 55 56 57

        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
58 59 60 61 62
        return cls

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


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

    def __init__(self, info=None, data_folder=None, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
79 80 81 82
        """
        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
83
        logger.debug("Initialising {}".format(info))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
84
        super(Plugin, self).__init__(**kwargs)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
85 86
        if info:
            self.update(info)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
87
        self.validate()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
88
        self.id = 'plugins/{}_{}'.format(self['name'], self['version'])
89
        self.is_activated = False
90
        self._lock = threading.Lock()
91
        self.data_folder = data_folder or os.getcwd()
92

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
93
    def validate(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
94 95 96 97 98 99
        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
100

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
101 102 103
    def get_folder(self):
        return os.path.dirname(inspect.getfile(self.__class__))

104 105 106 107 108 109
    def activate(self):
        pass

    def deactivate(self):
        pass

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
110 111 112 113 114 115 116 117
    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
118
            try:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
119
                self.test_case(case)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
120
                logger.debug('Test case passed:\n{}'.format(pprint.pformat(case)))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
121 122
            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
123 124
                raise

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
125 126 127
    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
128
        expected = case.get('expected', None)
129
        should_fail = case.get('should_fail', False)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
130 131
        try:
            params = api.parse_params(given_parameters, self.extra_params)
132 133 134 135 136 137 138
            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
139
        except models.Error:
140
            if should_fail:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
141
                return
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
142
            raise
143
        assert not should_fail
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
144

145 146 147
    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
148 149
        return open(fpath, *args, **kwargs)

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

153

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
154
# For backwards compatibility
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
155 156 157
SenpyPlugin = Plugin


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
158 159 160 161
class Analysis(Plugin):
    '''
    A subclass of Plugin that analyses text and provides an annotation.
    '''
162

163
    def analyse(self, *args, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
164
        raise NotImplementedError(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
165
            'Your plugin should implement either analyse or analyse_entry')
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
166 167 168 169 170 171 172 173

    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
174
        text = entry['nif:isString']
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
175 176 177 178 179
        params = copy.copy(parameters)
        params['input'] = text
        results = self.analyse(**params)
        for i in results.entries:
            yield i
180

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
181 182 183
    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
184 185 186 187 188 189 190 191 192 193 194 195 196
            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
197

198

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
199 200 201 202 203 204 205 206
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.
    '''
207
    pass
208

209

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
210 211 212 213 214 215 216
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
217 218
    minPolarityValue = 0
    maxPolarityValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
219

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
220 221
    def test_case(self, case):
        if 'polarity' in case:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
222
            expected = case.get('expected', {})
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
223 224 225 226 227 228 229 230 231 232 233 234 235
            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
236 237
    minEmotionValue = 0
    maxEmotionValue = 1
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
238 239


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
240 241 242 243
class EmotionConversion(Conversion):
    '''
    A subclass of Conversion that converts emotion annotations using different models
    '''
244
    pass
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
245 246


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
247 248 249
EmotionConversionPlugin = EmotionConversion


250 251 252 253 254 255 256
class Box(AnalysisPlugin):
    '''
    Black box plugins delegate analysis to a function.
    The flow is like so:

    .. code-block::

257
                   entry --> input() --> predict() --> output() --> entry'
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272


    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

273
    def predict(self, input):
274 275 276 277 278
        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)
279
            results = self.predict(input=input)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            yield self.output(output=results, entry=entry, params=params)


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


326 327 328 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
class EvaluationBox():
    '''
    A box plugin where it is implemented the evaluation. It is necessary to have a pipeline.
    '''

    def score(self, datasets):
        pipelines = [self._pipeline]

        ev = Eval(tuples = None,
            datasets = datasets,
            pipelines = pipelines)
        ev.evaluate()
        results = ev.results
        evaluations = self._evaluations_toJSONLD(results)
        return evaluations

    def _evaluations_toJSONLD(self, results):
        '''
        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['CV'] == False:
                evaluation['@type'] = ['StaticCV', 'Evaluation']
            evaluation.evaluatesOn = row['Dataset']
            evaluation.evaluates = row['Model']
            i = 0
            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

368 369
class MappingMixin(object):

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
370 371 372 373 374 375 376 377
    @property
    def mappings(self):
        return self._mappings

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

378 379 380 381 382 383 384 385
    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
386 387 388
class ShelfMixin(object):
    @property
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
389
        if not hasattr(self, '_sh') or self._sh is None:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
390
            self._sh = {}
391
            if os.path.isfile(self.shelf_file):
392
                try:
393
                    with self.open(self.shelf_file, 'rb') as p:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
394
                        self._sh = pickle.load(p)
395
                except (IndexError, EOFError, pickle.UnpicklingError):
396 397 398
                    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
399 400 401 402
        return self._sh

    @sh.deleter
    def sh(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
403 404
        if os.path.isfile(self.shelf_file):
            os.remove(self.shelf_file)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
405
            del self._sh
406
        self.save()
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
407

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
408 409 410 411
    @sh.setter
    def sh(self, value):
        self._sh = value

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
412 413
    @property
    def shelf_file(self):
414 415 416 417 418 419 420
        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
421

422
    def save(self):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
423
        logger.debug('saving pickle')
424
        if hasattr(self, '_sh') and self._sh is not None:
425
            with self.open(self.shelf_file, 'wb') as f:
426
                pickle.dump(self._sh, f)
427 428 429 430 431 432 433 434


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
435
    ptype = kwargs.pop('plugin_type', Plugin)
436 437 438
    logger.debug('#' * 100)
    logger.debug('ptype {}'.format(ptype))
    if ptype:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
439 440
        if isinstance(ptype, PluginMeta):
            ptype = ptype.__name__
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        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
462
    return candidates
463 464


465 466 467
def load_module(name, root=None):
    if root:
        sys.path.append(root)
468
    tmp = importlib.import_module(name)
469 470
    if root:
        sys.path.remove(root)
471 472 473
    return tmp


474
def _log_subprocess_output(process):
475 476 477 478 479 480 481
    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):
482
    installed = False
483 484 485
    for info in plugins:
        requirements = info.get('requirements', [])
        if requirements:
486
            pip_args = [sys.executable, '-m', 'pip', 'install', '--use-wheel']
487 488 489 490 491 492
            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)
493
            _log_subprocess_output(process)
494
            exitcode = process.wait()
495
            installed = True
496 497
            if exitcode != 0:
                raise models.Error("Dependencies not properly installed")
498
    return installed
499 500


501 502
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
503 504


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
505 506 507 508 509 510 511 512 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
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',)):
538
        raise ValueError('Plugin info is not valid: {}'.format(info))
539 540
    module = info["module"]

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
541 542 543 544
    if not root and '_path' in info:
        root = os.path.dirname(info['_path'])

    return one_from_module(module, root=root, info=info, **kwargs)
545 546


547
def parse_plugin_info(fpath):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
548
    logger.debug("Parsing plugin info: {}".format(fpath))
549 550
    with open(fpath, 'r') as f:
        info = yaml.load(f)
551
    info['_path'] = fpath
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
552
    return info
553 554


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

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
557 558 559 560 561 562
    if inspect.ismodule(module):
        res = _from_loaded_module(module, **kwargs)
    else:
        res = _from_module_name(module, **kwargs)
    for p in res:
        yield p
563

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
564 565 566 567 568 569 570 571 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 602 603 604 605 606 607

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