-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathserver.py
190 lines (161 loc) · 6.81 KB
/
server.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python
import os
import sys
import time
import json
import argparse
import websocket
from tornado import web, ioloop, queues, gen, process
from content_processor import ContentProcessor
class TranslatorInterface():
"""An interface to a single, possibly multilingual, model."""
def __init__(self, srclang, targetlang, service, model):
self.service = service
self.contentprocessor = ContentProcessor(
srclang,
targetlang,
sourcebpe=self.service.get('sourcebpe'),
targetbpe=self.service.get('targetbpe'),
sourcespm=self.service.get('sourcespm'),
targetspm=self.service.get('targetspm')
)
self.worker = model
# becomes nonempty if there are multiple target languages
self.preamble = ""
def translate(self, text):
sentences = self.contentprocessor.preprocess(text)
translatedSentences = self.worker.translate(self.preamble + '\n'.join(sentences))
translation = self.contentprocessor.postprocess(translatedSentences)
return ' '.join(translation)
def ready(self):
return self.worker != None and self.worker.ready()
def on_exit(self):
if self.worker != None:
self.worker.on_exit()
class TranslatorWorker():
"""Provides a running instance of marian-server."""
def __init__(self, host, port, configuration):
self.host = host
self.port = port
self.configuration = configuration
self.ws_url = "ws://{}:{}/translate".format(host, port)
self.run()
@gen.coroutine
def run(self):
process.Subprocess.initialize()
self.p = process.Subprocess(['marian-server', '-c',
self.configuration,
'-p', self.port,
'--allow-unk',
# enables translation with a mini-batch size of 64, i.e. translating 64 sentences at once, with a beam-size of 6.
'-b', '6',
'--mini-batch', '64',
# use a length-normalization weight of 0.6 (this usually increases BLEU a bit).
'--normalize', '0.6',
'--maxi-batch-sort', 'src',
'--maxi-batch', '100',
])
self.p.set_exit_callback(self.on_exit)
ret = yield self.p.wait_for_exit()
def on_exit(self):
print("Process exited")
def translate(self, sentences):
ws = websocket.create_connection(self.ws_url)
ws.send(sentences)
translatedSentences = ws.recv().split('\n')
ws.close()
return translatedSentences
def ready(self):
try:
ws = websocket.create_connection(self.ws_url)
ws.close()
except ConnectionError:
return False
return True
class ApiHandler(web.RequestHandler):
def initialize(self, api, config, worker_pool):
self.worker_pool = worker_pool
self.config = config
self.api = api
self.worker = None
self.args = {}
def prepare_args(self):
if self.request.headers['Content-Type'] == 'application/json':
self.args = json.loads(self.request.body)
def get(self):
if self.api == 'ready':
if all(map(lambda x: x.ready(), self.worker_pool.values())):
self.set_status(204)
else:
self.set_status(500, "Translation server(s) not responding")
elif self.api == 'languages':
languages = {}
for source_lang in self.config:
languages[source_lang] = []
targetLangs = self.config[source_lang]
for target_lang in targetLangs:
languages[source_lang].append(target_lang)
return self.write(dict(languages=languages))
def post(self):
self.prepare_args()
lang_pair = "{}-{}".format(self.args['from'], self.args['to'])
if lang_pair not in self.worker_pool:
self.write(
dict(error="Language pair {} not suppported".format(lang_pair)))
return
self.worker = self.worker_pool[lang_pair]
translation = self.worker.translate(self.args['source'])
self.write(dict(translation=translation))
class MainHandler(web.RequestHandler):
def initialize(self, config):
self.config = config
def get(self):
self.render("index.template.html", title="Opus MT")
def initialize_workers(config):
worker_pool = {}
models = {}
for source_lang in config:
targetLangs = config[source_lang]
for target_lang in targetLangs:
lang_pair = "{}-{}".format(source_lang, target_lang)
pair_config = targetLangs[target_lang]
if pair_config['configuration'] not in models:
models[pair_config['configuration']] = TranslatorWorker(
pair_config['host'], pair_config['port'], pair_config['configuration'])
worker_pool[lang_pair] = TranslatorInterface(
source_lang, target_lang, pair_config, models[pair_config['configuration']])
# Multi-target models have to be told which language to translate to
if len(targetLangs) > 1:
worker_pool[lang_pair].preamble = ">>{}<< ".format(target_lang)
return worker_pool
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "static"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
)
def make_app(args):
services = {}
with open(args.config, 'r') as configfile:
services = json.load(configfile)
worker_pool = initialize_workers(services)
handlers = [
(r"/", MainHandler, dict(config=services)),
(r"/api/translate", ApiHandler,
dict(api='translate', config=services, worker_pool=worker_pool)),
(r"/api/ready", ApiHandler,
dict(api='ready', config=services, worker_pool=worker_pool)),
(r"/api/languages", ApiHandler,
dict(api='languages', config=services, worker_pool=worker_pool))
]
application = web.Application(handlers, debug=False, **settings)
return application
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Marian MT translation server.')
parser.add_argument('-p', '--port', type=int, default=8888,
help='Port the server will listen on')
parser.add_argument('-c', '--config', type=str, default="services.json",
help='MT server configurations')
args = parser.parse_args()
application = make_app(args)
application.listen(args.port)
ioloop.IOLoop.current().start()