refactor(pipeline): 拆分 ParserService,把流水线抽离为 MediaPipeline

- 新增 services/parser.py:接管 infer_structure / get_target_info,纯计算无状态
- renamer.py 只保留扫描编排,物理改名委托 FileOpsService,移除 do_rename_single
- 恢复被误删的季目录/根目录重命名调用(task.py 侧已改用 FileOpsService)
- 新增 core/pipeline.py:接管文件扫描、电影/剧集混排与重复集号防爆锁、执行流程
- main.py 只保留 CLI 入口,watch 与手动模式统一调用 MediaPipeline
This commit is contained in:
Hraulein
2026-11-17 11:32:40 +08:00
parent 53fdb1572c
commit b389fc3901
4 changed files with 271 additions and 302 deletions
+5 -148
View File
@@ -2,154 +2,11 @@
import sys
import argparse
import re
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.task import TaskManager
from services.subtitle import SubtitleService
from services.metadata import MetadataService
from services.renamer import RenamerService
def run_pipeline(target_dir: Path, args, auto_execute=False):
"""流水线作业:可被手动或守护进程触发"""
# 💡 核心修改:废弃平铺的 glob,让所有模式(包括 extract-subs, clean-ads 等)统统使用 rglob 递归深入子目录
files_to_process = target_dir.rglob("*")
media_types_by_root = {}
valid_files = []
context_cache = {}
if not auto_execute: log.info("🔍 开始执行文件结构分析...")
for f in files_to_process:
if f.is_file() and f.suffix.lower() in config.SUPPORTED_EXTS:
# 🛡️ 神器 1:黑名单绝对拦截机制
if any(excl in str(f) for excl in config.EXCLUDE_DIRS):
log.debug(f"🛑 [黑名单拦截] 命中排除规则,跳过扫描: {f.parent.name}/{f.name}")
continue
# 🛠️ 神器 2:结构分析 (带上一票否决权 force_type)
struct = RenamerService.infer_structure(f, context_cache, forced_type=getattr(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}")
# 💣 神器 3:精确制导防爆锁 (防撞判定缩小到单个剧集/电影目录下)
if root_dir_path not in media_types_by_root:
media_types_by_root[root_dir_path] = set()
media_types_by_root[root_dir_path].add(m_type)
if len(media_types_by_root[root_dir_path]) > 1:
log.error(f"❌ 严重安全拦截:在同一目录 [{root_dir_path.name}] 下混合了电影和电视剧!")
log.error(f"⚠️ 触发拦截的嫌疑文件: {f.name} (被判定为 {m_type})")
log.error("💡 提示:通常是因为剧集根目录下散落了未标明 S01E01 格式的花絮(SP/NCOP等)。")
if not auto_execute: sys.exit(1)
return # 守护模式下直接 return,不中断进程
valid_files.append((f, *struct))
if not valid_files:
if not auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
return
dir_video_counts = {f.parent: 0 for f, *_ in valid_files}
for f, m_type, *_ in valid_files:
if m_type == "movie": dir_video_counts[f.parent] += 1
if not auto_execute: log.info("📝 正在生成执行计划...")
task_mgr = TaskManager()
# 🛡️ 神器 4:集数追尾防爆追踪器
# 用于记录:{(剧集根目录, SxxExx) : 原始文件路径}
tv_episode_tracker = {}
for f, m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder in valid_files:
is_multi = (m_type == "movie" and dir_video_counts.get(f.parent, 0) > 1)
target_stem, folder_name = RenamerService.get_target_info(f, m_type, title, year, season_num, is_multi)
# 💡 [保留原样] 新增:集数防撞绝对拦截逻辑
if m_type == "tv":
ep_match = re.search(r'(S\d{1,2}E\d{1,3})', target_stem)
if ep_match:
ep_id = ep_match.group(1) # 例如:S01E06
tracker_key = (str(root_dir_path), ep_id)
if tracker_key in tv_episode_tracker:
conflict_file = 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()}")
log.error("💡 提示:这通常是因为花絮/SP未加 S00 标签,或命名极其不规范导致正则提取碰撞。")
log.error("🛡️ 为保护您的数据不被覆盖或错乱命名,流水线已紧急拉闸。请手动排查上述两个文件。")
log.error("=" * 80)
if not auto_execute: sys.exit(1)
return # 守护模式下安全退出,不中断进程
else:
tv_episode_tracker[tracker_key] = f
# ==================== 💡 NEW: 智能路由决策中心 ====================
is_flat_tv = (m_type == "tv" and f.parent == root_dir_path)
if is_flat_tv:
# 扁平结构的 TV,提取季号,强制分配到根目录下的 Season 目录
ep_match = re.search(r'S(\d{1,2})E', target_stem)
s_num = ep_match.group(1) if ep_match else "01"
dest_dir = root_dir_path / f"Season {s_num}"
else:
# 电影,或原本就已经在子目录的 TV,目标仍是当前目录(由后期的文件夹重命名接管)
dest_dir = f.parent
# ==================================================================
is_perfect = (f.name == f"{target_stem}{f.suffix.lower()}")
skip_heavy = config.SKIP_PERFECT_MATCH and is_perfect and args.mode not in ["clean-ads", "extract-subs"]
if skip_heavy and not auto_execute:
if args.extract_internal:
log.info(f"💡 [特权放行] {f.name} 检测到强制参数,放行底层扫描。")
else:
log.debug(f"✨ [完美豁免] {f.name} 已达最高工业标准,直接放行~")
if args.mode != "clean-ads":
# 💡 步骤 1:先扫描外挂字幕,接收状态反馈
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, task_mgr)
# 💡 步骤 2:联动决策
# 如果没有外挂字幕,或者用户在 config 开了全局强制,或者使用了 --extract-internal 参数,才执行内置提取
should_extract_internal = (not has_ext_sub) or config.EXTRACT_INTERNAL_SUBS or args.extract_internal
if should_extract_internal and (not skip_heavy or args.extract_internal or args.mode == "extract-subs"):
SubtitleService.scan_subtitles(f, task_mgr, target_stem, dest_dir)
if args.mode != "extract-subs" and not skip_heavy:
MetadataService.scan_ads(f, task_mgr)
MetadataService.scan_audio_tracks(f, task_mgr)
if args.mode not in ["clean-ads", "extract-subs"]:
# 💡 传入 dest_dir
RenamerService.scan_rename(f, target_stem, m_type, dest_dir, target_season_folder, root_dir_path, folder_name, task_mgr)
# 💡 [保留原样] 核心修复:提前拦截空任务,不再进入预览流程产生逻辑报错
if not task_mgr.has_tasks():
if not auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
return
# 这里才真正进入交互流程
if task_mgr.preview_and_confirm(auto_execute):
if not auto_execute: log.info("⚙️ 正在执行物理任务...")
task_mgr.execute()
log.info("🎉 流水线操作圆满落地!")
elif not auto_execute:
log.info("💤 任务已由用户取消。")
from core.pipeline import MediaPipeline # 💡 引入高度封装的管道中枢
def main():
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
@@ -168,7 +25,6 @@ def main():
target_dir = Path(args.path).resolve()
log.info(f"🚀 启动模式: [{args.mode.upper()}] | 扫描目标: {target_dir}")
# 💡 守护模式接管入口
if args.mode == "watch":
try:
from core.watcher import start_watch_daemon
@@ -177,15 +33,16 @@ def main():
sys.exit(1)
def scan_callback():
run_pipeline(target_dir, args, auto_execute=True)
# 💡 将重任交接给全新的 MediaPipeline
MediaPipeline(target_dir, args, auto_execute=True).run()
start_watch_daemon(target_dir, scan_callback)
else:
run_pipeline(target_dir, args, auto_execute=False)
MediaPipeline(target_dir, args, auto_execute=False).run()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
log.error("🛑 接收到手动中断指令 (Ctrl+C),任务已安全终止。")
sys.exit(130)
sys.exit(130)