-
Notifications
You must be signed in to change notification settings - Fork 38
/
Elan.py
1822 lines (1624 loc) · 77.9 KB
/
Elan.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
from xml.etree import cElementTree as etree
import re
import sys
import time
import pathlib
import warnings
VERSION = '1.70.2'
class Eaf:
"""Read and write Elan's Eaf files.
.. note:: All times are in milliseconds and can't have decimals.
:var dict adocument: Annotation document TAG entries.
:var list licenses: Licences included in the file of the form:
``(name, url)``.
:var dict header: XML header.
:var list media_descriptors: Linked files, where every file is of the
form: ``{attrib}``.
:var list properties: Properties, where every property is of the form:
``(key, value)``.
:var list linked_file_descriptors: Secondary linked files, where every
linked file is of the form: ``{attrib}``.
:var dict timeslots: Timeslot data of the form: ``{id -> time(ms)}``.
:var dict tiers: Tiers, where every tier is of the form:
``{tier_name -> (aligned_annotations, reference_annotations,
attributes, ordinal)}``,
aligned_annotations of the form: ``[{id -> (begin_ts, end_ts, value,
svg_ref)}]``,
reference annotations of the form: ``[{id -> (reference, value,
previous, svg_ref)}]``.
:var list linguistic_types: Linguistic types, where every type is of the
form: ``{id -> attrib}``.
:var dict locales: Locales, of the form:
``{lancode -> (countrycode, variant)}``.
:var dict languages: Languages, of the form:
``{langid -> (langdef, langlabel)}``.
:var dict constraints: Constraints, every constraint is of the form:
``{stereotype -> description}``.
:var dict controlled_vocabularies: Controlled vocabulary, where every
controlled vocabulary is of the form: ``{id -> (descriptions, entries,
ext_ref)}``,
descriptions of the form: ``[(value, lang_ref, description)]``,
entries of the form: ``{id -> (values, ext_ref)}``,
values of the form: ``[(lang_ref, description, text)]``.
:var list external_refs: External references of the form:
``{id -> (type, value)}``.
:var list lexicon_refs: Lexicon references, where every reference is of
the form: ``{id -> {attribs}}``.
:var dict annotations: Dictionary of annotations of the form:
``{id -> tier}``, this is only used internally.
"""
ETYPES = {'iso12620', 'ecv', 'cve_id', 'lexen_id', 'resource_url'}
CONSTRAINTS = {
'Time_Subdivision': "Time subdivision of parent annotation's time inte"
'rval, no time gaps allowed within this interval',
'Symbolic_Subdivision': 'Symbolic subdivision of a parent annotation. '
'Annotations refering to the same parent are ordered',
'Symbolic_Association': '1-1 association with a parent annotation',
'Included_In': 'Time alignable annotations within the parent annotatio'
"n's time interval, gaps are allowed"}
MIMES = {'wav': 'audio/x-wav', 'mpg': 'video/mpeg', 'mpeg': 'video/mpg',
'mp4': 'video/mp4', 'xml': 'text/xml'}
def __init__(self, file_path=None, author='pympi',
suppress_version_warning=False):
"""Construct either a new Eaf file or read on from a file/stream.
:param str file_path: Path to read from, - for stdin. If ``None`` an
empty Eaf file will be created.
:param str author: Author of the file.
:param bool supress_version_warning: Suppress the warning for
unsupported EAF file versions
"""
ctz = -time.altzone if time.localtime(time.time()).tm_isdst and\
time.daylight else -time.timezone
self.maxts = 1
self.maxaid = 1
self.adocument = {
'AUTHOR': author,
'DATE': time.strftime('%Y-%m-%dT%H:%M:%S{:0=+3d}:{:0=2d}').format(
ctz // 3600, ctz % 3600),
'VERSION': '2.8',
'FORMAT': '2.8',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:noNamespaceSchemaLocation':
'http://www.mpi.nl/tools/elan/EAFv2.8.xsd'}
self.annotations = {}
self.constraints = {}
self.controlled_vocabularies = {}
self.external_refs = {}
self.header = {}
self.languages = {}
self.lexicon_refs = {}
self.linguistic_types = {}
self.locales = {}
self.tiers = {}
self.timeslots = {}
self.licenses = []
self.linked_file_descriptors = []
self.media_descriptors = []
self.properties = []
if file_path is None:
self.add_linguistic_type('default-lt')
self.constraints = self.CONSTRAINTS.copy()
self.properties.append(('lastUsedAnnotation', 0))
self.add_tier('default')
else:
parse_eaf(file_path, self, suppress_version_warning)
def add_annotation(self, id_tier, start, end, value='', svg_ref=None):
"""Add an annotation.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:param str value: Value of the annotation.
:param str svg_ref: Svg reference.
:raises KeyError: If the tier is non existent.
:raises ValueError: If one of the values is negative or start is bigger
then end or if the tiers already contains ref
annotations.
"""
if self.tiers[id_tier][1]:
raise ValueError('Tier already contains ref annotations...')
if not isinstance(start, int) or not isinstance(end, int):
raise ValueError('start and end must be an integer...')
if start == end:
raise ValueError('Annotation length is zero...')
if start > end:
raise ValueError('Annotation length is negative...')
if start < 0:
raise ValueError('Start is negative...')
start_ts = self.generate_ts_id(start)
end_ts = self.generate_ts_id(end)
aid = self.generate_annotation_id()
self.annotations[aid] = id_tier
self.tiers[id_tier][0][aid] = (start_ts, end_ts, value, svg_ref)
def add_controlled_vocabulary(self, cv_id, ext_ref=None):
"""Add a controlled vocabulary. This will initialize the controlled
vocabulary without entries.
:param str cv_id: Name of the controlled vocabulary.
:param str ext_ref: External reference.
"""
self.controlled_vocabularies[cv_id] = ([], {}, ext_ref)
def add_cv_entry(self, cv_id, cve_id, values, ext_ref=None):
"""Add an entry to a controlled vocabulary.
:param str cv_id: Name of the controlled vocabulary to add an entry.
:param str cve_id: Name of the entry.
:param list values: List of values of the form:
``(value, lang_ref, description)`` where description can be
``None``.
:param str ext_ref: External reference.
:throws KeyError: If there is no controlled vocabulary with that id.
:throws ValueError: If a language in one of the entries doesn't exist.
"""
for value, lang_ref, description in values:
if lang_ref not in self.languages:
raise ValueError('Language not present: {}'.format(lang_ref))
self.controlled_vocabularies[cv_id][1][cve_id] = (values, ext_ref)
def add_cv_description(self, cv_id, lang_ref, description=None):
"""Add a description to a controlled vocabulary.
:param str cv_id: Name of the controlled vocabulary to add the
description.
:param str lang_ref: Language reference.
:param str description: Description, this can be none.
:throws KeyError: If there is no controlled vocabulary with that id.
:throws ValueError: If the language provided doesn't exist.
"""
if lang_ref not in self.languages:
raise ValueError('Language not present: {}'.format(lang_ref))
self.controlled_vocabularies[cv_id][0].append((lang_ref, description))
def add_external_ref(self, eid, etype, value):
"""Add an external reference.
:param str eid: Name of the external reference.
:param str etype: Type of the external reference, has to be in
``['iso12620', 'ecv', 'cve_id', 'lexen_id', 'resource_url']``.
:param str value: Value of the external reference.
:throws KeyError: if etype is not in the list of possible types.
"""
if etype not in self.ETYPES:
raise KeyError('etype not in {}'.format(self.ETYPES))
self.external_refs[eid] = (etype, value)
def add_language(self, lang_id, lang_def=None, lang_label=None):
"""Add a language.
:param str lang_id: ID of the language.
:param str lang_def: Definition of the language(preferably ISO-639-3).
:param str lang_label: Label of the language.
"""
self.languages[lang_id] = (lang_def, lang_label)
def add_lexicon_ref(self, lrid, name, lrtype, url, lexicon_id,
lexicon_name, datcat_id=None, datcat_name=None):
"""Add lexicon reference.
:param str lrid: Lexicon reference internal ID.
:param str name: Lexicon reference display name.
:param str lrtype: Lexicon reference service type.
:param str url: Lexicon reference service location
:param str lexicon_id: Lexicon reference service id.
:param str lexicon_name: Lexicon reference service name.
:param str datacat_id: Lexicon reference identifier of data category.
:param str datacat_name: Lexicon reference name of data category.
"""
self.lexicon_refs[lrid] = {
'LEX_REF_ID': lrid,
'NAME': name,
'TYPE': lrtype,
'URL': url,
'LEXICON_ID': lexicon_id,
'LEXICON_NAME': lexicon_name,
'DATCAT_ID': datcat_id,
'DATCAT_NAME': datcat_name
}
def add_license(self, name, url):
"""Add a license
:param str name: Name of the license.
:param str url: URL of the license.
"""
self.licenses.append((name, url))
def add_linguistic_type(self, lingtype, constraints=None,
timealignable=True, graphicreferences=False,
extref=None, param_dict=None):
"""Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param str constraints: Constraint name.
:param bool timealignable: Flag for time alignable.
:param bool graphicreferences: Flag for graphic references.
:param str extref: External reference.
:param dict param_dict: TAG attributes, when this is not ``None`` it
will ignore all other options. Please only use
dictionaries coming from the
:func:`get_parameters_for_linguistic_type`
:raises KeyError: If a constraint is not defined
"""
if param_dict:
self.linguistic_types[lingtype] = param_dict
else:
if constraints:
self.constraints[constraints]
self.linguistic_types[lingtype] = {
'LINGUISTIC_TYPE_ID': lingtype,
'TIME_ALIGNABLE': str(timealignable).lower(),
'GRAPHIC_REFERENCES': str(graphicreferences).lower(),
'CONSTRAINTS': constraints}
if extref is not None:
self.linguistic_types[lingtype]['EXT_REF'] = extref
def add_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, ex_from=None):
"""Add a linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: Mimetype of the file, if ``None`` it tries to
guess it according to the file extension which currently only works
for wav, mpg, mpeg and xml.
:param int time_origin: Time origin for the media file.
:param str ex_from: Extracted from field.
:raises KeyError: If mimetype had to be guessed and a non standard
extension or an unknown mimetype.
"""
if mimetype is None:
mimetype = self.MIMES[file_path.split('.')[-1].lower()]
self.media_descriptors.append({
'MEDIA_URL': file_path, 'RELATIVE_MEDIA_URL': relpath,
'MIME_TYPE': mimetype, 'TIME_ORIGIN': time_origin,
'EXTRACTED_FROM': ex_from})
def add_locale(self, language_code, country_code=None, variant=None):
"""Add a locale.
:param str language_code: The language code of the locale.
:param str country_code: The country code of the locale.
:param str variant: The variant of the locale.
"""
self.locales[language_code] = (country_code, variant)
def add_property(self, key, value):
"""Add a property
:param str key: Key of the property.
:param str value: Value of the property.
"""
self.properties.append((key, value))
def add_ref_annotation(self, id_tier, tier2, time, value='',
prev=None, svg=None):
"""Add a reference annotation.
.. note:: When a timepoint matches two annotations the new reference
annotation will reference to the first annotation. To circumvent this
it's always safer to take the middle of the annotation you want to
reference to.
:param str id_tier: Name of the tier.
:param str tier2: Tier of the referenced annotation.
:param int time: Time of the referenced annotation.
:param str value: Value of the annotation.
:param str prev: Id of the previous annotation.
:param str svg_ref: Svg reference.
:raises KeyError: If the tier is non existent.
:raises ValueError: If the tier already contains normal annotations or
if there is no annotation in the tier on the time to reference to.
"""
if self.tiers[id_tier][0]:
raise ValueError('This tier already contains normal annotations.')
ann = None
# tier2 is an independent (aligned reference) tier
if self.tiers[tier2][0]:
for aid, (begin, end, _, _) in self.tiers[tier2][0].items():
begin = self.timeslots[begin]
end = self.timeslots[end]
if begin <= time and end >= time:
ann = aid
break
# tier2 is a reference tier, so we grab the top tier in the hierarchy
else:
for aid, (reference, _, _, _) in self.tiers[tier2][1].items():
refann = self.get_parent_aligned_annotation(aid)
begin = self.timeslots[refann[0]]
end = self.timeslots[refann[1]]
if begin <= time and end >= time:
ann = aid
break
if not ann:
raise ValueError('There is no annotation to reference to.')
aid = self.generate_annotation_id()
self.annotations[aid] = id_tier
self.tiers[id_tier][1][aid] = (ann, value, prev, svg)
def add_secondary_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, assoc_with=None):
"""Add a secondary linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: Mimetype of the file, if ``None`` it tries to
guess it according to the file extension which currently only works
for wav, mpg, mpeg and xml.
:param int time_origin: Time origin for the media file.
:param str assoc_with: Associated with field.
:raises KeyError: If mimetype had to be guessed and a non standard
extension or an unknown mimetype.
"""
if mimetype is None:
mimetype = self.MIMES[file_path.split('.')[-1]]
self.linked_file_descriptors.append({
'LINK_URL': file_path, 'RELATIVE_LINK_URL': relpath,
'MIME_TYPE': mimetype, 'TIME_ORIGIN': time_origin,
'ASSOCIATED_WITH': assoc_with})
def add_tier(self, tier_id, ling='default-lt', parent=None, locale=None,
part=None, ann=None, language=None, tier_dict=None):
"""Add a tier. When no linguistic type is given and the default
linguistic type is unavailable then the assigned linguistic type will
be the first in the list.
:param str tier_id: Name of the tier.
:param str ling: Linguistic type, if the type is not available it will
warn and pick the first available type.
:param str parent: Parent tier name.
:param str locale: Locale, if the locale is not present this option is
ignored and the locale will not be set.
:param str part: Participant.
:param str ann: Annotator.
:param str language: Language , if the language is not present this
option is ignored and the language will not be set.
:param dict tier_dict: TAG attributes, when this is not ``None`` it
will ignore all other options. Please only use
dictionaries coming from the
:func:`get_parameters_for_tier`
:raises ValueError: If the tier_id is empty
"""
if not tier_id:
raise ValueError('Tier id is empty...')
if ling not in self.linguistic_types:
ling = sorted(self.linguistic_types.keys())[0]
if locale and locale not in self.locales:
locale = None
if language and language not in self.languages:
language = None
if tier_dict is None:
self.tiers[tier_id] = ({}, {}, {
'TIER_ID': tier_id,
'LINGUISTIC_TYPE_REF': ling,
'PARENT_REF': parent,
'PARTICIPANT': part,
'DEFAULT_LOCALE': locale,
'LANG_REF': language,
'ANNOTATOR': ann}, len(self.tiers))
else:
self.tiers[tier_id] = ({}, {}, tier_dict, len(self.tiers))
def child_tiers_for(self, id_tier):
""".. deprecated: 1.5
Use :func:`get_child_tiers_for`
"""
return self.get_child_tiers_for(id_tier)
def clean_time_slots(self):
"""Clean up all unused timeslots.
.. warning:: This can and will take time for larger tiers.
When you want to do a lot of operations on a lot of tiers please unset
the flags for cleaning in the functions so that the cleaning is only
performed afterwards.
"""
ts = ((a[0], a[1]) for t in self.tiers.values() for a in t[0].values())
for a in {a for b in ts for a in b} ^ set(self.timeslots):
del(self.timeslots[a])
def copy_tier(self, eaf_obj, tier_name):
"""Copies a tier to another :class:`pympi.Elan.Eaf` object.
:param pympi.Elan.Eaf eaf_obj: Target Eaf object.
:param str tier_name: Name of the tier.
:raises KeyError: If the tier doesn't exist.
"""
if tier_name in eaf_obj.get_tier_names():
eaf_obj.remove_tier(tier_name)
eaf_obj.add_tier(tier_name,
tier_dict=self.get_parameters_for_tier(tier_name))
for ann in self.get_annotation_data_for_tier(tier_name):
eaf_obj.insert_annotation(tier_name, ann[0], ann[1], ann[2])
def create_gaps_and_overlaps_tier(self, tier1, tier2, tier_name=None,
maxlen=-1, fast=False):
"""Create a tier with the gaps and overlaps of the annotations.
For types see :func:`get_gaps_and_overlaps`
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param str tier_name: Name of the new tier, if ``None`` the name will
be generated.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:param bool fast: Flag for using the fast method.
:returns: List of gaps and overlaps of the form:
``[(type, start, end)]``.
:raises KeyError: If a tier is non existent.
:raises IndexError: If no annotations are available in the tiers.
"""
if tier_name is None:
tier_name = '{}_{}_ftos'.format(tier1, tier2)
self.add_tier(tier_name)
ftos = []
ftogen = self.get_gaps_and_overlaps2(tier1, tier2, maxlen) if fast\
else self.get_gaps_and_overlaps(tier1, tier2, maxlen)
for fto in ftogen:
ftos.append(fto)
if fto[1]-fto[0] >= 1:
self.add_annotation(tier_name, fto[0], fto[1], fto[2])
self.clean_time_slots()
return ftos
def extract(self, start, end):
"""Extracts the selected time frame as a new object.
:param int start: Start time.
:param int end: End time.
:returns: class:`pympi.Elan.Eaf` object containing the extracted frame.
"""
from copy import deepcopy
eaf_out = deepcopy(self)
align_tier_names = []
ref_tier_names = []
for t in eaf_out.get_tier_names():
t_type = eaf_out.tiers[t][2]['LINGUISTIC_TYPE_REF']
if eaf_out.linguistic_types[t_type]['TIME_ALIGNABLE'] == 'true':
align_tier_names.append(t)
else:
ref_tier_names.append(t)
# Make sure that annotations on reference tiers are removed first (so
# that it's possible to look up their start and end times from their
# time-aligned parent annotations when calling 'remove_annotation').
for t in ref_tier_names + align_tier_names:
for ab, ae, value, *_ in eaf_out.get_annotation_data_for_tier(t):
if ab > end or ae < start:
eaf_out.remove_annotation(t, (ae + ab) // 2, False)
eaf_out.clean_time_slots()
return eaf_out
def filter_annotations(self, tier, tier_name=None, filtin=None,
filtex=None, regex=False, safe=False):
"""Filter annotations in a tier using an exclusive and/or inclusive
filter.
:param str tier: Name of the tier.
:param str tier_name: Name of the output tier, when ``None`` the name
will be generated.
:param list filtin: List of strings to be included, if None all
annotations all is included.
:param list filtex: List of strings to be excluded, if None no strings
are excluded.
:param bool regex: If this flag is set, the filters are seen as regex
matches.
:param bool safe: Ignore zero length annotations(when working with
possible malformed data).
:returns: Name of the created tier.
:raises KeyError: If the tier is non existent.
"""
if tier_name is None:
tier_name = '{}_filter'.format(tier)
self.add_tier(tier_name)
func = (lambda x, y: re.match(x, y)) if regex else lambda x, y: x == y
for begin, end, value in self.get_annotation_data_for_tier(tier):
if (filtin and not any(func(f, value) for f in filtin)) or\
(filtex and any(func(f, value) for f in filtex)):
continue
if not safe or end > begin:
self.add_annotation(tier_name, begin, end, value)
self.clean_time_slots()
return tier_name
def generate_annotation_id(self):
"""Generate the next annotation id, this function is mainly used
internally.
"""
if not self.maxaid:
valid_anns = [int(''.join(filter(str.isdigit, a)))
for a in self.timeslots]
self.maxaid = max(valid_anns + [1])+1
else:
self.maxaid += 1
return 'a{:d}'.format(self.maxaid)
def generate_ts_id(self, time=None):
"""Generate the next timeslot id, this function is mainly used
internally
:param int time: Initial time to assign to the timeslot.
:raises ValueError: If the time is negative.
"""
if time and time < 0:
raise ValueError('Time is negative...')
if not self.maxts:
valid_ts = [int(''.join(filter(str.isdigit, a)))
for a in self.timeslots]
self.maxts = max(valid_ts + [1])+1
else:
self.maxts += 1
ts = 'ts{:d}'.format(self.maxts)
self.timeslots[ts] = time
return ts
def get_annotation_data_at_time(self, id_tier, time):
"""Give the annotations at the given time. When the tier contains
reference annotations this will be returned, check
:func:`get_ref_annotation_data_at_time` for the format.
:param str id_tier: Name of the tier.
:param int time: Time of the annotation.
:returns: List of annotations at that time.
:raises KeyError: If the tier is non existent.
"""
if self.tiers[id_tier][1]:
return self.get_ref_annotation_at_time(id_tier, time)
anns = self.tiers[id_tier][0]
return sorted([(self.timeslots[m[0]], self.timeslots[m[1]], m[2])
for m in anns.values() if
self.timeslots[m[0]] <= time and
self.timeslots[m[1]] >= time])
def get_annotation_data_after_time(self, id_tier, time):
"""Give the annotation before a given time. When the tier contains
reference annotations this will be returned, check
:func:`get_ref_annotation_data_before_time` for the format. If an
annotation overlaps with ``time`` that annotation will be returned.
:param str id_tier: Name of the tier.
:param int time: Time to get the annotation before.
:raises KeyError: If the tier is non existent.
"""
if self.tiers[id_tier][1]:
return self.get_ref_annotation_after_time(id_tier, time)
befores = self.get_annotation_data_between_times(
id_tier, time, self.get_full_time_interval()[1])
if befores:
return [min(befores, key=lambda x: x[0])]
else:
return []
def get_annotation_data_before_time(self, id_tier, time):
"""Give the annotation before a given time. When the tier contains
reference annotations this will be returned, check
:func:`get_ref_annotation_data_before_time` for the format. If an
annotation overlaps with ``time`` that annotation will be returned.
:param str id_tier: Name of the tier.
:param int time: Time to get the annotation before.
:raises KeyError: If the tier is non existent.
"""
if self.tiers[id_tier][1]:
return self.get_ref_annotation_before_time(id_tier, time)
befores = self.get_annotation_data_between_times(id_tier, 0, time)
if befores:
return [max(befores, key=lambda x: x[0])]
else:
return []
def get_annotation_data_between_times(self, id_tier, start, end):
"""Gives the annotations within the times.
When the tier contains reference annotations this will be returned,
check :func:`get_ref_annotation_data_between_times` for the format.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:returns: List of annotations within that time.
:raises KeyError: If the tier is non existent.
"""
if self.tiers[id_tier][1]:
return self.get_ref_annotation_data_between_times(
id_tier, start, end)
anns = ((self.timeslots[a[0]], self.timeslots[a[1]], a[2])
for a in self.tiers[id_tier][0].values())
return sorted(a for a in anns if a[1] >= start and a[0] <= end)
def get_annotation_data_for_tier(self, id_tier):
"""Gives a list of annotations of the form: ``(begin, end, value)``
When the tier contains reference annotations this will be returned,
check :func:`get_ref_annotation_data_for_tier` for the format.
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
if self.tiers[id_tier][1]:
return self.get_ref_annotation_data_for_tier(id_tier)
a = self.tiers[id_tier][0]
return [(self.timeslots[a[b][0]], self.timeslots[a[b][1]], a[b][2])
for b in a]
def get_annotation_data_for_symbsub_tier(self, id_tier):
""""Give a list of all annotations of id_tier with their calculated start, end and value of the form:
``[(start, end, value, value)]``
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
:returns: Reference annotations within that tier.
"""
ref_ann = self.get_ref_annotation_data_for_tier(id_tier)
bucket = []
children = []
begin,end,value,ref = ref_ann[0]
prevEnd = end
for i in range(0, len(ref_ann)-1):
if ref_ann[i][1] == prevEnd:
children.append([ref_ann[i][0],ref_ann[i][1],ref_ann[i][2]])
else:
nbChildren = len(children)
duration = round((children[nbChildren-1][1] - children[0][0])/nbChildren)
for j in range(0,nbChildren-1):
children[j][0] = begin
children[j][1] = children[j][0] + duration
begin = children[j][1]
children[nbChildren-1][0] = begin
children[nbChildren-1][1] = prevEnd
for child in children:
bucket.append((child[0],child[1],child[2]))
children = []
prevEnd = ref_ann[i][1]
begin = ref_ann[i][0]
children.append([begin, end, ref_ann[i][2]])
#print('bucket');print(bucket)
return bucket
def get_child_tiers_for(self, id_tier):
"""Give all child tiers for a tier.
:param str id_tier: Name of the tier.
:returns: List of all children
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier]
return [m for m in self.tiers if 'PARENT_REF' in self.tiers[m][2] and
self.tiers[m][2]['PARENT_REF'] == id_tier]
def get_full_time_interval(self):
"""Give the full time interval of the file. Note that the real interval
can be longer because the sound file attached can be longer.
:returns: Tuple of the form: ``(min_time, max_time)``.
"""
return (0, 0) if not self.timeslots else\
(min(v for v in self.timeslots.values() if v is not None),
max(v for v in self.timeslots.values() if v is not None))
def get_gaps_and_overlaps(self, tier1, tier2, maxlen=-1):
"""Give gaps and overlaps. The return types are shown in the table
below. The string will be of the format: ``id_tiername_tiername``.
.. note:: There is also a faster method: :func:`get_gaps_and_overlaps2`
For example when a gap occurs between tier1 and tier2 and they are
called ``speakerA`` and ``speakerB`` the annotation value of that gap
will be ``G12_speakerA_speakerB``.
| The gaps and overlaps are calculated using Heldner and Edlunds
method found in:
| *Heldner, M., & Edlund, J. (2010). Pauses, gaps and overlaps in
conversations. Journal of Phonetics, 38(4), 555–568.
doi:10.1016/j.wocn.2010.08.002*
+-----+---------------------------------------------+
| id | Description |
+=====+=============================================+
| O12 | Overlap from tier1 to tier2 |
+-----+---------------------------------------------+
| O21 | Overlap from tier2 to tier1 |
+-----+---------------------------------------------+
| G12 | Between speaker gap from tier1 to tier2 |
+-----+---------------------------------------------+
| G21 | Between speaker gap from tier2 to tier1 |
+-----+---------------------------------------------+
| W12 | Within speaker overlap from tier2 in tier1 |
+-----+---------------------------------------------+
| W21 | Within speaker overlap from tier1 in tier2 |
+-----+---------------------------------------------+
| P1 | Pause for tier1 |
+-----+---------------------------------------------+
| P2 | Pause for tier2 |
+-----+---------------------------------------------+
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:yields: Tuples of the form ``[(start, end, type)]``.
:raises KeyError: If a tier is non existent.
:raises IndexError: If no annotations are available in the tiers.
"""
spkr1anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]])
for a in self.tiers[tier1][0].values())
spkr2anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]])
for a in self.tiers[tier2][0].values())
line1 = []
def isin(x, lst):
return False if\
len([i for i in lst if i[0] <= x and i[1] >= x]) == 0 else True
minmax = (min(spkr1anns[0][0], spkr2anns[0][0]),
max(spkr1anns[-1][1], spkr2anns[-1][1]))
last = (1, minmax[0])
for ts in range(*minmax):
in1, in2 = isin(ts, spkr1anns), isin(ts, spkr2anns)
if in1 and in2: # Both speaking
if last[0] == 'B':
continue
ty = 'B'
elif in1: # Only 1 speaking
if last[0] == '1':
continue
ty = '1'
elif in2: # Only 2 speaking
if last[0] == '2':
continue
ty = '2'
else: # None speaking
if last[0] == 'N':
continue
ty = 'N'
line1.append((last[0], last[1], ts))
last = (ty, ts)
line1.append((last[0], last[1], minmax[1]))
for i in range(len(line1)):
if line1[i][0] == 'N':
if i != 0 and i < len(line1) - 1 and\
line1[i-1][0] != line1[i+1][0]:
t = ('G12', tier1, tier2) if line1[i-1][0] == '1' else\
('G21', tier2, tier1)
if maxlen == -1 or abs(line1[i][1]-line1[i][2]) < maxlen:
yield (line1[i][1], line1[i][2]-1, '_'.join(t))
else:
t = ('P1', tier1) if line1[i-1][0] == '1' else\
('P2', tier2)
if maxlen == -1 or abs(line1[i][1]-line1[i][2]) < maxlen:
yield (line1[i][1], line1[i][2]-1, '_'.join(t))
elif line1[i][0] == 'B':
if i != 0 and i < len(line1) - 1 and\
line1[i-1][0] != line1[i+1][0]:
t = ('O12', tier1, tier2) if line1[i-1][0] == '1' else\
('O21', tier2, tier1)
yield (line1[i][1], line1[i][2]-1, '_'.join(t))
else:
t = ('W12', tier1, tier2) if line1[i-1][0] == '1' else\
('W21', tier2, tier1)
yield (line1[i][1], line1[i][2]-1, '_'.join(t))
def get_gaps_and_overlaps2(self, tier1, tier2, maxlen=-1):
"""Faster variant of :func:`get_gaps_and_overlaps`. Faster in this case
means almost 100 times faster...
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:yields: Tuples of the form ``[(start, end, type)]``.
:raises KeyError: If a tier is non existent.
"""
ad = sorted(((a, i+1) for i, t in enumerate([tier1, tier2]) for a in
self.get_annotation_data_for_tier(t)), reverse=True)
if ad:
last = (lambda x: (x[0][0], x[0][1], x[1]))(ad.pop())
def thr(x, y):
return maxlen == -1 or abs(x-y) < maxlen
while ad:
(begin, end, _), current = ad.pop()
if last[2] == current and thr(begin, last[1]):
yield (last[1], begin, 'P{}'.format(current))
elif last[0] < begin and last[1] > end:
yield (begin, end, 'W{}{}'.format(last[2], current))
continue
elif last[1] > begin:
yield (begin, last[1], 'O{}{}'.format(last[2], current))
elif last[1] < begin and thr(begin, last[1]):
yield (last[1], begin, 'G{}{}'.format(last[2], current))
last = (begin, end, current)
def get_controlled_vocabulary_names(self):
"""Gives all the controlled vocabulary names"""
return self.controlled_vocabularies.keys()
def get_cv_entries(self, cv_id):
"""Gives all the controlled vocabulary entries names.
:param str cv_id: Name of the controlled vocabulary.
:throws KeyError: If there is no controlled vocabulary with that id.
"""
return self.controlled_vocabularies[cv_id][1]
def get_cv_descriptions(self, cv_id):
"""Gives all the controlled vocabulary descriptions.
:param str cv_id: Name of the controlled vocabulary.
:throws KeyError: If there is no controlled vocabulary with that id.
"""
return self.controlled_vocabularies[cv_id][0]
def get_external_ref(self, eid):
"""Give the external reference matching the id.
:param str eid: Name of the external reference.
:throws KeyError: If there is no external reference with that id.
"""
return self.external_refs[eid]
def get_external_ref_names(self):
"""Gives all the external reference names."""
return self.external_refs.keys()
def get_lexicon_ref(self, reid):
"""Gives the lexicon reference.
:param str reid: Lexicon reference id.
:throws KeyError: If there is no lexicon reference matching the id.
"""
return self.lexicon_refs[reid]
def get_lexicon_ref_names(self):
"""Gives all the lexicon reference names."""
return self.lexicon_refs.keys()
def get_languages(self):
"""Gives all the languages in the format:
``{lang_id -> (lang_def, lang_label)}``
"""
return self.languages
def get_licenses(self):
"""Gives all the licenses in the format: ``[(name, url)]``"""
return self.licenses
def get_linguistic_type_names(self):
"""Give a list of available linguistic types.
:returns: List of linguistic type names.
"""
return self.linguistic_types.keys()
def get_linked_files(self):
"""Give all linked files."""
return self.media_descriptors
def get_locales(self):
"""Gives all the locales in the format: ``{language_code ->
(country_code, variant)}``
"""
return self.locales
def get_parameters_for_linguistic_type(self, lingtype):
"""Give the parameter dictionary, this is usable in
:func:`add_linguistic_type`.
:param str lingtype: Name of the linguistic type.
:raises KeyError: If the linguistic type doesn't exist.
"""
return self.linguistic_types[lingtype]
def get_parameters_for_tier(self, id_tier):
"""Give the parameter dictionary, this is useable in :func:`add_tier`.
:param str id_tier: Name of the tier.
:returns: Dictionary of parameters.
:raises KeyError: If the tier is non existent.
"""
return self.tiers[id_tier][2]
def get_properties(self):
"""Gives all the properties in the format: ``[(key, value)]``"""
return self.properties
def get_ref_annotation_at_time(self, tier, time):
"""Give the ref annotations at the given time of the form
``[(start, end, value, refvalue)]``
:param str tier: Name of the tier.
:param int time: Time of the annotation of the parent.
:returns: List of annotations at that time.
:raises KeyError: If the tier is non existent.
"""
bucket = []
for aid, (ref, value, _, _) in self.tiers[tier][1].items():
begin, end, rvalue, _ = self.tiers[self.annotations[ref]][0][ref]
begin = self.timeslots[begin]
end = self.timeslots[end]
if begin <= time and end >= time:
bucket.append((begin, end, value, rvalue))
return bucket
def get_ref_annotation_data_after_time(self, id_tier, time):
"""Give the ref annotation after a time. If an annotation overlaps
with `ktime`` that annotation will be returned.
:param str id_tier: Name of the tier.
:param int time: Time to get the annotation after.
:returns: Annotation after that time in a list
:raises KeyError: If the tier is non existent.
"""
befores = self.get_ref_annotation_data_between_times(
id_tier, time, self.get_full_time_interval())
if befores:
return [min(befores, key=lambda x: x[0])]
else:
return []
def get_ref_annotation_data_before_time(self, id_tier, time):
"""Give the ref annotation before a time. If an annotation overlaps
with ``time`` that annotation will be returned.
:param str id_tier: Name of the tier.
:param int time: Time to get the annotation before.
:returns: Annotation before that time in a list
:raises KeyError: If the tier is non existent.
"""
befores = self.get_ref_annotation_data_between_times(id_tier, 0, time)
if befores:
return [max(befores, key=lambda x: x[0])]
else:
return []
def get_ref_annotation_data_between_times(self, id_tier, start, end):
"""Give the ref annotations between times of the form
``[(start, end, value, refvalue)]``
:param str tier: Name of the tier.
:param int start: End time of the annotation of the parent.
:param int end: Start time of the annotation of the parent.
:returns: List of annotations at that time.
:raises KeyError: If the tier is non existent.
"""
bucket = []