thrift_client.py
1.93 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Michał Lenart
# This is THRIFT client for Multiservice platform.
# It is available on the same license as the Multiservice itself.
#
import sys
import re
import jsonpickle
import json
import StringIO
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from multiservice.facade import Multiservice
from multiservice.facade.ttypes import *
from multiservice.types.ttypes import *
from multiservice.types.ttypes import THeader
HOST = 'multiservice.nlp.ipipan.waw.pl'
PORT = 20000
transport = None
def createSampleRequest(text):
ttext=TText(paragraphs=[TParagraph(text=chunk)
for chunk in re.split(r'\n\n+', text)])
chain = [
RequestPart(serviceName='Pantera')]
request = ObjectRequest(ttext, chain)
return request
def getThriftTransportAndClient():
transport = TSocket.TSocket(HOST, PORT)
try:
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Multiservice.Client(protocol)
transport.open()
return (transport, client)
except:
transport.close()
raise
def getResultAsJSON(result):
jsonStr = jsonpickle.encode(result, unpicklable=False)
return json.dumps(json.load(StringIO.StringIO(jsonStr)), sort_keys=True, indent=4)
transport, client = getThriftTransportAndClient()
request = createSampleRequest(sys.stdin.read())
try:
token = client.putObjectRequest(request)
status = None
while status not in [RequestStatus.DONE, RequestStatus.FAILED]:
status = client.getRequestStatus(token)
if status == RequestStatus.DONE:
result = client.getResultObject(token)
print getResultAsJSON(result)
else:
print >> sys.stderr, client.getException(token)
finally:
transport.close()