-
Notifications
You must be signed in to change notification settings - Fork 34
/
marian_client.py
50 lines (40 loc) · 1.41 KB
/
marian_client.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
#!/usr/bin/env python3
"""
A client that connects to a Marian server and translates text interactively.
Run `python utils.marian_client.py` and type a text to translate in the terminal
Source: https://github.com/marian-nmt/marian-dev/blob/master/scripts/server/client_example.py
"""
from __future__ import division, print_function, unicode_literals
import argparse
import sys
from websocket import create_connection
if __name__ == "__main__":
# handle command-line options
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawTextHelpFormatter, # Preserves whitespace in the help text.
)
parser.add_argument("-b", "--batch-size", type=int, default=1)
parser.add_argument("-p", "--port", type=int, default=8886)
args = parser.parse_args()
# open connection
ws = create_connection(f"ws://localhost:{args.port}/translate")
count = 0
batch = ""
for line in sys.stdin:
count += 1
batch += line.decode("utf-8") if sys.version_info < (3, 0) else line
if count == args.batch_size:
# translate the batch
ws.send(batch)
result = ws.recv()
print(result.rstrip())
count = 0
batch = ""
if count:
# translate the remaining sentences
ws.send(batch)
result = ws.recv()
print(result.rstrip())
# close connection
ws.close()