- --rename-only:只做重命名,跳过字幕抽取/广告清理/音轨扫描。 整库改名时 auto 模式会顺带抽内嵌 ASS(每个 2 分钟),本次回溯因此中断过一次 - renamer 保留 <规范名>-YYYYMMDD.期名 的尾巴:技术标签变化会重算前缀, 之前会把期名整段丢掉(WEB-DL 里的连字符不能当作分隔符) - 已按新标签回溯全库:动漫电影 117、动漫节目 92、电影 404、电视节目 3309、 综艺 603 条重命名,0 错误、0 冲突副本
275 lines
14 KiB
Python
275 lines
14 KiB
Python
# src/core/pipeline.py
|
||
|
||
import sys
|
||
from pathlib import Path
|
||
from core.logger import log
|
||
from core import config
|
||
from core.constants import RegexPatterns
|
||
from core.task import TaskManager
|
||
from services.parser import ParserService
|
||
from services.subtitle import SubtitleService
|
||
from services.metadata import MetadataService
|
||
from services.renamer import RenamerService
|
||
from services.preflight import PreflightService, BLOCKED, TRANSCODE
|
||
|
||
class MediaPipeline:
|
||
"""中央流水线协调器:接管扫描、判定与防爆防撞逻辑"""
|
||
|
||
def __init__(self, target_dir: Path, args, auto_execute=False):
|
||
self.target_dir = target_dir
|
||
self.args = args
|
||
self.auto_execute = auto_execute
|
||
self.task_mgr = TaskManager()
|
||
self.context_cache = {}
|
||
self.media_types_by_root = {}
|
||
self.tv_episode_tracker = {}
|
||
self.valid_files = []
|
||
self.preflight = []
|
||
|
||
def run(self):
|
||
"""返回退出码:0 正常(含无需变更),2 用户取消。"""
|
||
if getattr(self.args, "mode", "") == "variety":
|
||
return self.run_variety()
|
||
|
||
self._analyze_files()
|
||
if not self.valid_files:
|
||
if not self.auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
|
||
return 0
|
||
|
||
self._generate_plan()
|
||
# 只在「整库扫描」且存在 PREP/BLOCKED 时落报告,避免每个剧目录多一个 CSV
|
||
if self.target_dir.resolve() == config.MEDIA_ROOT.resolve():
|
||
PreflightService.write_report(self.target_dir, self.preflight, only_issues=True)
|
||
|
||
if not self.task_mgr.has_tasks():
|
||
if not self.auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
|
||
return 0
|
||
|
||
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
||
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||
self.task_mgr.execute()
|
||
log.info("🎉 流水线操作圆满落地!")
|
||
return 0
|
||
elif not self.auto_execute:
|
||
log.info("💤 任务已由用户取消。")
|
||
return 2
|
||
return 0
|
||
|
||
def run_variety(self) -> int:
|
||
"""综艺整理:按日期匹配集号,产出 改名 / extras / 删除 三类动作。"""
|
||
from services.variety import VarietyService
|
||
|
||
folder = self.target_dir
|
||
show = self._resolve_variety_show(folder)
|
||
if not show:
|
||
log.error("❌ 无法识别剧集:请在目录名里加 [tmdbid-xxx],或用 --show <id> 指定")
|
||
return 1
|
||
show_id, show_name, season_years, media_title = show
|
||
|
||
plan = VarietyService.plan(folder, show_id, show_name, season_years)
|
||
VarietyService.preview(plan, season_years, media_title)
|
||
|
||
total = len(plan["renames"]) + len(plan["extras"]) + len(plan["deletes"])
|
||
if not total:
|
||
log.info("✨ 无需整理。")
|
||
return 0
|
||
|
||
if not self.auto_execute:
|
||
try:
|
||
answer = input("⚠️ 是否执行以上变更(含删除)?[y/n/q]: ").strip().lower()
|
||
except EOFError:
|
||
log.warning("⛔ 没有可用的终端输入,按取消处理。")
|
||
return 2
|
||
if answer not in {"y", "yes"}:
|
||
log.info("💤 任务已由用户取消。")
|
||
return 2
|
||
|
||
stats = VarietyService.execute(plan, season_years, media_title)
|
||
log.info(f"🎉 综艺整理完成:改名 {stats['renamed']},extras {stats['extras']},"
|
||
f"删除 {stats['deleted']},跳过 {stats['skipped']}")
|
||
return 0
|
||
|
||
def _resolve_variety_show(self, folder: Path):
|
||
"""返回 (tmdb_id, 标题, season_years, media_title);识别失败返回 None。"""
|
||
import re as _re
|
||
from services.tmdb import TMDBService
|
||
|
||
match = _re.search(r"\[tmdbid-(\d+)\]", folder.name)
|
||
known = int(match.group(1)) if match else getattr(self.args, "show", None)
|
||
|
||
videos = [p for p in folder.rglob("*")
|
||
if p.is_file() and p.suffix.lower() in {".mkv", ".mp4", ".avi"}]
|
||
if not videos:
|
||
return None
|
||
probe = videos[0]
|
||
|
||
title = _re.sub(r"\[tmdbid-\d+\]", "", folder.name)
|
||
title = _re.sub(r"[\(\(]?\s*(19|20)\d{2}\s*[\)\)]?", "", title)
|
||
title = _re.sub(r"第\s*[0-9一二三四五六七八九十]+\s*季", "", title)
|
||
title = _re.sub(r"[Ss]eason\s*\d+", "", title)
|
||
title = _re.sub(r"[._]+", " ", title).strip(" -_")
|
||
|
||
year_match = _re.search(r"(19|20)\d{2}", folder.name)
|
||
year = year_match.group(0) if year_match else None
|
||
|
||
log.info(f"🔎 识别剧集:标题=「{title}」年份={year or '无'}"
|
||
f"{' 已知 id=' + str(known) if known else ''}")
|
||
entity = TMDBService.search_media(title, year, "tv", None,
|
||
known_tmdb_id=known, media_path=probe)
|
||
if not entity:
|
||
return None
|
||
return (entity["tmdb_id"], entity["title"],
|
||
entity.get("season_years") or {}, entity.get("media_title") or entity["title"])
|
||
|
||
def _analyze_files(self):
|
||
files_to_process = self.target_dir.rglob("*")
|
||
if not self.auto_execute: log.info("🔍 开始执行文件结构分析...")
|
||
|
||
for f in files_to_process:
|
||
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
|
||
|
||
# 跳过隐藏目录(如 .preflight_backup 备份、.git 等)
|
||
if any(part.startswith('.') for part in f.relative_to(self.target_dir).parts):
|
||
continue
|
||
|
||
# Jellyfin 的额外内容目录(extras/trailers/featurettes…)不算正片
|
||
parents = {p.lower() for p in f.relative_to(self.target_dir).parts[:-1]}
|
||
if parents & set(config.EXTRAS_DIRS):
|
||
log.debug(f"⏭ [额外内容] 跳过: {f.parent.name}/{f.name}")
|
||
continue
|
||
|
||
# 黑名单拦截
|
||
if any(excl in str(f) for excl in config.EXCLUDE_DIRS):
|
||
log.debug(f"🛑 [黑名单拦截] 命中排除规则,跳过扫描: {f.parent.name}/{f.name}")
|
||
continue
|
||
|
||
struct = ParserService.infer_structure(f, self.context_cache, forced_type=getattr(self.args, 'force_type', None))
|
||
if not struct: continue
|
||
|
||
m_type = struct[0]
|
||
root_dir_path = struct[5]
|
||
|
||
log.debug(f"判定: [{m_type.upper():^5}] <- {f.parent.name}/{f.name}")
|
||
|
||
# 剧集电影目录防爆锁
|
||
if root_dir_path not in self.media_types_by_root:
|
||
self.media_types_by_root[root_dir_path] = set()
|
||
|
||
self.media_types_by_root[root_dir_path].add(m_type)
|
||
|
||
if len(self.media_types_by_root[root_dir_path]) > 1:
|
||
log.error(f"❌ 严重安全拦截:在同一目录 [{root_dir_path.name}] 下混合了电影和电视剧!")
|
||
log.error(f"⚠️ 触发拦截的嫌疑文件: {f.name} (被判定为 {m_type})")
|
||
if not self.auto_execute: sys.exit(1)
|
||
return
|
||
|
||
self.valid_files.append((f, *struct))
|
||
|
||
def _generate_plan(self):
|
||
if not self.auto_execute: log.info("📝 正在生成执行计划...")
|
||
dir_video_counts = {f.parent: 0 for f, *_ in self.valid_files}
|
||
for f, m_type, *_ in self.valid_files:
|
||
if m_type == "movie": dir_video_counts[f.parent] += 1
|
||
|
||
for f, m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder in self.valid_files:
|
||
# 🧪 入库前体检:能否在电视上直传
|
||
pf = PreflightService.evaluate(f)
|
||
self.preflight.append((f, pf))
|
||
if pf.verdict == BLOCKED:
|
||
log.error(f"⛔ 无法直传,跳过入库: {f.name} | {'; '.join(pf.reasons)}")
|
||
continue
|
||
|
||
is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
|
||
target_stem, folder_name = ParserService.get_target_info(
|
||
f, m_type, title, year, season_num, is_multi)
|
||
|
||
# 集数防撞防爆锁
|
||
if m_type == "tv":
|
||
ep_match = RegexPatterns.TRACKER_EP.search(target_stem)
|
||
if ep_match:
|
||
ep_id = ep_match.group(1)
|
||
tracker_key = (str(root_dir_path), ep_id)
|
||
|
||
if tracker_key in self.tv_episode_tracker:
|
||
conflict_file = self.tv_episode_tracker[tracker_key]
|
||
log.error("=" * 80)
|
||
log.error(f"❌ 严重安全拦截:同剧集下发现重复的集号 [{ep_id}]!")
|
||
log.error(f" ├─ [冲突文件 A]: {conflict_file.absolute()}")
|
||
log.error(f" └─ [冲突文件 B]: {f.absolute()}")
|
||
if not self.auto_execute: sys.exit(1)
|
||
return
|
||
else:
|
||
self.tv_episode_tracker[tracker_key] = f
|
||
|
||
# 智能路由决策中心
|
||
is_flat_tv = (m_type == "tv" and f.parent == root_dir_path)
|
||
if is_flat_tv:
|
||
ep_match = RegexPatterns.ROUTING_S_NUM.search(target_stem)
|
||
s_num = ep_match.group(1) if ep_match else "01"
|
||
dest_dir = root_dir_path / f"Season {s_num}"
|
||
else:
|
||
dest_dir = f.parent
|
||
|
||
# 「<目标名>-描述」视为已规范:综艺整理会在技术标签后用「-期名」补充说明,
|
||
# 整库扫描不应把它当作错名再改回去。
|
||
is_perfect = (f.name == f"{target_stem}{f.suffix.lower()}"
|
||
or f.stem.startswith(f"{target_stem}-"))
|
||
skip_heavy = config.SKIP_PERFECT_MATCH and is_perfect and self.args.mode not in ["clean-ads", "extract-subs"]
|
||
|
||
if skip_heavy and not self.auto_execute:
|
||
if self.args.extract_internal:
|
||
log.info(f"💡 [特权放行] {f.name} 检测到强制参数,放行底层扫描。")
|
||
else:
|
||
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
|
||
|
||
if self.args.mode != "clean-ads" and not getattr(self.args, "rename_only", False):
|
||
# 文本字幕(ASS / SRT)外置化只对必须转码的片源做:
|
||
# 直传片源的内嵌字幕客户端能直接渲染,不需要外挂副本。
|
||
# 显式 extract-subs 或 --extract-internal 视为强制,不受此限制。
|
||
forced_subs = bool(self.args.extract_internal) or self.args.mode == "extract-subs"
|
||
want_text_subs = forced_subs or pf.verdict == TRANSCODE
|
||
|
||
# 外挂 SRT 兜底:只在没配置 ASS 导出时启用,
|
||
# 否则同一语言会同时出现 .internal.<lang>.ass 和 .srt 两份。
|
||
if (want_text_subs and config.EXPORT_TEXT_SUBS and pf.verdict == TRANSCODE
|
||
and 'ass' not in config.SUBTITLE_EXPORT):
|
||
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:
|
||
# 🎯 内嵌字幕优先:先看内嵌,有就不再处理外挂
|
||
internal_subs = 0
|
||
if want_text_subs:
|
||
if not skip_heavy or forced_subs:
|
||
internal_subs = SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||
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 want_text_subs and (not has_ext_sub or forced_subs) and (not skip_heavy or forced_subs):
|
||
SubtitleService.scan_subtitles(f, self.task_mgr, target_stem, dest_dir)
|
||
|
||
# 内嵌字体附件(ASS 特效字体还原):只有抽了 ASS 才有意义
|
||
if config.EXTRACT_FONTS and want_text_subs:
|
||
SubtitleService.scan_fonts(f, self.task_mgr, dest_dir)
|
||
|
||
if (self.args.mode != "extract-subs" and not skip_heavy
|
||
|
||
and not getattr(self.args, "rename_only", False)):
|
||
MetadataService.scan_ads(f, self.task_mgr)
|
||
MetadataService.scan_audio_tracks(f, self.task_mgr)
|
||
|
||
if self.args.mode not in ["clean-ads", "extract-subs"]:
|
||
RenamerService.scan_rename(f, target_stem, m_type, dest_dir, target_season_folder, root_dir_path, folder_name, self.task_mgr)
|