-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathupload_api-v2.py
More file actions
executable file
·1712 lines (1537 loc) · 75 KB
/
Copy pathupload_api-v2.py
File metadata and controls
executable file
·1712 lines (1537 loc) · 75 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
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, json, time, sys, thread, base64
import argparse
import unicodedata
import shutil
import subprocess
import threading
# import dlib
import math
import time
import os.path
import Queue
from threading import Timer
import requests
from collections import defaultdict
from flask import Flask, request, url_for, make_response, abort, Response, jsonify, send_from_directory, redirect
from flask_sqlalchemy import SQLAlchemy
from migrate_db import People, TrainSet, db, AutoGroupSet, Stranger, Frame
from sqlalchemy import exc
#from flask_script import Server, Manager
#from flask_migrate import Migrate, MigrateCommand
#from werkzeug.utils import secure_filename
from uuid import uuid1
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
from PIL import Image
#import tensorflow as tf
import numpy as np
from scipy import misc
from math import hypot
from multiprocessing import Process
from collections import OrderedDict
USE_DEFAULT_DATA=True # Enable to use "groupid_default" for SVM training
import facenet
#import clustering_people
from subprocess import Popen, PIPE
import FaceProcessing
from utilslib.mqttClient import MyMQTTClass
from utilslib.persistentUUID import getUUID
from utilslib.save2gst import save2gst, post2gst_motion, post2gst_video
from utilslib.save2gst import sendMessage2Group
from utilslib.getDeviceInfo import deviceId, get_current_groupid, get_deviceid, save_groupid_to_file, check_groupid_changed
from utilslib.qiniuUpload import qiniu_upload_img, qiniu_upload_video, qiniu_upload_data, SUFFIX
# from utilslib.make_a_gif import load_all_images, build_gif, url_to_image
# from utilslib.timer import Timer
from utilslib.clean_droped_data import clean_droped_embedding
from objects.generate_bottlenecks import resize
from faces import save_embedding
from utilslib.resultqueue import push_resultQueue, get_resultQueue
#deeepeye
from celery import Celery
from celery import Task
from billiard import current_process
from celery.signals import worker_process_init
from celery.signals import celeryd_after_setup
from celery.concurrency import asynpool
BASEDIR = os.getenv('RUNTIME_BASEDIR',os.path.abspath(os.path.dirname(__file__)))
TMP_DIR_PATH = os.path.join(BASEDIR, 'data', 'faces', 'tmp_pic_path')
UPLOAD_FOLDER = os.path.join(BASEDIR, 'image')
DATABASE = 'sqlite:///' + os.path.join(BASEDIR, 'data', 'data.sqlite')
face_tmp_objid = None
obje_tmp_objid = None
EN_OBJECT_DETECTION = False
FACE_DETECTION_WITH_DLIB = False # Disable DLIB at this time
EN_SOFTMAX = False
SOFTMAX_ONLY = False
isUpdatingDataSet = False
webShowFace = False
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'bitmap'])
EXT_IMG='png'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# db = SQLAlchemy(app)
db.init_app(app)
ENABLE_DEBUG_LOG_TO_GROUP = False
DO_NOT_UPLOAD_IMAGE = False
DO_NOT_REPORT_TO_SERVER = False
NEAR_FRONTIAL_ONLY = False
image_size = 112
margin = 6
facenet_model = os.path.join(BASEDIR, 'facenet_models/20170512-110547/20170512-110547.pb')
minsize = 50 # minimum size of face
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
confident_value = 0.67
mineyedist = 0.3 # Eye distance of width of face bounding box
CONFIDENT_VALUE_THRESHOLD = 0.80 #点圈显示的匹配度阈值,大于这个才显示,针对数据库遍历
FOR_ARLO = True
# BLURY_THREHOLD = 10 # Blur image if less than it. Reference: http://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/
uploadImg=None
mqttc=None
gbottlenecks=None
trainfromfottlenecks=None
gFlask_port=None
preFrameOnDevice = {}
all_face_index = 0 #每当识别出一个人脸就+1,当2个人同时出现在图片里面并且都不认识,需要区分开来
#deeepeye
asynpool.PROC_ALIVE_TIMEOUT = 60.0 #set this long enough
CLUSTER_REDIS_ADDRESS = os.getenv('CLUSTER_REDIS_ADDRESS','redis')
CLUSTER_REDIS_PORT = os.getenv('CLUSTER_REDIS_PORT','6379')
deepeye = Celery('upload_api-v2',
broker='redis://'+CLUSTER_REDIS_ADDRESS+':'+CLUSTER_REDIS_PORT+'/0',
backend='redis://'+CLUSTER_REDIS_ADDRESS+':'+CLUSTER_REDIS_PORT+'/0')
deepeye.count = 1
# run as worker only
CLUSTER_WORKERONLY = os.getenv('CLUSTER_WORKERONLY', False)
HAS_OPENCL = os.getenv('HAS_OPENCL', 'true')
EXTRACT_EMBEDDING_WITH_SERVER = os.getenv('EXTRACT_EMBEDDING_WITH_SERVER', 'true')
SAVE_ORIGINAL_FACE = False
original_face_img_path = os.path.join(BASEDIR, 'data', 'original_face_img')
if not os.path.exists(original_face_img_path):
os.mkdir(original_face_img_path)
SVM_CLASSIFIER_ENABLED=True
SVM_SAVE_TEST_DATASET=True
SVM_TRAIN_WITHOUT_CATEGORY=True
SVM_HIGH_SCORE_WITH_DB_CHECK=True
counter = 0
if HAS_OPENCL == 'false':
from embedding_client import get_remote_embedding
def featureCalculation(imgpath):
img = misc.imread(os.path.expanduser(imgpath))
prewhitened = facenet.prewhiten(img)
embedding = FaceProcessing.FaceProcessingImageData2(img)
return embedding
def allowed_file(filename):
"""
检查文件扩展名是否合法
:param filename:
:return: 合法 为 True
"""
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def insertOneImageIntoPeopleDB(filepath, uuid, group_id, objid, url, notFace=False, style="front"):
if notFace is True:
classId = "notface"
else:
classId = objid
if not os.path.exists(filepath):
print("file not exists %s" %(filepath))
return
embedding = featureCalculation2(filepath)
with app.app_context():
people = People(embed=embedding, uuid=uuid, group_id=group_id,
objId=objid, aliyun_url=url, classId=classId, style=style)
db.session.add(people)
db.session.commit()
os.remove(filepath)
return embedding
#For AutoGroup
#AutogroupFilesList = {}
#AutogroupDatasetFilesList = {}
AutogroupDB = None
AutogroupDatasetDB = None
isSyncAutogroupDataset = True
isStartAutogroup = False
AUTOGROUP_UNKNOWNFACES_DB = os.path.join(BASEDIR, 'autogroup_unknownfaces_db.json')
AUTOGROUP_DATASET_DB = os.path.join(BASEDIR, 'autogroup_dataset_db.json')
class MyDB:
def __init__(self, dbpath, isSave=False):
print("MyDB: __init__")
self.isSave = isSave
self.collection = {}
if (os.path.isfile(dbpath)):
with open(dbpath) as fJson:
self.collection = json.load(fJson)
self.dbpath = dbpath
def fetch(self):
return self.collection.copy()
def find(self, key, fields):
return self.collection.get(key, fields)
'''
if key is None:
return {}
if key in self.collection.keys():
if fields is None:
return self.collection[key]
subDic = self.collection[key]
isMatch = True
for subKey, subValue in fields:
if subKey not in subDic.keys() or subValue != subDic[subKey]:
isMatch = False
return {}
if isMatch is True:
return subDic
return {}
'''
def insert(self, key, fields):
self.collection[key] = fields
if self.isSave is True:
self.save()
def update(self, key, fields):
self.collection.update({key:fields})
if self.isSave is True:
self.save()
def remove(self, key):
self.collection.pop(key, "Key not Found!")
if self.isSave is True:
self.save()
def batch_insert(self, items):
print("items={}".format(items))
for key, value in items.items():
if isinstance(value,dict):
self.insert(key, value)
else:
print("batch_insert: invalid data format.")
if self.isSave is True:
self.save()
def save(self):
if self.dbpath is None:
return
with open(self.dbpath, 'w') as fJson:
json.dump(self.collection, fJson)
def AutoGroupSetInsert(obj):
print("test")
def AutoGroupSetUpdate(obj):
print("test")
def AutoGroupSetRemove(obj):
print("test")
def disposeAutoGroupFunc(type, json=None):
global AutogroupDB
global AutogroupDatasetDB
global isSyncAutogroupDataset
global isStartAutogroup
print("disposeAutoGroupFunc: type={}, json={}".format(type, json))
if AutogroupDB is None:
AutogroupDB = MyDB(AUTOGROUP_UNKNOWNFACES_DB)
if AutogroupDatasetDB is None:
AutogroupDatasetDB = MyDB(AUTOGROUP_DATASET_DB)
if type == "dataset":
AutogroupDatasetDB.batch_insert(json)
print("Download autogroup dataset...")
elif type == "syncdataset":
isSyncAutogroupDataset = True
print("Set isSyncAutogroupDataset to True")
elif type == "autogroup":
if json is not None:
AutogroupDB.batch_insert(json)
isStartAutogroup = True
print("Autogroup...")
#Path format: GroupID_FaceId/url_filename
def getFacialImagePath(img_path):
part1 = os.path.basename(os.path.dirname(img_path))
part2 = os.path.basename(img_path)
return part1+"/"+part2
def downloadAutogroupDataset(result, group_id):
failedDownloadedItems = []
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
print('--> {}'.format(faceId))
for url in urls:
#print(' {}'.format(url))
# url,faceid 从点圈群相册获取
# todo 可以用for循环解析群相册获取的json数据
img_url = url['url']
faceid = faceId
style = url['style']
if style != 'front':
#print("style=%s"%style);
continue
#status, embedding = down_img_embedding(img_url, group_id, faceid, style=style)
img_path = save_embedding.get_image_path_dst(img_url, group_id, faceId, style, "autogroup")
#print("img_path = {}".format(img_path))
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = None
if not os.path.exists(img_path):
img_path = save_embedding.download_img_for_svm_dst(img_url, group_id, faceId, style, "autogroup")
if img_path:
if not os.path.exists(embedding_path):
img = misc.imread(os.path.expanduser(img_path)) # 手动裁剪后的图片需要再缩放一下
aligned = misc.imresize(img, (image_size, image_size), interp='bilinear')
misc.imsave(img_path, aligned)
embedding = featureCalculation(img_path)
embedding_path = save_embedding.get_embedding_path(img_path)
save_embedding.create_embedding_string(embedding, embedding_path)
#print("1, type(embedding)={}".format(type(embedding)))
old_autogroup_set = AutoGroupSet.query.filter_by(url=img_url, group_id=group_id, is_or_isnot=True, style=style).first()
if not old_autogroup_set:
if embedding is None:
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = save_embedding.read_embedding_string(embedding_path)
embedding = np.asarray(embedding)
print("read_embedding_string...........")
print("2, type(embedding)={}".format(type(embedding)))
unique_face_id = ''
if unique_face_id in url:
unique_face_id = url['unique_face_id']
#unique_face_id = url['unique_face_id'] if unique_face_id in url else ''
autoGroupSet = AutoGroupSet(url=img_url, group_id=group_id, is_or_isnot=True,
device_id='', face_id=faceId, unique_face_id=unique_face_id, style=style, filepath=img_path, embed=embedding)
db.session.add(autoGroupSet)
db.session.commit()
print('-> syncAutogroupDataset downloaded url {} to {}'.format(url['url'], img_path))
else:
failedDownloadedItems.append(person)
return failedDownloadedItems
def syncAutogroupDatasetFunc():
group_id = get_current_groupid()
#host="http://localhost:3000/restapi/datasync/token/" + str(group_id)
API_SERVER_ADDRESS = os.getenv('API_SERVER_ADDRESS','workaihost.tiegushi.com')
API_SERVER_PORT = os.getenv('API_SERVER_PORT','80')
host = 'http://'+API_SERVER_ADDRESS+':'+API_SERVER_PORT+'/restapi/datasync/token/' + str(group_id)
result = None
try:
response = urlopen(host, timeout=10)
except HTTPError as e:
print('HTTPError: ', e.code)
return False
except URLError as e:
print('URLError: ', e.reason)
return False
except Exception as e:
print('Error: ', e)
return False
else:
# everything is fine
if 200 == response.getcode():
result = response.readline()
#print(result)
result = json.loads(result)
failedDownloadedItems = downloadAutogroupDataset(result, group_id)
try_count = 0
while len(failedDownloadedItems) > 0:
try_count = try_count+1
print("len(failedDownloadedItems) = {}, try_count={}".format(len(failedDownloadedItems), try_count))
if try_count > 3:
print("We have tried 3 times to download the autogroup dataset.")
break
failedDownloadedItems = downloadAutogroupDataset(failedDownloadedItems, group_id)
#Remove invalid data from local DB
urlsInLocalDB = AutoGroupSet.query.filter_by(group_id=group_id, style="front").all()
urlsOnServer = dict()
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
for url in urls:
img_url = url['url']
faceid = faceId
style = url['style']
urlsOnServer[img_url] = group_id, faceId, style
print("len(urlsInLocalDB) = {}".format(len(urlsInLocalDB)))
print("len(urlsOnServer) = {}".format(len(urlsOnServer)))
#print("urlsOnServer = {}".format(urlsOnServer))
if urlsInLocalDB:
for item in urlsInLocalDB:
image_path = None
#print("item = {}, item.url={}".format(item, item.url))
if item.url not in urlsOnServer.keys():
print("{}, {}, {}, {} is not on server, delete it from local DB.".format(item.url, item.group_id, item.face_id, item.style))
if item.filepath:
image_path = item.filepath
db.session.delete(item)
db.session.commit()
if image_path and os.path.isfile(image_path):
print('Remove image from local {}'.format(image_path))
os.remove(image_path)
embedding_path = save_embedding.get_embedding_path(image_path)
if embedding_path and os.path.isfile(embedding_path):
print('Remove embedding from local {}:'.format(embedding_path))
os.remove(embedding_path)
#Remove invalid photos from local
'''
dataset = []
for path in paths.split(':'):
path_exp = os.path.expanduser(path)
classes = [path for path in os.listdir(path_exp) \
if os.path.isdir(os.path.join(path_exp, path))]
classes.sort()
nrof_classes = len(classes)
for i in range(nrof_classes):
class_name = classes[i]
facedir = os.path.join(path_exp, class_name)
image_paths = []
if os.path.isdir(facedir):
images = os.listdir(facedir)
for img in images:
dataset.append(os.path.join(facedir,img))
if len(dataset) > 0:
for image_path in dataset:
l5 = (item for item in urlsInLocalDB if item.filepath == image_path)
if not l5:
print("image_path({}) only in local.".format(image_path))
if image_path and os.path.exists(image_path):
os.remove(filepath)
embedding_path = save_embedding.get_embedding_path(image_path)
if embedding_path and os.path.isfile(embedding_path):
os.remove(embedding_path)
'''
return True
else:
print('response code != 200')
return False
#Sync train data sets
def recover_db(img_url, group_id, faceid, filepath, embedding, style='front'):
# 恢复embedding到db
uuid = get_deviceid()
p = People.query.filter_by(aliyun_url=img_url, group_id=group_id).first()
if not p:
people = People(embed=embedding, uuid=uuid, group_id=group_id,
objId=faceid, aliyun_url=img_url, classId=faceid, style=style)
db.session.add(people)
db.session.commit()
print("Add people")
#return True
#else:
#print("No need add people")
#return False
old_train_set = TrainSet.query.filter_by(url=img_url, group_id=group_id).first() # 一张图片对应的人是唯一的
if not old_train_set:
new_train_set = TrainSet(url=img_url, group_id=group_id, is_or_isnot=True,
device_id='', face_id=faceid, filepath=filepath, drop=False, style=style)
db.session.add(new_train_set)
db.session.commit()
else:
if old_train_set.filepath != filepath:
print("Update filepath in local DB")
TrainSet.query.filter_by(url=img_url, group_id=group_id).update(dict(filepath=filepath))
db.session.commit()
def check_image_valid(filepath):
if filepath is None:
return False
if not os.path.exists(filepath):
print("not found {}".format(filepath))
return False
if os.path.getsize(filepath) < 1:
print("invalid file size {}".format(filepath))
return False
return True
def downloadTrainDatasets(result, group_id):
failedDownloadedItems = []
img_path = None
embedding_path = None
try:
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
print('--> {}'.format(faceId))
for url in urls:
#print(' {}'.format(url))
# url,faceid 从点圈群相册获取
# todo 可以用for循环解析群相册获取的json数据
img_url = url['url']
faceid = faceId
style = url['style']
if SVM_TRAIN_WITHOUT_CATEGORY is True:
style = 'front'
else:
if style == 'left_side' or style == 'right_side' or style == 'lower_head' or style == 'blury':
continue
else:
style = 'front'
#status, embedding = down_img_embedding(img_url, group_id, faceid, style=style)
print('img_url: ', img_url)
img_path = save_embedding.get_image_path(img_url, group_id, faceId, style)
print("img_path = {}".format(img_path))
embedding_path = save_embedding.get_embedding_path(img_path)
print("embedding_path = {}".format(embedding_path))
denoise_path = save_embedding.get_image_denoise_path(img_path)
recreate_embedding = False
embedding = None
if not os.path.exists(img_path):
print('img-path not exists ----- ')
img_path = save_embedding.download_img_for_svm(img_url, group_id, faceId, style)
if img_path and check_image_valid(img_path):
if not os.path.exists(denoise_path):
img = misc.imread(os.path.expanduser(img_path))
save_embedding.save_image_denoise(img, denoise_path)
recreate_embedding = True
if os.path.exists(denoise_path) is True and check_image_valid(denoise_path) is False:
os.remove(embedding_path)
os.remove(denoise_path)
recreate_embedding = False
continue
if not os.path.exists(embedding_path) or recreate_embedding == True:
img = misc.imread(os.path.expanduser(denoise_path)) # 手动裁剪后的图片需要再缩放一下
aligned = misc.imresize(img, (image_size, image_size), interp='bilinear')
misc.imsave(img_path, aligned)
print('......')
print('img_path: ',img_path)
embedding = featureCalculation2(img_path)
print('----------')
#embedding = featureCalculation(img_path)
embedding_path = save_embedding.get_embedding_path(img_path)
save_embedding.create_embedding_string(embedding, embedding_path)
#print("1, type(embedding)={}".format(type(embedding)))
else:
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = save_embedding.read_embedding_string(embedding_path)
embedding = np.asarray(embedding)
recover_db(img_url, group_id, faceid, img_path, embedding, style=style)
#print('-> downloadTrainDatasets downloaded url {} to {}'.format(url['url'], img_path))
else:
if img_path is not None and os.path.exists(img_path):
os.remove(img_path)
failedDownloadedItems.append(person)
except Exception as ex:
print('downloadTrainDatasets: except:', ex)
if img_path and os.path.isfile(img_path):
print('downloadTrainDatasets: Remove image from local {}'.format(img_path))
os.remove(img_path)
if embedding_path and os.path.isfile(embedding_path):
print('downloadTrainDatasets: Remove embedding from local {}'.format(embedding_path))
os.remove(embedding_path)
return failedDownloadedItems
def disposeFinalSyncDatasetsThreadFunc(device_id, toid):
invalid_images_onserver = 0
try:
group_id = get_current_groupid()
#host="http://localhost:3000/restapi/datasync/token/" + str(group_id)
API_SERVER_ADDRESS = os.getenv('API_SERVER_ADDRESS','workaihost.tiegushi.com')
API_SERVER_PORT = os.getenv('API_SERVER_PORT','80')
host = 'http://'+API_SERVER_ADDRESS+':'+API_SERVER_PORT+'/restapi/datasync/token/' + str(group_id)
result = None
try:
response = urlopen(host, timeout=10)
except HTTPError as e:
print('HTTPError: ', e.code)
return False
except URLError as e:
print('URLError: ', e.reason)
return False
except Exception as e:
print('Error: ', e)
return False
else:
# everything is fine
if 200 == response.getcode():
result = response.readline()
#print(result)
result = json.loads(result)
failedDownloadedItems = downloadTrainDatasets(result, group_id)
try_count = 0
while len(failedDownloadedItems) > 0:
try_count = try_count+1
print("len(failedDownloadedItems) = {}, try_count={}".format(len(failedDownloadedItems), try_count))
if try_count > 3:
print("We have tried 3 times to download the training dataset.")
break
failedDownloadedItems = downloadTrainDatasets(failedDownloadedItems, group_id)
#Remove invalid data from local DB
urlsInLocalDB = TrainSet.query.filter_by(group_id=group_id).all()
urlsOnServer = dict()
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
for url in urls:
img_url = url['url']
faceid = faceId
style = url['style']
if style == 'left_side' or style == 'right_side' or style == 'lower_head' or style == 'blury':
invalid_images_onserver += 1
continue
urlsOnServer[img_url] = group_id, faceId, style
print("Trainsets: len(urlsInLocalDB) = {}".format(len(urlsInLocalDB)))
print("Trainsets: len(urlsOnServer) = {}".format(len(urlsOnServer)))
urlsTemp = {}
deleteUrlsInLocalDB = []
if urlsInLocalDB:
for item in urlsInLocalDB:
image_path = None
#print("item = {}, item.url={}".format(item, item.url))
if (item.url in urlsTemp and urlsTemp[item.url] == 1) or item.url not in urlsOnServer.keys():
print("{}, {}, {}, {} is not on server, delete it from local DB.".format(item.url, item.group_id, item.face_id, item.style))
deleteUrlsInLocalDB.append(item)
if item.filepath:
image_path = item.filepath
db.session.delete(item)
db.session.commit()
if image_path and os.path.isfile(image_path):
print('Remove image from local {}'.format(image_path))
os.remove(image_path)
embedding_path = save_embedding.get_embedding_path(image_path)
if embedding_path and os.path.isfile(embedding_path):
print('Remove embedding from local {}:'.format(embedding_path))
os.remove(embedding_path)
urlsTemp[item.url] = 1
if len(deleteUrlsInLocalDB) > 0:
for item in deleteUrlsInLocalDB:
urlsInLocalDB.remove(item)
urlsTemp = None
print("Trainsets: 2, len(urlsInLocalDB) = {}".format(len(urlsInLocalDB)))
print("Trainsets: 2, len(urlsOnServer) = {}".format(len(urlsOnServer)))
#Remove invalid photos from local
dataset = []
style = ''
# if SVM_TRAIN_WITHOUT_CATEGORY is True:
# style = 'front'
style = 'front'
path = os.path.dirname(os.path.dirname(save_embedding.get_image_path('http://test/noname', group_id, faceId, style)))
# style = ''
# if SVM_TRAIN_WITHOUT_CATEGORY is True:
# style = 'front'
print("path={}".format(path)) #Frank
path_exp = os.path.expanduser(path)
classes = [path for path in os.listdir(path_exp) \
if os.path.isdir(os.path.join(path_exp, path))]
classes.sort()
nrof_classes = len(classes)
#print("classes={}".format(classes)) #Frank
for i in range(nrof_classes):
class_name = classes[i]
if USE_DEFAULT_DATA is True:
if class_name == "groupid_defaultfaceid":
continue;
facedir = os.path.join(path_exp, class_name)
image_paths = []
print("facedir={}".format(facedir))
if os.path.isdir(facedir):
images = os.listdir(facedir)
for img in images:
dataset.append(os.path.join(facedir,img))
willRemoveCount = 0
print("len(dataset)={}".format(len(dataset))) #Frank
#print("dataset={}".format(dataset))
#print("urlsInLocalDB={}".format(urlsInLocalDB))
if len(dataset) > 0:
for image_path in dataset:
l5 = (item for item in urlsInLocalDB if item.filepath.replace('front/','') == image_path.replace('front/',''))
count = sum(1 for x in l5)
if count == 0:
print("sum={}".format(count))
willRemoveCount = willRemoveCount+1
print("image_path({}) only in local, remove it.".format(image_path))
if image_path and os.path.exists(image_path):
os.remove(image_path)
print("Remove image_path={}".format(image_path))
embedding_path = save_embedding.get_embedding_path(image_path)
if embedding_path and os.path.isfile(embedding_path):
os.remove(embedding_path)
if len(device_id) > 1 and len(toid) > 1:
message = 'image_path({}) only in local, remove it.'.format(image_path)
print(message)
sendMessage2Group(device_id, toid, message)
if len(device_id) > 1 and len(toid) > 1:
message = 'Stat: localDB={}, server={}/{}, localfiles={}'.format(len(urlsInLocalDB), len(urlsOnServer), invalid_images_onserver, len(dataset)-willRemoveCount)
print(message)
sendMessage2Group(device_id, toid, message)
return True
else:
print('response code != 200')
return False
except Exception as ex:
print('disposeFinalSyncDatasetsThreadFunc: except:', ex)
def disposeSyncStatusInfoThreadFunc(device_id, toid):
invalid_images_onserver = 0
try:
group_id = get_current_groupid()
#host="http://localhost:3000/restapi/datasync/token/" + str(group_id)
API_SERVER_ADDRESS = os.getenv('API_SERVER_ADDRESS','workaihost.tiegushi.com')
API_SERVER_PORT = os.getenv('API_SERVER_PORT','80')
host = 'http://'+API_SERVER_ADDRESS+':'+API_SERVER_PORT+'/restapi/datasync/token/' + str(group_id)
result = None
try:
response = urlopen(host, timeout=10)
except HTTPError as e:
print('HTTPError: ', e.code)
return False
except URLError as e:
print('URLError: ', e.reason)
return False
except Exception as e:
print('Error: ', e)
return False
else:
# everything is fine
if 200 == response.getcode():
result = response.readline()
#print(result)
result = json.loads(result)
#Remove invalid data from local DB
urlsInLocalDB = TrainSet.query.filter_by(group_id=group_id).all()
urlsOnServer = dict()
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
for url in urls:
img_url = url['url']
faceid = faceId
style = url['style']
if style == 'left_side' or style == 'right_side' or style == 'lower_head' or style == 'blury':
invalid_images_onserver += 1
continue
urlsOnServer[img_url] = group_id, faceId, style
print("Trainsets: len(urlsInLocalDB) = {}".format(len(urlsInLocalDB)))
print("Trainsets: len(urlsOnServer) = {}".format(len(urlsOnServer)))
#Remove invalid photos from local
dataset = []
# style = ''
# if SVM_TRAIN_WITHOUT_CATEGORY is True:
style = 'front'
path = os.path.dirname(os.path.dirname(save_embedding.get_image_path('http://test/noname', group_id, faceId, style)))
style = ''
if SVM_TRAIN_WITHOUT_CATEGORY is True:
style = 'front'
print("path={}".format(path)) #Frank
path_exp = os.path.expanduser(path)
classes = [path for path in os.listdir(path_exp) \
if os.path.isdir(os.path.join(path_exp, path))]
classes.sort()
nrof_classes = len(classes)
#print("classes={}".format(classes)) #Frank
for i in range(nrof_classes):
class_name = classes[i]
facedir = os.path.join(path_exp, class_name)
image_paths = []
print("facedir={}".format(facedir))
if os.path.isdir(facedir):
images = os.listdir(facedir)
for img in images:
dataset.append(os.path.join(facedir,img))
if len(device_id) > 1 and len(toid) > 1:
message = 'StatInfo: localDB={}, server={}/{}, localfiles={}'.format(len(urlsInLocalDB), len(urlsOnServer), invalid_images_onserver, len(dataset))
print(message)
sendMessage2Group(device_id, toid, message)
return True
else:
print('response code != 200')
return False
except Exception as ex:
print('disposeSyncStatusInfoThreadFunc: except:', ex)
# @app.before_first_request
def migration():
if os.path.exists('migrate_db.exe'):
out_put = subprocess.check_output(['./migrate_db.exe', 'db', 'upgrade'])
else:
out_put = subprocess.check_output(['python', 'migrate_db.py', 'db', 'upgrade'])
print(out_put)
print('> finish migrate upgrade')
@app.route('/api/status', methods=['GET'])
def get_status():
global isUpdatingDataSet
if isUpdatingDataSet is False:
resp = Response(json.dumps({"status":"alive"}), status=200, mimetype='application/json')
else:
resp = Response(json.dumps({"status":"busy"}), status=401, mimetype='application/json')
return resp
@app.route('/api/images/<filename>', methods=['GET'])
def img(filename):
# p = People.query.filter_by(filename=filename).first()
# if p and p.aliyun_url:
# return redirect(p.aliyun_url)
if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
# 返回图片
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
# 返回json
# data = {'img_name': filename, 'img_url': request.url}
# js = json.dumps(data)
# resp = Response(js, status=200, mimetype='application/json')
# return resp
else:
return abort(404)
def format_img_filename(old_filename):
"""
给文件名加上gFlask_port,防止重名
:param old_filename: 旧文件名
:return: new_filename, uuid, ts
"""
ext = old_filename.rsplit('.', 1)[-1]
unix_time = time.time()
uuid = request.args.get('uuid', '')
ts = request.args.get('ts', str(unix_time * 1000))
new_filename = uuid + '_' + str(gFlask_port) + '_' + str(unix_time).replace('.', '') + '_' + str(ts) + '.' + ext
return new_filename, uuid, ts
@app.route('/api/upload_video/', methods=['POST'])
def upload_video():
video_local_path = request.form.get('videopath')
thumbnail_local_path = request.form.get('thumbnail', '')
ts = int(time.time()*1000) # 时间戳
offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
ts_offset = offset/60/60 * -1 # 时区 8
uuid = request.args.get('uuid', '')
key = uuid + str(ts)
video_src = qiniu_upload_video(key+'video', video_local_path) # 上传本地视频,获取视频播放地址
video_post = qiniu_upload_img(key+'thumbnail', thumbnail_local_path) # 视频封面预览图地址
person_id = request.args.get('objid', '')
if len(video_post) < 1:
video_post = 'http://data.tiegushi.com/fTnmgpdDN4hF9re8F_1493176458747.jpg';
payload = {'uuid': uuid,
'person_id': person_id,
'video_post': video_post,
'video_src': video_src,
'ts': ts,
'ts_offset': ts_offset,
}
post2gst_video(payload)
print('upload_video'.center(50,'-'))
print(payload)
return Response(json.dumps({"result": "ok"}), status=200, mimetype='application/json')
def sendDebugLogToGroup(uuid, current_groupid, message):
if ENABLE_DEBUG_LOG_TO_GROUP is True:
sendMessage2Group(uuid, current_groupid, message)
def showRecognizedImage(image_path, queue_index):
if os.path.exists(image_path):
recognized_img_path = os.path.join(os.path.dirname(image_path), 'face{}.png'.format(queue_index))
shutil.copy(image_path, recognized_img_path)
FACE_COUNT = defaultdict(int)
OBJ_COUNT = 0
def updateDataSet(url, objId, group_id, device_id, drop, img_type, sqlId, style, img_ts, rm_reason):
isUpdatingDataSet = True
try:
_updateDataSet(url, objId, group_id, device_id, drop, img_type, sqlId, style, img_ts, rm_reason)
except Exception as ex:
print("updateDataSet error:", ex)
isUpdatingDataSet = False
#raise
isUpdatingDataSet = False
FAILEDDOWNLOADINFOFILE = os.path.join(BASEDIR, 'failed_download_info.json')
FAILEDDOWNLOADINFOFILE2 = os.path.join(BASEDIR, 'failed_download_info2.json')
fileMuxlock = threading.Lock()
def loadFailedDownloadInfo():
failedDownloadInfo = {}
failedDownloadInfo['dInfo'] = []
if (os.path.isfile(FAILEDDOWNLOADINFOFILE)):
with open(FAILEDDOWNLOADINFOFILE) as fJson:
failedDownloadInfo = json.load(fJson)
return failedDownloadInfo
def recordFailedDownload(url, group_id, face_id, style, device_id):
failedDownloadInfo = loadFailedDownloadInfo()
failedDownloadInfo['dInfo'].append({
'url': url,
'group_id': group_id,
'face_id': face_id,
'style': style,
'device_id': device_id
})
with open(FAILEDDOWNLOADINFOFILE, 'w') as fJson:
json.dump(failedDownloadInfo, fJson)
def loadFailedDownloadList(filepath):
failedDownloadInfo = {}
failedDownloadInfo['dInfo'] = []
if (os.path.isfile(filepath)):
with open(filepath) as fJson:
failedDownloadInfo = json.load(fJson)
return failedDownloadInfo
def addFailedDownloadInfo(url, group_id, face_id, style, device_id):
fileMuxlock.acquire()
failedDownloadInfo = loadFailedDownloadList(FAILEDDOWNLOADINFOFILE2)
failedDownloadInfo['dInfo'].append({
'url': url,
'group_id': group_id,
'face_id': face_id,
'style': style,
'device_id': device_id
})
print('addFailedDownloadInfo: url='+url)
with open(FAILEDDOWNLOADINFOFILE2, 'w') as fJson:
json.dump(failedDownloadInfo, fJson)
fileMuxlock.release()
def mergeTwoJsonFiles():
fileMuxlock.acquire()
failedDownloadInfo1 = loadFailedDownloadList(FAILEDDOWNLOADINFOFILE)
failedDownloadInfo2 = loadFailedDownloadList(FAILEDDOWNLOADINFOFILE2)
mergedJson = {key: value for (key, value) in (failedDownloadInfo1.items() + failedDownloadInfo2.items())}
if (len(mergedJson['dInfo']) > 0):
print('mergeTwoJsonFiles: mergedJson=')
for key, value in mergedJson.items():
print(key, ':', value)
with open(FAILEDDOWNLOADINFOFILE, 'w') as fJson:
json.dump(mergedJson, fJson)
if (os.path.isfile(FAILEDDOWNLOADINFOFILE2)):
os.remove(FAILEDDOWNLOADINFOFILE2)
fileMuxlock.release()
def mergeFailedDownloadInfo(json1):
fileMuxlock.acquire()
failedDownloadInfo = loadFailedDownloadList(FAILEDDOWNLOADINFOFILE2)
mergedJson = {key: value for (key, value) in (json1.items() + failedDownloadInfo.items())}
if (len(mergedJson['dInfo']) > 0):
print('mergeFailedDownloadInfo: mergedJson=')
for key, value in mergedJson.items():
print(key, ':', value)
with open(FAILEDDOWNLOADINFOFILE, 'w') as fJson:
json.dump(mergedJson, fJson)
if (os.path.isfile(FAILEDDOWNLOADINFOFILE2)):
os.remove(FAILEDDOWNLOADINFOFILE2)
fileMuxlock.release()
def downloadFunc():
global FACE_COUNT
global OBJ_COUNT
while True:
try:
tmpFailedDownloadInfo = {}
tmpFailedDownloadInfo['dInfo'] = []
mergeTwoJsonFiles()
failedDownloadInfo = loadFailedDownloadList(FAILEDDOWNLOADINFOFILE)
for info in failedDownloadInfo['dInfo']:
if SVM_TRAIN_WITHOUT_CATEGORY is True:
info['style'] = 'front'
img_path = save_embedding.get_image_path(info['url'], info['group_id'], info['face_id'], info['style'])
embedding_path = save_embedding.get_embedding_path(img_path)
denoise_path = save_embedding.get_image_denoise_path(img_path)
recreate_embedding = False
if not os.path.exists(img_path):
img_path = save_embedding.download_img_for_svm(info['url'], info['group_id'], info['face_id'], style=info['style'])
if img_path:
if not os.path.exists(denoise_path):
img = misc.imread(os.path.expanduser(img_path))
save_embedding.save_image_denoise(img, denoise_path)