-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (76 loc) · 2.73 KB
/
app.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import os
path_to_packages = os.path.abspath(os.path.join("venv/lib/site-packages"))
sys.path.insert(0, path_to_packages)
from flask import Flask, render_template, jsonify, request
from flask_wtf import FlaskForm
from flask_pagedown import PageDown
from flask_pagedown.fields import PageDownField
from wtforms.fields import SubmitField
import requests
import json
import re
from flask import Flask, jsonify, request
from waitress import serve
from onmt.translate import TranslationServer, ServerModelError
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
pagedown = PageDown(app)
STATUS_OK = "ok"
STATUS_ERROR = "error"
config_file = "available_models/conf.json"
translation_server = TranslationServer()
translation_server.start(config_file)
class PageDownFormExample(FlaskForm):
pagedown = PageDownField('')
submit = SubmitField('Translate')
def translate(inputs):
# inputs = request.get_json(force=True)
debug = False
out = {}
try:
trans, scores, n_best, _, aligns = translation_server.run(inputs)
assert len(trans) == len(inputs) * n_best
assert len(scores) == len(inputs) * n_best
assert len(aligns) == len(inputs) * n_best
out = [[] for _ in range(n_best)]
for i in range(len(trans)):
response = {"src": inputs[i // n_best]['src'], "tgt": trans[i],
"n_best": n_best, "pred_score": scores[i]}
if len(aligns[i]) > 0 and aligns[i][0] is not None:
response["align"] = aligns[i]
out[i % n_best].append(response)
except ServerModelError as e:
model_id = inputs[0].get("id")
translation_server.models[model_id].unload()
out['error'] = str(e)
out['status'] = STATUS_ERROR
return out
@app.route('/', methods=['GET', 'POST'])
def index():
form = PageDownFormExample()
text = None
language = "en-fr" #Default
if form.validate_on_submit():
source = form.pagedown.data
source = re.sub(r"([?.!,:;¿])", r" \1 ", source)
source = re.sub(r'[" "]+', " ", source)
source = re.sub(r"m ", "M ", source) #changes "aham" to "ahaM"
language = str(request.form.get('lang'))
data = [{"src": source, "id": 100}]
response = translate(data)
t = type(response)
text = response[0][0]['tgt']
text = re.sub(r" ([?.!,:،؛؟¿])", r"\1", text)
else:
form.pagedown.data = ('namaste.')
return render_template('index.html', form=form, language=language, text=text)
@app.route('/about/')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run()