summaryrefslogtreecommitdiff
path: root/searx/engines/lingva.py
blob: ecebe4587680acf9f6d72bbe3cc13d997260a908 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Lingva (alternative Google Translate frontend)"""

about = {
    "website": 'https://lingva.ml',
    "wikidata_id": None,
    "official_api_documentation": 'https://github.com/thedaviddelta/lingva-translate#public-apis',
    "use_official_api": True,
    "require_api_key": False,
    "results": 'JSON',
}

engine_type = 'online_dictionary'
categories = ['general', 'translate']

url = "https://lingva.thedaviddelta.com"
search_url = "{url}/api/v1/{from_lang}/{to_lang}/{query}"


def request(_query, params):
    params['url'] = search_url.format(
        url=url, from_lang=params['from_lang'][1], to_lang=params['to_lang'][1], query=params['query']
    )
    return params


def response(resp):
    results = []

    result = resp.json()
    info = result["info"]
    from_to_prefix = "%s-%s " % (resp.search_params['from_lang'][1], resp.search_params['to_lang'][1])

    if "typo" in info:
        results.append({"suggestion": from_to_prefix + info["typo"]})

    if 'definitions' in info:  # pylint: disable=too-many-nested-blocks
        for definition in info['definitions']:
            for item in definition.get('list', []):
                for synonym in item.get('synonyms', []):
                    results.append({"suggestion": from_to_prefix + synonym})

    data = []

    for definition in info['definitions']:
        for translation in definition['list']:
            data.append(
                {
                    'text': result['translation'],
                    'definitions': [translation['definition']] if translation['definition'] else [],
                    'examples': [translation['example']] if translation['example'] else [],
                    'synonyms': translation['synonyms'],
                }
            )

    for translation in info["extraTranslations"]:
        for word in translation["list"]:
            data.append(
                {
                    'text': word['word'],
                    'definitions': word['meanings'],
                }
            )

    if not data and result['translation']:
        data.append({'text': result['translation']})

    results.append(
        {
            'answer': data[0]['text'],
            'answer_type': 'translations',
            'translations': data,
        }
    )

    return results