"""SRT 条目解析与序列化:正文可多行或为空,保留原始毫秒时间戳。""" from __future__ import annotations import re from dataclasses import dataclass _TIMESTAMP = re.compile(r"^(\d{2,}:\d{2}:\d{2},\d{3})\s*-->\s*(\d{2,}:\d{2}:\d{2},\d{3})$") @dataclass(frozen=True) class Cue: """一个字幕条目;序号在输出时重排,时间戳与多行正文独立保存。""" start: str end: str text: str def parse_srt(text: str) -> list[Cue]: """解析合法 SRT,兼容 BOM、CRLF、多余空行、空 cue 和末尾无空行。 非空的坏条目明确报错,避免静默漏字幕;空文件返回空列表。 """ lines = text.lstrip("\ufeff").splitlines() entries = [] index = 0 while index < len(lines): if not lines[index].strip(): index += 1 continue if not lines[index].strip().isdigit() or index + 1 >= len(lines): raise ValueError(f"invalid SRT index at line {index + 1}") match = _TIMESTAMP.fullmatch(lines[index + 1].strip()) if match is None: raise ValueError(f"invalid SRT timestamp at line {index + 2}") index += 2 body = [] while index < len(lines) and lines[index].strip(): # 正文行不允许是时间戳行:出现即说明条目之间缺少空行分隔。 # 若不报错,下一条的序号与时间轴会被当成上一条正文吞掉, # 静默产出时间与文本错位的字幕(同“静默错位”类缺陷)。 if _TIMESTAMP.fullmatch(lines[index].strip()): raise ValueError( f"missing blank line before cue at line {index + 1}" ) body.append(lines[index]) index += 1 entries.append(Cue(match[1], match[2], "\n".join(body))) return entries def serialize_srt(entries: list[Cue]) -> str: """按条目输出连续序号,空正文仍保留该条目的时间轴。""" return "\n".join( f"{i}\n{cue.start} --> {cue.end}\n{cue.text}\n" for i, cue in enumerate(entries, 1) )