summaryrefslogtreecommitdiff
path: root/realtime/realtime.py
blob: f99478b03b2d381709f5c02a9bf17e4bd2e5e1a6 (plain)
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
#!/usr/bin/env python

import argparse
import logging
import sys
import threading
import time

import rt

ABOUT = '''Realtime adaptive translation with cdec (See README.md)

Code by Michael Denkowski

Citation:
@InProceedings{realtime,
    author       = {Michael Denkowski and Chris Dyer and Alon Lavie},
    title        = {Learning from Post-Editing: Online Model Adaptation for Statistical Machine Translation},
    booktitle    = {Proceedings of the 14th Conference of the European Chapter of the Association for Computational Linguistics}
    year         = {2014},
}

'''

class Parser(argparse.ArgumentParser):

    def error(self, message):
        sys.stderr.write(ABOUT)
        self.print_help()
        sys.stderr.write('\n{}\n'.format(message))
        sys.exit(2)

def handle_line(translator, line, output, ctx_name):
    res = translator.command_line(line, ctx_name)
    if res:
        output.write('{}\n'.format(res))
        output.flush()

def test1(translator, input, output, ctx_name):
    inp = open(input)
    out = open(output, 'w')
    for line in inp:
        handle_line(translator, line.strip(), out, ctx_name)
    out.close()

def debug(translator, input):
    # Test 1: multiple contexts
    threads = []
    for i in range(4):
        t = threading.Thread(target=test1, args=(translator, input, '{}.out.{}'.format(input, i), str(i)))
        threads.append(t)
        t.start()
        time.sleep(30)
    # Test 2: flood
    out = open('{}.out.flood'.format(input), 'w')
    inp = open(input)
    while True:
        line = inp.readline()
        if not line:
            break
        line = line.strip()
        t = threading.Thread(target=handle_line, args=(translator, line.strip(), out, None))
        threads.append(t)
        t.start()
        time.sleep(1) 
    translator.drop_ctx(None)
    # Join test threads
    for t in threads:
        t.join()

def main():

    parser = Parser()
    parser.add_argument('-c', '--config', required=True, help='Config directory')
    parser.add_argument('-s', '--state', help='Load state file to default context (saved incremental data)')
    parser.add_argument('-n', '--normalize', help='Normalize text (tokenize, translate, detokenize)', action='store_true')
    parser.add_argument('-T', '--temp', help='Temp directory (default /tmp)', default='/tmp')
    parser.add_argument('-a', '--cache', help='Grammar cache size (default 5)', default='5')
    parser.add_argument('-v', '--verbose', help='Info to stderr', action='store_true')
    parser.add_argument('-D', '--debug-test', help='Run debug tests on input file')
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    with rt.RealtimeTranslator(args.config, tmpdir=args.temp, cache_size=int(args.cache), norm=args.normalize) as translator:

        # Debugging
        if args.debug_test:
            debug(translator, args.debug_test)
            return

        # Load state if given
        if args.state:
            rtd.load_state(state)

        # Read lines and commands
        while True:
            line = sys.stdin.readline()
            if not line:
                break
            line = line.strip()
            res = translator.command_line(line)
            if res:
                sys.stdout.write('{}\n'.format(res))
                sys.stdout.flush()
     
if __name__ == '__main__':
    main()