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)
This commit is contained in:
ali
2026-11-18 22:29:15 +08:00
parent 0ae4d4c8a1
commit 61facaa75f
6 changed files with 252 additions and 91 deletions
+131 -61
View File
@@ -10,7 +10,11 @@ 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:
@@ -18,8 +22,6 @@ class SubtitleService:
注意:不要用 SSAFile.remove() 原地删除——pysubs2 按值比较,会把
与目标"相等"的另一条事件删掉,导致误删对白、漏删绘图。重建更安全。
ASS 里的 \\p1 绘图(logo、特效字、遮罩)转成 SRT 后会变成
'm 463 33 l 468 -29 ...' 这类路径文本;多层事件还会产生重复行。
"""
cleaned = pysubs2.SSAFile()
cleaned.info = subs.info
@@ -50,7 +52,7 @@ class SubtitleService:
@staticmethod
def _drop_external_copies(internal_srt: Path) -> int:
"""内嵌字幕优先:同一集的外挂 srt 副本直接删除(源 .ass 仍保留,可随时重转)。"""
"""内嵌字幕优先:同一集的外挂 srt 副本直接删除(源文件仍保留,可随时重转)。"""
prefix = internal_srt.name.split('.internal.')[0] + '.'
removed = 0
for cand in internal_srt.parent.iterdir():
@@ -67,88 +69,148 @@ class SubtitleService:
return removed
@staticmethod
def has_internal_srt(dest_dir: Path, target_stem: str) -> bool:
"""目标目录里是否已经有该集的内嵌字幕(用于跳过 ffprobe 的快速判断)。"""
def has_internal_sub(dest_dir: Path, target_stem: str) -> bool:
"""目标目录里是否已有该集的内嵌字幕(ass 或 srt)。"""
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()
)
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:
return False
pass
return False
# ------------------------------------------------------------ 语言与轨道
@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}")
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:
streams = data.get('streams', [])
lang_counts = {}
for s in streams:
for s in data.get('streams', []):
codec = s.get('codec_name', '')
if codec not in config.EXTRACT_SUBTITLE_CODECS:
continue
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
lang = s.get('tags', {}).get('language', 'und').lower()
title = s.get('tags', {}).get('title', '').lower()
stream_idx = s['index']
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]
if config.EXTRACT_SUBTITLE_LANGUAGES and lang_code not in config.EXTRACT_SUBTITLE_LANGUAGES:
continue
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"
suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
queued += 1
# 幂等保护:已经提取过就跳过;顺便清掉重复的外挂副本(内嵌优先)
if desired_out_srt.exists() and desired_out_srt.stat().st_size > 0:
log.debug(f"✨ [跳过提取] 目标内置字幕已存在: {desired_out_srt.name}")
SubtitleService._drop_external_copies(desired_out_srt)
continue
# ⚠️ 临时文件必须短:长标题(尤其日文/多字节)下会超过 255 字节文件名上限
temp_ass = dest_dir / f".scenerename-{uuid4().hex[:12]}.ass"
task_mgr.add_extract(
f"[提取内置字幕] {file_path.name} (轨道 {stream_idx}) --> {desired_out_srt.name}",
SubtitleService.do_extract,
(file_path, stream_idx, temp_ass, desired_out_srt)
)
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)]
@@ -170,3 +232,11 @@ class SubtitleService:
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}")