-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.py
298 lines (217 loc) · 6.7 KB
/
node.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
'''
Node Module of the Chord System used to store facial encodings
Authors:
Thomas Binu
Ruzan Sasuri
Amol Gaikwad
'''
import json
import socket
import requests
from flask import Flask, request
from utils import log, find_successor, get_hash_value, send_as_json, is_in_range, print_encoding_hash_values, get_nodes_from_json_dict
import threading
import time
import cv2
import face_recognition
import numpy as np
from os.path import join, exists
import glob
import pickle
from resizeimage import resizeimage
import logging
SERVER_URL = 'http://172.17.0.2:5000'
HOST_NAME = socket.gethostbyname(socket.gethostname())
PORT = 5000
URLS = {
'register': '/register',
'models': '/models',
'model': '/model',
'test': '/test',
'successor_encodings': '/successor_encodings',
'search_image' : '/search_image'
}
node_id = -1
nodes = dict() # Key as node id and value as ip address
face_encodings = dict()
app = Flask(__name__)
has_registered = False
SENSITIVITY = 2
IMAGE_WIDTH = 1000
IMAGE_HEIGHT = 1000
# Show camera
def show_camera():
pass
# Register Node on the server
def register():
global nodes, node_id
message = {
'ip': HOST_NAME
}
response = send_as_json(SERVER_URL + URLS['register'], message)
if 'error' in response:
print(response['error'])
else:
node_id = response['id']
log('Assigned node ID:' + str(node_id))
show_camera()
get_encodings_from_successor()
# Search Images
@app.route('/search_image', methods=['POST'])
def search_image():
global nodes, face_encodings
response = request.get_json(force=True)
unknown_face_encoding = np.asarray(response['encoding'])
message = {
'name': search_encodings(unknown_face_encoding)
}
return json.dumps(message)
def search_encodings(unknown_face_encoding):
log('Comparing face distances')
for name, face_encoding in face_encodings.items():
face_distances = face_recognition.face_distance([face_encoding], unknown_face_encoding)
log('face distance', face_distances, name)
if face_distances[0] <= 0.5:
log('Matched to', name)
return name
return ''
# Update face encodings
@app.route('/update_encodings', methods=['POST'])
def update_encodings():
global nodes, face_encodings
log('Updated Encodings from Server')
response = request.get_json(force=True)
face_encodings = response['encodings']
for name, face_encoding in face_encodings.items():
log(name + ':' + str(get_hash_value(np.asarray(face_encoding))))
message = {
'success': True
}
return json.dumps(message)
# Send encodings to predecessor
@app.route('/successor_encodings', methods=['POST'])
def successor_encodings():
global face_encodings
response = request.get_json(force=True)
predecessor_node_id = int(response['node_id'])
encodings_to_transfer = {}
delete_keys = []
log('Transferring encodings from {} to {}'.format(node_id, predecessor_node_id))
for name, face_encoding in face_encodings.items():
hash_value = get_hash_value(np.asarray(face_encoding))
if is_in_range(node_id, predecessor_node_id, hash_value):
encodings_to_transfer[name] = face_encoding
delete_keys.append(name)
log(name + ':' + str(get_hash_value(np.asarray(face_encoding))))
for key in delete_keys:
del face_encodings[key]
message = {
'encodings': encodings_to_transfer
}
log('\nEncodings in node:-')
for name, face_encoding in face_encodings.items():
log(name, str(get_hash_value(np.asarray(face_encoding))))
return json.dumps(message)
# Get encoding from successor
def get_encodings_from_successor():
global face_encodings, node_id
if len(nodes) == 0:
log('No Nodes Yet')
return
successor_id = find_successor(node_id, nodes)
if successor_id == node_id:
return
url = nodes[successor_id] + URLS['successor_encodings']
message = {
'node_id': node_id
}
response = send_as_json(url, message)
face_encodings = response['encodings']
log('Encodings after update from {}:'.format(successor_id))
print_encoding_hash_values(face_encodings)
# Update the list of online nodes
@app.route('/update_online', methods=['POST'])
def update_nodes():
global nodes, has_registered
response = request.get_json(force=True)
nodes_json = response['nodes']
nodes = get_nodes_from_json_dict(nodes_json)
log('updating nodes to:' + str(nodes))
message = {
'success': True
}
return json.dumps(message)
# Search encoding in node
def search_encoding_in_nodes(test_image_encoding):
hash_value = get_hash_value(test_image_encoding, 5) # Add threshold
log('image has hash value', hash_value)
count = 0
log('Starting image search through nodes')
while count < SENSITIVITY:
successor_node_id = find_successor(hash_value, nodes)
log('Successor of {} is {} at loop {}'.format(hash_value, successor_node_id, count + 1))
if successor_node_id == node_id: # If its the same node, search the node and return the value
log('\nSearching at the same node as request was made\n')
person_name = search_encodings(test_image_encoding)
if person_name != '':
return person_name
else:
break
message = {
'encoding': test_image_encoding.tolist(),
'count': count
}
url = nodes[successor_node_id] + URLS['search_image']
response = send_as_json(url, message)
if response['name'] == '':
log('Could not find encoding at ', successor_node_id)
hash_value = successor_node_id
count += 1
else:
return 'Welcome ' + response['name']
return 'Person not found'
# Search for image , this function will be modified to fit in a camera
def search_image_from_user():
image_name = input('Enter image name to search:')
image_name = image_name + '.jpg'
image_path = join("images", 'test', image_name)
if exists(image_path):
test_image = face_recognition.load_image_file(image_path)
# test_image = resizeimage.resize_cover(test_image, [IMAGE_WIDTH, IMAGE_HEIGHT])
test_image_encoding = face_recognition.face_encodings(test_image)[0]
result = search_encoding_in_nodes(test_image_encoding)
print(result)
else:
print('No such image found')
@app.route('/test_encoding', methods=['POST'])
def test_encoding():
log('Requested for encoding search...')
request_json = request.get_json(force=True)
encoding = request_json['encoding']
search_result = search_encoding_in_nodes(np.asarray(encoding))
log('Search result is', search_result)
message = {
'result': search_result
}
return json.dumps(message)
@app.route('/')
def hello_world():
return 'Dockerized'
# Start the flask service
def start_server():
threading.Thread(target=app.run, args=(HOST_NAME, PORT)).start()
time.sleep(0.5)
def main():
try:
start_server()
except Exception as e:
logging.exception('Could not start flask server')
return
try:
register()
except Exception:
logging.exception('Could not connect to registration server')
return
# search_image_from_user()
if __name__ == '__main__':
main()