-
Notifications
You must be signed in to change notification settings - Fork 22
/
elements.py
1105 lines (781 loc) · 31.5 KB
/
elements.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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2020, Sandflow Consulting LLC
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''Process TTML elements'''
from __future__ import annotations
import logging
from fractions import Fraction
import typing
import ttconv.model as model
import ttconv.imsc.namespaces as xml_ns
import ttconv.imsc.attributes as imsc_attr
from ttconv.imsc.style_properties import StyleProperties
import ttconv.imsc.style_properties as imsc_styles
LOGGER = logging.getLogger(__name__)
class TTMLElement:
'''Static information about a TTML element
'''
class ParsingContext:
'''State information when parsing a TTML element'''
def __init__(self, ttml_class: TTMLElement, parent_ctx: typing.Optional[TTMLElement.ParsingContext] = None):
self.doc = parent_ctx.doc if parent_ctx is not None else model.Document()
self.style_context = parent_ctx.style_context if parent_ctx else imsc_styles.StyleParsingContext()
self.style_elements: typing.Dict[str, StyleElement] = parent_ctx.style_elements if parent_ctx else {}
self.temporal_context = parent_ctx.temporal_context if parent_ctx else imsc_attr.TemporalAttributeParsingContext()
self.ttml_class: TTMLElement = ttml_class
self.lang = None
self.space = None
self.time_container: imsc_attr.TimeContainer = imsc_attr.TimeContainer.par
self.explicit_begin = None
self.implicit_begin = None
self.desired_begin = None
self.explicit_end = None
self.implicit_end = None
self.desired_end = None
self.explicit_dur = None
def process_lang_attribute(self, parent_ctx: TTMLElement.ParsingContext, xml_elem):
'''Processes the xml:lang attribute, including inheritance from the parent
'''
self.lang = imsc_attr.XMLLangAttribute.extract(xml_elem) or parent_ctx.lang
def process_space_attribute(self, parent_ctx: TTMLElement.ParsingContext, xml_elem):
'''Processes the xml:space attribute, including inheritance from the parent
'''
self.space = imsc_attr.XMLSpaceAttribute.extract(xml_elem) or parent_ctx.space
@staticmethod
def is_instance(xml_elem) -> bool:
'''Returns true if the XML element `xml_elem` is an instance of the class
'''
raise NotImplementedError
@staticmethod
def from_xml(parent_ctx, xml_elem):
'''Returns a parsing context for the TTML element represented by the XML element `xml_elem` and
given the parent context `parent_ctx`
'''
raise NotImplementedError
class TTElement(TTMLElement):
'''Processes the TTML <tt> element
'''
class ParsingContext(TTMLElement.ParsingContext):
'''State information when parsing a <tt> element'''
qn = f"{{{xml_ns.TTML}}}tt"
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == TTElement.qn
@staticmethod
def from_xml(_parent_ctx: typing.Optional[TTMLElement.ParsingContext], xml_elem) -> TTElement.ParsingContext:
'''`_parent_ctx` is ignored and can be set to `None`
'''
tt_ctx = TTElement.ParsingContext(TTElement)
tt_ctx.space = imsc_attr.XMLSpaceAttribute.extract(xml_elem) or model.WhiteSpaceHandling.DEFAULT
lang_attr = imsc_attr.XMLLangAttribute.extract(xml_elem)
if lang_attr is None:
LOGGER.warning("xml:lang not specified on tt")
lang_attr = ""
tt_ctx.lang = lang_attr
tt_ctx.doc.set_lang(tt_ctx.lang)
tt_ctx.doc.set_cell_resolution(
imsc_attr.CellResolutionAttribute.extract(xml_elem)
)
px_resolution = imsc_attr.ExtentAttribute.extract(xml_elem)
if px_resolution is not None:
tt_ctx.doc.set_px_resolution(px_resolution)
active_area = imsc_attr.ActiveAreaAttribute.extract(xml_elem)
if active_area is not None:
tt_ctx.doc.set_active_area(active_area)
tt_ctx.temporal_context.frame_rate = imsc_attr.FrameRateAttribute.extract(xml_elem)
tt_ctx.temporal_context.tick_rate = imsc_attr.TickRateAttribute.extract(xml_elem)
# process children elements elements
has_body = False
has_head = False
for child_element in xml_elem:
if BodyElement.is_instance(child_element):
if not has_body:
has_body = True
body_element = ContentElement.from_xml(tt_ctx, child_element)
tt_ctx.doc.set_body(body_element.model_element if body_element is not None else None)
else:
LOGGER.error("More than one body element present")
elif HeadElement.is_instance(child_element):
if not has_head:
has_head = True
HeadElement.from_xml(tt_ctx, child_element)
else:
LOGGER.error("More than one head element present")
return tt_ctx
class HeadElement(TTMLElement):
'''Processes the TTML <head> element
'''
class ParsingContext(TTMLElement.ParsingContext):
'''Maintains state when parsing a <head> element
'''
qn = f"{{{xml_ns.TTML}}}head"
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == HeadElement.qn
@staticmethod
def from_xml(parent_ctx: TTMLElement.ParsingContext, xml_elem) -> HeadElement.ParsingContext:
head_ctx = HeadElement.ParsingContext(HeadElement, parent_ctx)
head_ctx.process_lang_attribute(parent_ctx, xml_elem)
head_ctx.process_space_attribute(parent_ctx, xml_elem)
# process children elements
has_layout = False
has_styling = False
for child_element in xml_elem:
if LayoutElement.is_instance(child_element):
if not has_layout:
has_layout = True
LayoutElement.from_xml(
head_ctx,
child_element
)
else:
LOGGER.error("Multiple layout elements")
elif StylingElement.is_instance(child_element):
if not has_styling:
has_styling = True
StylingElement.from_xml(
head_ctx,
child_element
)
else:
LOGGER.error("Multiple styling elements")
return head_ctx
class LayoutElement(TTMLElement):
'''Process the TTML <layout> element
'''
class ParsingContext(TTMLElement.ParsingContext):
'''Maintains state when parsing a <layout> element
'''
qn = f"{{{xml_ns.TTML}}}layout"
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == LayoutElement.qn
@staticmethod
def from_xml(parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[LayoutElement.ParsingContext]:
layout_ctx = LayoutElement.ParsingContext(LayoutElement, parent_ctx)
layout_ctx.process_lang_attribute(parent_ctx, xml_elem)
layout_ctx.process_space_attribute(parent_ctx, xml_elem)
for child_element in xml_elem:
if RegionElement.is_instance(child_element):
r = RegionElement.from_xml(layout_ctx, child_element)
if r is not None:
layout_ctx.doc.put_region(r.model_element)
else:
LOGGER.warning("Unexpected child of layout element")
return layout_ctx
class StylingElement(TTMLElement):
'''Process the TTML <styling> element
'''
class ParsingContext(TTMLElement.ParsingContext):
'''Maintains state when parsing a <styling> element
'''
def merge_chained_styles(self, style_element: StyleElement):
'''Flattens Chained Referential Styling of the target `style_element` by specifying
the style properties of the referenced style elements directly in the target element
'''
while len(style_element.style_refs) > 0:
style_ref = style_element.style_refs.pop()
if style_ref not in self.style_elements:
LOGGER.error("Style id not present")
continue
self.merge_chained_styles(self.style_elements[style_ref])
for style_prop, value in self.style_elements[style_ref].styles.items():
style_element.styles.setdefault(style_prop, value)
qn = f"{{{xml_ns.TTML}}}styling"
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == StylingElement.qn
@staticmethod
def from_xml(parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[StylingElement.ParsingContext]:
styling_ctx = StylingElement.ParsingContext(StylingElement, parent_ctx)
for child_xml_elem in xml_elem:
if InitialElement.is_instance(child_xml_elem):
InitialElement.from_xml(styling_ctx, child_xml_elem)
elif StyleElement.is_instance(child_xml_elem):
style_element = StyleElement.from_xml(styling_ctx, child_xml_elem)
if style_element is None:
continue
if style_element.id in styling_ctx.style_elements:
LOGGER.error("Duplicate style id")
continue
style_element.style_elements[style_element.id] = style_element
# merge style elements
for style_element in parent_ctx.style_elements.values():
styling_ctx.merge_chained_styles(style_element)
return styling_ctx
class StyleElement(TTMLElement):
'''Process the TTML <style> element
'''
class ParsingContext(TTMLElement.ParsingContext):
'''Maintains state when parsing the element
'''
def __init__(self, parent_ctx: typing.Optional[TTMLElement.ParsingContext] = None):
self.styles: typing.Dict[imsc_styles.StyleProperty, typing.Any] = dict()
self.style_refs: typing.List[str] = None
self.id: str = None
super().__init__(StyleElement, parent_ctx)
qn = f"{{{xml_ns.TTML}}}style"
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == StyleElement.qn
@staticmethod
def from_xml(parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[StyleElement.ParsingContext]:
style_ctx = StyleElement.ParsingContext(parent_ctx)
for attr in xml_elem.attrib:
prop = StyleProperties.BY_QNAME.get(attr)
if not prop:
continue
try:
style_ctx.styles[prop.model_prop] = prop.extract(style_ctx.style_context, xml_elem.attrib.get(attr))
except ValueError:
LOGGER.error("Error reading style property: %s", prop.__name__)
if issubclass(parent_ctx.ttml_class, RegionElement):
# nested styling
# merge style properties with the parent Region element
for style_prop, value in style_ctx.styles.items():
region_style = parent_ctx.model_element.get_style(style_prop)
if region_style is None:
parent_ctx.model_element.set_style(style_prop, value)
return None
# styling > style element
style_ctx.style_refs = imsc_attr.StyleAttribute.extract(xml_elem)
style_ctx.id = imsc_attr.XMLIDAttribute.extract(xml_elem)
if style_ctx.id is None:
LOGGER.error("A style element must have an id")
return None
return style_ctx
class InitialElement(TTMLElement):
'''Process the TTML <initial> element
'''
class ParsingContext(TTMLElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}initial"
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == InitialElement.qn
@staticmethod
def from_xml(parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[InitialElement.ParsingContext]:
initial_ctx = InitialElement.ParsingContext(InitialElement, parent_ctx)
for attr in xml_elem.attrib:
prop = StyleProperties.BY_QNAME.get(attr)
if not prop:
continue
try:
initial_ctx.doc.put_initial_value(
prop.model_prop,
prop.extract(initial_ctx.style_context, xml_elem.attrib.get(attr))
)
except (ValueError, TypeError):
LOGGER.error("Error reading style property: %s", prop.__name__)
return initial_ctx
#
# process content elements
#
class ContentElement(TTMLElement):
'''TTML content elements: body, div, p, span, br
'''
class ParsingContext(TTMLElement.ParsingContext):
'''Maintains state when parsing the element
'''
def __init__(
self,
ttml_class: typing.Optional[TTMLElement],
parent_ctx: TTMLElement.ParsingContext,
model_element: typing.Optional[model.ContentElement] = None
):
self.children: typing.List[model.ContentElement] = []
self.model_element: model.ContentElement = model_element
super().__init__(ttml_class, parent_ctx)
def process_region_property(self, xml_elem):
'''Reads and processes the `region` attribute
'''
rid = xml_elem.attrib.get('region')
if rid is None:
return
r = self.doc.get_region(rid)
if r is not None:
self.model_element.set_region(r)
else:
LOGGER.warning("Element references unknown region")
def process_referential_styling(self, xml_elem):
'''Processes referential styling
'''
for style_ref in imsc_attr.StyleAttribute.extract(xml_elem):
style_element = self.style_elements.get(style_ref)
if style_element is None:
LOGGER.error("non existant style id")
continue
for model_prop, value in style_element.styles.items():
if self.model_element.get_style(model_prop) is None:
self.model_element.set_style(model_prop, value)
def process_specified_styling(self, xml_elem):
'''Processes specified styling
'''
for attr in xml_elem.attrib:
prop = StyleProperties.BY_QNAME.get(attr)
if prop is None:
continue
try:
self.model_element.set_style(
prop.model_prop,
prop.extract(self.style_context, xml_elem.attrib.get(attr))
)
except ValueError:
LOGGER.error("Error reading style property: %s", prop.__name__)
def process_set_style_properties(self, parent_ctx: TTMLElement, xml_elem):
'''Processes style properties on `<set>` element
'''
if parent_ctx.model_element is None:
LOGGER.error("Set parent does not exist")
return
if not issubclass(parent_ctx.ttml_class, ContentElement):
LOGGER.error("Set parent is not a content element")
return
for attr in xml_elem.attrib:
prop = StyleProperties.BY_QNAME.get(attr)
if prop is not None:
try:
parent_ctx.model_element.add_animation_step(
model.DiscreteAnimationStep(
prop.model_prop,
self.desired_begin,
self.desired_end,
prop.extract(self.style_context, xml_elem.attrib.get(attr))
)
)
break
except ValueError:
LOGGER.error("Error reading style property: %s", prop.__name__)
def process_lang_attribute(self, parent_ctx: TTMLElement.ParsingContext, xml_elem):
super().process_lang_attribute(parent_ctx, xml_elem)
self.model_element.set_lang(self.lang)
def process_space_attribute(self, parent_ctx: TTMLElement.ParsingContext, xml_elem):
super().process_space_attribute(parent_ctx, xml_elem)
self.model_element.set_space(self.space)
# pylint: disable=too-many-branches
def process(self, parent_ctx: TTMLElement.ParsingContext, xml_elem):
'''Generic processing applicable to TTML elements rooted in `region` and `body` elements
'''
self.process_lang_attribute(parent_ctx, xml_elem)
self.process_space_attribute(parent_ctx, xml_elem)
if self.ttml_class.has_region:
self.process_region_property(xml_elem)
if issubclass(self.ttml_class, SetElement):
self.process_set_style_properties(parent_ctx, xml_elem)
elif self.ttml_class.has_styles:
self.process_specified_styling(xml_elem)
# temporal processing
self.time_container = imsc_attr.TimeContainerAttribute.extract(xml_elem)
self.explicit_begin = imsc_attr.BeginAttribute.extract(self.temporal_context, xml_elem)
self.explicit_dur = imsc_attr.DurAttribute.extract(self.temporal_context, xml_elem)
self.explicit_end = imsc_attr.EndAttribute.extract(self.temporal_context, xml_elem)
if parent_ctx.time_container.is_par():
self.implicit_begin = Fraction(0)
else:
self.implicit_begin = parent_ctx.implicit_end - parent_ctx.desired_begin
self.desired_begin = self.implicit_begin + (self.explicit_begin if self.explicit_begin is not None else Fraction(0))
if issubclass(self.ttml_class, (BrElement, RegionElement, SetElement)) and \
parent_ctx.time_container.is_par():
self.implicit_end = None
else:
self.implicit_end = self.desired_begin
# process children elements
if self.ttml_class.is_mixed and xml_elem.text is not None and self.time_container.is_par():
self.children.append(ContentElement.make_anonymous_span(self.doc, self.model_element, xml_elem.text))
self.implicit_end = None
for child_xml_element in xml_elem:
if issubclass(self.ttml_class, RegionElement) and StyleElement.is_instance(child_xml_element):
StyleElement.from_xml(self, child_xml_element)
continue
child_element = ContentElement.from_xml(self, child_xml_element)
if child_element is not None:
if self.time_container.is_seq():
self.implicit_end = child_element.desired_end
else:
if self.implicit_end is not None and child_element.desired_end is not None:
self.implicit_end = max(self.implicit_end, child_element.desired_end)
else:
self.implicit_end = None
# skip child if it has no temporal extent
if not issubclass(child_element.ttml_class, SetElement) or \
child_element.desired_begin is None or \
child_element.desired_end is None and \
child_element.desired_begin != child_element.desired_end:
self.children.append(child_element.model_element)
# process tail text node
if self.ttml_class.is_mixed and child_xml_element.tail is not None and self.time_container.is_par():
self.children.append(
ContentElement.make_anonymous_span(
self.doc,
self.model_element,
child_xml_element.tail
)
)
self.implicit_end = None
if self.ttml_class.has_styles:
self.process_referential_styling(xml_elem)
try:
self.model_element.push_children(self.children)
except (ValueError, TypeError) as e:
LOGGER.error(str(e))
return
# temporal end processing
if self.explicit_end is not None and self.explicit_dur is not None:
self.desired_end = min(self.desired_begin + self.explicit_dur, self.implicit_begin + self.explicit_end)
self.desired_end = min(self.desired_begin + self.explicit_dur, self.implicit_begin + self.explicit_end)
elif self.explicit_end is None and self.explicit_dur is not None:
self.desired_end = self.desired_begin + self.explicit_dur
elif self.explicit_end is not None and self.explicit_dur is None:
self.desired_end = self.implicit_begin + self.explicit_end
else:
self.desired_end = self.implicit_end
if self.ttml_class.has_timing:
self.model_element.set_begin(self.desired_begin if self.desired_begin != 0 else None)
self.model_element.set_end(self.desired_end)
# pylint: enable=too-many-branches
@property
def has_timing(self):
'''`True` if the element supports temporal attributes
'''
raise NotImplementedError
@property
def has_region(self):
'''`True` if the element can reference a region
'''
raise NotImplementedError
@property
def has_styles(self):
'''`True` if the element can contain style properties
'''
raise NotImplementedError
@property
def is_mixed(self):
'''`True` if the element can contain text
'''
raise NotImplementedError
@property
def has_children(self):
'''`True` if the element can contain children elements
'''
raise NotImplementedError
@staticmethod
def make_anonymous_span(document, model_element, span_text):
'''Creates an anonymous span in the element `model_element` from the text contained in `span_text`
'''
if isinstance(model_element, model.Span):
return model.Text(document, span_text)
s = model.Span(document)
s.push_child(model.Text(document, span_text))
return s
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[ContentElement.ParsingContext]:
content_classes = [
BodyElement,
DivElement,
PElement,
SpanElement,
RubyElement,
RbElement,
RtElement,
RpElement,
RbcElement,
RtcElement,
BrElement,
SetElement,
RegionElement
]
for ttml_elem_class in content_classes:
if ttml_elem_class.is_instance(xml_elem):
return ttml_elem_class.from_xml(parent_ctx, xml_elem)
return None
# pylint: disable=too-many-branches
class RegionElement(ContentElement):
'''Process the TTML <region> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}region"
has_timing = True
has_region = False
has_styles = True
is_mixed = False
has_children = False
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == RegionElement.qn
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[RegionElement.ParsingContext]:
rid = imsc_attr.XMLIDAttribute.extract(xml_elem)
if rid is None:
LOGGER.error("All regions must have an id")
return None
region_ctx = RegionElement.ParsingContext(RegionElement, parent_ctx, model.Region(rid, parent_ctx.doc))
region_ctx.process(parent_ctx, xml_elem)
return region_ctx
class SetElement(ContentElement):
'''Process TTML <set> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}set"
has_region = False
has_styles = False
has_timing = True
is_mixed = False
has_children = False
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == DivElement.qn
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[SetElement.ParsingContext]:
set_ctx = SetElement.ParsingContext(SetElement, parent_ctx)
set_ctx.process(parent_ctx, xml_elem)
return set_ctx
class BodyElement(ContentElement):
'''Process TTML body element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}body"
has_region = True
has_styles = True
has_timing = True
is_mixed = False
has_children = True
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == BodyElement.qn
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[BodyElement.ParsingContext]:
body_ctx = BodyElement.ParsingContext(BodyElement, parent_ctx, model.Body(parent_ctx.doc))
body_ctx.process(parent_ctx, xml_elem)
return body_ctx
class DivElement(ContentElement):
'''Process TTML <div> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}div"
has_region = True
has_styles = True
has_timing = True
is_mixed = False
has_children = True
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == DivElement.qn
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[DivElement.ParsingContext]:
div_ctx = DivElement.ParsingContext(DivElement, parent_ctx, model.Div(parent_ctx.doc))
div_ctx.process(parent_ctx, xml_elem)
return div_ctx
class PElement(ContentElement):
'''Process TTML <p> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}p"
has_timing = True
has_region = True
has_styles = True
is_mixed = True
has_children = True
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == PElement.qn
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[PElement.ParsingContext]:
p_ctx = PElement.ParsingContext(PElement, parent_ctx, model.P(parent_ctx.doc))
p_ctx.process(parent_ctx, xml_elem)
return p_ctx
class SpanElement(ContentElement):
'''Process the TTML <span> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
qn = f"{{{xml_ns.TTML}}}span"
has_timing = True
has_region = True
has_styles = True
is_mixed = True
has_children = True
@staticmethod
def is_instance(xml_elem):
return xml_elem.tag == SpanElement.qn and SpanElement.get_ruby_attr(xml_elem) is None
@staticmethod
def get_ruby_attr(ttml_span):
'''extracts the value of the TTML `tts:ruby` attribute from the XML element `ttml_span`
'''
return ttml_span.get(f"{{{xml_ns.TTS}}}ruby")
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[SpanElement.ParsingContext]:
span_ctx = SpanElement.ParsingContext(SpanElement, parent_ctx, model.Span(parent_ctx.doc))
span_ctx.process(parent_ctx, xml_elem)
return span_ctx
class RubyElement(ContentElement):
'''Process the TTML <span tts:ruby="container"> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
ruby = "container"
has_timing = True
has_region = True
has_styles = True
is_mixed = False
has_children = True
@staticmethod
def is_instance(xml_elem):
return xml_elem.tag == SpanElement.qn and SpanElement.get_ruby_attr(xml_elem) == RubyElement.ruby
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[RubyElement.ParsingContext]:
ruby_ctx = RubyElement.ParsingContext(RubyElement, parent_ctx, model.Ruby(parent_ctx.doc))
ruby_ctx.process(parent_ctx, xml_elem)
return ruby_ctx
class RbElement(ContentElement):
'''Process the TTML <span tts:ruby="base"> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
ruby = "base"
has_timing = True
has_region = True
has_styles = True
is_mixed = True
has_children = True
@staticmethod
def is_instance(xml_elem):
return xml_elem.tag == SpanElement.qn and SpanElement.get_ruby_attr(xml_elem) == RbElement.ruby
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[RbElement.ParsingContext]:
rb_ctx = RbElement.ParsingContext(RbElement, parent_ctx, model.Rb(parent_ctx.doc))
rb_ctx.process(parent_ctx, xml_elem)
return rb_ctx
class RtElement(ContentElement):
'''Process the TTML <span tts:ruby="text"> element
'''
class ParsingContext(ContentElement.ParsingContext):
'''Maintains state when parsing the element
'''
ruby = "text"
has_timing = True
has_region = True
has_styles = True
is_mixed = True
has_children = True
@staticmethod
def is_instance(xml_elem) -> bool:
return xml_elem.tag == SpanElement.qn and SpanElement.get_ruby_attr(xml_elem) == RtElement.ruby
@classmethod
def from_xml(cls, parent_ctx: TTMLElement.ParsingContext, xml_elem) -> typing.Optional[RtElement.ParsingContext]:
rt_ctx = RtElement.ParsingContext(RtElement, parent_ctx, model.Rt(parent_ctx.doc))