Passed
Pull Request — master (#496)
by
unknown
02:00
created

annif.transformer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 6

2 Functions

Rating   Name   Duplication   Size   Complexity  
A parse_specs() 0 16 3
A get_transform() 0 10 3
1
"""Functionality for obtaining text transformation from string specification"""
2
3
import re
4
from . import transformer
5
from . import inputlimiter
6
from .transformer import IdentityTransform
7
from annif.util import parse_args
8
from annif.exception import ConfigurationException
9
10
__all__ = ["IdentityTransform"]
11
12
13
def parse_specs(transform_specs):
14
    """Parse a transformation specification into a list of tuples, e.g.
15
    'transf_1(x),transf_2(y=42),transf_3' is parsed to
16
    [(transf_1, [x], {}), (transf_2, [], {y: 42}), (transf_3, [], {})]."""
17
18
    parsed = []
19
    # Split by commas not inside parentheses
20
    parts = re.split(r',\s*(?![^()]*\))', transform_specs)
21
    for part in parts:
22
        match = re.match(r'(\w+)(\((.*)\))?', part)
23
        if match is None:
24
            continue
25
        transform = match.group(1)
26
        posargs, kwargs = parse_args(match.group(3))
27
        parsed.append((transform, posargs, kwargs))
28
    return parsed
29
30
31
def get_transform(transform_specs, project):
32
    transform_defs = parse_specs(transform_specs)
33
    transform_classes = []
34
    args = []
35
    for trans, posargs, kwargs in transform_defs:
36
        if trans not in _transforms:
37
            raise ConfigurationException(f"No such transform {trans}")
38
        transform_classes.append(_transforms[trans])
39
        args.append((posargs, kwargs))
40
    return transformer.TransformChain(transform_classes, args, project)
41
42
43
_transforms = {
44
    transformer.IdentityTransform.name: transformer.IdentityTransform,
45
    inputlimiter.InputLimiter.name: inputlimiter.InputLimiter}
46