Package miopia :: Package classifier :: Module ServerStrategy
[hide private]
[frames] | no frames]

Source Code for Module miopia.classifier.ServerStrategy

 1  ''' 
 2  Created on 09/06/2014 
 3   
 4  @author: david.vilares 
 5  ''' 
 6  import codecs 
 7  import socket 
 8  import base64 
 9  import time 
10  import json 
11   
12   
13 -class ServerStrategy(object):
14 ''' 15 ServerStrategy is intented to process an instance at a time. 16 ''' 17
18 - def __init__(self, host,port,model_name,arff_header,max_bufsize=4092):
19 ''' 20 Constructor 21 @param host: A String 22 @param port: An integer 23 @param model_name: A String. It indicates the name of a existent model at the Server 24 @param arff_header: A String. It indicates the header of the ARFF for the specified model 25 ''' 26 self._host = host 27 self._port = port 28 self._model_name = model_name 29 self._arff_header = arff_header 30 self._max_bufsize = max_bufsize 31 self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 32 self._socket.connect((self._host, self._port))
33
34 - def get_arff_header(self):
35 return self._arff_header
36
37 - def get_instance_data(self, arff_file):
38 39 arff_text = codecs.open(arff_file).read() 40 arff_data = arff_text.split("@DATA\n")[1] 41 return base64.b64encode(arff_data)
42
43 - def _call_server(self, data_string):
44 self._socket.sendall('model:'+self._model_name+'\ntext:%s\n\n'%data_string) #sendall to send all data 45 recv = "" 46 # NOTE: every time we receive on a socket, there is no guarantee that it be a complete line, 47 # nor that it will be a single line. Therefore we'll store the complete response before processing 48 while True: 49 line = self._socket.recv(self._max_bufsize)#.replace('\n','').strip('[').strip(']').split(',') 50 if line == '': break 51 recv+=line 52 print "RECV>",recv 53 for line in recv.split('\n'): 54 if line.startswith("classification:"): 55 return json.loads(line.split("classification:")[1])#.strip('\n').strip('[').strip(']').replace(' ','')
56
57 - def classify(self, arff_file,dict_position_instanceid=None):
58 """ 59 @param arff_file: 60 """ 61 #classifications = [] 62 return self._call_server(self.get_instance_data(arff_file))
63 #print "server_lines:",lines 64 #return lines 65 #lines= self._get_model_classifications(arff_file) 66 #line_id = 0 67 #for line in lines: 68 # classifications.append((dict_position_instanceid[line_id], 69 # line, 1)) 70 # line_id += 1 71 #return lines.split(',') 72 73 #s = ServerStrategy('zipi.dc.fi.udc.es',8081,"polarity_3c_es","/tmp/header.arff") 74 #s.classify("/tmp/header_with_data.arff",{0:2000,1:2001}) 75