forked from PaddlePaddle/PLSC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathface_service.py
92 lines (74 loc) · 2.34 KB
/
face_service.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
# coding:utf-8
import sys
import time
from base64 import b64encode
import ujson
import os
from PIL import Image
_ver = sys.version_info
is_py2 = (_ver[0] == 2)
is_py3 = (_ver[0] == 3)
if is_py2:
import httplib
if is_py3:
import http.client as httplib
class FaceService():
def __init__(self):
self.con_list = []
self.con_index = 0
self.server_list = []
def connect(self, server='127.0.0.1:8010'):
self.server_list.append(server)
con = httplib.HTTPConnection(server)
self.con_list.append(con)
def connect_all_server(self, server_list):
for server in server_list:
self.server_list.append(server)
self.con_list.append(httplib.HTTPConnection(server))
def infer(self, request_msg):
try:
cur_con = self.con_list[self.con_index]
cur_con.request('POST', "/FaceClassifyService/inference",
request_msg, {"Content-Type": "application/json"})
response = cur_con.getresponse()
response_msg = response.read()
#print(response_msg)
response_msg = ujson.loads(response_msg)
self.con_index += 1
self.con_index = self.con_index % len(self.con_list)
return response_msg
except BaseException as err:
del self.con_list[self.con_index]
print(err)
if len(self.con_list) == 0:
print('All server failed')
return 'fail'
else:
self.con_index = 0
return 'retry'
def encode(self, images):
request = []
for image in range(images):
request.append(b64encode(image).decode('ascii'))
#request
request = {"base64_string": request}
request_msg = ujson.dumps(request)
response_msg = self.infer(request_msg)
result = []
for msg in response_msg["instance"]:
result.append(msg["embedding"])
#request end
return result
def close(self):
for con in self.con_list:
con.close()
def test():
with open('./data/00000000.jpg', 'rb') as f:
image = f.read()
bc = FaceService()
bc.connect('127.0.0.1:8010')
result = bc.encode([image])
print(result[0])
bc.close()
if __name__ == '__main__':
test()