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
+22 -154
View File
@@ -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}|(?<!\d)(?:EP|E|第)(\d{1,3})(?:集)?(?!\d)', file_path.stem, re.IGNORECASE)
pure_number_match = re.fullmatch(r'\d{1,3}', file_path.stem)
# 💡 核心改动:最高优先级判断 forced_type
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:
# 扁平 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
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})(?:集|话)?|(?<![a-zA-Z0-9])(\d{1,4})(?![a-zA-Z0-9])'
match = re.search(regex, f_path.stem, re.IGNORECASE)
ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01"
# 💡 核心新增:提取本季独立年份
# 默认使用主年份兜底,如果缓存中有 season_years 且包含当前 season_num,则覆盖
episode_year = year
if tmdb and "season_years" in tmdb:
episode_year = tmdb["season_years"].get(season_num, year)
# 文件名使用本季独立年份 episode_year
return f"{display_name}.S{season_num}E{ep}.{episode_year}.{tech}", target_folder
@staticmethod
def detect_subtitle_language(sub_path: Path) -> 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})|(?<!\d)E(\d{1,3})(?!\d)', sub.name, re.IGNORECASE)
match = RegexPatterns.SUB_EP_MATCH.search(sub.name)
if match:
ep = next((g for g in match.groups() if g), None)
target_ep_match = re.search(r'E(\d{2,3})', target_stem)
target_ep_match = RegexPatterns.SUB_TARGET_EP.search(target_stem)
if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1):
is_match = True
if is_match:
has_external_sub = True # 💡 只要匹配到,就说明存在外挂字幕
lang_tag = RenamerService.detect_subtitle_language(sub)
has_external_sub = True
lang_tag = MediaUtil.detect_subtitle_language(sub)
# 💡 核心修改 1.2: 如果不是 srt,执行转换任务
if sub.suffix.lower() != '.srt':
desired_path = dest_dir / f"{target_stem}.{lang_tag}.srt"
# ==========================================
# 🛡️ 恢复丢失的外挂转换前置拦截器
# ==========================================
if desired_path.exists() and desired_path.stat().st_size > 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() 统一接管输出,此处无需重复打印