File size: 5,822 Bytes
b165696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Parse VTT and SRT subtitle files into timed segments.

Supports:
  - WebVTT (.vtt)  — primary format from YouTube via yt-dlp
  - SubRip  (.srt) — fallback format
"""

from __future__ import annotations

import logging
import re
from pathlib import Path

logger = logging.getLogger(__name__)

_SRT_TIMESTAMP_RE = re.compile(
    r"(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})[,.](\d{3})"
)
_VTT_TIMESTAMP_RE = re.compile(
    r"(\d{1,2}):(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{1,2}):(\d{2}):(\d{2})\.(\d{3})"
)
_VTT_SHORTTS_RE = re.compile(
    r"(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{2}):(\d{2})\.(\d{3})"
)
_HTML_TAG_RE = re.compile(r"<[^>]+>")
_CUE_META_RE = re.compile(r"^(align|line|position|size):", re.IGNORECASE)


def _ts_to_seconds(h: str, m: str, s: str, ms: str) -> float:
    return int(h) * 3600 + int(m) * 60 + int(s) + int(ms) / 1000


class SubtitleParser:
    def parse(self, path: str) -> list[dict]:
        """
        Auto-detect format and parse subtitle file.

        Returns
        -------
        list of { "start": float, "end": float, "text": str }
        """
        path = Path(path)
        if not path.exists():
            raise FileNotFoundError(f"Subtitle file not found: {path}")

        content = path.read_text(encoding="utf-8", errors="replace")

        if path.suffix.lower() == ".vtt" or content.strip().startswith("WEBVTT"):
            return self._parse_vtt(content)
        return self._parse_srt(content)

    # ------------------------------------------------------------------
    # VTT
    # ------------------------------------------------------------------

    def _parse_vtt(self, content: str) -> list[dict]:
        segments = []
        lines = content.splitlines()
        i = 0

        while i < len(lines):
            line = lines[i].strip()

            # Try full HH:MM:SS.mmm --> HH:MM:SS.mmm
            m = _VTT_TIMESTAMP_RE.search(line)
            if m:
                start = _ts_to_seconds(m.group(1), m.group(2), m.group(3), m.group(4))
                end = _ts_to_seconds(m.group(5), m.group(6), m.group(7), m.group(8))
                i += 1
                text_lines = []
                while i < len(lines) and lines[i].strip():
                    raw = lines[i].strip()
                    if not _CUE_META_RE.match(raw):
                        cleaned = _HTML_TAG_RE.sub("", raw).strip()
                        if cleaned:
                            text_lines.append(cleaned)
                    i += 1
                text = " ".join(text_lines).strip()
                if text:
                    segments.append({"start": start, "end": end, "text": text})
                continue

            # Try short MM:SS.mmm --> MM:SS.mmm
            m2 = _VTT_SHORTTS_RE.search(line)
            if m2:
                start = _ts_to_seconds("0", m2.group(1), m2.group(2), m2.group(3))
                end = _ts_to_seconds("0", m2.group(4), m2.group(5), m2.group(6))
                i += 1
                text_lines = []
                while i < len(lines) and lines[i].strip():
                    raw = lines[i].strip()
                    if not _CUE_META_RE.match(raw):
                        cleaned = _HTML_TAG_RE.sub("", raw).strip()
                        if cleaned:
                            text_lines.append(cleaned)
                    i += 1
                text = " ".join(text_lines).strip()
                if text:
                    segments.append({"start": start, "end": end, "text": text})
                continue

            i += 1

        logger.info("VTT parsed: %d segments", len(segments))
        return self._merge_overlapping(segments)

    # ------------------------------------------------------------------
    # SRT
    # ------------------------------------------------------------------

    def _parse_srt(self, content: str) -> list[dict]:
        segments = []
        blocks = re.split(r"\n\n+", content.strip())

        for block in blocks:
            lines = block.strip().splitlines()
            if len(lines) < 2:
                continue

            # Find timestamp line
            ts_line = None
            text_start = 0
            for idx, l in enumerate(lines):
                m = _SRT_TIMESTAMP_RE.search(l)
                if m:
                    ts_line = m
                    text_start = idx + 1
                    break

            if ts_line is None:
                continue

            start = _ts_to_seconds(
                ts_line.group(1), ts_line.group(2), ts_line.group(3), ts_line.group(4)
            )
            end = _ts_to_seconds(
                ts_line.group(5), ts_line.group(6), ts_line.group(7), ts_line.group(8)
            )

            text = " ".join(
                _HTML_TAG_RE.sub("", l).strip()
                for l in lines[text_start:]
                if l.strip()
            ).strip()

            if text:
                segments.append({"start": start, "end": end, "text": text})

        logger.info("SRT parsed: %d segments", len(segments))
        return self._merge_overlapping(segments)

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    def _merge_overlapping(self, segments: list[dict]) -> list[dict]:
        """Merge consecutive segments with identical text (YouTube often duplicates cues)."""
        if not segments:
            return []
        merged = [segments[0].copy()]
        for seg in segments[1:]:
            prev = merged[-1]
            if seg["text"] == prev["text"] and seg["start"] <= prev["end"] + 0.1:
                prev["end"] = max(prev["end"], seg["end"])
            else:
                merged.append(seg.copy())
        return merged