-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
88 lines (72 loc) · 3.13 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from flask import Flask, request, jsonify
import requests as r
session = r.session()
show_other_translations = False # if you want to show other translations, set this to True (it will be slower)
def translate(text, input_lang, output_lang):
# i make a request to the deepl translate without the api key
# and i get the cookie from the response
session.get("https://www.deepl.com/translator")
# then i make a request to the deepl translate with the api key
# and the cookie from the previous request
response = session.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": ["DE", "EN"],
"source_lang_user_selected": input_lang.upper(),
"target_lang": output_lang.upper(),
},
"priority": -1,
"commonJobParams": {},
"timestamp": 1623621579000,
},
"id": 40890006,
},
)
# i get the translated text from the response
# translated_text = response.json()["result"]["translations"][0]["beams"][0]["postprocessed_sentence"]
if show_other_translations:
translate_response = {
"text": response.json()["result"]["translations"][0]["beams"][0]["postprocessed_sentence"],
"other_translations": {}
}
index = 0
for i in response.json()["result"]["translations"][0]["beams"]:
if not index == 0:
translate_response["other_translations"][index-1] = i["postprocessed_sentence"]
index += 1
return translate_response
else:
if "message" in response.json() and response.json()["message"] == "Too many requests":
return "Too many requests."
translated_text = response.json()["result"]["translations"][0]["beams"][0]["postprocessed_sentence"]
return translated_text
# print(translate("""Bu gün nasılsın dostum?\nBu bir satır denemesidir.""", "TR", "EN"))
app = Flask(__name__)
@app.route('/', methods=['POST'])
def translate_text():
text = request.form.get('text')
input_lang = request.form.get('input_lang').upper()
output_lang = request.form.get('output_lang').upper()
if not text.strip():
return jsonify({'success': 'false', 'message': 'Text data cannot be empty'})
try:
translated_data = translate(text, input_lang, output_lang)
except Exception as e:
return jsonify({'success': 'false', 'message': f'Error: {str(e)}'})
return jsonify({'success': 'true', 'translated': {'text': translated_data}})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=30)