fix: SRT 按 cue 解析并按 ID 回填译文,OCR 空帧分段与失败重试
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
"""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():
|
||||
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)
|
||||
)
|
||||
Reference in New Issue
Block a user