- 新增 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
139 lines
6.6 KiB
Python
139 lines
6.6 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
|
||
|
||
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 = []
|
||
|
||
def run(self):
|
||
self._analyze_files()
|
||
if not self.valid_files:
|
||
if not self.auto_execute: log.warning("⚠️ 扫描结束:未检测到任何需要处理的媒体文件。")
|
||
return
|
||
|
||
self._generate_plan()
|
||
|
||
if not self.task_mgr.has_tasks():
|
||
if not self.auto_execute: log.info("✨ 您的媒体库目前处于完美状态,无需任何物理变更。")
|
||
return
|
||
|
||
if self.task_mgr.preview_and_confirm(self.auto_execute):
|
||
if not self.auto_execute: log.info("⚙️ 正在执行物理任务...")
|
||
self.task_mgr.execute()
|
||
log.info("🎉 流水线操作圆满落地!")
|
||
elif not self.auto_execute:
|
||
log.info("💤 任务已由用户取消。")
|
||
|
||
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:
|
||
|
||
# 黑名单拦截
|
||
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:
|
||
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()}")
|
||
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":
|
||
has_ext_sub = RenamerService.scan_existing_subtitles(f, target_stem, m_type, dest_dir, self.task_mgr)
|
||
should_extract_internal = (not has_ext_sub) or config.EXTRACT_INTERNAL_SUBS or self.args.extract_internal
|
||
|
||
if should_extract_internal 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)
|
||
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)
|