forked from ml-lab/DeepVideoAnalytics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfabfile.py
826 lines (746 loc) · 28.7 KB
/
fabfile.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
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
import os,logging,time,boto3, glob,subprocess,calendar,sys
from fabric.api import task,local,run,put,get,lcd,cd,sudo,env,puts
import json
import random
import shutil
from urllib import urlretrieve
from collections import defaultdict
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='logs/fab.log',
filemode='a')
@task
def shell():
"""
start a local django shell
:return:
"""
local('python manage.py shell')
@task
def local_static():
"""
Collect static
:return:
"""
local('python manage.py collectstatic')
@task
def migrate():
"""
Make migrations and migrate database
:return:
"""
local('python manage.py makemigrations')
local('python manage.py migrate')
@task
def server():
"""
Start server locally
:return:
"""
local("python manage.py runserver")
@task
def start_container():
"""
Start container
:param test:
:return:
"""
local('sleep 20')
migrate()
launch_queues_env()
if 'LAUNCH_SERVER' in os.environ:
local('python manage.py runserver 0.0.0.0:8000')
elif 'LAUNCH_SERVER_NGINX' in os.environ:
migrate()
local('chmod 0777 -R /tmp')
try:
local("mv docker/configs/nginx.conf /etc/nginx/")
except:
print "warning assuming that the config was already moved"
pass
if 'ENABLE_BASICAUTH' in os.environ:
try:
local("mv docker/configs/nginx-app_password.conf /etc/nginx/sites-available/default")
except:
print "warning assuming that the config was already moved"
pass
else:
try:
local("mv docker/configs/nginx-app.conf /etc/nginx/sites-available/default")
except:
print "warning assuming that the config was already moved"
pass
try:
local("mv docker/configs/supervisor-app.conf /etc/supervisor/conf.d/")
except:
print "warning assuming that the config was already moved"
pass
local("python manage.py collectstatic --no-input")
local("chmod 0777 -R dva/staticfiles/")
local("chmod 0777 -R dva/media/")
local('supervisord -n')
@task
def clean():
"""
Reset database, migrate, clear media folder, and (only on my dev machine) kill workers/clear all queues.
:return:
"""
import django, os
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.conf import settings
from dvaapp.models import VDNServer
if sys.platform == 'darwin':
for qname in set(settings.TASK_NAMES_TO_QUEUE.values()):
try:
local('rabbitmqadmin purge queue name={}'.format(qname))
except:
logging.warning("coudnt clear queue {}".format(qname))
migrate()
local('python manage.py flush --no-input')
migrate()
local("rm -rf {}/*".format(settings.MEDIA_ROOT))
local("mkdir {}/queries".format(settings.MEDIA_ROOT))
if sys.platform == 'darwin':
local("rm logs/*.log")
try:
local("ps auxww | grep 'celery -A dva worker' | awk '{print $2}' | xargs kill -9")
except:
pass
server = VDNServer()
server.url = "http://www.visualdata.network/"
server.name = "VisualData.Network"
server.save()
@task
def restart_queues(detection=False):
"""
tries to kill all celery workers and restarts them
:return:
"""
kill()
local('fab startq:qextractor &')
local('fab startq:qindexer &')
local('fab startq:qretriever &')
local('fab startq:qface &')
local('fab startq:qfacedetector &')
if detection:
local('fab startq:qdetector &')
@task
def kill():
try:
local("ps auxww | grep 'celery -A dva worker * ' | awk '{print $2}' | xargs kill -9")
except:
pass
@task
def ci():
"""
Used in conjunction with travis for Continuous Integration testing
:return:
"""
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
import base64
from django.core.files.uploadedfile import SimpleUploadedFile
from dvaapp.views import handle_uploaded_file, handle_youtube_video, create_query
from dvaapp.models import Video, Clusters,IndexEntries
from django.conf import settings
from dvaapp.tasks import extract_frames, perform_face_indexing, inception_index_by_id, perform_ssd_detection_by_id,\
perform_yolo_detection_by_id, inception_index_ssd_detection_by_id, export_video_by_id, import_video_by_id,\
inception_query_by_image, perform_clustering
for fname in glob.glob('tests/ci/*.mp4'):
name = fname.split('/')[-1].split('.')[0]
f = SimpleUploadedFile(fname, file(fname).read(), content_type="video/mp4")
handle_uploaded_file(f, name, False)
for fname in glob.glob('tests/*.zip'):
name = fname.split('/')[-1].split('.')[0]
f = SimpleUploadedFile(fname, file(fname).read(), content_type="application/zip")
handle_uploaded_file(f, name)
handle_youtube_video('tomorrow never dies', 'https://www.youtube.com/watch?v=gYtz5sw98Bc')
for i,v in enumerate(Video.objects.all()):
extract_frames(v.pk)
inception_index_by_id(v.pk)
if i ==0: # save travis time by just running detection on first video
perform_ssd_detection_by_id(v.pk)
perform_yolo_detection_by_id(v.pk)
perform_face_indexing(v.pk)
inception_index_ssd_detection_by_id(v.pk)
fname = export_video_by_id(v.pk)
f = SimpleUploadedFile(fname, file("{}/exports/{}".format(settings.MEDIA_ROOT,fname)).read(), content_type="application/zip")
vimported = handle_uploaded_file(f, fname)
import_video_by_id(vimported.pk)
dc = Clusters()
dc.indexer_algorithm = 'inception'
dc.included_index_entries_pk = [k.pk for k in IndexEntries.objects.all().filter(algorithm=dc.indexer_algorithm)]
dc.components = 32
dc.save()
perform_clustering(dc.pk)
query,dv = create_query(10,False,['inception',],[],'data:image/png;base64,'+base64.encodestring(file('tests/query.png').read()))
inception_query_by_image(query.pk)
query,dv = create_query(10,True,['inception',],[],'data:image/png;base64,'+base64.encodestring(file('tests/query.png').read()))
inception_query_by_image(query.pk)
test_backup()
@task
def quick(detection=False):
"""
Used on my local Mac for quickly cleaning and testing
:param detection:
:return:
"""
clean()
superu()
test()
launch(detection)
@task
def test_backup():
"""
Test if backup followed by restore works
:return:
"""
local('fab backup')
clean()
local('fab restore:backups/*.zip')
@task
def superu():
"""
Create a superuser
:return:
"""
local('echo "from django.contrib.auth.models import User; User.objects.create_superuser(\'akshay\', \'[email protected]\', \'super\')" | python manage.py shell')
@task
def launch(detection=False):
"""
Launch workers for each queue
:param detection: use fab launch_queues:1 to lauch detector queue in addition to all others
:return:
"""
local('fab startq:qextract &')
local('fab startq:qindexer &')
local('fab startq:qretriever &')
local('fab startq:qfaceretriever &')
local('fab startq:qfacedetector &')
local('fab startq:qclusterer &')
if detection:
local('fab startq:qdetector &')
@task
def launch_queues_env():
"""
Launch workers for each queue
:param detection: use fab launch_queues:1 to lauch detector queue in addition to all others
:return:
"""
import django, os
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from dvaapp.models import Video,VDNServer
for k in os.environ:
if k.startswith('LAUNCH_Q_'):
queue_name = k.split('_')[-1]
local('fab startq:{} &'.format(queue_name))
if not ('DISABLE_VDN' in os.environ):
if VDNServer.objects.count() == 0:
server = VDNServer()
server.url = "http://www.visualdata.network/"
server.name = "VisualData.Network"
server.save()
if 'TEST' in os.environ and Video.objects.count() == 0:
test()
@task
def startq(queue_name):
"""
Start worker to handle a queue, Usage: fab startq:indexer
Concurrency is set to 1 but you can edit code to change.
:param queue_name: indexer, extractor, retriever, detector
:return:
"""
import django, os
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.conf import settings
if queue_name in settings.QUEUES:
if queue_name == settings.Q_EXTRACTOR:
command = 'celery -A dva worker -l info -c {} -Q {} -n {}.%h -f logs/{}.log'.format(1, queue_name,queue_name,queue_name)
else:
command = 'celery -A dva worker -l info -P solo -c {} -Q {} -n {}.%h -f logs/{}.log'.format(1, queue_name,queue_name,queue_name)
logging.info(command)
os.system(command)
else:
raise ValueError, "Queue {} not found".format(queue_name)
@task
def test():
"""
Run tests by launching tasks
:return:
"""
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.core.files.uploadedfile import SimpleUploadedFile
from dvaapp.views import handle_uploaded_file, handle_youtube_video
for fname in glob.glob('tests/*.mp4'):
name = fname.split('/')[-1].split('.')[0]
f = SimpleUploadedFile(fname, file(fname).read(), content_type="video/mp4")
handle_uploaded_file(f, name)
for fname in glob.glob('tests/*.zip'):
name = fname.split('/')[-1].split('.')[0]
f = SimpleUploadedFile(fname, file(fname).read(), content_type="application/zip")
handle_uploaded_file(f, name)
handle_youtube_video('tomorrow never dies', 'https://www.youtube.com/watch?v=gYtz5sw98Bc')
@task
def backup():
"""
Take a backup, backups are store as a single zip file in backups/ folder
:return:
"""
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.conf import settings
try:
os.mkdir('backups')
except:
pass
media_dir = settings.MEDIA_ROOT
db = settings.DATABASES.values()[0]
pg = '/Users/aub3/PostgreSQL/pg96/bin/pg_dump' if sys.platform == 'darwin' else 'pg_dump'
with open('{}/postgres.dump'.format(media_dir), 'w') as dumpfile:
dump = subprocess.Popen([pg, '--clean', '--dbname',
'postgresql://{}:{}@{}:5432/{}'.format(db['USER'], db['PASSWORD'], db['HOST'],
db['NAME'])], cwd=media_dir, stdout=dumpfile)
dump.communicate()
print dump.returncode
current_path = os.path.abspath(os.path.dirname(__file__))
command = ['zip', '-r', '{}/backups/backup_{}.zip'.format(current_path, calendar.timegm(time.gmtime())), '.']
print ' '.join(command)
zipper = subprocess.Popen(command, cwd=media_dir)
zipper.communicate()
os.remove('{}/postgres.dump'.format(media_dir))
print zipper.returncode
@task
def restore(path):
"""
Restore a backup using path provided. Note that arugment are provided in following format. fab restore:backups/backup_1.zip
:param path:
:return:
"""
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.conf import settings
media_dir = settings.MEDIA_ROOT
current_path = os.path.abspath(os.path.dirname(__file__))
command = ['unzip', '-o', '{}'.format(os.path.join(current_path, path))]
print ' '.join(command)
zipper = subprocess.Popen(command, cwd=media_dir)
zipper.communicate()
db = settings.DATABASES.values()[0]
pg = '/Users/aub3/PostgreSQL/pg96/bin/psql' if sys.platform == 'darwin' else 'psql'
with open('{}/postgres.dump'.format(media_dir)) as dumpfile:
dump = subprocess.Popen(
[pg, '--dbname', 'postgresql://{}:{}@{}:5432/{}'.format(db['USER'], db['PASSWORD'], db['HOST'], db['NAME'])],
cwd=media_dir, stdin=dumpfile)
dump.communicate()
print dump.returncode
os.remove('{}/postgres.dump'.format(media_dir))
print zipper.returncode
@task
def yolo_detect(video_id):
"""
This is a HACK since Tensorflow is absolutely atrocious in allocating and freeing up memory.
Once a process / session is allocated a memory it cannot be forced to clear it up.
As a result this code gets called via a subprocess which clears memory when it exits.
:param video_id:
:return:
"""
import django
from PIL import Image
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.conf import settings
from dvaapp.models import Video,Detection,Frame
from dvalib import entity,detector
dv = Video.objects.get(id=video_id)
frames = Frame.objects.all().filter(video=dv)
v = entity.WVideo(dvideo=dv, media_dir=settings.MEDIA_ROOT)
wframes = {df.pk: entity.WFrame(video=v, frame_index=df.frame_index, primary_key=df.pk) for df in frames}
detection_count = 0
algorithm = detector.YOLODetector()
logging.info("starting detection {}".format(algorithm.name))
frame_detections = algorithm.detect(wframes.values())
for frame_pk,detections in frame_detections.iteritems():
for d in detections:
dd = Detection()
dd.video = dv
dd.frame_id = frame_pk
dd.object_name = d['name']
dd.confidence = d['confidence']
dd.x = d['left']
dd.y = d['top']
dd.w = d['right'] - d['left']
dd.h = d['bot'] - d['top']
dd.save()
img = Image.open(wframes[frame_pk].local_path())
img2 = img.crop((d['left'], d['top'], d['right'], d['bot']))
img2.save("{}/{}/detections/{}.jpg".format(settings.MEDIA_ROOT, video_id, dd.pk))
detection_count += 1
dv.refresh_from_db()
dv.detections = dv.detections + detection_count
dv.save()
@task
def ssd_detect(video_id):
"""
This is a HACK since Tensorflow is absolutely atrocious in allocating and freeing up memory.
Once a process / session is allocated a memory it cannot be forced to clear it up.
As a result this code gets called via a subprocess which clears memory when it exits.
:param video_id:
:return:
"""
import django
from PIL import Image
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.conf import settings
from dvaapp.models import Video,Detection,Frame
from dvalib import entity,detector
dv = Video.objects.get(id=video_id)
frames = Frame.objects.all().filter(video=dv)
v = entity.WVideo(dvideo=dv, media_dir=settings.MEDIA_ROOT)
wframes = {df.pk: entity.WFrame(video=v, frame_index=df.frame_index, primary_key=df.pk) for df in frames}
detection_count = 0
algorithm = detector.SSDetector()
logging.info("starting detection {}".format(algorithm.name))
frame_detections = algorithm.detect(wframes.values())
for frame_pk,detections in frame_detections.iteritems():
for d in detections:
dd = Detection()
dd.video = dv
dd.frame_id = frame_pk
dd.object_name = d['name']
dd.confidence = d['confidence']
dd.x = d['left']
dd.y = d['top']
dd.w = d['right'] - d['left']
dd.h = d['bot'] - d['top']
dd.save()
img = Image.open(wframes[frame_pk].local_path())
img2 = img.crop((d['left'], d['top'], d['right'], d['bot']))
img2.save("{}/{}/detections/{}.jpg".format(settings.MEDIA_ROOT, video_id, dd.pk))
detection_count += 1
dv.refresh_from_db()
dv.detections = dv.detections + detection_count
dv.save()
@task
def pyscenedetect(video_id,rescaled_width=600,rescale=True):
"""
Pyscenedetect often causes unexplainable double free errors on some machine when executing cap.release()
This ensures that the task recovers partial frame data i.e. every nth frame even if the command running inside a subprocess fails
:param video_id:
:param rescaled_width:
:return:
"""
import django
from PIL import Image
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from dvaapp.models import Video
from django.conf import settings
from dvalib import pyscenecustom,entity
dv = Video.objects.get(id=video_id)
v = entity.WVideo(dvideo=dv, media_dir=settings.MEDIA_ROOT)
if 'RESCALE_DISABLE' in os.environ:
rescale = False
manager = pyscenecustom.manager.SceneManager(save_image_prefix="{}/{}/frames/".format(settings.MEDIA_ROOT, video_id), rescaled_width=int(rescaled_width),rescale=rescale)
pyscenecustom.detect_scenes_file(v.local_path, manager)
@task
def process_video_list(filename):
"""
submit multiple videos from a json file
"""
import django,json
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from dvaapp.views import handle_youtube_video
vlist = json.load(file(filename))
for video in vlist:
handle_youtube_video(video['name'],video['url'])
@task
def perform_face_detection(video_id):
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from dvaapp.tasks import perform_face_indexing
perform_face_indexing(int(video_id))
def setup_django():
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
@task
def cluster():
from lopq.utils import load_xvecs
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from dvaapp.tasks import perform_clustering
from dvaapp.models import Video,Clusters,IndexEntries
c = Clusters()
c.indexer_algorithm = 'facenet'
c.included_index_entries_pk = [k.pk for k in IndexEntries.objects.all() if k.algorithm == c.indexer_algorithm]
c.components = 128
c.cluster_count = 32
c.save()
perform_clustering(c.pk,True)
@task
def heroku_migrate():
local('heroku run python vdn_manage.py migrate')
@task
def heroku_update_env():
local('heroku config:get DATABASE_URL > db.env')
@task
def heroku_shell():
local('heroku run python vdn_manage.py shell')
@task
def heroku_bash():
local('heroku run bash')
@task
def heroku_config():
local('heroku config')
@task
def heroku_psql():
local('heroku pg:psql')
@task
def heroku_make_migrate():
local('python vdn_manage.py makemigrations')
@task
def heroku_dbflush():
local('heroku pg:reset DATABASE_URL')
heroku_migrate()
local('heroku run python vdn_manage.py createsuperuser')
@task
def heroku_local_static():
local('python vdn_manage.py collectstatic')
@task
def heroku_migrate():
local('heroku run python vdn_manage.py migrate')
def get_coco_dirname():
if sys.platform == 'darwin':
dirname = '/Users/aub3/coco_input/'
else:
dirname = 'coco_input'
return dirname
@task
def download_coco(size=500):
dirname = get_coco_dirname()
try:
os.mkdir(dirname)
with lcd(dirname):
local("wget http://msvocds.blob.core.windows.net/annotations-1-0-3/instances_train-val2014.zip")
local("wget http://msvocds.blob.core.windows.net/annotations-1-0-3/person_keypoints_trainval2014.zip")
local("wget http://msvocds.blob.core.windows.net/annotations-1-0-3/captions_train-val2014.zip")
local('unzip "*.zip"')
except:
pass
train_data = json.load(file("{}/annotations/instances_train2014.json".format(dirname)))
captions_train_data = json.load(file("{}/annotations/captions_train2014.json".format(dirname)))
keypoints_train_data = json.load(file("{}/annotations/person_keypoints_train2014.json".format(dirname)))
sample = random.sample(train_data['images'], int(size))
ids = set()
for count, img in enumerate(sample):
if (count + 1) % 100 == 0:
print count
fname = os.path.join(dirname, img['file_name'])
if not os.path.exists(fname):
urlretrieve(img['coco_url'], fname)
ids.add(img['id'])
data = defaultdict(lambda: {'image': None, 'annotations': [], 'captions': [], 'keypoints': []})
id_to_license = {k['id']: k for k in train_data['licenses']}
id_to_category = {k['id']: k for k in train_data['categories']}
kp_id_to_category = {k['id']: k for k in keypoints_train_data['categories']}
for entry in train_data['images']:
if entry['id'] in ids:
entry['license'] = id_to_license[entry['license']]
data[entry['id']]['image'] = entry
for annotation in train_data['annotations']:
if annotation['image_id'] in ids:
annotation['category'] = id_to_category[annotation['category_id']]
data[annotation['image_id']]['annotations'].append(annotation)
del train_data
for annotation in captions_train_data['annotations']:
if annotation['image_id'] in ids:
data[annotation['image_id']]['captions'].append(annotation)
del captions_train_data
for annotation in keypoints_train_data['annotations']:
if annotation['image_id'] in ids:
annotation['category'] = kp_id_to_category[annotation['category_id']]
data[annotation['image_id']]['keypoints'].append(annotation)
del keypoints_train_data
with open('{}/coco_sample_metadata.json'.format(dirname), 'w') as output:
json.dump(data, output)
@task
def generate_vdn(fast=False):
kill()
import django
sys.path.append(os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings")
django.setup()
from django.core.files.uploadedfile import SimpleUploadedFile
from dvaapp.views import handle_uploaded_file, handle_youtube_video
from dvaapp import models
from dvaapp.tasks import extract_frames, perform_face_detection_indexing_by_id, inception_index_by_id, \
perform_ssd_detection_by_id, perform_yolo_detection_by_id, inception_index_ssd_detection_by_id, \
export_video_by_id
dirname = get_coco_dirname()
local('wget https://www.dropbox.com/s/2dq085iu34y0hdv/coco_input.zip?dl=1 -O coco.zip')
local('unzip coco.zip')
with lcd(dirname):
local("zip coco_input.zip -r *.jpg")
fname = '{}/coco_input.zip'.format(dirname)
with open('{}/coco_sample_metadata.json'.format(dirname)) as datafile:
data = json.load(datafile)
f = SimpleUploadedFile("coco_input.zip", file(fname).read(), content_type="application/zip")
v = handle_uploaded_file(f, 'mscoco_sample_500')
extract_frames(v.pk)
video = v
models.Annotation.objects.all().filter(video=video).delete()
for frame in models.Frame.objects.all().filter(video=video):
frame_id = str(int(frame.name.split('_')[-1].split('.')[0]))
annotation = models.Annotation()
annotation.video = v
annotation.frame = frame
annotation.full_frame = True
annotation.metadata_json = json.dumps(data[frame_id]['image'])
annotation.label = 'metadata'
annotation.save()
for frame in models.Frame.objects.all().filter(video=video):
frame_id = str(int(frame.name.split('_')[-1].split('.')[0]))
for a in data[frame_id][u'annotations']:
annotation = models.Annotation()
annotation.video = v
annotation.frame = frame
annotation.metadata_json = json.dumps(a)
annotation.full_frame = False
annotation.x = a['bbox'][0]
annotation.y = a['bbox'][1]
annotation.w = a['bbox'][2]
annotation.h = a['bbox'][3]
label, _ = models.VLabel.objects.get_or_create(video=video, label_name='coco_instance/{}/{}'.format(
a[u'category'][u'supercategory'], a[u'category'][u'name']))
annotation.label = label.label_name
annotation.label_parent = label
annotation.save()
for a in data[frame_id][u'keypoints']:
annotation = models.Annotation()
annotation.video = v
annotation.frame = frame
annotation.metadata_json = json.dumps(a)
annotation.x = a['bbox'][0]
annotation.y = a['bbox'][1]
annotation.w = a['bbox'][2]
annotation.h = a['bbox'][3]
label, _ = models.VLabel.objects.get_or_create(video=video, label_name='coco_keypoints/{}/{}'.format(
a[u'category'][u'supercategory'], a[u'category'][u'name']))
annotation.label = label.label_name
annotation.label_parent = label
annotation.save()
for caption in data[frame_id][u'captions']:
annotation = models.Annotation()
annotation.video = v
annotation.frame = frame
annotation.metadata_text = caption['caption']
annotation.full_frame = True
label, _ = models.VLabel.objects.get_or_create(video=video, label_name='coco_caption')
annotation.label = label.label_name
annotation.label_parent = label
annotation.save()
if not fast:
inception_index_by_id(v.pk)
perform_ssd_detection_by_id(v.pk)
perform_face_detection_indexing_by_id(v.pk)
inception_index_ssd_detection_by_id(v.pk)
export_video_by_id(v.pk)
v = handle_youtube_video("Zelda","https://www.youtube.com/watch?v=vHiTxNrbB4M")
extract_frames(v.pk)
if not fast:
inception_index_by_id(v.pk)
perform_ssd_detection_by_id(v.pk)
perform_face_detection_indexing_by_id(v.pk)
inception_index_ssd_detection_by_id(v.pk)
export_video_by_id(v.pk)
v = handle_youtube_video("Paris","https://www.youtube.com/watch?v=zEAqJmS6ajk")
extract_frames(v.pk)
if not fast:
inception_index_by_id(v.pk)
perform_ssd_detection_by_id(v.pk)
perform_face_detection_indexing_by_id(v.pk)
inception_index_ssd_detection_by_id(v.pk)
export_video_by_id(v.pk)
local('wget https://www.dropbox.com/s/g8dv5yeh9bmflec/lfw_funneled.zip?dl=1 -O lfw.zip')
f = SimpleUploadedFile("lfw.zip", file("lfw.zip").read(), content_type="application/zip")
v = handle_uploaded_file(f, 'LFW subset')
extract_frames(v.pk)
if not fast:
inception_index_by_id(v.pk)
perform_face_detection_indexing_by_id(v.pk)
export_video_by_id(v.pk)
@task
def benchmark():
"""
TODO :Just like Continuous integration, perform continuous benchmarking of the performance
of various algorithms.
:return:
"""
pass
@task
def make_requester_pays(bucket_name):
"""
Convert AWS S3 bucket into requester pays bucket
DOES NOT WORKS,
:param bucket_name:
:return:
"""
s3 = boto3.resource('s3')
bucket_request_payment = s3.BucketRequestPayment(bucket_name)
response = bucket_request_payment.put(RequestPaymentConfiguration={'Payer': 'Requester'})
bucket_policy = s3.BucketPolicy(bucket_name)
policy = {
"Id": "Policy1493037034955",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1493036947566",
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::{}".format(bucket_name),
"Principal": "*"
},
{
"Sid": "Stmt1493037029723",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::{}/*".format(bucket_name),
"Principal": {
"AWS": [
"*"
]
}
}
]}
response = bucket_policy.put(Policy=json.dumps(policy))