api.py 5.74 KB
Newer Older
1
from future.utils import iteritems
2
from .models import Error, Results, Entry, from_string
3 4 5
import logging
logger = logging.getLogger(__name__)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
6 7 8 9

boolean = (True, False)


10 11
API_PARAMS = {
    "algorithm": {
12
        "aliases": ["algorithms", "a", "algo"],
13
        "required": False,
14 15
        "description": ("Algorithms that will be used to process the request."
                        "It may be a list of comma-separated names."),
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
16 17 18
    },
    "expanded-jsonld": {
        "@id": "expanded-jsonld",
19
        "aliases": ["expanded"],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
20
        "options": boolean,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
21
        "required": True,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
22
        "default": False
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
23
    },
24 25 26
    "with_parameters": {
        "aliases": ['withparameters',
                    'with-parameters'],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
27
        "options": boolean,
28 29
        "default": False,
        "required": True
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30
    },
31 32 33 34
    "outformat": {
        "@id": "outformat",
        "aliases": ["o"],
        "default": "json-ld",
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
35
        "required": True,
36
        "options": ["json-ld", "turtle"],
37 38 39 40
    },
    "help": {
        "@id": "help",
        "description": "Show additional help to know more about the possible parameters",
41
        "aliases": ["h"],
42
        "required": True,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
43
        "options": boolean,
44 45 46 47 48 49 50 51 52 53 54 55 56
        "default": False
    },
    "emotionModel": {
        "@id": "emotionModel",
        "aliases": ["emoModel"],
        "required": False
    },
    "conversion": {
        "@id": "conversion",
        "description": "How to show the elements that have (not) been converted",
        "required": True,
        "options": ["filtered", "nested", "full"],
        "default": "full"
57 58 59
    }
}

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
EVAL_PARAMS = {
    "algorithm": {
        "aliases": ["plug", "p", "plugins", "algorithms", 'algo', 'a', 'plugin'],
        "description": "Plugins to be evaluated",
        "required": True,
        "help": "See activated plugins in /plugins"
    },
    "dataset": {
        "aliases": ["datasets", "data", "d"],
        "description": "Datasets to be evaluated",
        "required": True,
        "help": "See avalaible datasets in /datasets"
    }
}

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
75 76 77 78 79 80 81 82 83 84
PLUGINS_PARAMS = {
    "plugin_type": {
        "@id": "pluginType",
        "description": 'What kind of plugins to list',
        "aliases": ["pluginType"],
        "required": True,
        "default": 'analysisPlugin'
    }
}

85 86
WEB_PARAMS = {
    "inHeaders": {
87
        "aliases": ["headers"],
88
        "required": True,
89
        "default": False,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
90
        "options": boolean
91 92 93 94 95
    },
}

CLI_PARAMS = {
    "plugin_folder": {
96
        "aliases": ["folder"],
97 98 99
        "required": True,
        "default": "."
    },
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
100
}
101 102 103 104

NIF_PARAMS = {
    "input": {
        "@id": "input",
105
        "aliases": ["i"],
106 107 108 109 110
        "required": True,
        "help": "Input text"
    },
    "intype": {
        "@id": "intype",
111
        "aliases": ["t"],
112 113 114 115
        "required": False,
        "default": "direct",
        "options": ["direct", "url", "file"],
    },
116 117 118 119 120
    "informat": {
        "@id": "informat",
        "aliases": ["f"],
        "required": False,
        "default": "text",
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
121
        "options": ["text", "json-ld"],
122
    },
123 124
    "language": {
        "@id": "language",
125
        "aliases": ["l"],
126 127 128 129
        "required": False,
    },
    "prefix": {
        "@id": "prefix",
130
        "aliases": ["p"],
131 132 133 134 135
        "required": True,
        "default": "",
    },
    "urischeme": {
        "@id": "urischeme",
136
        "aliases": ["u"],
137 138
        "required": False,
        "default": "RFC5147String",
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
139
        "options": ["RFC5147String", ]
140
    }
141 142 143
}


144 145 146 147
def parse_params(indict, *specs):
    if not specs:
        specs = [NIF_PARAMS]
    logger.debug("Parsing: {}\n{}".format(indict, specs))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
148
    outdict = indict.copy()
149
    wrong_params = {}
150 151
    for spec in specs:
        for param, options in iteritems(spec):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
152 153
            for alias in options.get("aliases", []):
                # Replace each alias with the correct name of the parameter
154
                if alias in indict and alias != param:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
155
                    outdict[param] = indict[alias]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
156
                    del outdict[alias]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
157 158 159 160 161 162 163 164 165
                    continue
            if param not in outdict:
                if "default" in options:
                    # We assume the default is correct
                    outdict[param] = options["default"]
                elif options.get("required", False):
                    wrong_params[param] = spec[param]
                continue
            if "options" in options:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
166
                if options["options"] == boolean:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
167 168 169
                    outdict[param] = outdict[param] in [None, True, 'true', '1']
                elif outdict[param] not in options["options"]:
                    wrong_params[param] = spec[param]
170
    if wrong_params:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
171
        logger.debug("Error parsing: %s", wrong_params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
172
        message = Error(
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
173
            status=400,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
174
            message='Missing or invalid parameters',
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
175
            parameters=outdict,
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
176
            errors=wrong_params)
177
        raise message
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
178 179
    if 'algorithm' in outdict and not isinstance(outdict['algorithm'], tuple):
        outdict['algorithm'] = tuple(outdict['algorithm'].split(','))
180
    return outdict
181 182


J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
183
def parse_extra_params(request, plugin=None):
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    params = request.parameters.copy()
    if plugin:
        extra_params = parse_params(params, plugin.get('extra_params', {}))
        params.update(extra_params)
    return params


def parse_call(params):
    '''Return a results object based on the parameters used in a call/request.
    '''
    params = parse_params(params, NIF_PARAMS)
    if params['informat'] == 'text':
        results = Results()
        entry = Entry(nif__isString=params['input'])
        results.entries.append(entry)
    elif params['informat'] == 'json-ld':
        results = from_string(params['input'], cls=Results)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
201
    else:  # pragma: no cover
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
202
        raise NotImplementedError('Informat {} is not implemented'.format(params['informat']))
203 204
    results.parameters = params
    return results