Files
SceneMarshal/media/src/services/subtitle.py
T
ali 61facaa75f feat(subtitle): 内置字幕改为导出 ASS,配置集中到 config.ini
- [Subtitles] export = ass(默认):ass 轨 -c:s copy 原样导出,其余编码转 ass;
  命名 <视频名>.internal.<lang>.ass;export = srt 时退回旧的清洗 SRT 逻辑
- [Subtitles] languages / codecs / prefer_internal 取代 [Features] 里的旧键(旧键仍兼容)
- [Run] default_mode / default_path / force_type / extract_internal 作为 CLI 默认值
- [Archive] media_root / refresh_jellyfin 供 media-archive 读取
- 语言标签优先取轨道 tags(title 含「中」即 zh-CN)
2026-11-18 22:29:15 +08:00

243 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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)与外挂字幕规范化的全部实现。"""
# ------------------------------------------------------------------ 清洗
@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 has_internal_sub(dest_dir: Path, target_stem: str) -> bool:
"""目标目录里是否已有该集的内嵌字幕(ass 或 srt)。"""
prefix = f"{target_stem}.internal."
try:
for p in dest_dir.iterdir():
if not p.is_file() or not p.name.startswith(prefix):
continue
if p.suffix.lower() in {'.ass', '.srt'}:
return True
except OSError:
pass
return False
# ------------------------------------------------------------ 语言与轨道
@staticmethod
def _lang_code(stream: dict) -> str:
lang = stream.get('tags', {}).get('language', 'und').lower()
title = stream.get('tags', {}).get('title', '').lower()
lang_code = "und"
if lang in ['chi', 'zho', 'zh', 'chi-cn', 'zh-cn']: lang_code = 'zh-CN'
elif lang in ['tw', 'hk', 'zh-tw']: lang_code = 'zh-TW'
elif lang in ['eng', 'en']: lang_code = 'en'
elif lang in ['jpn', 'ja']: lang_code = 'ja'
elif lang in ['kor', 'ko']: lang_code = 'ko'
if '繁' in title or 'tw' in title or 'hk' in title or 'cht' in title: lang_code = 'zh-TW'
elif '简' in title or 'cn' in title or '双语' in title or '中' in title or 'chs' in title: lang_code = 'zh-CN'
elif '英' in title and lang_code == 'und': lang_code = 'en'
elif '中' in title 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 排队导出。
返回"该集已有/已排队的内嵌字幕数",供流水线判断是否还要处理外挂字幕。
"""
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
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:
queued += SubtitleService._queue_ass(
file_path, task_mgr, target_stem, dest_dir, stream_idx, codec, lang_code, suffix)
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}")
return queued
@staticmethod
def _queue_ass(file_path, task_mgr, target_stem, dest_dir, stream_idx, codec, lang_code, suffix) -> int:
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 1
temp_ass = dest_dir / f".scenerename-{uuid4().hex[:12]}.ass"
task_mgr.add_extract(
f"[导出内置 ASS] {file_path.name} (轨道 {stream_idx}) --> {out_ass.name}",
SubtitleService.do_export_ass,
(file_path, stream_idx, temp_ass, out_ass, codec),
)
return 1
@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
temp_ass = dest_dir / f".scenerename-{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 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_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 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}")