根因:valid_files 自 b389fc39 起存的是 (Path, 媒体类型, 标题, …) 元组,
_clean_ad_tags 却按 Path 列表写 f.suffix,一进广告清理阶段就抛
AttributeError: 'tuple' object has no attribute 'suffix',
整个整理任务在生成计划前失败(退出码 1)。
改动:取路径改为 `for f, *_ in self.valid_files`,与 _generate_plan 的写法一致。
实测:Windows 探针(桩掉 pysubs2/ffprobe)旧代码复现同一异常、新代码只把
视频文件交给 MetaCleanService.scan;N100 上 media-rename 全流程通过。
377 lines
18 KiB
Python
377 lines
18 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
|
||
|
||
# 阶段:清理容器里的广告元数据(治本:无损重封装丢掉全局标签)
|
||
if (getattr(config, "CLEAN_AD_TAGS", True)
|
||
and not getattr(self.args, "rename_only", False)):
|
||
self._clean_ad_tags()
|
||
|
||
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_specials(self) -> int:
|
||
"""特典放置:把 Season 00 按播出日期插进正季(写 NFO 的 airsbefore/airsafter)。"""
|
||
from services.specials import SpecialsService
|
||
|
||
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 = show[0], show[1], show[2]
|
||
|
||
plans = SpecialsService.compute(show_id)
|
||
if not plans:
|
||
log.info("✨ 该剧没有需要放置的特典(或 TMDB 未提供播出日期)。")
|
||
return 0
|
||
SpecialsService.preview(plans)
|
||
|
||
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 = SpecialsService.apply_via_api(show_name, plans)
|
||
log.info(f"🎉 {show_name}:写入 {stats['written']} 个放置信息,"
|
||
f"{stats['missing']} 个 Jellyfin 里没有对应条目,{stats.get('failed', 0)} 个失败")
|
||
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_year = show
|
||
|
||
plan = VarietyService.plan(folder, show_id, show_name, season_years, show_year)
|
||
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 run_jellyfin_fix(self) -> int:
|
||
"""Jellyfin 侧广告元数据修复:plot / genre / 工作室 / NFO。
|
||
|
||
文件侧的标签由整理流水线(MetaCleanService)抹掉;这里修的是 Jellyfin
|
||
自己库里的旧值,以及会被重新扫回去的 NFO sidecar。
|
||
"""
|
||
from services.jellyfinmeta import JellyfinAdFixService
|
||
|
||
dry_run = bool(getattr(self.args, "dry_run", False))
|
||
stats = JellyfinAdFixService.repair(self.target_dir, dry_run=dry_run,
|
||
auto_execute=self.auto_execute)
|
||
if stats.get("cancelled"):
|
||
return 2
|
||
if dry_run:
|
||
return 0
|
||
|
||
report = JellyfinAdFixService.write_report(stats)
|
||
log.info(f"📄 报告已写入 {report}")
|
||
if stats["remaining"] or stats["fields"]["failed"] or stats["entities"]["failed"]:
|
||
log.warning("⚠️ 仍有未修复的条目,详见上面的日志/报告")
|
||
return 1
|
||
log.info("🎉 Jellyfin 元数据已干净")
|
||
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 config.VIDEO_EXTS]
|
||
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"],
|
||
str(entity.get("year") or ""))
|
||
|
||
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 _clean_ad_tags(self) -> None:
|
||
"""阶段:清理容器里的广告元数据(comment/genre 等被发布组写成广告链接)。
|
||
|
||
治本做法是无损重封装丢掉全局元数据;顺手清掉同名 NFO 里的广告字段。
|
||
"""
|
||
from services.metaclean import MetaCleanService
|
||
|
||
files = [f for f, *_ in self.valid_files if f.suffix.lower() in config.VIDEO_EXTS]
|
||
if not files:
|
||
return
|
||
hits = []
|
||
for path in files:
|
||
junk = MetaCleanService.scan(path)
|
||
if junk:
|
||
hits.append((path, junk))
|
||
if not hits:
|
||
return
|
||
|
||
log.info(f"🧹 阶段:发现 {len(hits)} 个文件的容器元数据里带广告")
|
||
for path, junk in hits:
|
||
preview = "; ".join(f"{k}={str(v)[:40]}" for k, v in junk.items())
|
||
log.info(f" - {path.name[:50]} ← {preview}")
|
||
|
||
if not self.auto_execute:
|
||
try:
|
||
answer = input(f"⚠️ 是否重封装这 {len(hits)} 个文件以清除广告?[y/n]: ").strip().lower()
|
||
except EOFError:
|
||
log.warning("⛔ 没有可用的终端输入,跳过广告元数据清理。")
|
||
return
|
||
if answer not in {"y", "yes"}:
|
||
log.info("💤 已跳过广告元数据清理。")
|
||
return
|
||
|
||
stripped = 0
|
||
for path, _junk in hits:
|
||
result = MetaCleanService.process(path)
|
||
if result.get("stripped"):
|
||
stripped += 1
|
||
log.info(f"🧹 广告元数据清理完成:{stripped}/{len(hits)} 个文件已重封装")
|
||
|
||
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)
|