feat(subtitle): 转码片源自动补外挂文本字幕

- 对 preflight 判定为 TRANSCODE 的片源,若没有任何外挂字幕(srt/ass/ssa),
  把内嵌文本字幕导出为 <目标名>.<lang>.srt(PGS/DVD 等图形字幕跳过)
- 已存在同名外挂字幕则整体跳过,不覆盖用户字幕
- [Compatibility] export_text_subs 开关(默认 true)
- 验证:功夫 (2004) 的 ass 轨 → 80KB zh-CN.srt
This commit is contained in:
ali
2026-11-19 11:58:54 +08:00
parent 38a0e5832c
commit cd8a8c3927
3 changed files with 76 additions and 2 deletions
+3
View File
@@ -80,6 +80,8 @@ max_direct_mbps = 70
pre_extract_ass_gb = 15 pre_extract_ass_gb = 15
# 大文件自动抽 ASS(当前 export=ass 时已天然满足) # 大文件自动抽 ASS(当前 export=ass 时已天然满足)
auto_extract_ass = true auto_extract_ass = true
# 必须转码的片源(DV5/老编码等)若无外挂字幕,自动导出文本字幕为外挂 SRT
export_text_subs = true
# 每次扫描是否输出体检报告 # 每次扫描是否输出体检报告
write_report = true write_report = true
# 体检报告集中存放目录(每次生成带时间戳 xlsx) # 体检报告集中存放目录(每次生成带时间戳 xlsx)
@@ -182,6 +184,7 @@ JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0) MAX_DIRECT_MBPS = _parser.getfloat('Compatibility', 'max_direct_mbps', fallback=70.0)
PRE_EXTRACT_ASS_GB = _parser.getfloat('Compatibility', 'pre_extract_ass_gb', fallback=15.0) PRE_EXTRACT_ASS_GB = _parser.getfloat('Compatibility', 'pre_extract_ass_gb', fallback=15.0)
AUTO_EXTRACT_ASS = _parser.getboolean('Compatibility', 'auto_extract_ass', fallback=True) AUTO_EXTRACT_ASS = _parser.getboolean('Compatibility', 'auto_extract_ass', fallback=True)
EXPORT_TEXT_SUBS = _parser.getboolean('Compatibility', 'export_text_subs', fallback=True)
PREFLIGHT_REPORT = _parser.getboolean('Compatibility', 'write_report', fallback=True) PREFLIGHT_REPORT = _parser.getboolean('Compatibility', 'write_report', fallback=True)
PREFLIGHT_CACHE_PATH = BASE_DIR / 'preflight_cache.json' PREFLIGHT_CACHE_PATH = BASE_DIR / 'preflight_cache.json'
PREFLIGHT_CACHE_VERSION = 3 PREFLIGHT_CACHE_VERSION = 3
+11 -1
View File
@@ -10,7 +10,7 @@ from services.parser import ParserService
from services.subtitle import SubtitleService from services.subtitle import SubtitleService
from services.metadata import MetadataService from services.metadata import MetadataService
from services.renamer import RenamerService from services.renamer import RenamerService
from services.preflight import PreflightService, BLOCKED from services.preflight import PreflightService, BLOCKED, TRANSCODE
class MediaPipeline: class MediaPipeline:
"""中央流水线协调器:接管扫描、判定与防爆防撞逻辑""" """中央流水线协调器:接管扫描、判定与防爆防撞逻辑"""
@@ -141,6 +141,16 @@ class MediaPipeline:
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~") log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
if self.args.mode != "clean-ads": if self.args.mode != "clean-ads":
# 必须转码的片源:补外挂文本字幕,避免客户端选内嵌字幕时投递失败
if config.EXPORT_TEXT_SUBS and pf.verdict == TRANSCODE:
text_subs = [s for s in pf.info.get("subs", [])
if (s.get("codec") or "").lower() in SubtitleService.TEXT_SUB_CODECS]
if text_subs:
self.task_mgr.add_extract(
f"[导出外挂字幕] {f.name}({len(text_subs)} 条文本轨)",
SubtitleService.export_text_sidecars,
(f, dest_dir, target_stem),
)
if config.PREFER_INTERNAL: if config.PREFER_INTERNAL:
# 🎯 内嵌字幕优先:先看内嵌,有就不再处理外挂 # 🎯 内嵌字幕优先:先看内嵌,有就不再处理外挂
internal_subs = 0 internal_subs = 0
+62 -1
View File
@@ -12,7 +12,10 @@ from core.utils import FFprobeUtil
class SubtitleService: class SubtitleService:
"""内置字幕导出(ASS / SRT)与外挂字幕规范化的全部实现。""" """内置字幕导出(ASS / SRT)、外挂字幕规范化与转码片源的外挂字幕补齐。"""
# 可转换为外挂 SRT 的文本字幕编码(PGS/DVD/DVB 等图形字幕不在内)
TEXT_SUB_CODECS = {"subrip", "srt", "ass", "ssa", "webvtt", "mov_text"}
# ------------------------------------------------------------------ 清洗 # ------------------------------------------------------------------ 清洗
@@ -290,6 +293,64 @@ class SubtitleService:
f"ffmpeg={res.returncode} {detail}") f"ffmpeg={res.returncode} {detail}")
temp_ass.unlink(missing_ok=True) temp_ass.unlink(missing_ok=True)
@staticmethod
def export_text_sidecars(file_path: Path, dest_dir: Path, out_stem: str) -> int:
"""给必须转码的片源补外挂 SRT(客户端本地渲染,避开内嵌字幕投递)。
- 已有同名外挂字幕(srt/ass/ssa)时整体跳过,避免覆盖用户的字幕;
- 只处理文本字幕轨,图形字幕(PGS/DVD/DVB)跳过;
- 命名 <out_stem>.<lang>.srt,已存在则跳过。
"""
prefix = f"{out_stem}."
try:
for existing in dest_dir.iterdir():
if (existing.is_file() and existing.name.startswith(prefix)
and existing.suffix.lower() in {'.srt', '.ass', '.ssa'}):
log.debug(f"✨ [跳过外挂字幕] 已存在: {existing.name}")
return 0
except OSError:
pass
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)
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}.{lang}{suffix}.srt"
if out_srt.exists() and out_srt.stat().st_size > 0:
continue
temp = dest_dir / f".scenerename-{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 @staticmethod
def convert_to_srt(in_sub: Path, out_srt: Path): def convert_to_srt(in_sub: Path, out_srt: Path):
"""将非 srt 的外挂字幕洗白并转换为 srt,安全保留源文件""" """将非 srt 的外挂字幕洗白并转换为 srt,安全保留源文件"""