From b389fc39010ef523d3b3793284f85e4016fd70ee Mon Sep 17 00:00:00 2001 From: Hraulein Date: Tue, 17 Nov 2026 11:32:40 +0800 Subject: [PATCH] =?UTF-8?q?refactor(pipeline):=20=E6=8B=86=E5=88=86=20Pars?= =?UTF-8?q?erService=EF=BC=8C=E6=8A=8A=E6=B5=81=E6=B0=B4=E7=BA=BF=E6=8A=BD?= =?UTF-8?q?=E7=A6=BB=E4=B8=BA=20MediaPipeline?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 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 --- media/src/core/pipeline.py | 138 ++++++++++++++++++++++++++ media/src/main.py | 153 +---------------------------- media/src/services/parser.py | 106 ++++++++++++++++++++ media/src/services/renamer.py | 176 +++++----------------------------- 4 files changed, 271 insertions(+), 302 deletions(-) create mode 100644 media/src/core/pipeline.py create mode 100644 media/src/services/parser.py diff --git a/media/src/core/pipeline.py b/media/src/core/pipeline.py new file mode 100644 index 0000000..2276def --- /dev/null +++ b/media/src/core/pipeline.py @@ -0,0 +1,138 @@ +# 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) diff --git a/media/src/main.py b/media/src/main.py index 38c27b8..bf0a32a 100644 --- a/media/src/main.py +++ b/media/src/main.py @@ -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) \ No newline at end of file + sys.exit(130) diff --git a/media/src/services/parser.py b/media/src/services/parser.py new file mode 100644 index 0000000..a22f0ba --- /dev/null +++ b/media/src/services/parser.py @@ -0,0 +1,106 @@ +# src/services/parser.py + +from pathlib import Path +from core import config +from core.logger import log +from core.constants import RegexPatterns +from core.utils import StringUtil +from services.mediainfo import MediaInfoService +from services.tmdb import TMDBService + +class ParserService: + """纯业务计算与媒体结构解析器 (无状态)""" + + @staticmethod + def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None): + parent_name = file_path.parent.name + grandparent_name = file_path.parent.parent.name + + season_match = RegexPatterns.SEASON_DIR.match(parent_name) + flat_tv_match = RegexPatterns.FLAT_TV.search(file_path.stem) + pure_number_match = RegexPatterns.PURE_NUMBER.fullmatch(file_path.stem) + + if forced_type == "tv" or (not forced_type and season_match): + m_type = "tv" + if season_match: + season_num = season_match.group(1).zfill(2) + target_season_folder = f"Season {season_num}" + target_name, root_dir_path = grandparent_name, file_path.parent.parent + else: + season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2) + target_season_folder = None + target_name, root_dir_path = parent_name, file_path.parent + + elif forced_type == "movie" or (not forced_type and not season_match and not (flat_tv_match or pure_number_match)): + m_type = "movie" + season_num = "01" + target_season_folder = None + + if season_match: + target_name, root_dir_path = grandparent_name, file_path.parent.parent + else: + target_name, root_dir_path = parent_name, file_path.parent + + elif not forced_type and (flat_tv_match or pure_number_match): + m_type = "tv" + season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2) + target_season_folder = None + target_name, root_dir_path = parent_name, file_path.parent + else: + return None + + root_key = str(root_dir_path) + if root_key not in context_cache: + clean_name = RegexPatterns.TMDB_CLEAN.sub('', target_name).strip() + tm = RegexPatterns.TMDB_CLEAN.search(target_name) + if tm: + title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2) + else: + title, year = clean_name.strip().replace(' ', '.'), "" + + if not year: + context_path = " / ".join(file_path.parts[-3:]) + log.warning(f"目录命名不规范: {root_dir_path.name}") + log.warning(f"📁 案发现场: {context_path}") + + user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip() + if user_title: title = user_title.replace(' ', '.') + while not RegexPatterns.YEAR_EXACT.match(year): + year = input(f" ➤ 请输入 4 位年份: ").strip() + + context_cache[root_key] = (title, year) + + title, year = context_cache[root_key] + return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})" + + @staticmethod + def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False): + tags = MediaInfoService.get_scene_tags(f_path) + tmdb = TMDBService.search_media(title, year, m_type, season_num) + + orig = tmdb['original_title'] if tmdb else "" + if orig: + display_name = orig + else: + display_name = StringUtil.sanitize_title(title) + + tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else "" + + source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL" + tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}" + + target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip() + + if m_type == "movie": + if is_multi_version: + return f"{title} ({year}) - {tech}", target_folder + return f"{display_name}.{year}.{tech}", target_folder + else: + match = RegexPatterns.TARGET_EP.search(f_path.stem) + ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01" + + episode_year = year + if tmdb and "season_years" in tmdb: + episode_year = tmdb["season_years"].get(season_num, year) + + return f"{display_name}.S{season_num}E{ep}.{episode_year}.{tech}", target_folder diff --git a/media/src/services/renamer.py b/media/src/services/renamer.py index 264d277..eb228f3 100644 --- a/media/src/services/renamer.py +++ b/media/src/services/renamer.py @@ -1,175 +1,64 @@ # src/services/renamer.py -import re from pathlib import Path -from .mediainfo import MediaInfoService -from .tmdb import TMDBService from core import config from core.logger import log +from core.constants import RegexPatterns +from core.utils import MediaUtil +from services.fileops import FileOpsService class RenamerService: + """媒体文件规范重命名编排器""" - @staticmethod - def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None): - parent_name = file_path.parent.name - grandparent_name = file_path.parent.parent.name - - season_match = re.match(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', parent_name, re.IGNORECASE) - flat_tv_match = re.search(r'S(\d{1,2})E\d{1,3}|(?= 1 and flat_tv_match.group(1) else "01").zfill(2) - target_season_folder = None - target_name, root_dir_path = parent_name, file_path.parent - - elif forced_type == "movie" or (not forced_type and not season_match and not (flat_tv_match or pure_number_match)): - m_type = "movie" - season_num = "01" - target_season_folder = None - - # 容错:如果用户把电影放进了 "Season 1" 这种文件夹里,且被强制指定为 movie,需向上一级找根目录 - if season_match: - target_name, root_dir_path = grandparent_name, file_path.parent.parent - else: - target_name, root_dir_path = parent_name, file_path.parent - - elif not forced_type and (flat_tv_match or pure_number_match): - # 原本的自动扁平 TV 判断 - m_type = "tv" - season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2) - target_season_folder = None - target_name, root_dir_path = parent_name, file_path.parent - else: - return None # 异常流保护 - - root_key = str(root_dir_path) - if root_key not in context_cache: - clean_name = re.sub(r'\s*[\[\(]tmdbid-\d+[\]\)]', '', target_name).strip() - tm = re.search(r'^(.*?)\s*[\[\(](\d{4})[\]\)]', clean_name) - if tm: - title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2) - else: - title, year = clean_name.strip().replace(' ', '.'), "" - - if not year: - # 💡 取路径的最后三级(爷爷/爸爸/儿子),给用户提供充足的上下文 - context_path = " / ".join(file_path.parts[-3:]) - log.warning(f"目录命名不规范: {root_dir_path.name}") - log.warning(f"📁 案发现场: {context_path}") # 👈 增加这一行,清晰定位 - - user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip() - if user_title: title = user_title.replace(' ', '.') - while not re.match(r'^\d{4}$', year): - year = input(f" ➤ 请输入 4 位年份: ").strip() - - context_cache[root_key] = (title, year) - - title, year = context_cache[root_key] - return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})" - - @staticmethod - def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False): - tags = MediaInfoService.get_scene_tags(f_path) - # 💡 这里多传一个 season_num,让 TMDB 服务自己决定要不要更新缓存 - tmdb = TMDBService.search_media(title, year, m_type, season_num) - orig = tmdb['original_title'] if tmdb else "" - if orig: - display_name = orig - else: - display_name = re.sub(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+', '.', title.replace("'", "").replace("’", "")).strip('.') - - tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else "" - - source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL" - tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}" - - # ⚠️ 根目录文件夹使用主年份 (剧集首播年份) - target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip() - - if m_type == "movie": - if is_multi_version: - return f"{title} ({year}) - {tech}", target_folder - return f"{display_name}.{year}.{tech}", target_folder - else: - regex = r'S\d{1,2}E(\d{1,4})|(?:EP|E|第|期)(\d{1,4})(?:集|话)?|(? str: - name = sub_path.name.lower() - if re.search(r'\.(cht|big5|zh-tw|tw|繁体)\.', name): return "zh-TW" - if re.search(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', name): return "zh-CN" - if re.search(r'\.(eng|en|english)\.', name): return "en" - - try: - content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000] - if re.search(r'[\u4e00-\u9fa5]', content): - return "zh-TW" if len(re.findall(r'[傳統萬與飛沒]', content)) > 5 else "zh-CN" - return "und" - except: return "und" - @staticmethod def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr) -> bool: - has_external_sub = False # 💡 初始化状态标识 + has_external_sub = False for sub in f_path.parent.glob("*"): if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}: is_match = False if f_path.stem in sub.name: is_match = True elif m_type == "tv": - match = re.search(r'S\d{1,2}E(\d{1,3})|(? 0: + log.debug(f"✨ [跳过转换] 孪生 SRT 已存在,忽略外挂源文件: {sub.name}") + continue + reserved_path = task_mgr.reserve_path(desired_path, source_path=sub) - from services.subtitle import SubtitleService # 延迟导入 + from services.subtitle import SubtitleService task_mgr.add_extract( f"[外挂字幕转换] {sub.name} --> {reserved_path.name}", SubtitleService.convert_to_srt, (sub, reserved_path) ) else: - # 是 srt,正常走重命名 desired_path = dest_dir / f"{target_stem}.{lang_tag}.srt" reserved_path = task_mgr.reserve_path(desired_path, source_path=sub) if sub.resolve() != reserved_path.resolve(): task_mgr.add_file_rename( f"[规范外挂字幕] {sub.name} --> {reserved_path.name}", - RenamerService.do_rename_single, + FileOpsService.move_file, (sub, reserved_path) ) - return has_external_sub # 💡 把结果返回给 main.py + return has_external_sub @staticmethod def scan_rename(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr): @@ -179,31 +68,23 @@ class RenamerService: if f_path.resolve() != reserved_new_path.resolve(): task_mgr.add_file_rename( f"[主视频] {f_path.name} --> {reserved_new_path.name}", - RenamerService.do_rename_single, + FileOpsService.move_file, (f_path, reserved_new_path) ) for asset in f_path.parent.glob(f"{f_path.stem}*"): if asset.is_file() and asset.suffix.lower() in config.SIDECAR_EXTS: - - # 💡 核心修复:边界安全检查 - # 截取被匹配文件名多出来的“尾巴”部分 rest_of_name = asset.name[len(f_path.stem):] - - # 如果尾巴的第一个字符是字母或数字(比如 E10 匹配到了 E103,尾巴是 '3.nfo') - # 说明这是一个“假匹配”,立刻跳过! if rest_of_name and rest_of_name[0].isalnum(): continue - # 💡 安全组装:目标主文件名 + 剩余的合法尾巴 (如 '-thumb.jpg' 或 '.nfo') new_asset_name = f"{target_stem}{rest_of_name}" - reserved_asset = task_mgr.reserve_path(dest_dir / new_asset_name, source_path=asset) if asset.resolve() != reserved_asset.resolve(): task_mgr.add_file_rename( f"[附属元数据] {asset.name} --> {reserved_asset.name}", - RenamerService.do_rename_single, + FileOpsService.move_file, (asset, reserved_asset) ) @@ -214,16 +95,3 @@ class RenamerService: if root_dir_path.name != target_root_folder: task_mgr.add_root_dir_rename(root_dir_path, root_dir_path.with_name(target_root_folder)) - - @staticmethod - def do_rename_single(old_path: Path, new_path: Path): - """执行物理重命名/移动任务,并记录审计日志""" - if old_path.exists() and old_path != new_path: - # 💡 物理层变更审计:检测并创建缺失的季目录/电影目录 - if not new_path.parent.exists(): - log.info(f"🆕 发现目标目录不存在,正在执行物理创建: {new_path.parent.absolute()}") - new_path.parent.mkdir(parents=True, exist_ok=True) - - # 执行移动 - old_path.rename(new_path) - # 注意:成功移动后的日志由 task.py 的 execute() 统一接管输出,此处无需重复打印 \ No newline at end of file