feat(pipeline): 批量归档确认、字幕判重与综艺幂等收尾

- 批量归档拆 plan/execute,多目录一次确认;worker 按目录计数
- 字幕按已有 sidecar 判重,避免重抽
- 综艺按集号锁定、已规范不计入 rename,预览显示完整目标名
- 特典在整理阶段写 NFO(airs/display),归档后 Jellyfin 直接生效
- docs/rules/项目记忆同步
This commit is contained in:
ali
2026-11-28 13:53:17 +08:00
parent d5a39af9cb
commit 659a6af456
14 changed files with 732 additions and 196 deletions
+168 -76
View File
@@ -65,6 +65,41 @@ class ArchiveResult:
return self.skipped is None
@dataclass
class ArchivePlan:
"""只算不搬的计划:批量归档先出全量清单,确认后再逐条执行。"""
src: Path
kind: str = "movie"
title: str = ""
tmdb_id: str | None = None
files: int = 0
size: int = 0
suggestion: str | None = None
available: list = field(default_factory=list)
category: str | None = None
dest: Path | None = None
merging: bool = False
merge_plan: dict | None = None
skipped: str | None = None
@property
def ok(self) -> bool:
return self.skipped is None
@property
def new_files(self) -> int:
return len(self.merge_plan["new"]) if self.merge_plan else 0
@property
def dup_files(self) -> int:
return len(self.merge_plan["dupes"]) if self.merge_plan else 0
@property
def conflict_files(self) -> int:
return len(self.merge_plan["conflicts"]) if self.merge_plan else 0
class ArchiveService:
# ------------------------------------------------------------------ 基础
@@ -443,19 +478,18 @@ class ArchiveService:
return f"仍有未下载完的文件({residues[0].name}),本次不归档"
return None
# ------------------------------------------------------------------ 主流程
# ------------------------------------------------------------------ 计划
@classmethod
def run(cls, src: Path, to: str | None = None, yes: bool = False,
dry_run: bool = False, non_interactive: bool = False,
merge: bool = True, refresh: bool = True) -> ArchiveResult:
"""归档一个目录。
def plan(cls, src: Path, to: str | None = None, merge: bool = True,
gate: bool = False, quiet: bool = False) -> ArchivePlan:
"""只算不搬:识别、分类建议、落点、增量合并预演。
non_interactive=True 用于「整理完自动归档」:不提问,闸门不满足就返回
result.skipped(不算失败);分类只接受唯一建议,没建议就跳过。
gate=True 走非交互闸门(无视频 / 有下载残留就跳过),对应自动归档;
手动归档交给人判断,不预筛。
"""
src = Path(src).resolve()
result = ArchiveResult(src=src)
out = ArchivePlan(src=src)
if not src.is_dir():
raise ArchiveError(f"目录不存在: {src}")
@@ -463,83 +497,73 @@ class ArchiveService:
if src.parent == media_root or media_root in src.parents:
raise ArchiveError(f"源目录已经在媒体库里了: {src}")
if non_interactive:
if gate:
reason = cls._gate(src)
if reason:
result.skipped = reason
log.info(f"⏭ 跳过归档:{reason}")
return result
out.skipped = reason
return out
kind = cls.detect_kind(src)
tmdb_id = cls.tmdb_id_of(src.name)
info = cls.tmdb_info(tmdb_id, kind) if tmdb_id else None
suggestion = cls.suggest_category(kind, info)
cats = cls.list_categories(media_root)
if suggestion and suggestion not in cats:
suggestion = None
files, size = cls.count_media(src)
label = "剧集" if kind == "tv" else "电影"
title = (info or {}).get("title") or src.name
log.info(f"📁 源目录 : {src}")
log.info(f"🎬 识别 : {label} | {title}"
+ (f" | tmdbid-{tmdb_id}" if tmdb_id else " | 无 tmdbid"))
if tmdb_id and info is None:
log.warning("⚠️ TMDB 查询失败(网络或 api_key),将不提供分类建议")
log.info(f"📦 内容 : {files} 个文件, {cls.human_size(size)}")
out.kind = cls.detect_kind(src)
out.tmdb_id = cls.tmdb_id_of(src.name)
info = cls.tmdb_info(out.tmdb_id, out.kind) if out.tmdb_id else None
out.suggestion = cls.suggest_category(out.kind, info)
out.available = cls.list_categories(media_root)
if out.suggestion and out.suggestion not in out.available:
out.suggestion = None
out.files, out.size = cls.count_media(src)
out.title = (info or {}).get("title") or src.name
if to:
category = cls.resolve_category(media_root, to, cats)
category = cls.resolve_category(media_root, to, out.available)
if not category:
raise ArchiveError(f"分类不存在: {to}\n可用: " + ", ".join(cats))
elif non_interactive:
if not suggestion:
result.skipped = "没有唯一的 TMDB 分类建议"
log.info(f"⏭ 跳过归档:{result.skipped},请手动归档")
return result
category = suggestion
else:
category = cls.choose_category(cats, suggestion)
if not category:
raise ArchiveCancelled("用户取消")
raise ArchiveError(f"分类不存在: {to}\n可用: " + ", ".join(out.available))
out.category = category
elif out.suggestion:
out.category = out.suggestion
if not quiet:
label = "剧集" if out.kind == "tv" else "电影"
log.info(f"📁 源目录 : {src}")
log.info(f"🎬 识别 : {label} | {out.title}"
+ (f" | tmdbid-{out.tmdb_id}" if out.tmdb_id else " | 无 tmdbid"))
if out.tmdb_id and info is None:
log.warning("⚠️ TMDB 查询失败(网络或 api_key),将不提供分类建议")
log.info(f"📦 内容 : {out.files} 个文件, {cls.human_size(out.size)}")
cls._attach_dest(out)
return out
@classmethod
def _attach_dest(cls, out: ArchivePlan) -> None:
"""按当前 category 算落点并预演增量合并(不移动任何文件)。"""
if not out.category:
out.dest = None
out.merging = False
out.merge_plan = None
return
out.dest = config.MEDIA_ROOT / out.category / out.src.name
out.merging = out.dest.exists()
out.merge_plan = cls.plan_merge(out.src, out.dest) if out.merging else None
# ------------------------------------------------------------------ 执行
@classmethod
def execute(cls, plan: ArchivePlan, merge: bool = True,
refresh: bool = False) -> ArchiveResult:
"""按已确认的计划落地:整目录移动或增量合并,搬完做完整性校验。"""
if not plan.ok:
return ArchiveResult(src=plan.src, skipped=plan.skipped)
if not plan.category or not plan.dest:
raise ArchiveError("计划里没有目标分类,无法执行")
src, dest, merging = plan.src, plan.dest, plan.merging
files, size = plan.files, plan.size
result = ArchiveResult(src=src, dest=dest, merged=merging)
dest = media_root / category / src.name
if dest.exists() and not merge:
raise ArchiveError(f"目标已存在,未移动: {dest}")
merging = dest.exists()
merge_plan = None
if merging:
merge_plan = cls.plan_merge(src, dest)
log.info(f"➡️ 目标已存在,按增量合并: {dest}")
log.info(f" 新增 {len(merge_plan['new'])} 个文件")
if merge_plan["dupes"]:
log.info(f" 跳过同名同大小 {len(merge_plan['dupes'])} 个(重复下载)")
if merge_plan["conflicts"]:
log.warning(f" ⚠️ 冲突 {len(merge_plan['conflicts'])} 个(不覆盖、不移动)")
for rel, reason in merge_plan["conflicts"][:10]:
log.warning(f" - {rel} ← {reason}")
else:
log.info(f"➡️ 将移动到: {dest}")
cls._assert_writable(dest, plan.merge_plan["new"] if merging else None)
if dry_run:
log.info("(dry-run,未执行移动)")
result.dest = dest
result.merged = merging
return result
cls._assert_writable(dest, merge_plan["new"] if merging else None)
if not yes:
try:
confirm = unicodedata.normalize("NFKC", input("确认归档?[Y/n]: ")).strip().lower()
except EOFError:
confirm = "n"
if confirm not in {"", "y", "yes"}:
raise ArchiveCancelled("用户取消")
result.dest = dest
result.merged = merging
if merging:
rep = cls.merge_into(src, dest)
after_files, after_size = cls.count_media(dest)
@@ -570,4 +594,72 @@ class ArchiveService:
if refresh:
log.info("🎞️ " + cls.refresh_jellyfin())
return result
return result
# ------------------------------------------------------------------ 主流程
@classmethod
def run(cls, src: Path, to: str | None = None, yes: bool = False,
dry_run: bool = False, non_interactive: bool = False,
merge: bool = True, refresh: bool = True) -> ArchiveResult:
"""归档一个目录(单目录交互:分类选择 + 确认,与旧版行为一致)。
non_interactive=True 用于「整理完自动归档」:不提问,闸门不满足就返回
result.skipped(不算失败);分类只接受唯一建议,没建议就跳过。
批量归档不走这里——见 `main.py` 的 `_run_archive_batch`(先汇总再确认)。
"""
plan = cls.plan(Path(src), to=to, merge=merge, gate=non_interactive)
result = ArchiveResult(src=plan.src)
if plan.skipped:
result.skipped = plan.skipped
log.info(f"⏭ 跳过归档:{plan.skipped}")
return result
if to:
category = plan.category
elif non_interactive:
if not plan.category:
result.skipped = "没有唯一的 TMDB 分类建议"
log.info(f"⏭ 跳过归档:{result.skipped},请手动归档")
return result
category = plan.category
else:
category = cls.choose_category(plan.available, plan.suggestion)
if not category:
raise ArchiveCancelled("用户取消")
if category != plan.category:
# 用户在列表里换了分类:落点与合并预演都得按新分类重算
plan.category = category
cls._attach_dest(plan)
dest = plan.dest
if dest.exists() and not merge:
raise ArchiveError(f"目标已存在,未移动: {dest}")
if plan.merging:
log.info(f"➡️ 目标已存在,按增量合并: {dest}")
log.info(f" 新增 {plan.new_files} 个文件")
if plan.dup_files:
log.info(f" 跳过同名同大小 {plan.dup_files} 个(重复下载)")
if plan.conflict_files:
log.warning(f" ⚠️ 冲突 {plan.conflict_files} 个(不覆盖、不移动)")
for rel, reason in plan.merge_plan["conflicts"][:10]:
log.warning(f" - {rel} ← {reason}")
else:
log.info(f"➡️ 将移动到: {dest}")
if dry_run:
log.info("(dry-run,未执行移动)")
result.dest = dest
result.merged = plan.merging
return result
if not yes:
try:
confirm = unicodedata.normalize("NFKC", input("确认归档?[Y/n]: ")).strip().lower()
except EOFError:
confirm = "n"
if confirm not in {"", "y", "yes"}:
raise ArchiveCancelled("用户取消")
return cls.execute(plan, merge=merge, refresh=refresh)
+2 -2
View File
@@ -319,11 +319,11 @@ class JellyfinAdFixService:
if not dry_run and not auto_execute:
try:
answer = input(f"⚠️ 是否修复以上 {len(targets)} 个条目(含 NFO 清理)?[y/n/q]: ").strip().lower()
answer = input(f"⚠️ 是否修复以上 {len(targets)} 个条目(含 NFO 清理)?[Y/n/q]: ").strip().lower()
except EOFError:
log.warning("⛔ 没有可用的终端输入,按取消处理。")
return {"cancelled": True}
if answer not in {"y", "yes"}:
if answer in {"n", "q"}:
log.info("💤 任务已由用户取消。")
return {"cancelled": True}
+91 -21
View File
@@ -73,14 +73,49 @@ class SubtitleService:
return removed
@staticmethod
def has_internal_sub(dest_dir: Path, target_stem: str) -> bool:
"""目标目录里是否已有该集的内嵌字幕(ass 或 srt)。"""
prefix = f"{target_stem}.internal."
def _video_stems(file_path, target_stem: str) -> list[str]:
"""该视频可能对应的文件名前缀:目标名 + 磁盘上的现用名。
流水线是「先抽字幕(阶段 3)、后改名(阶段 5)」,所以判断「已有字幕」时
磁盘上的 sidecar 往往还挂在旧名下。只认 target_stem 会把旧 name 的
`.internal.zh-CN.ass` 当成不存在,于是整条轨白抽一遍。
"""
stems = [target_stem]
source_stem = getattr(file_path, "stem", "")
if source_stem and source_stem != target_stem:
stems.append(source_stem)
return stems
# 同一语言的不同写法归一化:chi / zho-Hans / zh_cn / zh-CN 视为中文简体
_LANG_CANON = {
'chi': 'zh-cn', 'zho': 'zh-cn', 'zh': 'zh-cn', 'chs': 'zh-cn', 'sc': 'zh-cn',
'zh-cn': 'zh-cn', 'zh-hans': 'zh-cn', 'zho-hans': 'zh-cn', 'zh-hans-cn': 'zh-cn',
'cht': 'zh-tw', 'tc': 'zh-tw', 'zh-tw': 'zh-tw', 'zh-hant': 'zh-tw',
'zho-hant': 'zh-tw', 'zh-hk': 'zh-tw',
'zh-en': 'zh-en', 'zho-en': 'zh-en',
'eng': 'en', 'en': 'en', 'jpn': 'ja', 'ja': 'ja', 'jp': 'ja',
'kor': 'ko', 'ko': 'ko',
}
@staticmethod
def _norm_lang(code: str) -> str:
key = (code or "").strip().lower().replace("_", "-")
return SubtitleService._LANG_CANON.get(key, key)
@staticmethod
def _sidecar_lang(asset: Path) -> str:
match = config.LANG_TAIL_PATTERN.search(asset.stem)
return match.group(0).lstrip(".-_") if match else ""
@staticmethod
def has_internal_sub(dest_dir: Path, target_stem: str, file_path=None) -> bool:
"""目标目录里是否已有该视频的内嵌字幕(ass 或 srt)。"""
stems = SubtitleService._video_stems(file_path, target_stem)
try:
for p in dest_dir.iterdir():
if not p.is_file() or not p.name.startswith(prefix):
if not p.is_file() or p.suffix.lower() not in {'.ass', '.srt'}:
continue
if p.suffix.lower() in {'.ass', '.srt'}:
if any(p.name.startswith(f"{stem}.internal.") for stem in stems):
return True
except OSError:
pass
@@ -157,7 +192,7 @@ class SubtitleService:
if want_ass:
present, spec = SubtitleService._plan_ass(
target_stem, dest_dir, stream_idx, codec, lang_code, suffix)
file_path, target_stem, dest_dir, stream_idx, codec, lang_code, suffix)
if spec is not None:
ass_specs.append(spec)
if present or spec is not None:
@@ -173,25 +208,58 @@ class SubtitleService:
return queued
@staticmethod
def _existing_sidecar(dest_dir: Path, target_stem: str, lang: str, suffix: str) -> Path | None:
"""同语言外挂字幕是否已存在(含早期不带 .internal 的命名与其它封装格式)。
def _existing_sidecar(file_path, dest_dir: Path, target_stem: str,
lang: str, suffix: str) -> Path | None:
"""同语言外挂字幕是否已存在(认旧名、旧命名、语言码异写)。
老库里的字幕多为 <stem>.<lang>.srt(旧命名),若不认这些,重复抽取会在
同一语言下再生成 .internal.<lang>.ass,Jellyfin 里就会出现两条同语言字幕。
三层判断,缺一层就会重复抽取:
1. 精确文件名(含 `.2` 这类同语言多轨后缀);
2. 目标名 / 源名两种前缀(整理先抽后改名,磁盘上常还是旧名);
3. 语言尾归一化(`chi`、`zho-Hans`、`zh_cn` 都算 `zh-CN`),且目录里
只有一个视频时允许前缀完全对不上(片名与文件名不一致的老库)。
"""
for name in (
f"{target_stem}.internal.{lang}{suffix}.ass",
f"{target_stem}.internal.{lang}{suffix}.srt",
f"{target_stem}.{lang}{suffix}.srt",
f"{target_stem}.{lang}{suffix}.ass",
):
p = dest_dir / name
if p.exists() and p.stat().st_size > 0:
stems = SubtitleService._video_stems(file_path, target_stem)
want = SubtitleService._norm_lang(lang)
for stem in stems:
for name in (
f"{stem}.internal.{lang}{suffix}.ass",
f"{stem}.internal.{lang}{suffix}.srt",
f"{stem}.{lang}{suffix}.srt",
f"{stem}.{lang}{suffix}.ass",
):
p = dest_dir / name
if p.exists() and p.stat().st_size > 0:
return p
# `.2` / `.3` 是同语言多轨的序号,语言层去重只对第一条轨生效
if suffix:
return None
try:
entries = [p for p in dest_dir.iterdir() if p.is_file()]
videos = [p for p in entries if p.suffix.lower() in config.SUPPORTED_EXTS]
single_video = len(videos) == 1
except OSError:
return None
for p in entries:
if p.suffix.lower() not in {'.ass', '.srt'} or p.name.startswith('.'):
continue
belongs = any(p.name.startswith(f"{stem}.") for stem in stems)
if not belongs:
if not single_video:
continue
if p.stem.strip().lower() in config.RESERVED_SIDECAR_STEMS:
continue
token = SubtitleService._sidecar_lang(p)
if token and SubtitleService._norm_lang(token) == want:
log.debug(f"✨ [跳过导出] 已有同语言外挂字幕: {p.name}")
return p
return None
@staticmethod
def _plan_ass(target_stem, dest_dir, stream_idx, codec, lang_code, suffix):
def _plan_ass(file_path, target_stem, dest_dir, stream_idx, codec, lang_code, suffix):
"""判断该 ASS 轨是否还要抽;返回 (已有外挂副本, 待抽 spec)。
已有(含旧命名)只计数、不排队;待抽 spec 由 _queue_ass_exports
@@ -201,7 +269,8 @@ class SubtitleService:
if out_ass.exists() and out_ass.stat().st_size > 0:
log.debug(f"✨ [跳过导出] 目标内置 ASS 已存在: {out_ass.name}")
return True, None
existing = SubtitleService._existing_sidecar(dest_dir, target_stem, lang_code, suffix)
existing = SubtitleService._existing_sidecar(
file_path, dest_dir, target_stem, lang_code, suffix)
if existing is not None:
log.debug(f"✨ [跳过导出] 同语言外挂字幕已存在: {existing.name}")
return True, None
@@ -245,7 +314,8 @@ class SubtitleService:
log.debug(f"✨ [跳过提取] 目标内置字幕已存在: {out_srt.name}")
SubtitleService._drop_external_copies(out_srt)
return 1
if SubtitleService._existing_sidecar(dest_dir, target_stem, lang_code, suffix) is not None:
if SubtitleService._existing_sidecar(
file_path, dest_dir, target_stem, lang_code, suffix) is not None:
log.debug(f"✨ [跳过提取] 同语言外挂字幕已存在: {target_stem}.{lang_code}{suffix}")
return 1
+113 -34
View File
@@ -201,12 +201,37 @@ class VarietyService:
# ---------------------------------------------------------------- 打分与分配
@staticmethod
def _score(candidate: dict, file_name: str, hint: str | None, compact: str) -> int:
# 归一化用:去掉分隔符与空白,方便做「集名 ↔ 文件名」重合判断
_SEP_RE = re.compile(r"[\s._\-·::,,()()\[\]【】]+")
_SEASON_WORD_RE = re.compile(r"第\s*[0-9一二三四五六七八九十]+\s*季")
_DATE_DIGITS_RE = re.compile(r"(?:19|20)\d{2}[-._]?\d{2}[-._]?\d{2}")
@classmethod
def _name_affinity(cls, episode_name: str, file_name: str) -> int:
"""集名与文件名的重合度。同一天多集(先导片上/下/纯享)靠它区分。
没有这一项时,同日期候选打分完全并列,贪心分配会按遍历顺序乱点鸳鸯,
于是「先导片上」被改名成「先导片纯享」。命中越高说明文件自称的期名对得上。
"""
ep = cls._SEP_RE.sub("", cls._SEASON_WORD_RE.sub("", episode_name or ""))
if not ep:
return 0
file_part = cls._SEP_RE.sub("", cls._DATE_DIGITS_RE.sub("", file_name or ""))
if not file_part:
return 0
if ep in file_part:
return 6 # 集名完整出现在文件名里
if len(file_part) >= 2 and file_part in ep:
return 5 # 文件名是集名的一部分(集名带副标题)
return 0
@classmethod
def _score(cls, candidate: dict, file_name: str, hint: str | None, compact: str) -> int:
score = 0
episode_name = candidate["name"]
if compact and compact in re.sub(r"[-.\s]", "", episode_name):
score += 6 # TMDB 集名里直接写了这个日期
score += cls._name_affinity(episode_name, file_name)
file_special = bool(_SPECIAL_WORDS.search(file_name))
ep_special = bool(_EP_NAME_SPECIAL.search(episode_name))
if file_special and ep_special:
@@ -247,8 +272,11 @@ class VarietyService:
# ---------------------------------------------------------------- 主流程
@classmethod
def plan(cls, folder: Path, show_id: int, show_name: str, season_years: dict, show_year: str = "") -> dict:
def plan(cls, folder: Path, show_id: int, show_name: str, season_years: dict,
show_year: str = "", media_title: str = "") -> dict:
index = cls.build_index(show_id)
# 文件名前缀用 media_title(可能与目录标题不同);不传就退回剧名
title_for_name = media_title or show_name
videos = [p for p in sorted(folder.rglob("*"))
if p.is_file() and p.suffix.lower() in cls.VIDEO_EXTS
and ".qkdownloading" not in p.name
@@ -266,14 +294,21 @@ class VarietyService:
for cand in candidates:
ep_index[(cand["season"], cand["ep"])] = air
# 文件自称的集号:已经带 SxxEyy 的,分配时按集号锁定,不再重新打分。
# 综艺同一天常有多集(先导片上/下/纯享),重新打分会让它们互相顶替,
# 于是「已经整理好的目录再跑一次」反而改名。
file_se: dict[Path, tuple[str, int]] = {}
for file in videos:
date, complete = cls.extract_date(file.name)
# 已有 SxxEyy 时以集号为准(文件名里的其它数字可能被误当成日期)
match = re.search(r"S(\d{2})E(\d{1,4})", file.stem, re.I)
if match:
by_ep = ep_index.get((match.group(1), int(match.group(2))))
key = (match.group(1), int(match.group(2)))
by_ep = ep_index.get(key)
if by_ep:
date, complete = by_ep, True
file_se[file] = key
if date and not complete:
hint = cls.season_hint(file.relative_to(folder)) or cls.season_hint(folder)
year = season_years.get(hint or "", "")
@@ -288,7 +323,10 @@ class VarietyService:
groups[date].append(file)
plan = {"show_id": show_id, "show": show_name, "folder": folder, "show_year": show_year,
"renames": [], "extras": [], "deletes": [], "undated": undated}
"renames": [], "extras": [], "deletes": [], "undated": undated,
# file → 目标路径(计划阶段算一次,预览/执行直接复用);
# normalized = 目标路径与现路径完全一致、无需改动的条目数
"targets": {}, "normalized": 0}
for date, files in sorted(groups.items()):
candidates = index.get(date) or []
@@ -298,31 +336,67 @@ class VarietyService:
hint = cls.season_hint(files[0].relative_to(folder)) or cls.season_hint(folder)
# 文件数多于候选数 → 同一天多份,按码率取前 N 个参与分配,
# 其余:同期数的低码率版本删除,无法归期的进 extras(绝不静默丢弃)
if len(files) > len(candidates):
ranked = sorted(files, key=cls._quality, reverse=True)
keep, surplus = ranked[:len(candidates)], ranked[len(candidates):]
assigned, _ = cls._assign(keep, candidates, hint)
kept_sigs = {cls._signature(f.name) for f in keep}
for file in surplus:
# 只有「期数 + 类型关键词」完全相同才算同一集的重复;
# 加更 / 超前探班 / 正片 是不同内容,绝不能当重复删掉。
if cls._signature(file.name) in kept_sigs:
plan["deletes"].append((file, "同集高码率已保留,此为重复版本"))
else:
plan["extras"].append(file)
else:
assigned, leftover = cls._assign(files, candidates, hint)
plan["extras"].extend(leftover)
# ① 先按「文件自称的集号」锁定,一集只锁一个文件
by_key = {(c["season"], c["ep"]): c for c in candidates}
assigned: list[tuple[Path, dict]] = []
pending: list[Path] = []
taken: set[tuple[str, int]] = set()
for file in files:
key = file_se.get(file)
if key in by_key and key not in taken:
taken.add(key)
assigned.append((file, by_key[key]))
else:
pending.append(file)
rest = [c for c in candidates if (c["season"], c["ep"]) not in taken]
for file, candidate, _score in assigned:
# ② 剩下的文件再按日期/关键词打分分配
if pending and rest:
if len(pending) > len(rest):
ranked = sorted(pending, key=cls._quality, reverse=True)
keep, surplus = ranked[:len(rest)], ranked[len(rest):]
got, _ = cls._assign(keep, rest, hint)
assigned.extend(got)
# 已锁定的文件也算「已保留」,否则同集低码率副本不会被判重复
kept_sigs = {cls._signature(item[0].name) for item in assigned}
for file in surplus:
# 只有「期数 + 类型关键词」完全相同才算同一集的重复;
# 加更 / 超前探班 / 正片 是不同内容,绝不能当重复删掉。
if cls._signature(file.name) in kept_sigs:
plan["deletes"].append((file, "同集高码率已保留,此为重复版本"))
else:
plan["extras"].append(file)
else:
got, leftover = cls._assign(pending, rest, hint)
assigned.extend(got)
plan["extras"].extend(leftover)
else:
plan["extras"].extend(pending)
# ③ 目标名算一次:与现路径相同的直接记为「已规范」,不进变更清单。
# 否则重跑已整理目录会报出上百条「改名」,确认后却一条也不改。
# assigned 里既有锁定的 (file, cand),也有 _assign 返回的 (file, cand, score)
for file, candidate, *_score in assigned:
target = cls._target_path(folder, file, candidate, title_for_name, season_years)
if target == file:
plan["normalized"] += 1
continue
plan["targets"][file] = target
plan["renames"].append((file, candidate))
# 无日期的一律进 extras(无法定位)
plan["extras"].extend(plan.pop("undated"))
return plan
@classmethod
def _target_path(cls, folder: Path, file: Path, candidate: dict,
media_title: str, season_years: dict) -> Path:
"""按 TMDB 季号归位后的目标路径(特典进 Season 00,正片进 Season XX)。"""
name = cls._target_name(file, candidate, media_title, season_years)
if candidate["season"]:
return folder / f"Season {candidate['season']}" / name
return file.with_name(name)
@staticmethod
def _quality(path: Path) -> tuple:
tags = MediaInfoService.get_scene_tags(path)
@@ -372,17 +446,22 @@ class VarietyService:
def preview(cls, plan: dict, season_years: dict, media_title: str) -> None:
log.info("=" * 60)
log.info(f"📺 综艺整理:{plan['show']}(tv/{plan['show_id']})")
log.info(f" 改名 {len(plan['renames'])} | 进 extras {len(plan['extras'])} | 删除 {len(plan['deletes'])}")
extra = f" | 已规范 {plan['normalized']}" if plan.get("normalized") else ""
log.info(f" 改名 {len(plan['renames'])} | 进 extras {len(plan['extras'])} | "
f"删除 {len(plan['deletes'])}{extra}")
targets = plan.get("targets") or {}
for file, candidate in plan["renames"][:8]:
target = cls._target_name(file, candidate, media_title, season_years)
log.info(f" [改名] {file.name[:46]}")
log.info(f" → {target[:80]}")
target = targets.get(file)
if target is None:
target = cls._target_path(plan["folder"], file, candidate, media_title, season_years)
log.info(f" [改名] {file.name}")
log.info(f" → {target.name}")
if len(plan["renames"]) > 8:
log.info(f" …… 其余 {len(plan['renames']) - 8} 个改名略")
for file in plan["extras"][:5]:
log.info(f" [extras] {file.name[:60]}")
log.info(f" [extras] {file.name}")
for file, reason in plan["deletes"][:5]:
log.info(f" [删除] {file.name[:60]} ← {reason}")
log.info(f" [删除] {file.name} ← {reason}")
log.info("=" * 60)
@classmethod
@@ -463,12 +542,12 @@ class VarietyService:
extras_dir = folder / "extras"
stats = {"renamed": 0, "extras": 0, "deleted": 0, "skipped": 0, "sidecars": 0}
targets = plan.get("targets") or {}
for file, candidate in plan["renames"]:
target = file.with_name(cls._target_name(file, candidate, media_title, season_years))
# 一律按 TMDB 季号归位:特典进 Season 00,正片进 Season XX。
# 不这样做的话,「源文件本来就在 Season 04」的特典会一直留在 Season 04。
if candidate["season"]:
target = folder / f"Season {candidate['season']}" / target.name
# 目标路径在 plan 阶段已算好(含「一律按 TMDB 季号归位」),这里直接复用
target = targets.get(file)
if target is None:
target = cls._target_path(folder, file, candidate, media_title, season_years)
if target == file:
cls._follow_sidecars(file, target)
continue