summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/webvtt/parsing/file-parsing/tools/parser.py
blob: b77e83de789ce6a7cc351c4de1894380a906e35e (plain)
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
"""
A direct translation of the webvtt file parsing algorithm.

See https://w3c.github.io/webvtt/#file-parsing for documentation
"""
import re
import string

SPACE_CHARACTERS = [' ', '\t', '\n', '\f', '\r']
SPACE_SPLIT_PATTERN = r"[{}]*".format(''.join(SPACE_CHARACTERS))
DIGITS = string.digits

class DictInit:
    def __init__(self, **dict):
        self.__dict__.update(dict)

class VTTCue(DictInit): pass
class VTTRegion(DictInit): pass
class Stylesheet(DictInit): pass

class W3CParser:
    input = None
    position = None

    def collect_characters(self, condition):
        result = ""
        while self.position < len(self.input) and condition(self.input[self.position]):
            result += self.input[self.position]
            self.position += 1
        return result

    def skip_whitespace(self):
        self.collect_characters(lambda c: c in SPACE_CHARACTERS)

    def parse_percentage_string(self, input):
        'parse a percentage string'

        # 1.
        input = input

        # 2.
        if not re.match(r'^\d+(\.\d+)?%$', input):
            return None

        # 3.
        percentage = float(input[:-1])

        # 4.
        if percentage < 0 or percentage > 100:
            return None

        # 5.
        return percentage

class VTTParser(W3CParser):
    def __init__(self, input):
        self.input = input
        self.position = 0
        self.seen_cue = False

        self.text_tracks = []
        self.stylesheets = []
        self.regions = []
        self.errors = []

    def parse(self):
        'WebVTT parser algorithm'

        # 1.
        self.input = self.input.replace('\0', '\ufffd').replace('\r\n', '\n').replace('\r', '\n')

        # 2.
        self.position = 0

        # 3.
        self.seen_cue = False

        # 4.
        if len(self.input) < 6:
            self.errors.append('input too small for webvtt')
            return

        # 5.
        if len(self.input) == 6 and self.input != 'WEBVTT':
            self.errors.append('invalid webvtt header')
            return

        # 6.
        if len(self.input) > 6:
            if not (self.input[0:6] == 'WEBVTT' and self.input[6] in ['\u0020', '\u0009', '\u000A']):
                self.errors.append('invalid webvtt header')
                return

        # 7.
        self.collect_characters(lambda c: c != '\n')

        # 8.
        if self.position >= len(self.input):
            return

        # 9.
        if self.input[self.position] == '\n':
            self.position += 1

        # 10.
        if self.position >= len(self.input):
            return

        # 11.
        if self.input[self.position] != '\n':
            self.collect_block(in_header = True)
        else:
            self.position += 1

        # 12.
        self.collect_characters(lambda c: c == '\n')

        # 13.
        self.regions = []

        # 14.
        while self.position < len(self.input):
            # 1.
            block = self.collect_block()

            # 2.
            if isinstance(block, VTTCue):
                self.text_tracks.append(block)

            # 3.
            elif isinstance(block, Stylesheet):
                self.stylesheets.append(block)

            # 4.
            elif isinstance(block, VTTRegion):
                self.regions.append(block)

            # 5.
            self.collect_characters(lambda c: c == '\n')

        # 15.
        return

    def collect_block(self, in_header = False):
        'collect a WebVTT block'

        # 1. (done by class)

        line_count = 0                    # 2.
        previous_position = self.position # 3.
        line = ""                         # 4.
        buffer = ""                       # 5.
        seen_eof = False                  # 6.
        seen_arrow = False                # 7.
        cue = None                        # 8.
        stylesheet = None                 # 9.
        region = None                     # 10.

        # 11.
        while True:
            # 1.
            line = self.collect_characters(lambda c: c != '\n')

            # 2.
            line_count += 1

            # 3.
            if self.position >= len(self.input):
                seen_eof = True
            else:
                self.position += 1

            # 4.
            if '-->' in line:
                # 1.
                if not in_header and (line_count == 1 or line_count == 2 and not seen_arrow):
                    # 1.
                    seen_arrow = True

                    # 2.
                    previous_position = self.position

                    # 3.
                    cue = VTTCue(
                        id = buffer,
                        pause_on_exit = False,
                        region = None,
                        writing_direction = 'horizontal',
                        snap_to_lines = True,
                        line = 'auto',
                        line_alignment = 'start alignment',
                        position = 'auto',
                        position_alignment = 'auto',
                        cue_size = 100,
                        text_alignment = 'center',
                        text = '',
                    )

                    # 4.
                    if not VTTCueParser(self, line, cue).collect_cue_timings_and_settings():
                        cue = None
                    else:
                        buffer = ''
                        self.seen_cue = True # DIFFERENCE

                else:
                    self.errors.append('invalid webvtt cue block')
                    self.position = previous_position
                    break

            # 5.
            elif line == '':
                break

            # 6.
            else:
                # 1.
                if not in_header and line_count == 2:
                    # 1.
                    if not self.seen_cue and re.match(r'^STYLE\s*$', buffer):
                        stylesheet = Stylesheet(
                            location = None,
                            parent = None,
                            owner_node = None,
                            owner_rule = None,
                            media = None,
                            title = None,
                            alternate = False,
                            origin_clean = True,
                            source = None,
                        )
                        buffer = ''
                    # 2.
                    elif not self.seen_cue and re.match(r'^REGION\s*$', buffer):
                        region = VTTRegion(
                            id = '',
                            width = 100,
                            lines = 3,
                            anchor_point = (0, 100),
                            viewport_anchor_point = (0, 100),
                            scroll_value = None,
                        )
                        buffer = ''

                # 2.
                if buffer != '':
                    buffer += '\n'

                # 3.
                buffer += line

                # 4.
                previous_position = self.position

            # 7.
            if seen_eof:
                break

        # 12.
        if cue is not None:
            cue.text = buffer
            return cue

        # 13.
        elif stylesheet is not None:
            stylesheet.source = buffer
            return stylesheet

        # 14.
        elif region is not None:
            self.collect_region_settings(region, buffer)
            return region

        # 15.
        return None

    def collect_region_settings(self, region, input):
        'collect WebVTT region settings'

        # 1.
        settings = re.split(SPACE_SPLIT_PATTERN, input)

        # 2.
        for setting in settings:
            # 1.
            if ':' not in setting:
                continue

            index = setting.index(':')
            if index in [0, len(setting) - 1]:
                continue

            # 2.
            name = setting[:index]

            # 3.
            value = setting[index + 1:]

            # 4.
            if name == "id":
                region.id = value

            elif name == "width":
                percentage = self.parse_percentage_string(value)
                if percentage is not None:
                    region.width = percentage

            elif name == "lines":
                # 1.
                if not re.match(r'^\d+$', value):
                    continue

                # 2.
                number = int(value)

                # 3.
                region.lines = number

            elif name == "regionanchor":
                # 1.
                if ',' not in value:
                    continue

                #. 2.
                index = value.index(',')
                anchorX = value[:index]

                # 3.
                anchorY = value[index + 1:]

                # 4.
                percentageX = self.parse_percentage_string(anchorX)
                percentageY = self.parse_percentage_string(anchorY)
                if None in [percentageX, percentageY]:
                    continue

                # 5.
                region.anchor_point = (percentageX, percentageY)

            elif name == "viewportanchor":
                # 1.
                if ',' not in value:
                    continue

                #. 2.
                index = value.index(',')
                viewportanchorX = value[:index]

                # 3.
                viewportanchorY = value[index + 1:]

                # 4.
                percentageX = self.parse_percentage_string(viewportanchorX)
                percentageY = self.parse_percentage_string(viewportanchorY)
                if None in [percentageX, percentageY]:
                    continue

                # 5.
                region.viewport_anchor_point = (percentageX, percentageY)

            elif name == "scroll":
                # 1.
                if value == "up":
                    region.scroll_value = "up"

            # 5.
            continue


class VTTCueParser(W3CParser):
    def __init__(self, parent, input, cue):
        self.parent = parent
        self.errors = self.parent.errors
        self.input = input
        self.position = 0
        self.cue = cue

    def collect_cue_timings_and_settings(self):
        'collect WebVTT cue timings and settings'

        # 1. (handled by class)

        # 2.
        self.position = 0

        # 3.
        self.skip_whitespace()

        # 4.
        timestamp = self.collect_timestamp()
        if timestamp is None:
            self.errors.append('invalid start time for VTTCue')
            return False
        self.cue.start_time = timestamp

        # 5.
        self.skip_whitespace()

        # 6.
        if self.input[self.position] != '-':
            return False
        self.position += 1

        # 7.
        if self.input[self.position] != '-':
            return False
        self.position += 1

        # 8.
        if self.input[self.position] != '>':
            return False
        self.position += 1

        # 9.
        self.skip_whitespace()

        # 10.
        timestamp = self.collect_timestamp()
        if timestamp is None:
            self.errors.append('invalid end time for VTTCue')
            return False
        self.cue.end_time = timestamp

        # 11.
        remainder = self.input[self.position:]

        # 12.
        self.parse_settings(remainder)

        # Extra
        return True

    def parse_settings(self, input):
        'parse the WebVTT cue settings'

        # 1.

        settings = re.split(SPACE_SPLIT_PATTERN, input)

        # 2.
        for setting in settings:
            # 1.
            if ':' not in setting:
                continue

            index = setting.index(':')
            if index in [0, len(setting) - 1]:
                continue

            # 2.
            name = setting[:index]

            # 3.
            value = setting[index + 1:]

            # 4.
            if name == 'region':
                # 1.
                last_regions = (region for region in reversed(self.parent.regions) if region.id == value)
                self.cue.region = next(last_regions, None)

            elif name == 'vertical':
                # 1. and 2.
                if value in ['rl', 'lr']:
                    self.cue.writing_direction = value

            elif name == 'line':
                # 1.
                if ',' in value:
                    index = value.index(',')
                    linepos = value[:index]
                    linealign = value[index + 1:]

                # 2.
                else:
                    linepos = value
                    linealign = None

                # 3.
                if not re.search(r'\d', linepos):
                    continue

                # 4.
                if linepos[-1] == '%':
                    number = self.parse_percentage_string(linepos)
                    if number is None:
                        continue
                else:
                    # 1.
                    if not re.match(r'^[-\.\d]*$', linepos):
                        continue

                    # 2.
                    if '-' in linepos[1:]:
                        continue

                    # 3.
                    if linepos.count('.') > 1:
                        continue

                    # 4.
                    if '.' in linepos:
                        if not re.search(r'\d\.\d', linepos):
                            continue

                    # 5.
                    number = float(linepos)

                # 5.
                if linealign == "start":
                    self.cue.line_alignment = 'start'

                # 6.
                elif linealign == "center":
                    self.cue.line_alignment = 'center'

                # 7.
                elif linealign == "end":
                    self.cue.line_alignment = 'end'

                # 8.
                elif linealign != None:
                    continue

                # 9.
                self.cue.line = number

                # 10.
                if linepos[-1] == '%':
                    self.cue.snap_to_lines = False
                else:
                    self.cue.snap_to_lines = True

            elif name == 'position':
                # 1.
                if ',' in value:
                    index = value.index(',')
                    colpos = value[:index]
                    colalign = value[index + 1:]

                # 2.
                else:
                    colpos = value
                    colalign = None

                # 3.
                number = self.parse_percentage_string(colpos)
                if number is None:
                    continue

                # 4.
                if colalign == "line-left":
                    self.cue.line_alignment = 'line-left'

                # 5.
                elif colalign == "center":
                    self.cue.line_alignment = 'center'

                # 6.
                elif colalign == "line-right":
                    self.cue.line_alignment = 'line-right'

                # 7.
                elif colalign != None:
                    continue

                # 8.
                self.cue.position = number

            elif name == 'size':
                # 1.
                number = self.parse_percentage_string(value)
                if number is None:
                    continue

                # 2.
                self.cue.cue_size = number

            elif name == 'align':
                # 1.
                if value == 'start':
                    self.cue.text_alignment = 'start'

                # 2.
                if value == 'center':
                    self.cue.text_alignment = 'center'

                # 3.
                if value == 'end':
                    self.cue.text_alignment = 'end'

                # 4.
                if value == 'left':
                    self.cue.text_alignment = 'left'

                # 5.
                if value == 'right':
                    self.cue.text_alignment = 'right'

            # 5.
            continue

    def collect_timestamp(self):
        'collect a WebVTT timestamp'

        # 1. (handled by class)

        # 2.
        most_significant_units = 'minutes'

        # 3.
        if self.position >= len(self.input):
            return None

        # 4.
        if self.input[self.position] not in DIGITS:
            return None

        # 5.
        string = self.collect_characters(lambda c: c in DIGITS)

        # 6.
        value_1 = int(string)

        # 7.
        if len(string) != 2 or value_1 > 59:
            most_significant_units = 'hours'

        # 8.
        if self.position >= len(self.input) or self.input[self.position] != ':':
            return None
        self.position += 1

        # 9.
        string = self.collect_characters(lambda c: c in DIGITS)

        # 10.
        if len(string) != 2:
            return None

        # 11.
        value_2 = int(string)

        # 12.
        if most_significant_units == 'hours' or self.position < len(self.input) and self.input[self.position] == ':':
            # 1.
            if self.position >= len(self.input) or self.input[self.position] != ':':
                return None
            self.position += 1

            # 2.
            string = self.collect_characters(lambda c: c in DIGITS)

            # 3.
            if len(string) != 2:
                return None

            # 4.
            value_3 = int(string)
        else:
            value_3 = value_2
            value_2 = value_1
            value_1 = 0

        # 13.
        if self.position >= len(self.input) or self.input[self.position] != '.':
            return None
        self.position += 1

        # 14.
        string = self.collect_characters(lambda c: c in DIGITS)

        # 15.
        if len(string) != 3:
            return None

        # 16.
        value_4 = int(string)

        # 17.
        if value_2 >= 59 or value_3 >= 59:
            return None

        # 18.
        result = value_1 * 60 * 60 + value_2 * 60 + value_3 + value_4 / 1000

        # 19.
        return result


def main(argv):
    files = [open(path, 'r') for path in argv[1:]]

    try:
        for file in files:
            parser = VTTParser(file.read())
            parser.parse()

            print("Results: {}".format(file))
            print("  Cues: {}".format(parser.text_tracks))
            print("  StyleSheets: {}".format(parser.stylesheets))
            print("  Regions: {}".format(parser.regions))
            print("  Errors: {}".format(parser.errors))
    finally:
        for file in files:
            file.close()

if __name__ == '__main__':
    import sys
    main(sys.argv);