This commit is contained in:
Hraulein
2026-05-09 20:00:30 +08:00
parent ab1fc775e9
commit d2fcb0df76
12 changed files with 604 additions and 235 deletions
+78 -77
View File
@@ -1,8 +1,11 @@
# python/services/renamer_srv.py
# 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
class RenamerService:
@staticmethod
@@ -10,6 +13,7 @@ class RenamerService:
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:
@@ -17,121 +21,109 @@ class RenamerService:
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"
target_season_folder = None
target_name, root_dir_path = parent_name, file_path.parent
# 💡 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)
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
else:
m_type, season_num = "movie", "01"
target_season_folder = None
target_name, root_dir_path = parent_name, file_path.parent
root_key = str(root_dir_path)
if root_key not in context_cache:
tm = re.match(r'^(.*?)(?:\s*[\[\(]?(\d{4})[\]\)]?)?$', target_name)
title = tm.group(1).strip().replace(' ', '.') if tm else target_name
year = tm.group(2) if tm else ""
# 💡 核心修复:先剔除已有的 [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)
else:
title, year = clean_name.strip().replace(' ', '.'), ""
if not year:
print(f"\n⚠️ 发现不规范的媒体目录: {root_dir_path.name}")
user_title = input(f" ➤ 请输入正确的标题 (回车默认使用 '{title}'): ").strip()
log.warning(f"目录命名不规范: {root_dir_path.name}")
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
if user_title: title = user_title.replace(' ', '.')
while not year:
year = input(f" ➤ 请输入正确的 4 位年份 (如 2023): ").strip()
if not re.match(r'^\d{4}$', year): year = ""
while not re.match(r'^\d{4}$', year):
year = input(f" ➤ 请输入 4 位年份: ").strip()
context_cache[root_key] = (title, year)
else:
title, year = context_cache[root_key]
target_root_folder = f"{title.replace('.', ' ')} ({year})"
return m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder
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_stem(f_path: Path, m_type: str, title: str, year: str, season: str, meta: dict) -> str:
tags = [title]
if m_type == "tv":
match = re.search(r'S\d{1,2}E(\d{1,3})|E(\d{1,3})|(?<!\d)(\d{2,3})(?!\d)', f_path.name, re.IGNORECASE)
ep = next((g for g in match.groups() if g), "00").zfill(2) if match else "00"
tags.append(f"S{season}E{ep}")
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)
if year: tags.append(year)
if meta.get("res"): tags.append(meta.get("res"))
if meta.get("hdr"): tags.append(meta.get("hdr"))
if meta.get("codec"): tags.append(meta.get("codec"))
if meta.get("bit"): tags.append(meta.get("bit"))
# 💡 策略:文件名用英文/原名,文件夹用中文
eng = tmdb['english_title'] if tmdb else ""
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
audio = meta.get("audio")
if audio:
if m_type == "movie" and meta.get("ch"): audio += f".{meta.get('ch')}.1"
tags.append(audio)
return re.sub(r'\s+', '.', ".".join(filter(None, tags)))
# 组装技术串 (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"{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
@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"
# 即使是中英双语,也统一归类为标准的 zh-CN
if re.search(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', name): return "zh-CN"
if re.search(r'\.(eng|en|english)\.', name): return "en"
if re.search(r'\.(jpn|ja|jp)\.', name): return "ja"
if re.search(r'\.(kor|ko|kr)\.', name): return "ko"
try:
# 嗅探文件头 5000 字符
content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000]
# 核心修复:剔除 ASS 字幕的特效代码头,防止英文误判
content = re.sub(r'\[.*?\]', '', content)
content = re.sub(r'(Format|Style|Dialogue):.*?\n', '', content)
if re.search(r'[\u4e00-\u9fa5]', content):
# 简单繁体特征字判定
if len(re.findall(r'[傳統萬與飛沒]', content)) > 5:
return "zh-TW"
return "zh-CN"
if re.search(r'[\u3040-\u30ff]', content): return "ja"
if re.search(r'[\uac00-\ud7af]', content): return "ko"
return "und"
except:
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, task_mgr):
"""扫描并重命名当前目录下现有的外挂字幕"""
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
if f_path.stem in sub.name: is_match = True
elif m_type == "tv":
# 匹配 E01 等集号
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)E(\d{1,3})(?!\d)', sub.name, re.IGNORECASE)
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)
if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1):
is_match = True
else:
# 电影:当前目录只有一个视频时,通吃所有字幕
videos = [v for v in f_path.parent.glob("*") if v.suffix.lower() in {'.mkv', '.mp4', '.avi'}]
if len(videos) == 1:
is_match = True
if is_match:
lang_tag = RenamerService.detect_subtitle_language(sub)
# 💡 核心修复:检查现有的名字是否已经完全合规
# 合规正则: target_stem + .lang_tag + (可选的 .数字) + 后缀
pattern = r'^' + re.escape(target_stem) + r'\.' + re.escape(lang_tag) + r'(?:\.\d+)?' + re.escape(sub.suffix.lower()) + r'$'
# 如果不能完美匹配这个正则,说明语言后缀不对(比如存在 .zh-CN.en 或 .und),必须重命名
if not re.match(pattern, sub.name):
desired_path = sub.with_name(f"{target_stem}.{lang_tag}{sub.suffix.lower()}")
new_sub_path = task_mgr.reserve_path(desired_path)
new_name = f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
if sub.name != new_name:
task_mgr.add_file_rename(
f"[外挂字幕] {sub.name} --> {new_sub_path.name}",
f"[外挂字幕] {sub.name} --> {new_name}",
RenamerService.do_rename_single,
(sub, new_sub_path)
(sub, task_mgr.reserve_path(sub.with_name(new_name)))
)
@staticmethod
@@ -144,8 +136,17 @@ class RenamerService:
RenamerService.do_rename_single,
(f_path, task_mgr.reserve_path(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)))
)
if m_type == "tv" and f_path.parent.name != target_season_folder:
# 💡 只有在 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))
if root_dir_path.name != target_root_folder: