aboutsummaryrefslogtreecommitdiff
path: root/parse_srt.py
blob: acd72c0137fb6b1be7a1b838c60177487fdbe304 (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
from __future__ import annotations
import dataclasses
import enum
import itertools
import re
from typing import List


@dataclasses.dataclass
class Event:
    start: str | None = None
    end: str | None = None
    content: str | None = None


class SRT:
    def __init__(self):
        self.events: List[Event] = []

    @staticmethod
    def from_str(text: str) -> SRT:
        class ParseState(enum.Enum):
            COUNTER = enum.auto()
            TIMING = enum.auto()
            CONTENT = enum.auto()

        PARSE_STATES = itertools.cycle(iter(ParseState))
        TIMESTAMP_CAPTURE = r"(\d\d:\d\d:\d\d,\d\d\d)"
        TIMING_REGEX = rf"{TIMESTAMP_CAPTURE} --> {TIMESTAMP_CAPTURE}"

        srt = SRT()
        lines = text.split("\n")
        counter = 1
        state = next(PARSE_STATES)
        event = Event()
        for line_num, line in enumerate(lines, 1):
            if not line:
                match state:
                    case ParseState.CONTENT:
                        srt.events.append(event)
                        event = Event()
                        state = next(PARSE_STATES)
                    case ParseState.COUNTER:
                        pass
                    case _:
                        raise ParseError(f"Unexpected blank line (line {line_num})")
                continue
            match state:
                case ParseState.COUNTER:
                    if int(line) == counter:
                        counter += 1
                        state = next(PARSE_STATES)
                    else:
                        raise ParseError(
                            f"Invalid counter, expected {counter} (line {line_num})"
                        )
                case ParseState.TIMING:
                    match = re.fullmatch(TIMING_REGEX, line)
                    if match is None:
                        raise ParseError(f"Invalid timing info (line {line_num})")
                    event.start, event.end = match[1], match[2]
                    state = next(PARSE_STATES)
                case ParseState.CONTENT:
                    event.content = (
                        event.content if event.content is not None else ""
                    ) + f"{line}\n"
        return srt

    def __str__(self):
        result = ""
        for counter, event in enumerate(self.events, 1):
            result += f"{counter}\n"
            result += f"{event.start} --> {event.end}\n"
            result += f"{event.content}\n"
        return result


class ParseError(Exception):
    pass