-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcore.py
More file actions
333 lines (285 loc) · 9.66 KB
/
core.py
File metadata and controls
333 lines (285 loc) · 9.66 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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"""
Deepstack core.
"""
import requests
from PIL import Image
from typing import Union, List, Set, Dict
from requests.models import Response
## Const
DEFAULT_API_KEY = ""
DEFAULT_TIMEOUT = 10 # seconds
DEFAULT_IP = "localhost"
DEFAULT_PORT = 80
DEFAULT_MIN_CONFIDENCE = 0.45
## HTTP codes
HTTP_OK = 200
BAD_URL = 404
## API urls
URL_BASE_VISION = "http://{ip}:{port}/v1/vision"
URL_CUSTOM = "/custom/{custom_model}"
URL_OBJECT_DETECTION = "/detection"
URL_FACE_DETECTION = "/face"
URL_FACE_REGISTER = "/face/register"
URL_FACE_RECOGNIZE = "/face/recognize"
URL_FACE_LIST = "/face/list"
URL_SCENE_RECOGNIZE = "/scene"
class DeepstackException(Exception):
pass
def format_confidence(confidence: Union[str, float]) -> float:
"""
Takes a confidence from the API like
0.55623 and returns 55.6 (%).
"""
DECIMALS = 1
return round(float(confidence) * 100, DECIMALS)
def get_confidences_above_threshold(
confidences: List[float], confidence_threshold: float
) -> List[float]:
"""Takes a list of confidences and returns those above a confidence_threshold."""
return [val for val in confidences if val >= confidence_threshold]
def get_recognized_faces(predictions: List[Dict]) -> List[Dict]:
"""
Get the recognized faces.
"""
try:
matched_faces = {
face["userid"]: round(face["confidence"] * 100, 1)
for face in predictions
if not face["userid"] == "unknown"
}
return matched_faces
except:
return {}
def get_objects(predictions: List[Dict]) -> List[str]:
"""
Get a list of the unique objects predicted.
"""
labels = [pred["label"] for pred in predictions]
return sorted(list(set(labels)))
def get_object_confidences(predictions: List[Dict], target_object: str) -> List[float]:
"""
Return the list of confidences of instances of target label.
"""
confidences = [
float(pred["confidence"])
for pred in predictions
if pred["label"] == target_object
]
return confidences
def get_objects_summary(predictions: List[Dict]):
"""
Get a summary of the objects detected.
"""
objects = get_objects(predictions)
return {
target_object: len(get_object_confidences(predictions, target_object))
for target_object in objects
}
def post_image(
url: str, image_bytes: bytes, timeout: int, data: dict
) -> requests.models.Response:
"""Post an image to Deepstack. Only handles exceptions."""
try:
return requests.post(
url, files={"image": image_bytes}, data=data, timeout=timeout
)
except requests.exceptions.Timeout:
raise DeepstackException(
f"Timeout connecting to Deepstack, the current timeout is {timeout} seconds, try increasing this value"
)
except requests.exceptions.ConnectionError or requests.exceptions.MissingSchema as exc:
raise DeepstackException(
f"Deepstack connection error, check your IP and port: {exc}"
)
def process_image(
url: str,
image_bytes: bytes,
api_key: str,
min_confidence: float,
timeout: int,
data: dict = {},
) -> Dict:
"""Process image_bytes and detect. Handles common status codes"""
data["api_key"] = api_key
data["min_confidence"] = min_confidence
response = post_image(url=url, image_bytes=image_bytes, timeout=timeout, data=data)
if response.status_code == HTTP_OK:
return response.json()
elif response.status_code == BAD_URL:
raise DeepstackException(f"Bad url supplied, url {url} raised error {BAD_URL}")
else:
raise DeepstackException(
f"Error from Deepstack request, status code: {response.status_code}"
)
def get_stored_faces(url, api_key, timeout) -> List:
"""Posts a request and get the stored faces as a list"""
try:
data = requests.post(url, timeout=timeout, data={"api_key": api_key})
except requests.exceptions.Timeout:
raise DeepstackException(
f"Timeout connecting to Deepstack, the current timeout is {timeout} seconds, try increasing this value"
)
except requests.exceptions.ConnectionError or requests.exceptions.MissingSchema as exc:
raise DeepstackException(
f"Deepstack connection error, check your IP and port: {exc}"
)
return data.json()
class DeepstackVision:
"""Base class for Deepstack vision."""
def __init__(
self,
ip: str = DEFAULT_IP,
port: int = DEFAULT_PORT,
api_key: str = DEFAULT_API_KEY,
timeout: int = DEFAULT_TIMEOUT,
min_confidence: float = DEFAULT_MIN_CONFIDENCE,
url_detect: str = "",
url_recognize: str = "",
url_register: str = "",
url_face_list: str = "",
):
self._api_key = api_key
self._timeout = timeout
self._min_confidence = min_confidence
self._url_base = URL_BASE_VISION.format(ip=ip, port=port)
self._url_detect = self._url_base + url_detect
self._url_recognize = self._url_base + url_recognize
self._url_register = self._url_base + url_register
self._url_face_list = self._url_base + url_face_list
def detect(self):
"""Process image_bytes and detect."""
raise NotImplementedError
def recognize(self):
"""Process image_bytes and recognize."""
raise NotImplementedError
def register(self):
"""Perform a registration."""
raise NotImplementedError
class DeepstackObject(DeepstackVision):
"""Work with objects"""
def __init__(
self,
ip: str = DEFAULT_IP,
port: int = DEFAULT_PORT,
api_key: str = DEFAULT_API_KEY,
timeout: int = DEFAULT_TIMEOUT,
min_confidence: float = DEFAULT_MIN_CONFIDENCE,
custom_model: str = "",
):
if custom_model:
url_detect = URL_CUSTOM.format(custom_model=custom_model)
else:
url_detect = URL_OBJECT_DETECTION
super().__init__(
ip=ip,
port=port,
api_key=api_key,
timeout=timeout,
min_confidence=min_confidence,
url_detect=url_detect,
)
def detect(self, image_bytes: bytes):
"""Process image_bytes and detect."""
response = process_image(
url=self._url_detect,
image_bytes=image_bytes,
api_key=self._api_key,
min_confidence=self._min_confidence,
timeout=self._timeout,
)
return response["predictions"]
class DeepstackScene(DeepstackVision):
"""Work with scenes"""
def __init__(
self,
ip: str = DEFAULT_IP,
port: int = DEFAULT_PORT,
api_key: str = DEFAULT_API_KEY,
timeout: int = DEFAULT_TIMEOUT,
min_confidence: float = DEFAULT_MIN_CONFIDENCE,
):
super().__init__(
ip=ip,
port=port,
api_key=api_key,
timeout=timeout,
min_confidence=min_confidence,
url_recognize=URL_SCENE_RECOGNIZE,
)
def recognize(self, image_bytes: bytes):
"""Process image_bytes and detect."""
response = process_image(
url=self._url_recognize,
image_bytes=image_bytes,
api_key=self._api_key,
min_confidence=self._min_confidence,
timeout=self._timeout,
)
del response["success"]
return response
class DeepstackFace(DeepstackVision):
"""Work with objects"""
def __init__(
self,
ip: str = DEFAULT_IP,
port: int = DEFAULT_PORT,
api_key: str = DEFAULT_API_KEY,
timeout: int = DEFAULT_TIMEOUT,
min_confidence: float = DEFAULT_MIN_CONFIDENCE,
):
super().__init__(
ip=ip,
port=port,
api_key=api_key,
timeout=timeout,
min_confidence=min_confidence,
url_detect=URL_FACE_DETECTION,
url_register=URL_FACE_REGISTER,
url_recognize=URL_FACE_RECOGNIZE,
url_face_list=URL_FACE_LIST,
)
def detect(self, image_bytes: bytes):
"""Process image_bytes and detect."""
response = process_image(
url=self._url_detect,
image_bytes=image_bytes,
api_key=self._api_key,
min_confidence=self._min_confidence,
timeout=self._timeout,
)
return response["predictions"]
def register(self, name: str, image_bytes: bytes):
"""
Register a face name to a file.
"""
response = process_image(
url=self._url_register,
image_bytes=image_bytes,
api_key=self._api_key,
min_confidence=self._min_confidence,
timeout=self._timeout,
data={"userid": name},
)
if response["success"] == True:
return response["message"]
elif response["success"] == False:
error = response["error"]
raise DeepstackException(
f"Deepstack raised an error registering a face: {error}"
)
def recognize(self, image_bytes: bytes):
"""Process image_bytes, performing recognition."""
response = process_image(
url=self._url_recognize,
image_bytes=image_bytes,
api_key=self._api_key,
min_confidence=self._min_confidence,
timeout=self._timeout,
)
return response["predictions"]
def get_registered_faces(self):
"""Get the name of the registered faces"""
response = get_stored_faces(
url=self._url_face_list, api_key=self._api_key, timeout=self._timeout
)
return response["faces"]