update 202605101839

This commit is contained in:
Hraulein
2026-05-10 18:39:16 +08:00
parent 5992a09da2
commit 13d433e731
9 changed files with 419 additions and 205 deletions
+114 -59
View File
@@ -8,39 +8,52 @@ from core import config
from core.logger import log
class RenamerService:
@staticmethod
def infer_structure(file_path: Path, context_cache: dict):
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
# 1. 标准季目录识别
season_match = re.match(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', parent_name, re.IGNORECASE)
if season_match:
m_type, season_num = "tv", 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:
# 💡 2. 扁平电视节目嗅探 (Flat TV Show)
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)
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)
if 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 # 🛡️ 核心保护:设为 None 表示禁止重命名父目录
target_name, root_dir_path = parent_name, file_path.parent
# 💡 核心改动:最高优先级判断 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:
m_type, season_num = "movie", "01"
# 扁平 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:
# 💡 核心修复:先剔除已有的 [tmdbid] 干扰
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)
@@ -48,7 +61,11 @@ class RenamerService:
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):
@@ -61,32 +78,40 @@ class RenamerService:
@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)
# 💡 调用新的 search_media,并把 m_type 传给它
tmdb = TMDBService.search_media(title, year, m_type)
# 💡 策略:文件名用英文/原名,文件夹用中文
eng = tmdb['english_title'] if tmdb else ""
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 ""
# 组装技术串 (Scene 规范)
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
# 📁 文件夹:中文 (年份) [tmdbid]
# ⚠️ 根目录文件夹使用主年份 (剧集首播年份)
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
# 🎬 文件名:英文原名.年份.技术串
display_name = eng if eng else title
if m_type == "movie":
if is_multi_version:
return f"{title} ({year}) - {display_name}.{tech}", target_folder
return f"{title} ({year}) - {tech}", target_folder
return f"{display_name}.{year}.{tech}", target_folder
else:
# 💡 强化正则:提取 S01E01, EP01, E01, 或纯数字 01
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)(?:EP|E|第)?(\d{1,3})(?:集)?(?!\d)', f_path.name, re.IGNORECASE)
ep = next((g for g in match.groups() if g), "01").zfill(2)
return f"{display_name}.S{season_num}E{ep}.{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:
@@ -103,7 +128,7 @@ class RenamerService:
except: return "und"
@staticmethod
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, task_mgr):
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr):
for sub in f_path.parent.glob("*"):
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
is_match = False
@@ -118,41 +143,71 @@ class RenamerService:
if is_match:
lang_tag = RenamerService.detect_subtitle_language(sub)
new_name = f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
if sub.name != new_name:
desired_path = dest_dir / f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
# 💡 传入 source_path,如果计算出的名字存在且就是自己,就不会强制加 .2
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} --> {new_name}",
f"[外挂字幕] {sub.name} --> {reserved_path.name}",
RenamerService.do_rename_single,
(sub, task_mgr.reserve_path(sub.with_name(new_name)))
(sub, reserved_path)
)
@staticmethod
def scan_rename(f_path: Path, target_stem: str, m_type: str, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr):
new_path = f_path.with_name(f"{target_stem}{f_path.suffix.lower()}")
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):
new_path = dest_dir / f"{target_stem}{f_path.suffix.lower()}"
reserved_new_path = task_mgr.reserve_path(new_path, source_path=f_path)
if f_path.name != new_path.name:
if f_path.resolve() != reserved_new_path.resolve():
task_mgr.add_file_rename(
f"[主视频] {f_path.name} --> {new_path.name}",
f"[主视频] {f_path.name} --> {reserved_new_path.name}",
RenamerService.do_rename_single,
(f_path, task_mgr.reserve_path(new_path))
(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:
new_asset_name = asset.name.replace(f_path.stem, target_stem, 1)
task_mgr.add_file_rename(
f"[附属元数据] {asset.name} --> {new_asset_name}",
RenamerService.do_rename_single,
(asset, task_mgr.reserve_path(asset.with_name(new_asset_name)))
)
# 💡 只有在 target_season_folder 存在时才允许修改季目录(完美跳过扁平电视节目)
if m_type == "tv" and target_season_folder and f_path.parent.name != target_season_folder:
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
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,
(asset, reserved_asset)
)
# 这里的目录重命名逻辑保持不变,但增加一个防爆锁
if m_type == "tv" and target_season_folder and f_path.parent.name != target_season_folder:
if f_path.parent != root_dir_path: # 🛡️ 防爆锁:绝不允许对根目录执行季目录改名
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
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:
old_path.rename(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() 统一接管输出,此处无需重复打印