feat(subtitle): 内置字幕清洗(去绘图/注释/空/重复)并改为内嵌优先
- _clean_events 重建新的 SSAFile:pysubs2 的 remove() 按值比较会误删对白、
漏删绘图(实测 830 个绘图事件只删了计数、201 个残留、误删约 217 条对白)
- 过滤 is_comment / is_drawing / 空文本 / 完全相同的事件,再剥 {\\...} 标签
- 内嵌优先:有内嵌字幕(已有或已排队)时不再转换外挂字幕,并删除同集外挂 srt 副本
- 提取失败时记录 ffmpeg 退出码与 stderr 末行
This commit is contained in:
@@ -124,11 +124,16 @@ class MediaPipeline:
|
||||
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||||
|
||||
if self.args.mode != "clean-ads":
|
||||
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||||
should_extract_internal = (not has_ext_sub) or config.EXTRACT_INTERNAL_SUBS or self.args.extract_internal
|
||||
|
||||
if should_extract_internal and (not skip_heavy or self.args.extract_internal or self.args.mode == "extract-subs"):
|
||||
SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
internal_subs = 0
|
||||
if not skip_heavy or self.args.extract_internal or self.args.mode == "extract-subs":
|
||||
internal_subs = SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
elif SubtitleService.has_internal_srt(dest_dir, target_stem):
|
||||
# 完美文件名豁免时不做 ffprobe,但仍需识别"已有内嵌字幕"
|
||||
internal_subs = 1
|
||||
|
||||
# 🎯 内嵌字幕优先:只要有内嵌字幕(已有或已排队),就不再转换/整理外挂字幕
|
||||
if internal_subs == 0:
|
||||
RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||||
|
||||
if self.args.mode != "extract-subs" and not skip_heavy:
|
||||
MetadataService.scan_ads(f, self.task_mgr)
|
||||
|
||||
@@ -12,28 +12,92 @@ from core.utils import FFprobeUtil
|
||||
|
||||
class SubtitleService:
|
||||
|
||||
@staticmethod
|
||||
def _clean_events(subs: pysubs2.SSAFile) -> pysubs2.SSAFile:
|
||||
"""返回清洗后的新 SSAFile:丢掉注释、矢量绘图、空文本与完全重复的事件。
|
||||
|
||||
注意:不要用 SSAFile.remove() 原地删除——pysubs2 按值比较,会把
|
||||
与目标"相等"的另一条事件删掉,导致误删对白、漏删绘图。重建更安全。
|
||||
ASS 里的 \\p1 绘图(logo、特效字、遮罩)转成 SRT 后会变成
|
||||
'm 463 33 l 468 -29 ...' 这类路径文本;多层事件还会产生重复行。
|
||||
"""
|
||||
cleaned = pysubs2.SSAFile()
|
||||
cleaned.info = subs.info
|
||||
cleaned.styles = subs.styles
|
||||
seen = set()
|
||||
for ev in subs:
|
||||
if getattr(ev, "is_comment", False) or getattr(ev, "is_drawing", False):
|
||||
continue
|
||||
text = re.sub(r'\{.*?\}', '', ev.text).strip()
|
||||
if not text:
|
||||
continue
|
||||
key = (ev.start, ev.end, text)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
ev.text = text
|
||||
cleaned.append(ev)
|
||||
return cleaned
|
||||
|
||||
@staticmethod
|
||||
def _save_clean_srt(src_path: Path, out_srt: Path) -> None:
|
||||
subs = pysubs2.load(str(src_path), encoding="utf-8")
|
||||
before = len(subs)
|
||||
cleaned = SubtitleService._clean_events(subs)
|
||||
if len(cleaned) != before:
|
||||
log.debug(f"🧹 字幕清洗: {out_srt.name} {before} → {len(cleaned)} 条")
|
||||
cleaned.save(str(out_srt), format="srt", encoding="utf-8")
|
||||
|
||||
@staticmethod
|
||||
def _drop_external_copies(internal_srt: Path) -> int:
|
||||
"""内嵌字幕优先:同一集的外挂 srt 副本直接删除(源 .ass 仍保留,可随时重转)。"""
|
||||
prefix = internal_srt.name.split('.internal.')[0] + '.'
|
||||
removed = 0
|
||||
for cand in internal_srt.parent.iterdir():
|
||||
if not cand.is_file() or cand.suffix.lower() != '.srt':
|
||||
continue
|
||||
if '.internal.' in cand.name or not cand.name.startswith(prefix):
|
||||
continue
|
||||
try:
|
||||
cand.unlink()
|
||||
removed += 1
|
||||
log.info(f"🧹 已删除外挂字幕副本(优先内嵌): {cand.name}")
|
||||
except OSError as e:
|
||||
log.warning(f"⚠️ 删除外挂字幕副本失败: {cand.name} -> {e}")
|
||||
return removed
|
||||
|
||||
@staticmethod
|
||||
def has_internal_srt(dest_dir: Path, target_stem: str) -> bool:
|
||||
"""目标目录里是否已经有该集的内嵌字幕(用于跳过 ffprobe 的快速判断)。"""
|
||||
prefix = f"{target_stem}.internal."
|
||||
try:
|
||||
return any(
|
||||
p.is_file() and p.name.startswith(prefix) and p.suffix.lower() == '.srt'
|
||||
for p in dest_dir.iterdir()
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def convert_to_srt(in_sub: Path, out_srt: Path):
|
||||
"""将非 srt 的外挂字幕洗白并转换为 srt,安全保留源文件"""
|
||||
try:
|
||||
subs = pysubs2.load(str(in_sub), encoding="utf-8")
|
||||
for line in subs:
|
||||
line.text = re.sub(r'\{.*?\}', '', line.text)
|
||||
subs.save(str(out_srt), format="srt", encoding="utf-8")
|
||||
|
||||
SubtitleService._save_clean_srt(in_sub, out_srt)
|
||||
except Exception as e:
|
||||
log.warning(f"⚠️ 外挂字幕转换 srt 失败: {in_sub.name} -> {e}")
|
||||
|
||||
@staticmethod
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path):
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path) -> int:
|
||||
"""扫描内置文本字幕轨道,返回"该集已有/已排队的内嵌字幕数"。"""
|
||||
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
|
||||
if not data:
|
||||
return
|
||||
|
||||
return 0
|
||||
|
||||
queued = 0
|
||||
try:
|
||||
streams = data.get('streams', [])
|
||||
lang_counts = {}
|
||||
|
||||
|
||||
for s in streams:
|
||||
codec = s.get('codec_name', '')
|
||||
if codec not in config.EXTRACT_SUBTITLE_CODECS:
|
||||
@@ -63,29 +127,27 @@ class SubtitleService:
|
||||
|
||||
lang_counts[lang_code] = lang_counts.get(lang_code, 0) + 1
|
||||
lang_suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
|
||||
|
||||
desired_out_srt = dest_dir / f"{target_stem}.internal.{lang_code}{lang_suffix}.srt"
|
||||
|
||||
# ==========================================
|
||||
# 🛡️ 恢复丢失的内置提取前置拦截器
|
||||
# ==========================================
|
||||
|
||||
queued += 1
|
||||
|
||||
# 幂等保护:已经提取过就跳过;顺便清掉重复的外挂副本(内嵌优先)
|
||||
if desired_out_srt.exists() and desired_out_srt.stat().st_size > 0:
|
||||
log.debug(f"✨ [跳过提取] 目标内置字幕已存在,触发幂等保护: {desired_out_srt.name}")
|
||||
continue
|
||||
log.debug(f"✨ [跳过提取] 目标内置字幕已存在: {desired_out_srt.name}")
|
||||
SubtitleService._drop_external_copies(desired_out_srt)
|
||||
continue
|
||||
|
||||
out_srt = task_mgr.reserve_path(desired_out_srt)
|
||||
|
||||
# ⚠️ 临时文件必须短:用 <目标名>.temp.<目标名>.ass 这种拼法在长标题(尤其日文/多字节)下
|
||||
# 会超过 Linux 的 255 字节文件名上限,导致 [Errno 36] File name too long。
|
||||
# ⚠️ 临时文件必须短:长标题(尤其日文/多字节)下会超过 255 字节文件名上限
|
||||
temp_ass = dest_dir / f".scenerename-{uuid4().hex[:12]}.ass"
|
||||
|
||||
task_mgr.add_extract(
|
||||
f"[提取内置字幕] {file_path.name} (轨道 {stream_idx}) --> {out_srt.name}",
|
||||
f"[提取内置字幕] {file_path.name} (轨道 {stream_idx}) --> {desired_out_srt.name}",
|
||||
SubtitleService.do_extract,
|
||||
(file_path, stream_idx, temp_ass, out_srt)
|
||||
(file_path, stream_idx, temp_ass, desired_out_srt)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"⚠️ 内置字幕扫描失败: {file_path.name} -> {e}")
|
||||
return queued
|
||||
|
||||
@staticmethod
|
||||
def do_extract(file_path, stream_index, temp_ass, out_srt):
|
||||
@@ -94,10 +156,8 @@ class SubtitleService:
|
||||
|
||||
if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0:
|
||||
try:
|
||||
subs = pysubs2.load(str(temp_ass), encoding="utf-8")
|
||||
for line in subs:
|
||||
line.text = re.sub(r'\{.*?\}', '', line.text)
|
||||
subs.save(str(out_srt), format="srt", encoding="utf-8")
|
||||
SubtitleService._save_clean_srt(temp_ass, out_srt)
|
||||
SubtitleService._drop_external_copies(out_srt)
|
||||
except Exception as e:
|
||||
log.warning(f"⚠️ 字幕 {out_srt.name} 洗白失败,已跳过。报错信息: {e}")
|
||||
finally:
|
||||
@@ -110,4 +170,3 @@ class SubtitleService:
|
||||
log.warning(f"⚠️ 内置字幕提取失败: {file_path.name} (轨道 {stream_index}) "
|
||||
f"ffmpeg={res.returncode} {detail}")
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user