.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
libretranslate.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""LibreTranslate (Free and Open Source Machine Translation API)"""
3
4import random
5from json import dumps
6
7about = {
8 "website": 'https://libretranslate.com',
9 "wikidata_id": None,
10 "official_api_documentation": 'https://libretranslate.com/docs/',
11 "use_official_api": True,
12 "require_api_key": False,
13 "results": 'JSON',
14}
15
16engine_type = 'online_dictionary'
17categories = ['general', 'translate']
18
19base_url = "https://translate.terraprint.co"
20api_key = ''
21
22
23def request(_query, params):
24 request_url = random.choice(base_url) if isinstance(base_url, list) else base_url
25 params['url'] = f"{request_url}/translate"
26
27 args = {'source': params['from_lang'][1], 'target': params['to_lang'][1], 'q': params['query']}
28 if api_key:
29 args['api_key'] = api_key
30 params['data'] = dumps(args)
31
32 params['method'] = 'POST'
33 params['headers'] = {'Content-Type': 'application/json'}
34 params['req_url'] = request_url
35
36 return params
37
38
39def response(resp):
40 results = []
41
42 json_resp = resp.json()
43 text = json_resp.get('translatedText')
44
45 from_lang = resp.search_params["from_lang"][1]
46 to_lang = resp.search_params["to_lang"][1]
47 query = resp.search_params["query"]
48 req_url = resp.search_params["req_url"]
49
50 if text:
51 results.append({"answer": text, "url": f"{req_url}/?source={from_lang}&target={to_lang}&q={query}"})
52
53 return results