-
Notifications
You must be signed in to change notification settings - Fork 1
/
pgfws-client.py
executable file
·101 lines (80 loc) · 2.26 KB
/
pgfws-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
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
#! /usr/bin/env python
# Turns strings in the STDIN to abstract trees in the STDOUT
# using the GF webservice.
# Author: Kaarel Kaljurand
# Version: 2012-02-29
#
# Example:
#
# echo "go five meters back" | python pgfws-client.py -g Go -f GoEng
#
import sys
import argparse
import subprocess
import threading
import os
import re
import time
import json
import urllib
import urllib2
from os.path import join
agent='PgfWsClient/0.0.1'
server_name="http://localhost"
server_port=41296
server_url=server_name + ":" + str(server_port)
prefix='| '
def process_strings():
"""
"""
count = 0
for line in sys.stdin:
line = line.strip()
# small correction to the input data
line = re.sub('\.$', ' .', line)
count = count + 1
lineAsArg = urllib.urlencode({ 'input' : line })
req = urllib2.Request(server_url + "&" + lineAsArg)
try:
res = urllib2.urlopen(req)
jsonAsStr = res.read()
data = json.loads(jsonAsStr)
print '{0}{1}'.format(prefix, get_first_tree(data).encode('utf8'))
except:
print >> sys.stderr, 'ERROR {0}'.format(line)
print >> sys.stderr, sys.exc_info()[0]
def get_first_tree(data):
"""
"""
return data[0]["trees"][0]
parser = argparse.ArgumentParser(description='Parse strings with the GF webservice')
parser.add_argument('-d', '--dir', type=str, action='store',
default='/grammars/',
dest='dir',
help='directory on the server where PGFs are hosted')
parser.add_argument('-g', '--grammar', type=str, action='store',
dest='grammar',
help='PGF grammar')
parser.add_argument('-c', '--command', type=str, action='store',
default='parse',
dest='command',
help='command')
parser.add_argument('-f', '--from', type=str, action='store',
dest='lang_from',
help='from')
parser.add_argument('-v', '--version', action='version', version='%(prog)s v0.1')
args = parser.parse_args()
if args.grammar is None:
print >> sys.stderr, 'ERROR: argument -g/--grammar is not specified'
exit()
if args.lang_from is None:
print >> sys.stderr, 'ERROR: argument -f/--from is not specified'
exit()
server_url += args.dir + "/" + args.grammar + ".pgf?" + urllib.urlencode({
'command' : args.command,
'from' : args.lang_from
})
time_start = time.time()
process_strings()
time_end = time.time()
print >> sys.stderr, 'Duration: {:.2f} sec'.format(time_end - time_start)