-
Notifications
You must be signed in to change notification settings - Fork 27
/
translate.py
53 lines (50 loc) · 1.75 KB
/
translate.py
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
import translators as ts
import requests
import time
from config import r_config, TRANSLATION_CONFIG
def multi_translate(text):
service = r_config(TRANSLATION_CONFIG, 'translation_service')
if service == 'DeepL Translate':
return deepl_translate(text)
elif service == 'Google Translate':
return google_translate(text)
else:
return 'Error: No Translation Service Available'
def deepl_translate(text):
text = text[:140] if len(text) > 140 else text
response = requests.post(
"https://www2.deepl.com/jsonrpc",
json = {
"jsonrpc":"2.0",
"method": "LMT_handle_jobs",
"params": {
"jobs":[{
"kind":"default",
"raw_en_sentence": text,
"raw_en_context_before":[],
"raw_en_context_after":[],
"preferred_num_beams":4,
"quality":"fast"
}],
"lang":{
"user_preferred_langs":["EN"],
"source_lang_user_selected": r_config(TRANSLATION_CONFIG, "source_lang").upper() or "JA",
"target_lang": r_config(TRANSLATION_CONFIG, "target_lang").upper() or "EN"
},
"priority":-1,
"commonJobParams":{},
"timestamp": int(round(time.time() * 1000))
},
"id": 40890008
})
output = response.json()
if output is not None:
if 'result' in output:
return output['result']['translations'][0]['beams'][0]["postprocessed_sentence"]
if 'error' in output:
return 'Error: ' + output['error']['message']
return 'Failed to Translate'
def google_translate(text):
# ts.preaccelerate()
result = ts.translate_text(text, 'google')
return result