-
Notifications
You must be signed in to change notification settings - Fork 12
/
core.py
1984 lines (1691 loc) · 96.8 KB
/
core.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
"""
VCD (Video Content Description) library v5.0.0
Project website: http://vcd.vicomtech.org
Copyright (C) 2021, Vicomtech (http://www.vicomtech.es/),
(Spain) all rights reserved.
VCD is a Python library to create and manage VCD content version 5.0.0.
VCD is distributed under MIT License. See LICENSE.
"""
import copy
import json
import warnings
from jsonschema import validate
from enum import Enum
import re
import uuid
import vcd.types as types
import vcd.utils as utils
import vcd.schema as schema
class TagType(Enum):
"""
Tag's first-level categories as defined in the OpenLABEL standard
"""
administrative = 1
odd = 2
behaviour = 3
custom = 4
class ResourceUID:
"""
This is a class to add additional UIDs to an element, according to its representation
in another resource.
E.g. A Lane or Road object labeled in VCD can correspond to a Lane or Road element in an
OpenDrive file.
Then the OpenDrive file path is added with
res_opendrive_uidopenlabel.add_resource("../resources/xodr/multi_intersections.xodr")
And any object added can add the elment UID at the resource using this ResourceUID class
openlabel.add_object("road1", "road", res_uid=ResourceUID(res_opendrive_uid, 217))
"""
def __init__(self, resource_uid, id_at_resource):
self.resource_uid = UID(resource_uid) # this is the UID of the resource file
self.id_at_resource = UID(id_at_resource) # this is the UID of the element in the resource
def as_dict(self):
return {self.resource_uid.as_str(): self.id_at_resource.as_str()}
class ElementType(Enum):
"""
Elements of VCD (Object, Action, Event, Context, Relation, Tag)
"""
object = 1
action = 2
event = 3
context = 4
relation = 5
tag = 6
class StreamType(Enum):
"""
Type of stream (sensor).
"""
camera = 1
lidar = 2
radar = 3
gps_imu = 4
other = 5
class RDF(Enum):
"""
Type of RDF agent (subject or object)
"""
subject = 1
object = 2
class FrameIntervals:
"""
FrameIntervals class aims to simplify management of frame intervals
"""
def __init__(self, frame_value=None, fuse=False):
self.fis_dict = []
self.fis_num = []
if frame_value is not None:
if isinstance(frame_value, int):
self.fis_dict = [{'frame_start': frame_value, 'frame_end': frame_value}]
self.fis_num = [(frame_value, frame_value)]
elif isinstance(frame_value, list):
if len(frame_value) == 0:
return
if all(isinstance(x, tuple) for x in frame_value):
# Then, frame_value is an array of tuples
self.fis_dict = utils.as_frame_intervals_array_dict(frame_value)
if fuse:
self.fis_dict = utils.fuse_frame_intervals(self.fis_dict)
self.fis_num = utils.as_frame_intervals_array_tuples(self.fis_dict)
elif all(isinstance(x, list) for x in frame_value):
# This is possibly a list of list, e.g. [[0, 10], [12, 15]], instead of the above case list of tupl
self.fis_dict = utils.as_frame_intervals_array_dict(frame_value)
if fuse:
self.fis_dict = utils.fuse_frame_intervals(self.fis_dict)
self.fis_num = utils.as_frame_intervals_array_tuples(self.fis_dict)
elif all(isinstance(x, dict) for x in frame_value):
# User provided a list of dict
self.fis_dict = frame_value
if fuse:
self.fis_dict = utils.fuse_frame_intervals(self.fis_dict)
self.fis_num = utils.as_frame_intervals_array_tuples(self.fis_dict)
elif isinstance(frame_value, tuple):
# Then, frame_value is a tuple (one single frame interval)
self.fis_num = [frame_value]
self.fis_dict = utils.as_frame_intervals_array_dict(self.fis_num)
elif isinstance(frame_value, dict):
# User provided a single dict
self.fis_dict = [frame_value]
self.fis_num = utils.as_frame_intervals_array_tuples(self.fis_dict)
else:
warnings.warn("ERROR: Unsupported FrameInterval format.")
def empty(self):
#if len(self.fis_dict) == 0 or len(self.fis_num) == 0:
return not self.fis_num
def get_dict(self):
return self.fis_dict
def get(self):
return self.fis_num
def get_length(self):
length = 0
for fi in self.fis_num:
length += fi[1] + 1 - fi[0]
return length
def rm_frame(self, frame_num):
self.fis_dict = utils.rm_frame_from_frame_intervals(self.fis_dict, frame_num)
self.fis_num = utils.as_frame_intervals_array_tuples(self.fis_dict)
def union(self, frame_intervals):
# Several quick cases
if not self.fis_dict:
return frame_intervals
elif frame_intervals.get() == self.get():
return frame_intervals
else:
# Generic case
fis_union = utils.fuse_frame_intervals(self.fis_dict + frame_intervals.get_dict())
return FrameIntervals(fis_union)
def intersection(self, frame_intervals):
fis_int = utils.intersection_between_frame_interval_arrays(self.fis_num, frame_intervals.get())
return FrameIntervals(fis_int)
def equals(self, frame_intervals):
fis_int = self.intersection(frame_intervals)
fis_union = self.union(frame_intervals)
if fis_int.get_length() == fis_union.get_length():
return True
else:
return False
def contains(self, frame_intervals):
fis_int = self.intersection(frame_intervals)
if fis_int.get_length() == frame_intervals.get_length():
return True
else:
return False
def is_contained_by(self, frame_intervals):
fis_int = self.intersection(frame_intervals)
if fis_int.get_length() == self.get_length():
return True
else:
return False
def get_outer(self):
return utils.get_outer_frame_interval(self.fis_dict)
def has_frame(self, frame_num):
return utils.is_inside_frame_intervals(frame_num, self.fis_num)
def to_str(self):
text = "["
for fi in self.fis_num:
text += "(" + str(fi[0]) + "," + str(fi[1]) + ")"
text += "]"
return text
class UID:
"""
This is a helper class that simplifies management of UIDs.
Public functions permits the user to introduce either int or string values as UIDs
Internal functions create the UID objects to ensure the proper format is used where needed
"""
def __init__(self, val=None):
if val is None:
# Void uid
self.__set("", -1, False)
else:
if isinstance(val, int):
self.__set(str(val), val, False)
elif isinstance(val, str):
if val == '':
self.__set("", -1, False)
else:
if val.strip('-').isnumeric(): # this holds true for "-3" and "3"
self.__set(val, int(val), False)
elif bool(re.match(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
val)):
self.__set(val, -1, True)
else:
warnings.warn("ERROR: Unsupported UID string type.")
self.__set("", -1, False)
else:
warnings.warn("ERROR: Unsupported UID type.")
self.__set("", -1, False)
def __set(self, uid_str=None, uid_int=None, is_uuid=False):
self.uid_str = uid_str
self.uid_int = uid_int
self.uuid = is_uuid
def is_uuid(self):
return self.uuid
def as_str(self):
return self.uid_str
def as_int(self):
if self.is_uuid():
warnings.warn("ERROR: This UID is not numeric, can't call getAsInt.")
else:
return self.uid_int
def is_none(self):
if self.uid_int == -1 and self.uid_str == "":
return True
else:
return False
class SetMode(Enum):
"""
The SetMode specifies how added content is inserted.
SetMode.union is the default value,
and determines that any new call to add functions (e.g. add_object, or add_action_data),
actually adds content, extending the frame_intervals of the recipient container to the
limits defined by the newly provided frame_intervals, effectively extending it to the union
of frame_intervals (existing plus new), substituting the content which already existed
with coincident frame (and name, uid, etc).
SetMode.replace acts replacing old content by new, potentially removing frames if the newly
provided frame_intervals are shorter than the existing ones.
"""
union = 1
replace = 2
class VCD:
"""
VCD class as main container of VCD content. Exposes functions to
add Elements, to get information and to remove data.
Internally manages all information as Python dictionaries, and can map
data into JSON strings.
"""
##################################################
# Constructor
##################################################
def __init__(self, file_name=None, validation=False):
self.use_uuid = False
if file_name is not None:
# Load from file
json_file = open(file_name, encoding='utf-8')
read_data = json.load(json_file) # Open without converting strings to integers
# Check VERSION and call converters if needed
if 'vcd' in read_data:
# This is 4.x
if 'version' in read_data['vcd']:
# This is 4.1-2
if read_data['vcd']['version'] == "4.2.0":
# This is VCD 4.2.0
warnings.warn("WARNING: Converting VCD 4.2.0 to OpenLABEL 1.0.0. A full revision is recommended.")
# Convert frame entries to int
frames = read_data['vcd']['frames']
if frames: # So frames is not empty
read_data['vcd']['frames'] = {int(key): value for key, value in frames.items()}
self.reset() # to init object
ConverterVCD420toOpenLabel100(read_data, self) # self is modified internally
elif read_data['vcd']['version'] == "4.1.0":
# This is VCD 4.1.0
raise Exception("ERROR: VCD 4.1.0 to OpenLABEL 1.0.0 conversion is not implemented.")
pass
elif 'metadata' in read_data['vcd']:
if 'schema_version' in read_data['vcd']['metadata']:
if read_data['vcd']['metadata']['schema_version'] == "4.3.0" or \
read_data['vcd']['metadata']['schema_version'] == "4.3.1":
# This is VCD 4.3.0 or VCD 4.3.1
self.data = read_data
warnings.warn("WARNING: Converting VCD 4.3.1 to OpenLABEL 1.0.0. A revision is recommended (specially for transforms and coordinate systems).")
# 'vcd' content was loaded, need to change root to 'openlabel'
# Let's substitute the root from 'vcd' to 'openlabel', and update the schema version
self.data['openlabel'] = self.data.pop('vcd')
self.data['openlabel']['metadata']['schema_version'] = schema.openlabel_schema_version
if validation:
if not hasattr(self, 'schema'):
self.schema = schema.openlabel_schema
validate(instance=self.data, schema=self.schema) # Raises errors if not validated
json_file.close()
# In VCD 4.3.1 uids are strings, because they can be numeric strings, or UUIDs
# but frames are still ints, so let's parse frame numbers as integers
if 'frames' in self.data['openlabel']:
frames = self.data['openlabel']['frames']
if frames: # So frames is not empty
self.data['openlabel']['frames'] = {int(key): value for key, value in frames.items()}
else:
raise Exception("ERROR: This vcd file does not seem to be 4.3.0, 4.3.1 nor 4.2.0")
else:
raise Exception("ERROR: This vcd file does not seem to be 4.3.0, 4.3.1 nor 4.2.0")
elif 'openlabel' in read_data:
# This is an OpenLABEL file
schema_version = read_data['openlabel']['metadata']['schema_version']
if schema_version == "1.0.0":
# This is OpenLABEL 1.0.0 (are equivalent)
self.data = read_data
if validation:
if not hasattr(self, 'schema'):
self.schema = schema.openlabel_schema
validate(instance=self.data, schema=self.schema) # Raises errors if not validated
json_file.close()
# In OpenLABEL 1.0.0 uids are strings, because they can be numeric strings, or UUIDs
# but frames are still indexed by ints, so let's parse frame numbers as integers
if 'frames' in self.data['openlabel']:
frames = self.data['openlabel']['frames']
if frames: # So frames is not empty
self.data['openlabel']['frames'] = {int(key): value for key, value in frames.items()}
else:
Exception(
"ERROR: This OpenLABEL file has version different than 1.0.0. This API is incompatible.")
# Close file
json_file.close()
# Final set-up
self.__compute_last_uid()
else:
# Init the VCD structures
self.reset()
def set_use_uuid(self, val):
assert(isinstance(val, bool))
self.use_uuid = val
def reset(self):
# Main VCD data
self.data = {'openlabel': {}}
self.data['openlabel']['metadata'] = {}
self.data['openlabel']['metadata']['schema_version'] = schema.openlabel_schema_version
# Schema information
self.schema = schema.openlabel_schema
# Additional auxiliary structures
self.__lastUID = dict()
self.__lastUID[ElementType.object] = -1
self.__lastUID[ElementType.action] = -1
self.__lastUID[ElementType.event] = -1
self.__lastUID[ElementType.context] = -1
self.__lastUID[ElementType.relation] = -1
self.__lastUID[ElementType.tag] = -1
##################################################
# Private API: inner functions
##################################################
def __get_uid_to_assign(self, element_type, uid):
assert isinstance(element_type, ElementType)
assert(isinstance(uid, UID))
if uid.is_none():
if self.use_uuid:
# Let's use UUIDs
uid_to_assign = UID(str(uuid.uuid4()))
else:
# Let's use integers
self.__lastUID[element_type] += 1
uid_to_assign = UID(self.__lastUID[element_type])
else:
# uid is not None
assert(isinstance(uid, UID))
if not uid.is_uuid():
# Ok, user provided a number, let's proceed
if uid.as_int() > self.__lastUID[element_type]:
self.__lastUID[element_type] = uid.as_int()
uid_to_assign = UID(self.__lastUID[element_type])
else:
uid_to_assign = uid
else:
# This is a UUID
self.use_uuid = True
uid_to_assign = uid
return uid_to_assign
def __set_vcd_frame_intervals(self, frame_intervals):
assert(isinstance(frame_intervals, FrameIntervals))
if not frame_intervals.empty():
self.data['openlabel']['frame_intervals'] = frame_intervals.get_dict()
def __update_vcd_frame_intervals(self, frame_intervals):
# This function creates the union of existing VCD with the input frameIntervals
assert (isinstance(frame_intervals, FrameIntervals))
if not frame_intervals.empty():
if 'frame_intervals' not in self.data['openlabel']:
self.data['openlabel']['frame_intervals'] = []
fis_current = FrameIntervals(self.data['openlabel']['frame_intervals'])
fis_union = fis_current.union(frame_intervals)
self.__set_vcd_frame_intervals(fis_union)
def __add_frame(self, frame_num):
if 'frames' not in self.data['openlabel']:
self.data['openlabel']['frames'] = {}
if frame_num not in self.data['openlabel']['frames']:
self.data['openlabel']['frames'][frame_num] = {}
def __compute_last_uid(self):
self.__lastUID = dict()
# Read all objects and fill lastUID
self.__lastUID[ElementType.object] = -1
if 'objects' in self.data['openlabel']:
for uid in self.data['openlabel']['objects']:
if int(uid) > self.__lastUID[ElementType.object]:
self.__lastUID[ElementType.object] = int(uid)
self.__lastUID[ElementType.action] = -1
if 'actions' in self.data['openlabel']:
for uid in self.data['openlabel']['actions']:
if int(uid) > self.__lastUID[ElementType.action]:
self.__lastUID[ElementType.action] = int(uid)
self.__lastUID[ElementType.event] = -1
if 'events' in self.data['openlabel']:
for uid in self.data['openlabel']['events']:
if int(uid) > self.__lastUID[ElementType.event]:
self.__lastUID[ElementType.event] = int(uid)
self.__lastUID[ElementType.context] = -1
if 'contexts' in self.data['openlabel']:
for uid in self.data['openlabel']['contexts']:
if int(uid) > self.__lastUID[ElementType.context]:
self.__lastUID[ElementType.context] = int(uid)
self.__lastUID[ElementType.relation] = -1
if 'relations' in self.data['openlabel']:
for uid in self.data['openlabel']['relations']:
if int(uid) > self.__lastUID[ElementType.relation]: # uid is a string!
self.__lastUID[ElementType.relation] = int(uid)
def __add_frames(self, frame_intervals, element_type, uid):
assert(isinstance(frame_intervals, FrameIntervals))
assert(isinstance(element_type, ElementType))
assert(isinstance(uid, UID))
if frame_intervals.empty():
return
else:
# Loop over frames and add
fis = frame_intervals.get()
for fi in fis:
for f in range(fi[0], fi[1]+1):
# Add frame
self.__add_frame(f)
# Add element entry
frame = self.get_frame(f)
frame.setdefault(element_type.name + 's', {})
frame[element_type.name + 's'].setdefault(uid.as_str(), {})
def __set_element(
self, element_type, name, semantic_type, frame_intervals, uid, ont_uid,
coordinate_system, set_mode, res_uid, **kwargs
):
assert (isinstance(uid, UID))
assert (isinstance(ont_uid, UID))
if res_uid is not None:
assert (isinstance(res_uid, ResourceUID))
assert (isinstance(frame_intervals, FrameIntervals))
assert (isinstance(set_mode, SetMode))
fis = frame_intervals
if set_mode == SetMode.union:
# Union means fusion, we are calling this function to "add" content, not to remove any
fis_existing = self.get_element_frame_intervals(element_type, uid.as_str())
fis = fis_existing.union(frame_intervals)
# 0.- Get uid_to_assign
uid_to_assign = self.__get_uid_to_assign(element_type, uid) # note: private functions use UID type for uids
# 1.- Set the root entries and frames entries
self.__set_element_at_root_and_frames(element_type, name, semantic_type, fis,
uid_to_assign, ont_uid, coordinate_system, res_uid)
# 2.- Kwargs
# Add any additional custom properties
element = self.data['openlabel'][element_type.name + 's'][uid_to_assign.as_str()]
for key, value in kwargs.items():
element[key] = value
return uid_to_assign
def __set_element_at_root_and_frames(
self, element_type, name, semantic_type, frame_intervals, uid, ont_uid, coordinate_system, res_uid
):
# 1.- Copy from existing or create new entry (this copies everything, including element_data)
# element_data_pointers and frame intervals
uidstr = uid.as_str()
element_existed = self.has(element_type, uidstr)# note: public functions use int or str for uids
self.data['openlabel'].setdefault(element_type.name + 's', {})
self.data['openlabel'][element_type.name + 's'].setdefault(uidstr, {})
element = self.data['openlabel'][element_type.name + 's'][uidstr]
fis_old = FrameIntervals()
if 'frame_intervals' in element:
fis_old = FrameIntervals(element['frame_intervals'])
# 2.- Copy from arguments
if name is not None:
element['name'] = name
if semantic_type is not None:
element['type'] = semantic_type
if not frame_intervals.empty() or (element_existed and not fis_old.empty()):
# So, either the newFis has something, or the fisOld had something (in which case needs to be substituted)
# Under the previous control, no 'frame_intervals' field is added to newly created static elements
# -> should 'frame_intervals' be mandatory
element['frame_intervals'] = frame_intervals.get_dict()
if not ont_uid.is_none() and self.get_ontology(ont_uid.as_str()):
element['ontology_uid'] = ont_uid.as_str()
if res_uid is not None:
resource_uid = res_uid.resource_uid
if not resource_uid.is_none() and self.get_resource(resource_uid.as_str()):
element['resource_uid'] = res_uid.as_dict()
if coordinate_system is not None and self.has_coordinate_system(coordinate_system):
element['coordinate_system'] = coordinate_system
# 2.bis.- For Relations obligue to have rdf_objects and rdf_subjects entries (to be compliant with schema)
if element_type is ElementType.relation:
if 'rdf_subjects' not in element:
element['rdf_subjects'] = []
if 'rdf_objects' not in element:
element['rdf_objects'] = []
# 3.- Reshape element_data_pointers according to this new frame intervals
if element_type.name + '_data_pointers' in element:
edps = element[element_type.name + '_data_pointers']
for edp_name in edps:
# NOW, we have to UPDATE frame intervals of pointers because we have modified the frame_intervals
# of the element itself, adn
# If we compute the intersection frame_intervals, we can copy that into
# element_data_pointers frame intervals
fis_int = FrameIntervals()
if not frame_intervals.empty():
fis_int = frame_intervals.intersection(FrameIntervals(edps[edp_name]['frame_intervals']))
# Update the pointers
element.setdefault(element_type.name + '_data_pointers', {})
element[element_type.name + '_data_pointers'][edp_name] = edps[edp_name]
element[element_type.name + '_data_pointers'][edp_name]['frame_intervals'] = fis_int.get_dict()
# 4.- Now set at frames
if not frame_intervals.empty():
# 2.1.- There is frame_intervals specified
if not element_existed:
# 2.1.a) Just create the new element
self.__add_frames(frame_intervals, element_type, uid)
self.__update_vcd_frame_intervals(frame_intervals)
else:
# 2.1.b) This is a substitution: depending on the new frame_intervals, we may need to delete/add frames
# Add
fis_new = frame_intervals
for fi in fis_new.get():
for f in range(fi[0], fi[1] + 1):
is_inside = fis_old.has_frame(f)
if not is_inside:
# New frame is not inside -> let's add this frame
fi_ = FrameIntervals(f)
self.__add_frames(fi_, element_type, uid)
self.__update_vcd_frame_intervals(fi_)
# Remove
if element_existed and fis_old.empty():
# Ok, the element was originally static (thus with fisOld empty)
# so potentially there are pointers of the element in all frames (in case there are frames)
# Now the element is declared with a specific frame intervals. Then we first need to remove all
# element entries (pointers) in all OTHER frames
vcd_frame_intervals = self.get_frame_intervals()
if not vcd_frame_intervals.empty():
for fi in vcd_frame_intervals.get():
for f in range(fi[0], fi[1] + 1):
if not fis_new.has_frame(f): # Only for those OTHER frames not those just added
elements_in_frame = self.data['openlabel']['frames'][f][element_type.name + 's']
if uidstr in elements_in_frame:
del elements_in_frame[uidstr]
if len(elements_in_frame) == 0:
del self.data['openlabel']['frames'][f][element_type.name + 's']
if len(self.data['openlabel']['frames'][f]) == 0:
self.__rm_frame(f)
# Next loop for is for the case fis_old wasn't empty, so we just need to remove old content
for fi in fis_old.get():
for f in range(fi[0], fi[1] + 1):
is_inside = fis_new.has_frame(f)
if not is_inside:
# Old frame not inside new ones -> let's remove this frame
elements_in_frame = self.data['openlabel']['frames'][f][element_type.name + 's']
del elements_in_frame[uidstr]
if len(elements_in_frame) == 0:
del self.data['openlabel']['frames'][f][element_type.name + 's']
if len(self.data['openlabel']['frames'][f]) == 0:
self.__rm_frame(f)
else:
# 2.2.- The element is declared as static
if element_type is not ElementType.relation: # frame-less relation must remain frame-less
vcd_frame_intervals = self.get_frame_intervals()
if not vcd_frame_intervals.empty():
# ... but VCD has already other elements or info that have established some frame intervals
# The element is then assumed to exist in all frames: let's add a pointer into all frames
self.__add_frames(vcd_frame_intervals, element_type, uid)
# But, if the element existed previously, and it was dynamic, there is already information inside frames.
# If there is element_data at frames, they are removed
if not fis_old.empty():
self.rm_element_data_from_frames(element_type, uid, fis_old)
# Additionally, we need to remove element entries at frames, and frames entirely to clean-up
for fi in fis_old.get():
for f in range(fi[0], fi[1] + 1):
elements_in_frame = self.data['openlabel']['frames'][f][element_type.name + 's']
del elements_in_frame[uidstr]
# Clean-up
if len(elements_in_frame) == 0:
del self.data['openlabel']['frames'][f][element_type.name + 's']
if len(self.data['openlabel']['frames'][f]) == 0:
self.__rm_frame(f)
def __set_element_data(self, element_type, uid, element_data, frame_intervals, set_mode):
assert(isinstance(uid, UID))
assert(isinstance(frame_intervals, FrameIntervals))
assert(isinstance(set_mode, SetMode))
# 0.- Checks
if not self.has(element_type, uid.as_str()):
warnings.warn("WARNING: Trying to set element_data for a non-existing element.")
return
element = self.get_element(element_type, uid.as_str())
# Read existing data about this element, so we can call __set_element
name = element.get('name')
semantic_type = element['type']
ont_uid = UID(None)
cs = None
if 'ontology_uid' in element:
ont_uid = UID(element['ontology_uid'])
res_uid = None
if 'resource_uid' in element:
res_uid = ResourceUID(element['resource_uid'].keys()[0],
element['resource_uid'].values()[0])
if 'coordinate_system' in element:
cs = element['coordinate_system']
if 'coordinate_system' in element_data.data:
if not self.has_coordinate_system(element_data.data['coordinate_system']):
warnings.warn("WARNING: Trying to set element_data with a non-declared coordinate system.")
return
if frame_intervals.empty() and set_mode == SetMode.union and not isinstance(element_data, types.mesh):
set_mode = SetMode.replace
if set_mode == SetMode.replace:
# Extend also the container Element just in case the frame_interval of this element_data is beyond it
# removes/creates frames if needed
# This call is to modify an existing element_data, which may imply removing some frames
if not frame_intervals.empty():
fis_existing = FrameIntervals(element['frame_intervals'])
fis_new = frame_intervals
fis_union = fis_existing.union(fis_new)
self.__set_element(element_type, name, semantic_type, fis_union, uid, ont_uid, cs, set_mode, res_uid)
self.__set_element_data_content_at_frames(element_type, uid, element_data, frame_intervals)
else:
# This is a static element_data. If it was declared dynamic before, let's remove it
#self.__set_element(element_type, name, semantic_type, frame_intervals, uid, ont_uid, cs, set_mode)
if self.has_element_data(element_type, uid.as_str(), element_data):
fis_old = self.get_element_data_frame_intervals(element_type, uid.as_str(), element_data.data['name'])
if not fis_old.empty():
self.rm_element_data_from_frames_by_name(element_type, uid, element_data.data['name'], fis_old)
self.__set_element_data_content(element_type, element, element_data)
# Set the pointers
self.__set_element_data_pointers(element_type, uid, element_data, frame_intervals)
else: # set_mode = SetMode.union
# This call is to add element_data to the element, substituting content if overlap, otherwise adding
# First, extend also the container Element just in case the frame_interval of this element_data is beyond
# the currently existing frame_intervals of the Element
# internally computes the union
self.__set_element(element_type, name, semantic_type, frame_intervals, uid, ont_uid, cs, set_mode, res_uid)
if not frame_intervals.empty():
fis_existing = FrameIntervals()
if element_type.name + '_data_pointers' in element:
edp = element[element_type.name + '_data_pointers']
if element_data.data['name'] in edp:
fis_existing = FrameIntervals(edp[element_data.data['name']]['frame_intervals'])
fis_new = frame_intervals
fis_union = fis_existing.union(fis_new)
# Dynamic
if element is not None:
# It is not a simple call with the union of frame intervals
# We need to substitute the content for just this frame_interval, without modifying the rest
# that must stay as it was
# Loop over the specified frame_intervals to create or substitute the content
self.__set_element_data_content_at_frames(element_type, uid, element_data, fis_new)
# Set the pointers (but the pointers we have to update using the union)
self.__set_element_data_pointers(element_type, uid, element_data, fis_union)
elif isinstance(element_data, types.mesh):
# This is only for mesh case that can have this static part
# (because it is an object data type which is both static and dynamic)
self.__set_element_data_content(element_type, element, element_data)
def __set_element_data_content_at_frames(self, element_type, uid, element_data, frame_intervals):
# Loop over the specified frame_intervals to create or substitute the content
# Create entries of the element_data at frames
fis = frame_intervals.get()
for fi in fis:
for f in range(fi[0], fi[1] + 1):
# Add element_data entry
frame = self.get_frame(f)
if frame is None:
self.__add_frame(f)
frame = self.get_frame(f)
frame.setdefault(element_type.name + 's', {})
frame[element_type.name + 's'].setdefault(uid.as_str(), {})
element = frame[element_type.name + 's'][uid.as_str()]
self.__set_element_data_content(element_type, element, element_data)
@staticmethod
def __set_tag_data_content(tag, tag_data):
tag.setdefault('val', {})
tag['val'].setdefault(tag_data.type.name, [])
list_aux = tag['val'][tag_data.type.name]
pos_list = [idx for idx, val in enumerate(list_aux) if val['name'] == tag_data.data['name']]
if len(pos_list) == 0:
tag['val'][tag_data.type.name].append(tag_data.data)
else:
pos = pos_list[0]
tag['val'][tag_data.type.name][pos] = tag_data.data
@staticmethod
def __set_element_data_content(element_type, element, element_data):
# Adds the element_data to the corresponding container
# If an element_data with same name exists, it is substituted
element.setdefault(element_type.name + '_data', {})
element[element_type.name + '_data'].setdefault(element_data.type.name, [])
# Find if element_data already there
if 'name' in element_data.data:
list_aux = element[element_type.name + '_data'][element_data.type.name]
pos_list = [idx for idx, val in enumerate(list_aux) if val['name'] == element_data.data['name']]
else:
pos_list = []
if len(pos_list) == 0:
# Not found, then just push this new element data
element[element_type.name + '_data'][element_data.type.name].append(element_data.data)
else:
# Found: let's substitute
pos = pos_list[0]
element[element_type.name + '_data'][element_data.type.name][pos] = element_data.data
def __set_element_data_pointers(self, element_type, uid, element_data, frame_intervals):
# For Tags, let's ignore element_data_pointers
if element_type == ElementType.tag:
return
assert(isinstance(uid, UID))
self.data['openlabel'][element_type.name + 's'][uid.as_str()].setdefault(element_type.name + '_data_pointers', {})
edp = self.data['openlabel'][element_type.name + 's'][uid.as_str()][element_type.name + '_data_pointers']
edp[element_data.data['name']] = {}
edp[element_data.data['name']]['type'] = element_data.type.name
if frame_intervals is None:
edp[element_data.data['name']]['frame_intervals'] = []
else:
edp[element_data.data['name']]['frame_intervals'] = frame_intervals.get_dict()
if 'attributes' in element_data.data:
edp[element_data.data['name']]['attributes'] = {}
for attr_type in element_data.data['attributes']: # attr_type might be 'boolean', 'text', 'num', or 'vec'
for attr in element_data.data['attributes'][attr_type]:
edp[element_data.data['name']]['attributes'][attr['name']] = attr_type
def __rm_frame(self, frame_num):
# This function deletes a frame entry from frames, and updates VCD accordingly
if 'frames' in self.data['openlabel']:
if frame_num in self.data['openlabel']['frames']:
del self.data['openlabel']['frames'][frame_num]
if len(self.data['openlabel']['frames']) == 0:
del self.data['openlabel']['frames']
# Remove from VCD frame intervals
if 'frame_intervals' in self.data['openlabel']:
fis_dict = self.data['openlabel']['frame_intervals']
fis_dict_new = utils.rm_frame_from_frame_intervals(fis_dict, frame_num)
# Now substitute
if len(fis_dict_new) == 0:
del self.data['openlabel']['frame_intervals']
else:
self.data['openlabel']['frame_intervals'] = fis_dict_new
def __compute_data_pointers(self):
# WARNING! This function might be extremely slow
# It does loop over all frames, and updates data pointers at objects, actions, etc
# It is useful to convert from VCD 4.2.0 into VCD 4.3.1 (use converter.ConverterVCD420toVCD430)
# Looping over frames and creating the necessary data_pointers
if 'frame_intervals' in self.data['openlabel']:
fis = self.data['openlabel']['frame_intervals']
for fi in fis:
for frame_num in range(fi['frame_start'], fi['frame_end'] + 1):
frame = self.get_frame(frame_num)
for element_type in ElementType:
if element_type.name + 's' in frame: # e.g. "objects", "actions"...
for uid, element in frame[element_type.name + 's'].items():
if element_type.name + '_data' in element:
# So this element has element_data in this frame
# and then we need to update the element_data_pointer at the root
# we can safely assume it already exists
# First, let's create a element_data_pointer at the root
self.data['openlabel'][element_type.name + 's'][uid].\
setdefault(element_type.name + '_data_pointers', {})
edp = self.data['openlabel'][element_type.name + 's'][uid]
[element_type.name + '_data_pointers']
# Let's loop over the element_data
for ed_type, ed_array in element[element_type.name + '_data'].items():
# e.g. ed_type is 'bbox', ed_array is the array of such bboxes content
for element_data in ed_array:
name = element_data['name']
edp.setdefault(name, {}) # this element_data may already exist
edp[name].setdefault('type', ed_type) # e.g. 'bbox'
edp[name].setdefault('frame_intervals', []) # in case it does not exist
fis_exist = FrameIntervals(edp[name]['frame_intervals'])
fis_exist.union(FrameIntervals(frame_num)) # So, let's fuse with this frame
edp[name]['frame_intervals'] = fis_exist.get_dict() # overwrite
# No need to manage attributes
##################################################
# Public API: add, update
##################################################
def add_file_version(self, version):
assert (type(version) is str)
if 'metadata' not in self.data['openlabel']:
self.data['openlabel']['metadata'] = {}
self.data['openlabel']['metadata']['file_version'] = version
def add_metadata_properties(self, properties):
assert(isinstance(properties, dict))
prop = self.data['openlabel']['metadata']
prop.update(properties)
def add_name(self, name):
assert(type(name) is str)
if 'metadata' not in self.data['openlabel']:
self.data['openlabel']['metadata'] = {}
self.data['openlabel']['metadata']['name'] = name
def add_annotator(self, annotator):
assert(type(annotator) is str)
if 'metadata' not in self.data['openlabel']:
self.data['openlabel']['metadata'] = {}
self.data['openlabel']['metadata']['annotator'] = annotator
def add_comment(self, comment):
assert(type(comment) is str)
if 'metadata' not in self.data['openlabel']:
self.data['openlabel']['metadata'] = {}
self.data['openlabel']['metadata']['comment'] = comment
def add_ontology(self, ontology_name, subset_include=None, subset_exclude=None, **kwargs):
self.data['openlabel'].setdefault('ontologies', dict())
for ont_uid in self.data['openlabel']['ontologies']:
if self.data['openlabel']['ontologies'][ont_uid] == ontology_name:
warnings.warn('WARNING: adding an already existing ontology')
return None
length = len(self.data['openlabel']['ontologies'])
if subset_include is None and subset_exclude is None and len(kwargs)==0:
self.data['openlabel']['ontologies'][str(length)] = ontology_name
else:
self.data['openlabel']['ontologies'][str(length)] = {"uri": ontology_name}
if subset_include is not None:
self.data['openlabel']['ontologies'][str(length)]["subset_include"] = subset_include
if subset_exclude is not None:
self.data['openlabel']['ontologies'][str(length)]["subset_exclude"] = subset_exclude
for key, value in kwargs.items():
self.data['openlabel']['ontologies'][str(length)][key] = value
return str(length)
def add_resource(self, resource_name):
self.data['openlabel'].setdefault('resources', dict())
for res_uid in self.data['openlabel']['resources']:
if self.data['openlabel']['resources'][res_uid] == resource_name:
warnings.warn('WARNING: adding an already existing resource')
return None
length = len(self.data['openlabel']['resources'])
self.data['openlabel']['resources'][str(length)] = resource_name
return str(length)
def add_coordinate_system(self, name, cs_type, parent_name="", pose_wrt_parent=None):
# Argument pose_wrt_parent can be used to quickly add a list containing the 4x4 matrix
# However, argument pose can be used to add any type of Pose object (created with types.Pose)
assert(isinstance(cs_type, types.CoordinateSystemType))
# Create entry
self.data['openlabel'].setdefault('coordinate_systems', {})
self.data['openlabel']['coordinate_systems'][name] = {'type': cs_type.name,
'parent': parent_name,
'children': []}
# Add Pose data
if pose_wrt_parent is not None:
assert(isinstance(pose_wrt_parent, types.PoseData))
self.data['openlabel']['coordinate_systems'][name].update({"pose_wrt_parent": pose_wrt_parent.data})
# Update parents
if parent_name != "":
found = False
for n, cs in self.data['openlabel']['coordinate_systems'].items():
if n == parent_name:
found = True
cs['children'].append(name)
if not found:
warnings.warn("WARNING: Creating a coordinate system with a non-defined parent coordinate system."
"Coordinate systems must be introduced in order")
def add_transform(self, frame_num, transform):
assert(isinstance(frame_num, int))
assert(isinstance(transform, types.Transform))
self.__add_frame(frame_num) # this function internally checks if the frame already exists
self.data['openlabel']['frames'][frame_num].setdefault('frame_properties', dict())
self.data['openlabel']['frames'][frame_num]['frame_properties'].setdefault('transforms', dict())
self.data['openlabel']['frames'][frame_num]['frame_properties']['transforms'].update(transform.data)
def add_stream(self, stream_name, uri, description, stream_type):
assert(isinstance(stream_name, str))
assert(isinstance(uri, str))
assert(isinstance(description, str))
self.data['openlabel'].setdefault('streams', dict())
self.data['openlabel']['streams'].setdefault(stream_name, dict())
if isinstance(stream_type, StreamType):
self.data['openlabel']['streams'][stream_name] = {
'description': description, 'uri': uri, 'type': stream_type.name
}
elif isinstance(stream_type, str):
self.data['openlabel']['streams'][stream_name] = {
'description': description, 'uri': uri, 'type': stream_type
}
def add_frame_properties(self, frame_num, timestamp=None, properties=None):
self.__add_frame(frame_num) # this function internally checks if the frame already exists
self.__update_vcd_frame_intervals(FrameIntervals(frame_num))
self.data['openlabel']['frames'][frame_num].setdefault('frame_properties', dict())
if timestamp is not None:
assert (isinstance(timestamp, (str, float)))
self.data['openlabel']['frames'][frame_num]['frame_properties']['timestamp'] = timestamp
if properties is not None:
assert (isinstance(properties, dict))