refactor(layout): 源码迁入 src/,项目根迁到 SceneMarshal

This commit is contained in:
ali
2026-11-20 14:31:34 +08:00
parent b804897029
commit e6a4113ca0
41 changed files with 129 additions and 128 deletions
+396
View File
@@ -0,0 +1,396 @@
# 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 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:
"""语言标签:词表见 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 排队导出。
返回"该集已有/已排队的内嵌字幕数",供流水线判断是否还要处理外挂字幕。
"""
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 _existing_sidecar(dest_dir: Path, target_stem: str, lang: str, suffix: str) -> Path | None:
"""同语言外挂字幕是否已存在(含早期不带 .internal 的命名与其它封装格式)。
老库里的字幕多为 <stem>.<lang>.srt(旧命名),若不认这些,重复抽取会在
同一语言下再生成 .internal.<lang>.ass,Jellyfin 里就会出现两条同语言字幕。
"""
for name in (
f"{target_stem}.internal.{lang}{suffix}.ass",
f"{target_stem}.internal.{lang}{suffix}.srt",
f"{target_stem}.{lang}{suffix}.srt",
f"{target_stem}.{lang}{suffix}.ass",
):
p = dest_dir / name
if p.exists() and p.stat().st_size > 0:
return p
return None
@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
existing = SubtitleService._existing_sidecar(dest_dir, target_stem, lang_code, suffix)
if existing is not None:
log.debug(f"✨ [跳过导出] 同语言外挂字幕已存在: {existing.name}")
return 1
temp_ass = dest_dir / f".scenemarshal-{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
if SubtitleService._existing_sidecar(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/<fonts_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_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)跳过;
- 命名 <out_stem>.internal.<lang>.srt,与内嵌抽取共用 .internal 标记;
中英双语轨出 <out_stem>.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}")