-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalytics_api.py
776 lines (695 loc) · 31.5 KB
/
analytics_api.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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
import json
import subprocess
import sys
import time
import requests
import websocket
SUBSCRIBED_TOPICS = [
"SIFIS:Privacy_Aware_Speech_Recognition",
"SIFIS:Privacy_Aware_Parental_Control",
"SIFIS:Privacy_Aware_Device_Anomaly_Detection",
"SIFIS:Privacy_Aware_Object_Recognition",
"SIFIS:Privacy_Aware_Face_Recognition",
"SIFIS:Publish_Alarms_Request",
"SIFIS:AUD_Manager_Request",
"SIFIS:Privacy_Aware_Speech_Recognition_Results",
"SIFIS:Privacy_Aware_Parental_Control_Results",
"SIFIS:Privacy_Aware_Object_Recognition_Results",
"SIFIS:Privacy_Aware_Object_Recognition_Frame_Results",
"SIFIS:Privacy_Aware_Device_Anomaly_Detection_Results",
"SIFIS:Netspot_Control_Results",
"SIFIS:AUD_Manager_Results",
"SIFIS:Object_Recognition",
"SIFIS:Object_Recognition_Frame_Results",
"SIFIS:Object_Recognition_Results",
"SIFIS:Privacy_Aware_Speaker_Verification",
"SIFIS:Privacy_Aware_Audio_Anomaly_Detection",
"SIFIS:Privacy_Aware_Audio_Anomaly_Detection_Results",
"SIFIS:Privacy_Aware_Face_Recognition_CAM",
]
def get_last_time():
"""Reads last_time.txt and returns timestamp from there or 0 for known errors"""
try:
file = open("last_time.txt")
timestamp = int(file.readline().rstrip())
file.close()
return timestamp
except (FileNotFoundError, ValueError):
return 0
def set_last_time():
"""Writes the current timestamp to the last_time.txt file"""
file = open("last_time.txt", "w")
file.write(str(time.time_ns()))
file.close()
def netspot_alarm_check(address, port, within_time=None):
# Get or make timestamp for alarms request
if within_time is None:
timestamp = get_last_time()
else:
timestamp = time.time_ns() - int(within_time * 6e10)
# Making the request
url = f"http://{address}:{port}/v1/netspots/alarms"
params = {"time": timestamp, "last": 50}
try:
reply = requests.get(url, params)
except requests.RequestException as e:
return False, str(e)
# Checking the reply
if reply.status_code == 200:
# Request was okay, save current time to be used with next request
set_last_time()
# Handling messages
messages = reply.json()
if len(messages) == 0:
# No alarms
return True, None
# Find messages with the highest probability
highest_probability = 0.0
most_urgent_message = ""
for message in messages:
if message["probability"] >= highest_probability:
highest_probability = message["probability"]
most_urgent_message = message
return True, most_urgent_message
# Server responded with error. Return status code and content in the message
return (
False,
f"Server responded with {reply.status_code}:\n{reply.content.decode('utf-8')}",
)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### Connection closed ###")
def on_open(ws):
print("### Connection established ###")
def on_message(ws, message):
print("Received:")
print(message)
json_message = json.loads(message)
if "Persistent" in json_message:
json_message = json_message["Persistent"]
if "topic_name" in json_message:
if json_message["topic_name"] in SUBSCRIBED_TOPICS:
if (
json_message["topic_name"]
== "SIFIS:Publish_Alarms_Request"
):
print("Received instance of " + json_message["topic_name"])
print("Topic Name: " + json_message["topic_name"])
print("Address: " + json_message["value"]["Address"])
print("Port: " + str(json_message["value"]["Port"]))
Address = json_message["value"]["Address"]
Port = json_message["value"]["Port"]
within_time = json_message["value"]["Within Time"]
device = json_message["value"]["Device name"]
if (
Address is not None
and Port is not None
and within_time is not None
):
print("Time is not None")
(success, message) = netspot_alarm_check(
Address, Port, within_time
)
elif (
Address is not None
and Port is not None
and within_time is None
):
print("Time is None")
(success, message) = netspot_alarm_check(Address, Port)
else:
print("Error, no variables were passed")
if success:
if message is None:
return 0
# We have an alarm message. Let us create DHT message from it.
ws_req = {
"RequestPostTopicUUID": {
"topic_name": "SIFIS:Netspot_Control_Results",
"topic_uuid": "AlarmResult",
"value": {
"description": "Netspot alarms check results",
"Device": device,
"Statistic": message["stat"],
"Status": message["status"],
"Probability": message["probability"],
"Time": message["time"],
},
}
}
ws.send(json.dumps(ws_req))
dht_message_json = json.dumps(
ws_req, separators=(",", ":")
)
print(dht_message_json)
return 1
print(
"Could not receive alarms:", message, file=sys.stdout
)
return 2
elif json_message["topic_name"] == "SIFIS:AUD_Manager_Request":
print("Received instance of " + json_message["topic_name"])
print("Topic Name: " + json_message["topic_name"])
print("Request: " + json_message["value"]["Request"])
Request = json_message["value"]["Request"]
cmd1 = "curl http://localhost:5050/" + str(Request)
cmd = cmd1.split()
print(cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = p.communicate()
# print(out)
print(out.decode("ascii"))
ws_req = {
"RequestPostTopicUUID": {
"topic_name": "SIFIS:AUD_Manager_Results",
"topic_uuid": "AUD_Manager_Results",
"value": {
"description": "AUD Manager Results",
"Request": str(Request),
"Results": out.decode("ascii"),
},
}
}
ws.send(json.dumps(ws_req))
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Speech_Recognition"
):
print("Received instance of " + json_message["topic_name"])
print("Audio File: " + json_message["value"]["Audio File"])
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
print(
"Entity Types: "
+ str(json_message["value"]["Entity Types"])
)
print("method: " + str(json_message["value"]["method"]))
audio = json_message["value"]["Audio File"]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
Entity_Types = json_message["value"]["Entity Types"]
method = json_message["value"]["method"]
if method == "DeepSpeeach":
cmd1 = "docker run -ti -v /var/run/docker.sock:/var/run/docker.sock -u root --net=host --name privacy_preserving_speech_recognition privacy_preserving_speech_recognition python -m recognize_wavFile_Func --audio "
cmd2 = cmd1 + audio
cmd = cmd2.split()
print(cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = p.communicate()
print(out)
cmd = "docker rm -f privacy_preserving_speech_recognition".split()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = p.communicate()
print(out)
elif method == "Whisper":
url = (
"http://localhost:5040/whisper/"
+ audio
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
file = {
"file": open("/analytics_api/data/" + audio, "rb")
}
response = requests.post(url, files=file)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict[
"RequestPostTopicUUID"
]["value"]
ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Audio_Anomaly_Detection"
):
print("Received instance of " + json_message["topic_name"])
print("Audio File: " + json_message["value"]["audio_file"])
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
print("method: " + str(json_message["value"]["method"]))
audio_file = json_message["value"]["audio_file"]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
method = json_message["value"]["method"]
url = (
"http://localhost:5000/model/predict/"
+ audio_file
+ "/"
+ method
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
file = {
"audio": (
"sample1.wav",
open("/analytics_api/data/" + audio_file, "rb"),
"audio/wav",
)
}
response = requests.post(url, files=file)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
for prediction in range(5):
print(
response_dict["predictions"][prediction][
"label"
],
response_dict["predictions"][prediction][
"probability"
],
)
ws_req = {
"RequestPostTopicUUID": {
"topic_name": "SIFIS:Privacy_Aware_Audio_Anomaly_Detection_Results",
"topic_uuid": "Audio_Anomaly_Detection_Results",
"value": {
"description": "Speech Recognition Results",
"requestor_id": str(
response_dict["requestor_id"]
),
"requestor_type": str(
response_dict["requestor_type"]
),
"request_id": str(
response_dict["request_id"]
),
"analyzer_id": str(
response_dict["analyzer_id"]
),
"analysis_id": str(
response_dict["analysis_id"]
),
"audio_file": str(
response_dict["audio_file"]
),
"method": str(response_dict["method"]),
"predictions": response_dict[
"predictions"
],
},
}
}
ws.send(json.dumps(ws_req))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Device_Anomaly_Detection"
):
print("Received instance of " + json_message["topic_name"])
print("Topic Name: " + json_message["topic_name"])
temp = json_message["value"]["Temperatures"]
t = " ".join(str(item) for item in temp)
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
url = (
"http://localhost:9090/temperature/"
+ str(t)
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
# Make the request
response = requests.get(url)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict["RequestPostTopicUUID"][
"value"
]
# ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Parental_Control"
):
print("Received instance of " + json_message["topic_name"])
print("file_name: " + json_message["value"]["file_name"])
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
print(
"Privacy_Parameter: "
+ str(json_message["value"]["Privacy_Parameter"])
)
file_name = json_message["value"]["file_name"]
Privacy_Parameter = json_message["value"][
"Privacy_Parameter"
]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
file_path = "/analytics_api/data/" + file_name
url = (
"http://localhost:6060/file_estimation/"
+ file_name
+ "/"
+ str(Privacy_Parameter)
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
file = {"file": open(file_path, "rb")}
response = requests.post(url, files=file)
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
print(response_dict)
# Make the request
response = requests.post(
url, files={"file": open(file_path, "rb")}
)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict["RequestPostTopicUUID"][
"value"
]
ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Object_Recognition"
):
print("Received instance of " + json_message["topic_name"])
print("file_path: " + json_message["value"]["file_path"])
print("file_name: " + json_message["value"]["file_name"])
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
print("epsilon: " + str(json_message["value"]["epsilon"]))
print(
"sensitivity: "
+ str(json_message["value"]["sensitivity"])
)
file_path = json_message["value"]["file_path"]
file_name = json_message["value"]["file_name"]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
epsilon = json_message["value"]["epsilon"]
sensitivity = json_message["value"]["sensitivity"]
url = (
"http://localhost:8080/file_object/"
+ file_name
+ "/"
+ str(epsilon)
+ "/"
+ str(sensitivity)
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
file_path = "/analytics_api/data/" + file_name
# Make the request
response = requests.post(
url, files={"file": open(file_path, "rb")}
)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict["RequestPostTopicUUID"][
"value"
]
ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Face_Recognition"
):
print("Received instance of " + json_message["topic_name"])
print("file_name: " + json_message["value"]["file_name"])
print(
"database_path: "
+ json_message["value"]["database_path"]
)
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
print(
"privacy_parameter: "
+ str(json_message["value"]["privacy_parameter"])
)
file_name = json_message["value"]["file_name"]
database_path = json_message["value"]["database_path"]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
privacy_parameter = json_message["value"][
"privacy_parameter"
]
url = (
"http://localhost:8090/check_directory/"
+ file_name
+ "/"
+ str(privacy_parameter)
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
file_path = "/analytics_api/data/" + file_name
# database_path = '/analytics_api/data/' + database_path
# database_path = '/app/database'
database_path = database_path
files = [
("file", open(file_path, "rb")),
("path", database_path),
]
# Make the request
response = requests.post(url, files=files)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict["RequestPostTopicUUID"][
"value"
]
ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Face_Recognition_CAM"
):
print("Received instance of " + json_message["topic_name"])
print("cam_link: " + json_message["value"]["cam_link"])
print(
"database_path: "
+ json_message["value"]["database_path"]
)
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
print(
"privacy_parameter: "
+ str(json_message["value"]["privacy_parameter"])
)
cam_link = json_message["value"]["cam_link"]
database_path = json_message["value"]["database_path"]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
privacy_parameter = json_message["value"][
"privacy_parameter"
]
url = (
"http://localhost:8090/cam_face_recognition/"
+ cam_link
+ "/"
+ str(privacy_parameter)
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
database_path = database_path
files = [
("path", database_path),
]
# Make the request
response = requests.post(url, files=files)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict["RequestPostTopicUUID"][
"value"
]
ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
elif (
json_message["topic_name"]
== "SIFIS:Privacy_Aware_Speaker_Verification"
):
print("Received instance of " + json_message["topic_name"])
print(
"First Audio File: "
+ json_message["value"]["first_audio_file"]
)
print(
"Second Audio File: "
+ json_message["value"]["second_audio_file"]
)
print(
"requestor_id: "
+ json_message["value"]["requestor_id"]
)
print(
"requestor_type: "
+ json_message["value"]["requestor_type"]
)
print("request_id: " + json_message["value"]["request_id"])
first_audio_file = json_message["value"][
"first_audio_file"
]
second_audio_file = json_message["value"][
"second_audio_file"
]
requestor_id = json_message["value"]["requestor_id"]
requestor_type = json_message["value"]["requestor_type"]
request_id = json_message["value"]["request_id"]
url = (
"http://localhost:7070/speaker_verification/"
+ first_audio_file
+ "/"
+ second_audio_file
+ "/"
+ requestor_id
+ "/"
+ requestor_type
+ "/"
+ request_id
)
files = [
(
"file1",
(
"filename1.wav",
open(
"/analytics_api/data/" + first_audio_file,
"rb",
),
"audio/wav",
),
),
(
"file2",
(
"filename2.wav",
open(
"/analytics_api/data/" + second_audio_file,
"rb",
),
"audio/wav",
),
),
]
response = requests.post(url, files=files)
# Check the response
if response.status_code == 200:
print("Request succeeded.")
response_dict = json.loads(response.content)
response_dict2 = response_dict["RequestPostTopicUUID"][
"value"
]
ws.send(json.dumps(response_dict))
else:
print("Request failed.")
print(response.content)
else:
print(
"We are not subscribed to this topic ",
json_message["topic_name"],
)
if __name__ == "__main__":
ws = websocket.WebSocketApp(
"ws://localhost:3000/ws",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close,
)
ws.run_forever()