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:
+79
-15
@@ -18,6 +18,14 @@ CONFIG_PATH = BASE_DIR / 'config.ini'
|
||||
# 💡 初始配置模板:当文件不存在时自动生成
|
||||
DEFAULT_CONFIG_CONTENT = """# Media Manager 初始配置文件
|
||||
|
||||
[Run]
|
||||
# 命令行未指定时的默认执行参数(CLI 参数优先)
|
||||
default_mode = auto
|
||||
# 留空表示当前目录
|
||||
default_path =
|
||||
force_type =
|
||||
extract_internal = false
|
||||
|
||||
[TMDB]
|
||||
api_key =
|
||||
language = zh-CN
|
||||
@@ -32,18 +40,35 @@ exclude_dirs =
|
||||
[Ads]
|
||||
keywords = TG频道,@yunpantv
|
||||
|
||||
[Subtitles]
|
||||
# 导出格式:ass(原始保真,默认)/ srt(清洗后);可写 ass,srt 同时导出
|
||||
export = ass
|
||||
# 只导出这些语言的轨;all 表示全部
|
||||
languages = zh-CN,zh-TW,en,und
|
||||
# 允许处理的字幕轨编码;ass 轨用 -c:s copy 原样抽出,其余转成 ass
|
||||
codecs = ass,ssa,webvtt,subrip,mov_text
|
||||
# 内嵌优先:有内嵌字幕时不再处理外挂字幕
|
||||
prefer_internal = true
|
||||
|
||||
[Features]
|
||||
include_tmdb_id = true
|
||||
extract_internal_subs = false
|
||||
skip_perfect_match = true
|
||||
extract_subtitle_codecs = ass,ssa,webvtt,subrip,mov_text
|
||||
extract_subtitle_languages = zh-CN,zh-TW,en,und
|
||||
|
||||
[Advanced]
|
||||
watch_delay = 15
|
||||
remux_bitrate_1080p = 22.0
|
||||
remux_bitrate_4k = 45.0
|
||||
|
||||
[Archive]
|
||||
# 媒体库根目录(media-archive 使用)
|
||||
media_root = /hdd/sda1/media
|
||||
# 归档后是否触发 Jellyfin 库刷新
|
||||
refresh_jellyfin = true
|
||||
|
||||
[Jellyfin]
|
||||
url = http://127.0.0.1:8096
|
||||
api_key =
|
||||
|
||||
[System]
|
||||
log_file_path = media_manager.log
|
||||
tmdb_cache_path = tmdb_data.json
|
||||
@@ -62,6 +87,20 @@ if not CONFIG_PATH.exists():
|
||||
|
||||
_parser.read(CONFIG_PATH, encoding='utf-8')
|
||||
|
||||
|
||||
def _csv_set(section: str, key: str, fallback: str = '') -> set:
|
||||
raw = _parser.get(section, key, fallback=fallback).strip()
|
||||
return {item.strip() for item in raw.split(',') if item.strip()}
|
||||
|
||||
|
||||
def _csv_set_or_all(section: str, key: str, fallback: str = 'all'):
|
||||
"""返回 None 表示不过滤(all)。"""
|
||||
raw = _parser.get(section, key, fallback=fallback).strip()
|
||||
if not raw or raw.lower() == 'all':
|
||||
return None
|
||||
return {item.strip() for item in raw.split(',') if item.strip()}
|
||||
|
||||
|
||||
# --- 核心数据解耦 ---
|
||||
|
||||
# 1. TMDB 配置
|
||||
@@ -73,31 +112,56 @@ TMDB_MAX_RETRIES = _parser.getint('TMDB', 'max_retries', fallback=3)
|
||||
# 2. 媒体与广告
|
||||
SUPPORTED_EXTS = set(_parser.get('Media', 'supported_exts', fallback='.mkv,.mp4,.avi').lower().split(','))
|
||||
SIDECAR_EXTS = set(_parser.get('Media', 'sidecar_exts', fallback='.nfo,.jpg,.jpeg,.png,.bif,.xml').lower().split(','))
|
||||
|
||||
# 💡 新增:读取并清洗黑名单关键词
|
||||
_excl_raw = _parser.get('Media', 'exclude_dirs', fallback='')
|
||||
EXCLUDE_DIRS = [d.strip() for d in _excl_raw.split(',') if d.strip()]
|
||||
|
||||
EXCLUDE_DIRS = [d.strip() for d in _parser.get('Media', 'exclude_dirs', fallback='').split(',') if d.strip()]
|
||||
AD_KEYWORDS = _parser.get('Ads', 'keywords', fallback='推广信息').split(',')
|
||||
|
||||
# 3. 功能开关
|
||||
# 3. 运行默认参数(CLI 未给出时生效)
|
||||
DEFAULT_MODE = (_parser.get('Run', 'default_mode', fallback='auto').strip() or 'auto').lower()
|
||||
DEFAULT_PATH = _parser.get('Run', 'default_path', fallback='').strip() or '.'
|
||||
DEFAULT_FORCE_TYPE = _parser.get('Run', 'force_type', fallback='').strip() or None
|
||||
DEFAULT_EXTRACT_INTERNAL = _parser.getboolean('Run', 'extract_internal', fallback=False)
|
||||
|
||||
# 4. 字幕导出策略
|
||||
# 兼容旧配置:没有 [Subtitles] 段时,沿用 [Features] 里的 codecs/languages
|
||||
SUBTITLE_EXPORT = _csv_set('Subtitles', 'export', fallback='')
|
||||
if not SUBTITLE_EXPORT:
|
||||
SUBTITLE_EXPORT = {'ass'}
|
||||
|
||||
if _parser.has_option('Subtitles', 'codecs'):
|
||||
SUBTITLE_CODECS = _csv_set('Subtitles', 'codecs', fallback='ass,ssa,webvtt,subrip,mov_text')
|
||||
else:
|
||||
SUBTITLE_CODECS = _csv_set('Features', 'extract_subtitle_codecs', fallback='ass,ssa,webvtt,subrip,mov_text')
|
||||
|
||||
if _parser.has_option('Subtitles', 'languages'):
|
||||
SUBTITLE_LANGUAGES = _csv_set_or_all('Subtitles', 'languages', fallback='all')
|
||||
else:
|
||||
_legacy_langs = _parser.get('Features', 'extract_subtitle_languages', fallback='all').strip()
|
||||
SUBTITLE_LANGUAGES = None if (not _legacy_langs or _legacy_langs.lower() == 'all') else _csv_set(
|
||||
'Features', 'extract_subtitle_languages', fallback='all')
|
||||
|
||||
PREFER_INTERNAL = _parser.getboolean('Subtitles', 'prefer_internal', fallback=True)
|
||||
|
||||
# 5. 功能开关
|
||||
INCLUDE_TMDB_ID = _parser.getboolean('Features', 'include_tmdb_id', fallback=True)
|
||||
EXTRACT_INTERNAL_SUBS = _parser.getboolean('Features', 'extract_internal_subs', fallback=False)
|
||||
SKIP_PERFECT_MATCH = _parser.getboolean('Features', 'skip_perfect_match', fallback=True)
|
||||
EXTRACT_SUBTITLE_CODECS = set(_parser.get('Features', 'extract_subtitle_codecs', fallback='ass,ssa,webvtt,subrip').split(','))
|
||||
_langs_raw = _parser.get('Features', 'extract_subtitle_languages', fallback='zh-CN,zh-TW,en,und').strip()
|
||||
EXTRACT_SUBTITLE_LANGUAGES = set(_langs_raw.split(',')) if _langs_raw.lower() != 'all' else None
|
||||
|
||||
# 4. 高级阈值
|
||||
# 6. 高级阈值
|
||||
WATCH_DELAY = _parser.getint('Advanced', 'watch_delay', fallback=15)
|
||||
REMUX_BITRATE_1080P = _parser.getfloat('Advanced', 'remux_bitrate_1080p', fallback=22.0)
|
||||
REMUX_BITRATE_4K = _parser.getfloat('Advanced', 'remux_bitrate_4k', fallback=45.0)
|
||||
|
||||
# 5. 系统与日志路径
|
||||
# 7. 归档与 Jellyfin
|
||||
_media_root = _parser.get('Archive', 'media_root', fallback='/hdd/sda1/media').strip()
|
||||
MEDIA_ROOT = Path(_media_root)
|
||||
REFRESH_JELLYFIN = _parser.getboolean('Archive', 'refresh_jellyfin', fallback=True)
|
||||
JELLYFIN_URL = _parser.get('Jellyfin', 'url', fallback='http://127.0.0.1:8096').strip() or 'http://127.0.0.1:8096'
|
||||
JELLYFIN_API_KEY = _parser.get('Jellyfin', 'api_key', fallback='').strip()
|
||||
|
||||
# 8. 系统与日志路径
|
||||
_raw_log_path = _parser.get('System', 'log_file_path', fallback='media_manager.log')
|
||||
LOG_FILE_PATH = BASE_DIR / _raw_log_path if not os.path.isabs(_raw_log_path) else Path(_raw_log_path)
|
||||
|
||||
# 💡 新增:缓存路径读取与绝对/相对路径适配
|
||||
_raw_cache_path = _parser.get('System', 'tmdb_cache_path', fallback='tmdb_cache.json')
|
||||
TMDB_CACHE_PATH = BASE_DIR / _raw_cache_path if not os.path.isabs(_raw_cache_path) else Path(_raw_cache_path)
|
||||
|
||||
|
||||
@@ -124,16 +124,23 @@ class MediaPipeline:
|
||||
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||||
|
||||
if self.args.mode != "clean-ads":
|
||||
if config.PREFER_INTERNAL:
|
||||
# 🎯 内嵌字幕优先:先看内嵌,有就不再处理外挂
|
||||
internal_subs = 0
|
||||
if not skip_heavy or self.args.extract_internal or self.args.mode == "extract-subs":
|
||||
internal_subs = SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
elif SubtitleService.has_internal_srt(dest_dir, target_stem):
|
||||
elif SubtitleService.has_internal_sub(dest_dir, target_stem):
|
||||
# 完美文件名豁免时不做 ffprobe,但仍需识别"已有内嵌字幕"
|
||||
internal_subs = 1
|
||||
|
||||
# 🎯 内嵌字幕优先:只要有内嵌字幕(已有或已排队),就不再转换/整理外挂字幕
|
||||
if internal_subs == 0:
|
||||
RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||||
else:
|
||||
# 旧行为:外挂优先,没有外挂(或强制)时才提取内嵌
|
||||
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||||
if (not has_ext_sub or self.args.extract_internal or self.args.mode == "extract-subs") and (
|
||||
not skip_heavy or self.args.extract_internal or self.args.mode == "extract-subs"):
|
||||
SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||||
|
||||
if self.args.mode != "extract-subs" and not skip_heavy:
|
||||
MetadataService.scan_ads(f, self.task_mgr)
|
||||
|
||||
+11
-4
@@ -4,16 +4,22 @@ import sys
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from core.logger import log
|
||||
from core import config
|
||||
from core.shell import check_dependencies
|
||||
from core.exceptions import MediaDependencyError
|
||||
from core.pipeline import MediaPipeline # 💡 引入高度封装的管道中枢
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
||||
parser.add_argument("mode", nargs='?', default="auto", choices=["manual", "auto", "clean-ads", "extract-subs", "watch"])
|
||||
parser.add_argument("-p", "--path", default=".")
|
||||
parser.add_argument("--extract-internal", action="store_true")
|
||||
parser.add_argument("-t", "--force-type", choices=["tv", "movie"], help="强制指定媒体类型 (tv 或 movie),解决正则误判")
|
||||
parser.add_argument("mode", nargs='?', default=config.DEFAULT_MODE,
|
||||
choices=["manual", "auto", "clean-ads", "extract-subs", "watch"],
|
||||
help=f"运行模式(默认取 config.ini [Run] default_mode = {config.DEFAULT_MODE})")
|
||||
parser.add_argument("-p", "--path", default=config.DEFAULT_PATH,
|
||||
help="扫描目录(默认取 config.ini [Run] default_path,留空为当前目录)")
|
||||
parser.add_argument("--extract-internal", action="store_true", default=config.DEFAULT_EXTRACT_INTERNAL,
|
||||
help="强制提取内置字幕(默认取 config.ini [Run] extract_internal)")
|
||||
parser.add_argument("-t", "--force-type", choices=["tv", "movie"], default=config.DEFAULT_FORCE_TYPE,
|
||||
help="强制指定媒体类型 (tv 或 movie),解决正则误判")
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
@@ -24,6 +30,7 @@ def main():
|
||||
|
||||
target_dir = Path(args.path).resolve()
|
||||
log.info(f"🚀 启动模式: [{args.mode.upper()}] | 扫描目标: {target_dir}")
|
||||
log.debug(f"字幕导出格式: {sorted(config.SUBTITLE_EXPORT)} | 内嵌优先: {config.PREFER_INTERNAL}")
|
||||
|
||||
if args.mode == "watch":
|
||||
try:
|
||||
|
||||
@@ -12,6 +12,10 @@ class RenamerService:
|
||||
|
||||
@staticmethod
|
||||
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr) -> bool:
|
||||
# 只导出 ASS 模式下不做 SRT 转换,外挂字幕保持原样
|
||||
if 'srt' not in config.SUBTITLE_EXPORT:
|
||||
return False
|
||||
|
||||
has_external_sub = False
|
||||
for sub in f_path.parent.glob("*"):
|
||||
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
||||
|
||||
+124
-54
@@ -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,45 +69,25 @@ 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:
|
||||
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}")
|
||||
# ------------------------------------------------------------ 语言与轨道
|
||||
|
||||
@staticmethod
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path) -> int:
|
||||
"""扫描内置文本字幕轨道,返回"该集已有/已排队的内嵌字幕数"。"""
|
||||
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
|
||||
if not data:
|
||||
return 0
|
||||
|
||||
queued = 0
|
||||
try:
|
||||
streams = data.get('streams', [])
|
||||
lang_counts = {}
|
||||
|
||||
for s in streams:
|
||||
codec = s.get('codec_name', '')
|
||||
if codec not in config.EXTRACT_SUBTITLE_CODECS:
|
||||
continue
|
||||
|
||||
lang = s.get('tags', {}).get('language', 'und').lower()
|
||||
title = s.get('tags', {}).get('title', '').lower()
|
||||
stream_idx = s['index']
|
||||
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'
|
||||
@@ -121,34 +103,114 @@ class SubtitleService:
|
||||
|
||||
if lang_code == "und" and lang != "und":
|
||||
lang_code = lang[:3]
|
||||
return lang_code
|
||||
|
||||
if config.EXTRACT_SUBTITLE_LANGUAGES and lang_code not in config.EXTRACT_SUBTITLE_LANGUAGES:
|
||||
@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
|
||||
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}")
|
||||
|
||||
@@ -26,7 +26,12 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
MEDIA_ROOT = Path(os.environ.get("SCENERENAME_MEDIA_ROOT", "/hdd/sda1/media"))
|
||||
def resolve_media_root(cfg: configparser.ConfigParser) -> Path:
|
||||
env = os.environ.get("SCENERENAME_MEDIA_ROOT")
|
||||
if env:
|
||||
return Path(env)
|
||||
raw = cfg.get("Archive", "media_root", fallback="").strip() if cfg.has_section("Archive") else ""
|
||||
return Path(raw or "/hdd/sda1/media")
|
||||
CONFIG_PATH = Path(
|
||||
os.environ.get(
|
||||
"SCENERENAME_CONFIG",
|
||||
@@ -179,6 +184,8 @@ def move_to(src: Path, dest: Path) -> None:
|
||||
|
||||
|
||||
def refresh_jellyfin(cfg: configparser.ConfigParser) -> str:
|
||||
if cfg.has_section("Archive") and not cfg.getboolean("Archive", "refresh_jellyfin", fallback=True):
|
||||
return "已按 [Archive] refresh_jellyfin=false 跳过刷新"
|
||||
if not cfg.has_section("Jellyfin"):
|
||||
return "未配置 [Jellyfin],跳过刷新"
|
||||
api_key = (cfg.get("Jellyfin", "api_key", fallback="") or "").strip()
|
||||
@@ -229,6 +236,7 @@ def choose_category(cats: list[str], suggestion: str | None) -> str | None:
|
||||
|
||||
|
||||
def main() -> int:
|
||||
global MEDIA_ROOT
|
||||
parser = argparse.ArgumentParser(description="把整理好的媒体目录归档进媒体库")
|
||||
parser.add_argument("path", nargs="?", default=".", help="要归档的目录(默认当前目录)")
|
||||
parser.add_argument("-p", "--path", dest="path_opt", help="要归档的目录(覆盖位置参数)")
|
||||
@@ -245,6 +253,7 @@ def main() -> int:
|
||||
die(f"源目录已经在媒体库里了: {src}")
|
||||
|
||||
cfg = load_config()
|
||||
MEDIA_ROOT = resolve_media_root(cfg)
|
||||
kind = detect_kind(src)
|
||||
tmdb_id = tmdb_id_of(src.name)
|
||||
info = tmdb_info(tmdb_id, kind, cfg) if tmdb_id else None
|
||||
|
||||
Reference in New Issue
Block a user