thrift_client.py 1.93 KB
#!/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()