forked from stanfordnmbl/opencap-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1392 lines (1117 loc) · 55.6 KB
/
utils.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
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
import yaml
import json
import os
import socket
import requests
import urllib.request
import shutil
import utilsDataman
import pickle
import glob
import mimetypes
import subprocess
import zipfile
import time
import numpy as np
import pandas as pd
from scipy import signal
from utilsAuth import getToken
from utilsAPI import getAPIURL
API_URL = getAPIURL()
API_TOKEN = getToken()
#%% Rest of utils
def getDataDirectory(isDocker=False):
computername = socket.gethostname()
# Paths to OpenPose folder for local testing.
if computername == 'SUHLRICHHPLDESK':
dataDir = 'C:/Users/scott.uhlrich/MyDrive/mobilecap/'
elif computername == "LAPTOP-7EDI4Q8Q":
dataDir = 'C:\MyDriveSym/mobilecap/'
elif computername == 'DESKTOP-0UPR1OH':
dataDir = 'C:/Users/antoi/Documents/MyRepositories/mobilecap_data/'
elif computername == 'HPL1':
dataDir = 'C:/Users/opencap/Documents/MyRepositories/mobilecap_data/'
elif computername == 'DESKTOP-GUEOBL2':
dataDir = 'C:/Users/opencap/Documents/MyRepositories/mobilecap_data/'
elif computername == 'DESKTOP-L9OQ0MS':
dataDir = 'C:/Users/antoi/Documents/MyRepositories/mobilecap_data/'
elif computername == 'clarkadmin-MS-7996':
dataDir = '/home/clarkadmin/Documents/MyRepositories/mobilecap_data/'
elif computername == 'DESKTOP-NJMGEBG':
dataDir = 'C:/Users/opencap/Documents/MyRepositories/mobilecap_data/'
elif isDocker:
dataDir = os.getcwd()
else:
dataDir = os.getcwd()
return dataDir
def getOpenPoseDirectory(isDocker=False):
computername = os.environ.get('COMPUTERNAME', None)
# Paths to OpenPose folder for local testing.
if computername == "DESKTOP-0UPR1OH":
openPoseDirectory = "C:/Software/openpose-1.7.0-binaries-win64-gpu-python3.7-flir-3d_recommended/openpose"
elif computername == "HPL1":
openPoseDirectory = "C:/Users/opencap/Documents/MySoftware/openpose-1.7.0-binaries-win64-gpu-python3.7-flir-3d_recommended/openpose"
elif computername == "DESKTOP-GUEOBL2":
openPoseDirectory = "C:/Software/openpose-1.7.0-binaries-win64-gpu-python3.7-flir-3d_recommended/openpose"
elif computername == "DESKTOP-L9OQ0MS":
openPoseDirectory = "C:/Software/openpose-1.7.0-binaries-win64-gpu-python3.7-flir-3d_recommended/openpose"
elif isDocker:
openPoseDirectory = "docker"
elif computername == 'SUHLRICHHPLDESK':
openPoseDirectory = "C:/openpose/"
elif computername == "LAPTOP-7EDI4Q8Q":
openPoseDirectory = "C:/openpose/"
elif computername == "DESKTOP-NJMGEBG":
openPoseDirectory = "C:/openpose/"
else:
openPoseDirectory = "C:/openpose/"
return openPoseDirectory
def getMMposeDirectory(isDocker=False):
computername = socket.gethostname()
# Paths to OpenPose folder for local testing.
if computername == "clarkadmin-MS-7996":
mmposeDirectory = "/home/clarkadmin/Documents/MyRepositories/MoVi_analysis/model_ckpts"
else:
mmposeDirectory = ''
return mmposeDirectory
def loadCameraParameters(filename):
open_file = open(filename, "rb")
cameraParams = pickle.load(open_file)
open_file.close()
return cameraParams
def importMetadata(filePath):
myYamlFile = open(filePath)
parsedYamlFile = yaml.load(myYamlFile, Loader=yaml.FullLoader)
return parsedYamlFile
def download_file(url, file_name):
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
def getTrialJson(trial_id):
trialJson = requests.get(API_URL + "trials/{}/".format(trial_id),
headers = {"Authorization": "Token {}".format(API_TOKEN)}).json()
return trialJson
def getSessionJson(session_id):
sessionJson = requests.get(API_URL + "sessions/{}/".format(session_id),
headers = {"Authorization": "Token {}".format(API_TOKEN)}).json()
# sort trials by time recorded
def getCreatedAt(trial):
return trial['created_at']
sessionJson['trials'].sort(key=getCreatedAt)
return sessionJson
def getSubjectJson(subject_id):
subjectJson = requests.get(API_URL + "subjects/{}/".format(subject_id),
headers = {"Authorization": "Token {}".format(API_TOKEN)}).json()
return subjectJson
def getTrialName(trial_id):
trial = getTrialJson(trial_id)
trial_name = trial['name']
trial_name = trial_name.replace(' ', '')
return trial_name
def writeMediaToAPI(API_URL,media_path,trial_id,tag=None,deleteOldMedia=False):
if deleteOldMedia:
deleteResult(trial_id, tag=tag)
for filename in os.listdir(media_path):
thisMimeType = mimetypes.guess_type(filename)
if thisMimeType[0] is not None and not os.path.isdir(filename):
print(filename)
fileType = thisMimeType[0][0:thisMimeType[0].find('/')]
if fileType == 'image' or fileType == 'video' or fileType == 'application':
fullpath = "{}/{}".format(media_path, filename)
if fileType == 'image' and tag == "calibration-img":
cam = filename[filename.find('Cam'):filename.find('.')]
if "altSoln" in filename:
altSoln = '_altSoln'
else:
altSoln = ''
device_id = cam + altSoln
else:
device_id = None
postFileToTrial(fullpath,trial_id,tag,device_id)
return
def getTrialNameIdMapping(session_id):
trials = getSessionJson(session_id)['trials']
# dict of session name->id and date
trialDict = {}
for t in trials:
trialDict[t['name']] = {'id':t['id'],'date':t['created_at']}
return trialDict
def postCalibrationOptions(session_path,session_id,overwrite=False):
calibration_id = getCalibrationTrialID(session_id)
trial = getTrialJson(calibration_id)
if trial['meta'] is None or overwrite == True:
calibOptionsJsonPath = os.path.join(session_path,'Videos','calibOptionSelections.json')
f = open(calibOptionsJsonPath)
calibOptionsJson = json.load(f)
f.close()
data = {
"meta":json.dumps({'calibration':calibOptionsJson})
}
trial_url = "{}{}{}/".format(API_URL, "trials/", calibration_id)
r= requests.patch(trial_url, data=data,
headers = {"Authorization": "Token {}".format(API_TOKEN)})
if r.status_code == 200:
print('Wrote calibration selections to metadata.')
def downloadVideosFromServer(session_id,trial_id, isDocker=True,
isCalibration=False, isStaticPose=False,
trial_name=None, session_name=None,
session_path=None, benchmark=False):
if session_name is None:
session_name = session_id
data_dir = getDataDirectory(isDocker)
if session_path is None:
session_path = os.path.join(data_dir,'Data', session_name)
if not os.path.exists(session_path):
os.makedirs(session_path, exist_ok=True)
trial = getTrialJson(trial_id)
if trial_name is None:
trial_name = trial['name']
trial_name = trial_name.replace(' ', '')
print("\nProcessing {}".format(trial_name))
# The videos are not always organized in the same order. Here, we save
# the order during the first trial processed in the session such that we
# can use the same order for the other trials.
if not benchmark:
if not os.path.exists(os.path.join(session_path, "Videos", 'mappingCamDevice.pickle')):
mappingCamDevice = {}
for k, video in enumerate(trial["videos"]):
os.makedirs(os.path.join(session_path, "Videos", "Cam{}".format(k), "InputMedia", trial_name), exist_ok=True)
video_path = os.path.join(session_path, "Videos", "Cam{}".format(k), "InputMedia", trial_name, trial_id + ".mov")
download_file(video["video"], video_path)
mappingCamDevice[video["device_id"].replace('-', '').upper()] = k
with open(os.path.join(session_path, "Videos", 'mappingCamDevice.pickle'), 'wb') as handle:
pickle.dump(mappingCamDevice, handle)
else:
with open(os.path.join(session_path, "Videos", 'mappingCamDevice.pickle'), 'rb') as handle:
mappingCamDevice = pickle.load(handle)
for video in trial["videos"]:
k = mappingCamDevice[video["device_id"].replace('-', '').upper()]
videoDir = os.path.join(session_path, "Videos", "Cam{}".format(k), "InputMedia", trial_name)
os.makedirs(videoDir, exist_ok=True)
video_path = os.path.join(videoDir, trial_id + ".mov")
if not os.path.exists(video_path):
if video['video'] :
download_file(video["video"], video_path)
# Import and save metadata
sessionYamlPath = os.path.join(session_path, "sessionMetadata.yaml")
if not os.path.exists(sessionYamlPath) or isStaticPose or isCalibration:
if isCalibration: # subject parameters won't be entered yet
session_desc = getMetadataFromServer(session_id,justCheckerParams = isCalibration)
else: # subject parameters will be entered when capturing static pose
session_desc = getMetadataFromServer(session_id)
# Load iPhone models.
phoneModel= []
for i,video in enumerate(trial["videos"]):
phoneModel.append(video['parameters']['model'])
session_desc['iphoneModel'] = {'Cam' + str(i) : phoneModel[i] for i in range(len(phoneModel))}
# Save metadata.
with open(sessionYamlPath, 'w') as file:
yaml.dump(session_desc, file)
return trial_name
def deleteCalibrationFiles(session_path):
calImagePath = os.path.join(session_path,'CalibrationImages')
if os.path.exists(calImagePath):
shutil.rmtree(calImagePath)
# Delete camera directories
camDirs = glob.glob(os.path.join(session_path,'Videos','Cam*'))
# Find extrinsic Filename
extrinsicFileFound = False
if len(camDirs)>1 and os.path.exists(os.path.join(camDirs[0], 'InputMedia')):
inputDir = os.path.join(camDirs[0], 'InputMedia')
dirContents = os.listdir(inputDir)
trialNames = [tName for tName in dirContents if os.path.isdir(os.path.join(inputDir,tName))]
for tName in trialNames:
if os.path.exists(os.path.join(inputDir,tName,'extrinsicImage0.png')):
extrinsicTrialName = tName
extrinsicFileFound = True
for camDir in camDirs:
extPath = os.path.join(camDir,'cameraIntrinsicsExtrinsics.pickle')
if os.path.exists(extPath):
os.remove(extPath)
#Find extrinsic Filename
if extrinsicFileFound:
extFolder = os.path.join(camDir,'InputMedia',extrinsicTrialName)
if os.path.isdir(extFolder):
shutil.rmtree(extFolder)
def deleteStaticFiles(session_path,staticTrialName='neutral'):
vidDir = os.path.join(session_path,'Videos')
camDirs = glob.glob(os.path.join(vidDir,'Cam*'))
markerDirs = glob.glob(os.path.join(session_path,'MarkerData'))
openSimDir = os.path.join(session_path,'OpenSimData')
# This is a hack, but os.walk doesn't work on attached server drives
for camDir in camDirs:
mediaDirs = glob.glob(os.path.join(camDir,'*'))
for medDir in mediaDirs:
try:
shutil.rmtree(os.path.join(camDir,medDir,staticTrialName))
_,camName = os.path.split()
print('deleting ' + camName + '/' + medDir + '/' + staticTrialName)
except:
pass
for mkrDir in markerDirs:
mkrFiles = glob.glob(os.path.join(mkrDir,'*'))
for mkrFile in mkrFiles:
if staticTrialName in mkrFile:
os.remove(mkrFile)
_,fName = os.split(mkrFile)
print('deleting '+ fName)
if os.path.exists(openSimDir):
shutil.rmtree(openSimDir) # Static will be the first opensim data saved, so this is safe
print('deleting openSimDir')
# # this works locally, but not on server drives. Saving in case we change storage
# for root, dirList, fileList in os.walk(session_path + './'):
# for thisFile in fileList:
# print(thisFile)
# if (bool(regex.match(staticTrialName + '.trc', thisFile)) or
# bool(regex.match(staticTrialName + '.mot', thisFile)) or
# bool(regex.match(staticTrialName + '.sto', thisFile))):
# filePath = os.path.join(root,thisFile)
# os.remove(filePath)
# print('removing ' + thisFile)
# for thisDir in dirList:
# print(thisDir)
# if thisDir == staticTrialName:
# dirPath = os.path.join(root,thisDir)
# shutil.rmtree(dirPath)
# print('removing ' + thisDir)
def switchCalibrationForCamera(cam,trial_id,session_path):
trialName = getTrialName(trial_id)
camPath = os.path.join(session_path,'Videos',cam)
trialPath = os.path.join(camPath,'InputMedia',trialName)
# change Picture
src = os.path.join(trialPath,'extrinsicCalib_soln1.jpg')
dest = os.path.join(session_path,'CalibrationImages','extrinsicCalib' + cam + '.jpg')
if os.path.exists(dest):
os.remove(dest)
shutil.copyfile(src,dest)
# change calibration parameters
src = os.path.join(trialPath,'cameraIntrinsicsExtrinsics_soln1.pickle')
dest = os.path.join(camPath,'cameraIntrinsicsExtrinsics.pickle')
if os.path.exists(dest):
os.remove(dest)
shutil.copyfile(src,dest)
def getMetadataFromServer(session_id,justCheckerParams=False):
defaultMetadataPath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'defaultSessionMetadata.yaml')
session_desc = importMetadata(defaultMetadataPath)
# Get session-specific metadata from api.
session = getSessionJson(session_id)
if session['meta'] is not None:
if not justCheckerParams:
# Backward compatibility
if 'subject' in session['meta']:
session_desc["subjectID"] = session['meta']['subject']['id']
session_desc["mass_kg"] = float(session['meta']['subject']['mass'])
session_desc["height_m"] = float(session['meta']['subject']['height'])
# Before implementing the subject feature, the posemodel was stored
# in session['meta']['subject']. After implementing the subject
# feature, the posemodel is stored in session['meta']['settings']
# and there is no session['meta']['subject'].
try:
session_desc["posemodel"] = session['meta']['subject']['posemodel']
except:
session_desc["posemodel"] = 'openpose'
# This might happen if openSimModel was changed post data collection.
if 'settings' in session['meta']:
try:
session_desc["openSimModel"] = session['meta']['settings']['openSimModel']
except:
session_desc["openSimModel"] = 'LaiUhlrich2022'
else:
subject_info = getSubjectJson(session['subject'])
session_desc["subjectID"] = subject_info['name']
session_desc["mass_kg"] = subject_info['weight']
session_desc["height_m"] = subject_info['height']
try:
session_desc["posemodel"] = session['meta']['settings']['posemodel']
except:
session_desc["posemodel"] = 'openpose'
try:
session_desc["openSimModel"] = session['meta']['settings']['openSimModel']
except:
session_desc["openSimModel"] = 'LaiUhlrich2022'
if 'sessionWithCalibration' in session['meta'] and 'checkerboard' not in session['meta']:
newSessionId = session['meta']['sessionWithCalibration']['id']
session = getSessionJson(newSessionId)
session_desc['checkerBoard']["squareSideLength_mm"] = float(session['meta']['checkerboard']['square_size'])
session_desc['checkerBoard']["black2BlackCornersWidth_n"] = int(session['meta']['checkerboard']['cols'])
session_desc['checkerBoard']["black2BlackCornersHeight_n"] = int(session['meta']['checkerboard']['rows'])
session_desc['checkerBoard']["placement"] = session['meta']['checkerboard']['placement']
else:
print('Couldn''t find session metadata in API, using default metadata. May be issues.')
return session_desc
def deleteResult(trial_id, tag=None,resultNum=None):
# Delete specific result number, or all results with a specific tag, or all results if tag==None
if resultNum != None:
resultNums = [resultNum]
elif tag != None:
trial = getTrialJson(trial_id)
resultNums = [r['id'] for r in trial['results'] if r['tag']==tag]
elif tag == None:
trial = getTrialJson(trial_id)
resultNums = [r['id'] for r in trial['results']]
for rNum in resultNums:
requests.delete(API_URL + "results/{}/".format(rNum),
headers = {"Authorization": "Token {}".format(API_TOKEN)})
def deleteAllResults(session_id):
session = getSessionJson(session_id)
for trial in session['trials']:
deleteResult(trial['id'])
def writeCalibrationOptionsToAPI(session_path,session_id,calibration_id=None,trialName = None):
if calibration_id == None:
calibration_id = getCalibrationTrialID(session_id)
if trialName == None:
trial = getTrialJson(calibration_id)
trialName = trial['name']
deleteResult(calibration_id, tag='camera_mapping')
videoDir = os.path.join(session_path,'Videos')
camDirs = glob.glob(os.path.join(videoDir,'Cam*'))
mapPath = os.path.join(videoDir, 'mappingCamDevice.pickle')
postFileToTrial(mapPath,calibration_id,'camera_mapping','all')
tag = 'calibration_parameters_options'
deleteResult(calibration_id, tag=tag)
for camDir in camDirs:
_,camName = os.path.split(camDir)
calibDir = os.path.join(camDir,'InputMedia',trialName)
# Post both solutions
for i in range(2):
filePath = os.path.join(calibDir,'cameraIntrinsicsExtrinsics_soln{}.pickle'.format(i))
device_id = camName+'_soln{}'.format(i)
postFileToTrial(filePath,calibration_id,tag,device_id)
def getCalibrationTrialID(session_id):
session = getSessionJson(session_id)
calib_ids = [t['id'] for t in session['trials'] if t['name'] == 'calibration']
if len(calib_ids)>0:
calibID = calib_ids[-1]
elif session['meta']['sessionWithCalibration']:
calibID = getCalibrationTrialID(session['meta']['sessionWithCalibration']['id'])
else:
raise Exception('No calibration trial in session.')
return calibID
def getNeutralTrialID(session_id):
session = getSessionJson(session_id)
neutral_ids = [t['id'] for t in session['trials'] if t['name'] == 'neutral']
if len(neutral_ids)>0:
neutralID = neutral_ids[-1]
elif session['meta']['neutral_trial']:
neutralID = session['meta']['neutral_trial']['id']
else:
raise Exception('No neutral trial in session.')
return neutralID
def postCalibration(session_id,session_path,calibTrialID=None):
videoDir = os.path.join(session_path,'Videos')
videoFolders = glob.glob(os.path.join(videoDir,'Cam*'))
if calibTrialID == None:
calibTrialID = getCalibrationTrialID(session_id)
# remove 'calibration_parameters' in case they exist already.
tag = 'calibration_parameters'
deleteResult(calibTrialID, tag=tag)
for vf in videoFolders:
_, camName = os.path.split(vf)
fPath = os.path.join(vf,'cameraIntrinsicsExtrinsics.pickle')
deviceID = camName
postFileToTrial(fPath,calibTrialID,'calibration_parameters',deviceID)
return
def getCalibration(session_id,session_path,trial_type='dynamic',getCalibrationOptions=False):
# look for calibration pickles on Django. If they are not there, then see if
# we need to do any switch calibration, then post the good calibration to django.
calibration_id = getCalibrationTrialID(session_id)
# Check if calibration has been posted to session
trial = getTrialJson(calibration_id)
calibResultTags = [res['tag'] for res in trial['results']]
# download the mapping
videoFolder = os.path.join(session_path,'Videos')
os.makedirs(videoFolder, exist_ok=True)
mapURL = trial['results'][calibResultTags.index('camera_mapping')]['media']
mapLocalPath = os.path.join(videoFolder,'mappingCamDevice.pickle')
download_file(mapURL,mapLocalPath)
# download calibration parameters and switch if necessary.
calibrationOptions = downloadAndSwitchCalibrationFromDjango(session_id,session_path,
calibTrialID=calibration_id,
getCalibrationOptions=getCalibrationOptions)
# Post calibration if neutral trial. The posted parameters are no longer
# used, but it is handy to know which ones were selected from both options.
if trial_type == 'static':
postCalibration(session_id,session_path,calibTrialID=calibration_id)
if getCalibrationOptions:
return calibrationOptions
def downloadAndSwitchCalibrationFromDjango(session_id,session_path,calibTrialID = None,
getCalibrationOptions=False):
if calibTrialID == None:
calibTrialID = getCalibrationTrialID(session_id)
trial = getTrialJson(calibTrialID)
calibURLs = {t['device_id']:t['media'] for t in trial['results'] if t['tag'] == 'calibration_parameters_options'}
if 'meta' in trial.keys() and trial['meta'] is not None and 'calibration' in trial['meta'].keys():
calibDict = trial['meta']['calibration']
else:
print('No metadata for camera switching. Using first solution.')
calibDict = {'Cam'+str(i):0 for i in range(len(trial['videos']))}
for cam,calibNum in calibDict.items():
camDir = os.path.join(session_path,'Videos',cam)
os.makedirs(camDir,exist_ok=True)
file_name = os.path.join(camDir,'cameraIntrinsicsExtrinsics.pickle')
if calibNum == 0:
download_file(calibURLs[cam+'_soln0'], file_name)
print('Downloading calibration for ' + cam)
elif calibNum == 1:
download_file(calibURLs[cam+'_soln1'], file_name)
print('Downloading alternate calibration camera for ' + cam)
# If static trial and we are automatically selecting a calibration
if getCalibrationOptions:
tempPath = os.path.join(session_path,'tempCalib.pickle')
calibrationOptions = {}
for cam in calibDict.keys():
calibrationOptions[cam] = []
download_file(calibURLs[cam+'_soln0'], tempPath)
calibrationOptions[cam].append(loadCameraParameters(tempPath))
os.remove(tempPath)
download_file(calibURLs[cam+'_soln1'], tempPath)
calibrationOptions[cam].append(loadCameraParameters(tempPath))
os.remove(tempPath)
return calibrationOptions
else:
return None
def changeSessionMetadata(session_ids,newMetaDict):
for session_id in session_ids:
session_url = "{}{}{}/".format(API_URL, "sessions/", session_id)
# get metadata
session = getSessionJson(session_id)
existingMeta = session['meta']
# change metadata
# Hack: wrong mapping between metadata and yaml
# mass in metadata is mass_kg in yaml
# height in metadata is height_m in yaml
mapping_metadata = {'mass': 'mass_kg',
'height': 'height_m'}
addedKey= {}
for key in existingMeta.keys():
if key in mapping_metadata:
key_t = mapping_metadata[key]
else:
key_t = key
if key_t in newMetaDict.keys():
existingMeta[key] = newMetaDict[key_t]
addedKey[key_t] = newMetaDict[key_t]
if type(existingMeta[key]) is dict:
for key2 in existingMeta[key].keys():
if key2 in mapping_metadata:
key_t = mapping_metadata[key2]
else:
key_t = key2
if key_t in newMetaDict.keys():
existingMeta[key][key2] = newMetaDict[key_t]
addedKey[key_t] = newMetaDict[key_t]
# add metadata if not existing (eg, specifying OpenSim model)
# only entries in settings_fields below are supported.
for newMeta in newMetaDict:
if not newMeta in addedKey:
print("Could not find {} in existing metadata, trying to add it.".format(newMeta))
settings_fields = ['framerate', 'posemodel', 'openSimModel']
if newMeta in settings_fields:
existingMeta['settings'][newMeta] = newMetaDict[newMeta]
addedKey[newMeta] = newMetaDict[newMeta]
print("Added {} to settings in metadata".format(newMetaDict[newMeta]))
else:
print("Could not add {} to the metadata; not recognized".format(newMetaDict[newMeta]))
data = {"meta":json.dumps(existingMeta)}
r= requests.patch(session_url, data=data,
headers = {"Authorization": "Token {}".format(API_TOKEN)})
if r.status_code !=200:
print('Changing metadata failed.')
# Also change this in the metadata yaml in neutral trial
trial_id = getNeutralTrialID(session_id)
trial = getTrialJson(trial_id)
resultTags = [res['tag'] for res in trial['results']]
metaPath = os.path.join(os.getcwd(),'sessionMetadata.yaml')
yamlURL = trial['results'][resultTags.index('session_metadata')]['media']
download_file(yamlURL,metaPath)
metaYaml = importMetadata(metaPath)
addedKey= {}
for key in metaYaml.keys():
if key in newMetaDict.keys():
metaYaml[key] = newMetaDict[key]
addedKey[key] = newMetaDict[key]
if type(metaYaml[key]) is dict:
for key2 in metaYaml[key].keys():
if key2 in newMetaDict.keys():
metaYaml[key][key2] = newMetaDict[key2]
addedKey[key2] = newMetaDict[key2]
for newMeta in newMetaDict:
if not newMeta in addedKey:
print("Could not find {} in existing yaml, adding it.".format(newMeta))
metaYaml[newMeta] = newMetaDict[newMeta]
with open(metaPath, 'w') as file:
yaml.dump(metaYaml, file)
deleteResult(trial_id, tag='session_metadata')
postFileToTrial(metaPath,trial_id,tag='session_metadata',device_id='all')
os.remove(metaPath)
def makeSessionPublic(session_id,publicStatus=True):
session_url = "{}{}{}/".format(API_URL, "sessions/", session_id)
data = {
"public":publicStatus
}
r= requests.patch(session_url, data=data,
headers = {"Authorization": "Token {}".format(API_TOKEN)})
if r.status_code == 200:
print('Successfully made ' + session_id + ' public.')
else:
print('server resp was ' + str(r.status_code))
return
def postMotionData(trial_id,session_path,trial_name=None,isNeutral=False):
if trial_name == None:
trial_name = getTrialJson(trial_id)['id']
# post pose pickles
# If we parallelize this, this will be redundant, and we will want to delete this posting of pickles
deleteResult(trial_id, tag='pose_pickle')
camDirs = glob.glob(os.path.join(session_path,'Videos','Cam*'))
for camDir in camDirs:
outputPklFolder = glob.glob(os.path.join(camDir,'OutputPkl*'))[0]
pklPath = glob.glob(os.path.join(outputPklFolder,trial_name,'*.pkl'))[0]
_,camName = os.path.split(camDir)
postFileToTrial(pklPath,trial_id,tag='pose_pickle',device_id=camName)
# post marker data
deleteResult(trial_id, tag='marker_data')
markerDir = os.path.join(session_path,'MarkerData','PostAugmentation')
markerPath = os.path.join(markerDir,trial_id + '.trc')
postFileToTrial(markerPath,trial_id,tag='marker_data',device_id='all')
if isNeutral:
# post model
deleteResult(trial_id, tag='opensim_model')
modelFolder = os.path.join(session_path,'OpenSimData','Model')
modelPath = glob.glob(modelFolder + '/*_scaled.osim')[0]
postFileToTrial(modelPath,trial_id,tag='opensim_model',device_id='all')
# post metadata
deleteResult(trial_id, tag='session_metadata')
metadataPath = os.path.join(session_path,'sessionMetadata.yaml')
postFileToTrial(metadataPath,trial_id,tag='session_metadata',device_id='all')
else:
# post ik data
deleteResult(trial_id, tag='ik_results')
ikPath = os.path.join(session_path,'OpenSimData','Kinematics',trial_id + '.mot')
postFileToTrial(ikPath,trial_id,tag='ik_results',device_id='all')
# post settings
deleteResult(trial_id, tag='main_settings')
mainSettingsPath = os.path.join(markerDir,'Settings_{}.yaml'.format(trial_id))
postFileToTrial(mainSettingsPath,trial_id,tag='main_settings',device_id='all')
return
def getMotionData(trial_id,session_path,simplePath=False):
trial = getTrialJson(trial_id)
trial_name = trial['name']
resultTags = [res['tag'] for res in trial['results']]
# get marker data
if 'ik_results' in resultTags:
markerFolder = os.path.join(session_path,'MarkerData','PostAugmentation',trial_name)
if simplePath:
markerFolder = os.path.join(session_path,'MarkerData')
markerPath = os.path.join(markerFolder,trial_name + '.trc')
os.makedirs(markerFolder, exist_ok=True)
markerURL = trial['results'][resultTags.index('marker_data')]['media']
download_file(markerURL,markerPath)
# get IK data
if 'ik_results' in resultTags:
ikFolder = os.path.join(session_path,'OpenSimData','Kinematics')
if simplePath:
ikFolder = os.path.join(session_path,'OpenSimData','Kinematics')
ikPath = os.path.join(ikFolder,trial_name + '.mot')
os.makedirs(ikFolder, exist_ok=True)
ikURL = trial['results'][resultTags.index('ik_results')]['media']
download_file(ikURL,ikPath)
# TODO will want to get pose pickles eventually, once those are processed elsewhere
return
def getModelAndMetadata(session_id,session_path,simplePath=False):
neutral_id = getNeutralTrialID(session_id)
trial = getTrialJson(neutral_id)
resultTags = [res['tag'] for res in trial['results']]
# get metadata
metadataPath = os.path.join(session_path,'sessionMetadata.yaml')
if not os.path.exists(metadataPath) :
metadataURL = trial['results'][resultTags.index('session_metadata')]['media']
download_file(metadataURL, metadataPath)
# get model if does not exist
modelURL = trial['results'][resultTags.index('opensim_model')]['media']
modelName = modelURL[modelURL.rfind('-')+1:modelURL.rfind('?')]
modelFolder = os.path.join(session_path,'OpenSimData','Model')
if simplePath:
modelFolder = os.path.join(session_path,'OpenSimData','Model')
modelPath = os.path.join(modelFolder,modelName)
if not os.path.exists(modelPath):
os.makedirs(modelFolder, exist_ok=True)
download_file(modelURL, modelPath)
return
def postFileToTrial(filePath,trial_id,tag,device_id):
# get S3 link
data = {'fileName':os.path.split(filePath)[1]}
r = requests.get(API_URL + "sessions/null/get_presigned_url/",data=data).json()
# upload to S3
files = {'file': open(filePath, 'rb')}
requests.post(r['url'], data=r['fields'],files=files)
files["file"].close()
# post link to and data to results
data = {
"trial": trial_id,
"tag": tag,
"device_id" : device_id,
"media_url" : r['fields']['key']
}
rResult = requests.post(API_URL + "results/", data=data,
headers = {"Authorization": "Token {}".format(API_TOKEN)})
if rResult.status_code != 201:
print('server response was + ' + str(r.status_code))
else:
print('Result posted to S3.')
return
def getSyncdVideos(trial_id,session_path):
trial = getTrialJson(trial_id)
trial_name = trial['name']
if trial['results']:
for result in trial['results']:
if result['tag'] == 'video-sync':
url = result['media']
cam,suff = os.path.splitext(url[url.rfind('_')+1:])
lastIdx = suff.find('?')
if lastIdx >0:
suff = suff[:lastIdx]
syncVideoPath = os.path.join(session_path,'Videos',cam,'InputMedia',trial_name,trial_name + '_sync' + suff)
download_file(url,syncVideoPath)
def downloadAndZipSession(session_id,deleteFolderWhenZipped=True,isDocker=True,
writeToDjango=False,justDownload=False,data_dir=None,
useSubjectNameFolder=False):
session = getSessionJson(session_id)
if data_dir is None:
data_dir = os.path.join(getDataDirectory(isDocker=isDocker),'Data')
if useSubjectNameFolder:
folderName = session['name']
else:
folderName = session_id
session_path = os.path.join(data_dir,folderName)
calib_id = getCalibrationTrialID(session_id)
neutral_id = getNeutralTrialID(session_id)
dynamic_ids = [t['id'] for t in session['trials'] if (t['name'] != 'calibration' and t['name'] !='neutral')]
# Calibration
downloadVideosFromServer(session_id,calib_id,isDocker=isDocker,
isCalibration=True,isStaticPose=False)
getCalibration(session_id,session_path)
# Neutral
getModelAndMetadata(session_id,session_path)
getMotionData(neutral_id,session_path)
downloadVideosFromServer(session_id,neutral_id,isDocker=isDocker,
isCalibration=False,isStaticPose=True,session_path=session_path)
getSyncdVideos(neutral_id,session_path)
# Dynamic
for dynamic_id in dynamic_ids:
getMotionData(dynamic_id,session_path)
downloadVideosFromServer(session_id,dynamic_id,isDocker=isDocker,
isCalibration=False,isStaticPose=False,session_path=session_path)
getSyncdVideos(dynamic_id,session_path)
if not justDownload:
# Zip
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
session_zip = '{}.zip'.format(session_path)
if os.path.isfile(session_zip):
os.remove(session_zip)
zipf = zipfile.ZipFile(session_zip, 'w', zipfile.ZIP_DEFLATED)
zipdir(session_path, zipf)
zipf.close()
# write zip as a result to last trial for now
if writeToDjango:
postFileToTrial(session_zip,dynamic_ids[-1],tag='session_zip',device_id='all')
if deleteFolderWhenZipped:
if os.path.exists(session_path):
shutil.rmtree(session_path)
if os.path.exists(session_zip):
os.remove(session_zip)
return
#test session
# downloadAndZipSession('a24a895a-aa62-4403-bd9e-cf637ac02eb6',deleteFolderWhenZipped=False,isDocker=False)
def numpy2TRC(f, data, headers, fc=50.0, t_start=0.0, units="m"):
header_mapping = {}
for count, header in enumerate(headers):
header_mapping[count+1] = header
# Line 1.
f.write('PathFileType 4\t(X/Y/Z) %s\n' % os.getcwd())
# Line 2.
f.write('DataRate\tCameraRate\tNumFrames\tNumMarkers\t'
'Units\tOrigDataRate\tOrigDataStartFrame\tOrigNumFrames\n')
num_frames=data.shape[0]
num_markers=len(header_mapping.keys())
# Line 3.
f.write('%.1f\t%.1f\t%i\t%i\t%s\t%.1f\t%i\t%i\n' % (
fc, fc, num_frames,
num_markers, units, fc,
1, num_frames))
# Line 4.
f.write("Frame#\tTime\t")
for key in sorted(header_mapping.keys()):
f.write("%s\t\t\t" % format(header_mapping[key]))
# Line 5.
f.write("\n\t\t")
for imark in np.arange(num_markers) + 1:
f.write('X%i\tY%s\tZ%s\t' % (imark, imark, imark))
f.write('\n')
# Line 6.
f.write('\n')
for frame in range(data.shape[0]):
f.write("{}\t{:.8f}\t".format(frame+1,(frame)/fc+t_start)) # opensim frame labeling is 1 indexed
for key in sorted(header_mapping.keys()):
f.write("{:.5f}\t{:.5f}\t{:.5f}\t".format(data[frame,0+(key-1)*3], data[frame,1+(key-1)*3], data[frame,2+(key-1)*3]))
f.write("\n")
def numpy2storage(labels, data, storage_file):
assert data.shape[1] == len(labels), "# labels doesn't match columns"
assert labels[0] == "time"
f = open(storage_file, 'w')
f.write('name %s\n' %storage_file)
f.write('datacolumns %d\n' %data.shape[1])
f.write('datarows %d\n' %data.shape[0])
f.write('range %f %f\n' %(np.min(data[:, 0]), np.max(data[:, 0])))
f.write('endheader \n')
for i in range(len(labels)):
f.write('%s\t' %labels[i])
f.write('\n')
for i in range(data.shape[0]):
for j in range(data.shape[1]):
f.write('%20.8f\t' %data[i, j])
f.write('\n')
f.close()
def lowpassFilter(inputData, filtFreq, order=4):
# Input is an array of nSteps x (nMeasures +1) because time is the first column
time = inputData[:,0]
fs=1/np.mean(np.diff(time))
wn = filtFreq/(fs/2)
sos = signal.butter(order/2,wn,btype='low',output='sos')
inputDataFilt = signal.sosfiltfilt(sos,inputData[:,1:],axis=0)
data = np.concatenate((np.expand_dims(time,1), inputDataFilt), axis=1)
return data
def TRC2numpy(pathFile, markers,rotation=None):
# rotation is a dict, eg. {'y':90} with axis, angle for rotation
trc_file = utilsDataman.TRCFile(pathFile)
time = trc_file.time
num_frames = time.shape[0]
data = np.zeros((num_frames, len(markers)*3))
if rotation != None:
for axis,angle in rotation.items():
trc_file.rotate(axis,angle)
for count, marker in enumerate(markers):
data[:,3*count:3*count+3] = trc_file.marker(marker)
this_dat = np.empty((num_frames, 1))
this_dat[:, 0] = time
data_out = np.concatenate((this_dat, data), axis=1)
return data_out