- 命名改为 标题.SxxEyy.年份.技术标签-期名,S00 年份取每集播出年 (与常规整理一致,避免两边各改一次) - renamer.scan_rename 把「<目标名>-说明」视为已规范,整库扫描不再改回去 - 新增 .variety.json 标识:综艺目录名常常不规范(「花儿与少年」会被 误匹配到衍生剧「同心季」),常规扫描据此按记录的 tmdb_id 识别 - 剧集根目录年份改用「首播年」而不是某集年份(综艺各集年份不同, 否则根目录会随扫描顺序乱变) - 附带把 花儿与少年 已整理的 70 个文件按集号重建为最终格式
156 lines
7.9 KiB
Python
156 lines
7.9 KiB
Python
# src/services/renamer.py
|
|
|
|
import re
|
|
from pathlib import Path
|
|
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 scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr) -> bool:
|
|
# 只导出 ASS 模式下不做 SRT 转换,外挂字幕保持原样
|
|
if 'srt' not in config.SUBTITLE_EXPORT:
|
|
return False
|
|
|
|
has_external_sub = False
|
|
for sub in f_path.parent.glob("*"):
|
|
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
|
# 🛡️ 幂等保护:本工具已按目标名生成过的字幕(含 *.internal.<lang>.srt 与去重用的 .2/.3 后缀)
|
|
# 不再参与"外挂字幕规范化",否则复跑时会被改名成 <目标名>.zh-CN.2.srt,丢掉 internal 标识且不断产生新后缀。
|
|
if sub.name.startswith(f"{target_stem}."):
|
|
continue
|
|
is_match = False
|
|
if f_path.stem in sub.name: is_match = True
|
|
elif m_type == "tv":
|
|
match = RegexPatterns.SUB_EP_MATCH.search(sub.name)
|
|
if match:
|
|
ep = next((g for g in match.groups() if g), None)
|
|
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 = MediaUtil.detect_subtitle_language(sub)
|
|
|
|
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
|
|
task_mgr.add_extract(
|
|
f"[外挂字幕转换] {sub.name} --> {reserved_path.name}",
|
|
SubtitleService.convert_to_srt,
|
|
(sub, reserved_path)
|
|
)
|
|
else:
|
|
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}",
|
|
FileOpsService.move_file,
|
|
(sub, reserved_path)
|
|
)
|
|
|
|
return has_external_sub
|
|
|
|
# 单视频目录下可以「兜底认领」的附属文件类型。
|
|
# 只收字幕:movie.nfo / tvshow.nfo / season.nfo 是 Jellyfin 的目录级元数据,
|
|
# poster/fanart/logo 等是目录图片,都不能跟着视频改名。
|
|
SIDECAR_PER_VIDEO_EXTS = {".srt", ".ass", ".ssa", ".vtt"}
|
|
# 目录级文件名(不含扩展名),任何情况下都不当作单个视频的附属文件
|
|
RESERVED_SIDECAR_STEMS = {
|
|
"movie", "tvshow", "season", "episode", "poster", "folder", "fanart",
|
|
"backdrop", "logo", "banner", "clearart", "landscape", "disc", "thumb",
|
|
"keyart", "cover", "default",
|
|
}
|
|
LANG_TAIL = re.compile(
|
|
r"(?i)[.\-_](zh[-_]?cn|zh[-_]?tw|zh[-_]?hk|chs|cht|sc|tc|zh|en|eng|ja|jpn|jp|"
|
|
r"kor|fr|de|es|it|rus|por|thai)([.\-_][a-z]{2,3})?$"
|
|
)
|
|
|
|
@staticmethod
|
|
def _sidecar_lang(asset: Path) -> str:
|
|
match = RenamerService.LANG_TAIL.search(asset.stem)
|
|
return match.group(0).lstrip(".-_") if match else ""
|
|
|
|
@staticmethod
|
|
def _sidecar_rest(asset: Path, video: Path, single_video: bool) -> str | None:
|
|
"""判断 asset 是否属于 video;是则返回拼到目标名后的后缀(含前导点)。"""
|
|
name = asset.name
|
|
if name.startswith(video.stem):
|
|
rest = name[len(video.stem):]
|
|
return rest if rest and not rest[0].isalnum() else None
|
|
|
|
# 前缀对不上时(例如视频按日文原名、字幕用中文名),
|
|
# 若该目录只有这一个视频,就把字幕直接认领给它。
|
|
if not single_video or asset.suffix.lower() not in RenamerService.SIDECAR_PER_VIDEO_EXTS:
|
|
return None
|
|
if asset.stem.strip().lower() in RenamerService.RESERVED_SIDECAR_STEMS:
|
|
return None
|
|
lang = RenamerService._sidecar_lang(asset)
|
|
return f".{lang}{asset.suffix.lower()}" if lang else asset.suffix.lower()
|
|
|
|
@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):
|
|
# 「<目标名>-说明」视为已规范:综艺整理会在技术标签后用「-期名」补充描述,
|
|
# 整库扫描不应把它当作错名再改回去。
|
|
if f_path.stem == target_stem or f_path.stem.startswith(f"{target_stem}-"):
|
|
reserved_new_path = f_path
|
|
else:
|
|
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.resolve() != reserved_new_path.resolve():
|
|
task_mgr.add_file_rename(
|
|
f"[主视频] {f_path.name} --> {reserved_new_path.name}",
|
|
FileOpsService.move_file,
|
|
(f_path, reserved_new_path)
|
|
)
|
|
|
|
# 附属文件单独处理:即使视频本身已经命名正确,
|
|
# 也要把对不上的外挂字幕/元数据纠正过来。
|
|
siblings = [p for p in f_path.parent.iterdir()
|
|
if p.is_file() and p.suffix.lower() in config.SUPPORTED_EXTS]
|
|
single_video = len(siblings) == 1
|
|
|
|
for asset in sorted(f_path.parent.iterdir()):
|
|
if not asset.is_file() or asset.suffix.lower() not in config.SIDECAR_EXTS:
|
|
continue
|
|
rest = RenamerService._sidecar_rest(asset, f_path, single_video)
|
|
if rest is None:
|
|
continue
|
|
|
|
new_asset_name = f"{target_stem}{rest}"
|
|
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}",
|
|
FileOpsService.move_file,
|
|
(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))
|