This commit is contained in:
Hraulein
2026-05-08 16:26:07 +08:00
commit b1e38b8992
14 changed files with 592 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
# python/src/services/subtitle_srv.py
import re
import json
import subprocess
from pathlib import Path
import pysubs2
class SubtitleService:
@staticmethod
def scan_subtitles(file_path: Path, task_mgr, target_stem: str):
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "s", str(file_path)]
res = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
try:
data = json.loads(res.stdout)
streams = data.get('streams', [])
# 允许提取的文本字幕编码
text_codecs = ['ass', 'ssa', 'mov_text', 'webvtt', 'subrip']
for s in streams:
codec = s.get('codec_name', '')
if codec not in text_codecs:
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'
# 标题语义纠偏:所有双语均归为标准 zh-CN
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]
desired_out_srt = file_path.with_name(f"{target_stem}.{lang_code}.srt")
out_srt = task_mgr.reserve_path(desired_out_srt)
# 💡 核心改变:临时文件使用 .ass 后缀,让 ffmpeg 完整保留结构
temp_ass = file_path.with_name(f"{target_stem}.temp.{out_srt.name}.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)
)
except Exception:
pass
@staticmethod
def do_extract(file_path, stream_index, temp_ass, out_srt):
# 1. 使用 ffmpeg 原样抽出 ASS 字幕(强制封入 ass 容器,防止丢失原始时间轴和特效块)
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.DEVNULL)
# 如果 ffmpeg 提取成功且文件不为空
if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0:
try:
# 2. 召唤 pysubs2 进行降维打击
subs = pysubs2.load(str(temp_ass), encoding="utf-8")
# 双重保险:pysubs2 导出时会自动去掉特效,但为了防止某些极端绘图代码残留,手动擦除 {\...} 标签
for line in subs:
line.text = re.sub(r'\{.*?\}', '', line.text)
# 3. 输出为完美纯净的 srt
subs.save(str(out_srt), format="srt", encoding="utf-8")
except Exception as e:
print(f"\n⚠️ 字幕 {out_srt.name} 深度洗白失败,已跳过。报错信息: {e}")
finally:
# 无论成功失败,都清理临时文件
temp_ass.unlink(missing_ok=True)
else:
temp_ass.unlink(missing_ok=True)