# src/services/subtitle.py import re import subprocess from pathlib import Path from uuid import uuid4 import pysubs2 from core import config from core.logger import log from core.utils import FFprobeUtil class SubtitleService: """内置字幕导出(ASS / SRT)、外挂字幕规范化与转码片源的外挂字幕补齐。""" # 可转换为外挂 SRT 的文本字幕编码(PGS/DVD/DVB 等图形字幕不在内) # 值见 config.ini [Subtitles] text_codecs TEXT_SUB_CODECS = config.SUBTITLE_TEXT_CODECS # ------------------------------------------------------------------ 清洗 @staticmethod def _clean_events(subs: pysubs2.SSAFile) -> pysubs2.SSAFile: """返回清洗后的新 SSAFile:丢掉注释、矢量绘图、空文本与完全重复的事件。 注意:不要用 SSAFile.remove() 原地删除——pysubs2 按值比较,会把 与目标"相等"的另一条事件删掉,导致误删对白、漏删绘图。重建更安全。 """ 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 副本直接删除(源文件仍保留,可随时重转)。""" 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 _video_stems(file_path, target_stem: str) -> list[str]: """该视频可能对应的文件名前缀:目标名 + 磁盘上的现用名。 流水线是「先抽字幕(阶段 3)、后改名(阶段 5)」,所以判断「已有字幕」时 磁盘上的 sidecar 往往还挂在旧名下。只认 target_stem 会把旧 name 的 `.internal.zh-CN.ass` 当成不存在,于是整条轨白抽一遍。 """ stems = [target_stem] source_stem = getattr(file_path, "stem", "") if source_stem and source_stem != target_stem: stems.append(source_stem) return stems # 同一语言的不同写法归一化:chi / zho-Hans / zh_cn / zh-CN 视为中文简体 _LANG_CANON = { 'chi': 'zh-cn', 'zho': 'zh-cn', 'zh': 'zh-cn', 'chs': 'zh-cn', 'sc': 'zh-cn', 'zh-cn': 'zh-cn', 'zh-hans': 'zh-cn', 'zho-hans': 'zh-cn', 'zh-hans-cn': 'zh-cn', 'cht': 'zh-tw', 'tc': 'zh-tw', 'zh-tw': 'zh-tw', 'zh-hant': 'zh-tw', 'zho-hant': 'zh-tw', 'zh-hk': 'zh-tw', 'zh-en': 'zh-en', 'zho-en': 'zh-en', 'eng': 'en', 'en': 'en', 'jpn': 'ja', 'ja': 'ja', 'jp': 'ja', 'kor': 'ko', 'ko': 'ko', } @staticmethod def _norm_lang(code: str) -> str: key = (code or "").strip().lower().replace("_", "-") return SubtitleService._LANG_CANON.get(key, key) @staticmethod def _sidecar_lang(asset: Path) -> str: match = config.LANG_TAIL_PATTERN.search(asset.stem) return match.group(0).lstrip(".-_") if match else "" @staticmethod def has_internal_sub(dest_dir: Path, target_stem: str, file_path=None) -> bool: """目标目录里是否已有该视频的内嵌字幕(ass 或 srt)。""" stems = SubtitleService._video_stems(file_path, target_stem) try: for p in dest_dir.iterdir(): if not p.is_file() or p.suffix.lower() not in {'.ass', '.srt'}: continue if any(p.name.startswith(f"{stem}.internal.") for stem in stems): return True except OSError: pass return False # ------------------------------------------------------------ 语言与轨道 @staticmethod def _lang_code(stream: dict) -> str: """语言标签:词表见 config.ini [Subtitles] *_words / lang_aliases。""" lang = stream.get('tags', {}).get('language', 'und').lower() title = stream.get('tags', {}).get('title', '').lower() def hit(words) -> bool: return any(word in title for word in words) # 中英双语轨:标题里同时出现中文与英文标识(或直接写"双语")时优先判定, # 否则会被下面的"简/繁"规则吞成单语。输出 zh-en,与 zh-CN / zh-TW 区分。 has_cn = hit(config.SUBTITLE_CHINESE_WORDS) has_en = hit(config.SUBTITLE_ENGLISH_WORDS) if hit(config.SUBTITLE_BILINGUAL_WORDS) or (has_cn and has_en): return 'zh-en' if has_en and not has_cn: return 'en' lang_code = config.SUBTITLE_LANG_ALIASES.get(lang, "und") if hit(config.SUBTITLE_TRADITIONAL_WORDS): lang_code = 'zh-TW' elif hit(config.SUBTITLE_SIMPLIFIED_WORDS): lang_code = 'zh-CN' elif hit(config.SUBTITLE_ENGLISH_WORDS) and lang_code == 'und': lang_code = 'en' elif hit(config.SUBTITLE_CHINESE_WORDS) and lang_code == 'und': lang_code = 'zh-CN' if lang_code == "und" and lang != "und": lang_code = lang[:3] return lang_code @staticmethod def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path) -> int: """扫描内置文本字幕轨道,按 config.ini [Subtitles] export 排队导出。 返回“该集已有/已排队的内嵌字幕数”,供流水线判断是否还要处理外挂字幕。 ASS 轨先收集,最后交给 _queue_ass_exports 统一排队: mkv 里的 ass 轨走一次 mkvextract(一次读盘导出多条),其余仍走 ffmpeg。 """ data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s") if not data: return 0 want_ass = 'ass' in config.SUBTITLE_EXPORT want_srt = 'srt' in config.SUBTITLE_EXPORT if not (want_ass or want_srt): return 0 queued = 0 ass_specs = [] try: lang_counts = {} for s in data.get('streams', []): codec = s.get('codec_name', '') if codec not in config.SUBTITLE_CODECS: continue lang_code = SubtitleService._lang_code(s) if config.SUBTITLE_LANGUAGES and lang_code not in config.SUBTITLE_LANGUAGES: continue stream_idx = s['index'] lang_counts[lang_code] = lang_counts.get(lang_code, 0) + 1 suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}" if want_ass: present, spec = SubtitleService._plan_ass( file_path, target_stem, dest_dir, stream_idx, codec, lang_code, suffix) if spec is not None: ass_specs.append(spec) if present or spec is not None: queued += 1 if want_srt: queued += SubtitleService._queue_srt( file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix) except Exception as e: log.warning(f"⚠️ 内置字幕扫描失败: {file_path.name} -> {e}") if ass_specs: SubtitleService._queue_ass_exports(file_path, task_mgr, ass_specs) return queued @staticmethod def _existing_sidecar(file_path, dest_dir: Path, target_stem: str, lang: str, suffix: str) -> Path | None: """同语言外挂字幕是否已存在(认旧名、旧命名、语言码异写)。 三层判断,缺一层就会重复抽取: 1. 精确文件名(含 `.2` 这类同语言多轨后缀); 2. 目标名 / 源名两种前缀(整理先抽后改名,磁盘上常还是旧名); 3. 语言尾归一化(`chi`、`zho-Hans`、`zh_cn` 都算 `zh-CN`),且目录里 只有一个视频时允许前缀完全对不上(片名与文件名不一致的老库)。 """ stems = SubtitleService._video_stems(file_path, target_stem) want = SubtitleService._norm_lang(lang) for stem in stems: for name in ( f"{stem}.internal.{lang}{suffix}.ass", f"{stem}.internal.{lang}{suffix}.srt", f"{stem}.{lang}{suffix}.srt", f"{stem}.{lang}{suffix}.ass", ): p = dest_dir / name if p.exists() and p.stat().st_size > 0: return p # `.2` / `.3` 是同语言多轨的序号,语言层去重只对第一条轨生效 if suffix: return None try: entries = [p for p in dest_dir.iterdir() if p.is_file()] videos = [p for p in entries if p.suffix.lower() in config.SUPPORTED_EXTS] single_video = len(videos) == 1 except OSError: return None for p in entries: if p.suffix.lower() not in {'.ass', '.srt'} or p.name.startswith('.'): continue belongs = any(p.name.startswith(f"{stem}.") for stem in stems) if not belongs: if not single_video: continue if p.stem.strip().lower() in config.RESERVED_SIDECAR_STEMS: continue token = SubtitleService._sidecar_lang(p) if token and SubtitleService._norm_lang(token) == want: log.debug(f"✨ [跳过导出] 已有同语言外挂字幕: {p.name}") return p return None @staticmethod def _plan_ass(file_path, target_stem, dest_dir, stream_idx, codec, lang_code, suffix): """判断该 ASS 轨是否还要抽;返回 (已有外挂副本, 待抽 spec)。 已有(含旧命名)只计数、不排队;待抽 spec 由 _queue_ass_exports 决定合并成一次 mkvextract 还是逐条 ffmpeg。 """ out_ass = dest_dir / f"{target_stem}.internal.{lang_code}{suffix}.ass" if out_ass.exists() and out_ass.stat().st_size > 0: log.debug(f"✨ [跳过导出] 目标内置 ASS 已存在: {out_ass.name}") return True, None existing = SubtitleService._existing_sidecar( file_path, dest_dir, target_stem, lang_code, suffix) if existing is not None: log.debug(f"✨ [跳过导出] 同语言外挂字幕已存在: {existing.name}") return True, None temp_ass = dest_dir / f".scenemarshal-{uuid4().hex[:12]}.ass" return False, {"index": stream_idx, "codec": codec, "temp": temp_ass, "out": out_ass} @staticmethod def _queue_ass_exports(file_path, task_mgr, specs) -> int: """把待抽 ASS 排成任务:mkv 的 ass 轨合并成一次 mkvextract,其余逐条 ffmpeg。 逐条 ffmpeg 每次都要把整部片读一遍,60GB 级 REMUX 每条轨约 10 分钟; 一次 mkvextract 导出多条只读一遍,多轨影片能省掉 N-1 遍读盘。 """ log.info(f"🎞️ 待导出内置 ASS: {file_path.name}({len(specs)} 条轨)") batchable = [s for s in specs if s["codec"] == "ass" and file_path.suffix.lower() in {".mkv", ".mka"}] if batchable: tracks = ", ".join(str(s["index"]) for s in batchable) names = "、".join(s["out"].name for s in batchable) task_mgr.add_extract( f"[导出内置 ASS] {file_path.name} (轨道 {tracks}) --> {names}", SubtitleService.do_export_ass_multi, (file_path, batchable), ) for spec in specs: if spec in batchable: continue task_mgr.add_extract( f"[导出内置 ASS] {file_path.name} (轨道 {spec['index']}) --> {spec['out'].name}", SubtitleService.do_export_ass, (file_path, spec["index"], spec["temp"], spec["out"], spec["codec"]), ) return len(specs) @staticmethod def _queue_srt(file_path, task_mgr, target_stem, dest_dir, stream_idx, lang_code, suffix) -> int: out_srt = dest_dir / f"{target_stem}.internal.{lang_code}{suffix}.srt" if out_srt.exists() and out_srt.stat().st_size > 0: log.debug(f"✨ [跳过提取] 目标内置字幕已存在: {out_srt.name}") SubtitleService._drop_external_copies(out_srt) return 1 if SubtitleService._existing_sidecar( file_path, dest_dir, target_stem, lang_code, suffix) is not None: log.debug(f"✨ [跳过提取] 同语言外挂字幕已存在: {target_stem}.{lang_code}{suffix}") return 1 temp_ass = dest_dir / f".scenemarshal-{uuid4().hex[:12]}.ass" task_mgr.add_extract( f"[提取内置字幕] {file_path.name} (轨道 {stream_idx}) --> {out_srt.name}", SubtitleService.do_extract, (file_path, stream_idx, temp_ass, out_srt), ) return 1 @staticmethod def scan_fonts(file_path: Path, task_mgr, dest_dir: Path) -> int: """把 mkv 内嵌字体附件抽到 dest_dir//,返回排队/已存在数量。""" if not config.EXTRACT_FONTS: return 0 data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "t") if not data: return 0 fonts_dir = dest_dir / config.FONTS_DIR_NAME queued = 0 for ordinal, s in enumerate(data.get('streams', []), 1): if s.get('codec_type') != 'attachment': continue tags = s.get('tags', {}) or {} raw_name = tags.get('filename') or tags.get('title') or f"attachment-{ordinal}.ttf" safe_name = Path(str(raw_name).replace('\\', '/')).name.strip() or f"attachment-{ordinal}.ttf" target = fonts_dir / safe_name if target.exists() and target.stat().st_size > 0: log.debug(f"✨ [跳过字体] 已存在: {safe_name}") queued += 1 continue task_mgr.add_extract( f"[导出内嵌字体] {file_path.name} ({safe_name})", SubtitleService.do_dump_font, (file_path, ordinal, target), ) queued += 1 return queued @staticmethod def do_dump_font(file_path, ordinal, target): """用 mkvextract 抽取字体附件(比 ffmpeg -dump_attachment 快得多)。""" target.parent.mkdir(parents=True, exist_ok=True) temp = target.with_name(f".{target.stem}.part{target.suffix}") temp.unlink(missing_ok=True) cmd = ["mkvextract", "attachments", str(file_path), f"{ordinal}:{temp}"] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="ignore") if res.returncode == 0 and temp.exists() and temp.stat().st_size > 0: try: temp.replace(target) log.debug(f"🔤 已导出内嵌字体: {target.name}") except OSError as e: log.warning(f"⚠️ 字体重命名失败: {target.name} -> {e}") temp.unlink(missing_ok=True) else: tail = [line for line in (res.stderr or "").strip().splitlines() if line.strip()] detail = tail[-1][:200] if tail else "" log.warning(f"⚠️ 内嵌字体导出失败: {file_path.name} #{ordinal} " f"mkvextract={res.returncode} {detail}") temp.unlink(missing_ok=True) # ------------------------------------------------------------------ 执行 @staticmethod def do_export_ass(file_path, stream_index, temp_ass, out_ass, codec): """导出内置字幕为 ASS:ass 轨直接 copy 保真,其余转成 ass。""" def run(copy_mode: str): codec_opt = 'copy' if copy_mode == 'copy' else 'ass' cmd = ["ffmpeg", "-v", "error", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", codec_opt, "-f", "ass", "-y", str(temp_ass)] return subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="ignore") res = run('copy' if codec == 'ass' else 'ass') if res.returncode != 0 and codec == 'ass': # 极少数 mkv 的 ass 轨无法直接 copy 到 ass muxer,退回转码 log.debug(f"↩️ ass copy 失败,改为转码: {file_path.name}") res = run('ass') if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0: try: temp_ass.replace(out_ass) log.debug(f"🎞️ 已导出内置 ASS: {out_ass.name}") except OSError as e: log.warning(f"⚠️ 重命名 ASS 失败: {out_ass.name} -> {e}") temp_ass.unlink(missing_ok=True) else: detail = "" if res.stderr: tail = [line for line in res.stderr.strip().splitlines() if line.strip()] detail = tail[-1][:200] if tail else "" log.warning(f"⚠️ 内置 ASS 导出失败: {file_path.name} (轨道 {stream_index}) " f"ffmpeg={res.returncode} {detail}") temp_ass.unlink(missing_ok=True) @staticmethod def do_export_ass_multi(file_path, specs): """一次 mkvextract 读出多条 ASS 轨:同一部片只读一遍盘。 60GB 级 REMUX 逐条 ffmpeg 抽取时每条轨都要读完整部片(约 10 分钟/条), 多轨影片用 mkvextract 合并成一次读取;失败时回退逐条 ffmpeg。 """ log.info(f"🎞️ 批量导出内置 ASS: {file_path.name}({len(specs)} 条轨)") cmd = ["mkvextract", "tracks", str(file_path)] cmd += [f"{spec['index']}:{spec['temp']}" for spec in specs] try: res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="ignore", timeout=config.REMUX_TIMEOUT) except (OSError, subprocess.TimeoutExpired) as exc: log.warning(f"⚠️ mkvextract 批量导出失败: {file_path.name} -> {exc};回退 ffmpeg 逐条抽取") for spec in specs: SubtitleService.do_export_ass(file_path, spec["index"], spec["temp"], spec["out"], spec["codec"]) return failed = [] for spec in specs: temp, out = spec["temp"], spec["out"] if res.returncode == 0 and temp.exists() and temp.stat().st_size > 0: try: temp.replace(out) log.debug(f"🎞️ 已导出内置 ASS: {out.name}") except OSError as exc: log.warning(f"⚠️ 重命名 ASS 失败: {out.name} -> {exc}") temp.unlink(missing_ok=True) failed.append(spec) else: temp.unlink(missing_ok=True) failed.append(spec) if failed: tail = [line for line in (res.stderr or "").strip().splitlines() if line.strip()] detail = tail[-1][:200] if tail else "" log.warning(f"⚠️ mkvextract 批量导出失败 {len(failed)}/{len(specs)} 条" f"(mkvextract={res.returncode}){detail};回退 ffmpeg 逐条抽取") for spec in failed: SubtitleService.do_export_ass(file_path, spec["index"], spec["temp"], spec["out"], spec["codec"]) @staticmethod def do_extract(file_path, stream_index, temp_ass, out_srt): cmd = ["ffmpeg", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", "ass", "-f", "ass", "-y", str(temp_ass)] res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="ignore") if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0: try: 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: temp_ass.unlink(missing_ok=True) else: detail = "" if res.stderr: tail = [line for line in res.stderr.strip().splitlines() if line.strip()] detail = tail[-1][:200] if tail else "" log.warning(f"⚠️ 内置字幕提取失败: {file_path.name} (轨道 {stream_index}) " f"ffmpeg={res.returncode} {detail}") temp_ass.unlink(missing_ok=True) @staticmethod def export_text_sidecars(file_path: Path, dest_dir: Path, out_stem: str) -> int: """给必须转码的片源补外挂 SRT(客户端本地渲染,避开内嵌字幕投递)。 - 按轨逐条补:只导出目录里还缺的语言,已有的不动(便于老库补齐, 例如后来才发现的中英双语轨); - 只处理文本字幕轨,图形字幕(PGS/DVD/DVB)跳过; - 命名 .internal..srt,与内嵌抽取共用 .internal 标记; 中英双语轨出 .internal.zh-en.srt。 """ data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s") if not data: return 0 exported = 0 lang_counts = {} for s in data.get('streams', []): codec = (s.get('codec_name') or '').lower() if codec not in SubtitleService.TEXT_SUB_CODECS: continue lang = SubtitleService._lang_code(s) # 与内嵌抽取共用一份语言白名单,避免把马来语/泰米尔语这类杂轨也导出来 if config.SUBTITLE_LANGUAGES and lang not in config.SUBTITLE_LANGUAGES: continue lang_counts[lang] = lang_counts.get(lang, 0) + 1 suffix = "" if lang_counts[lang] == 1 else f".{lang_counts[lang]}" out_srt = dest_dir / f"{out_stem}.internal.{lang}{suffix}.srt" # 早期版本不带 .internal 标记,同语言外挂已存在时同样视为已补齐,避免重复 legacy_srt = dest_dir / f"{out_stem}.{lang}{suffix}.srt" if (out_srt.exists() and out_srt.stat().st_size > 0) or ( legacy_srt.exists() and legacy_srt.stat().st_size > 0): continue temp = dest_dir / f".scenemarshal-{uuid4().hex[:12]}.srt" cmd = ["ffmpeg", "-v", "error", "-i", str(file_path), "-map", f"0:{s['index']}", "-an", "-vn", "-c:s", "srt", "-f", "srt", "-y", str(temp)] res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="ignore") if res.returncode == 0 and temp.exists() and temp.stat().st_size > 0: try: temp.replace(out_srt) exported += 1 log.info(f"📝 已导出外挂字幕: {out_srt.name}") except OSError as e: log.warning(f"⚠️ 外挂字幕改名失败: {out_srt.name} -> {e}") temp.unlink(missing_ok=True) else: tail = [ln for ln in (res.stderr or "").strip().splitlines() if ln.strip()] log.warning(f"⚠️ 外挂字幕导出失败: {file_path.name} 轨{s['index']} " f"ffmpeg={res.returncode} {tail[-1][:160] if tail else ''}") temp.unlink(missing_ok=True) return exported @staticmethod def convert_to_srt(in_sub: Path, out_srt: Path): """将非 srt 的外挂字幕洗白并转换为 srt,安全保留源文件""" try: SubtitleService._save_clean_srt(in_sub, out_srt) except Exception as e: log.warning(f"⚠️ 外挂字幕转换 srt 失败: {in_sub.name} -> {e}")