# src/services/variety.py """综艺整理:按「文件名日期 ↔ TMDB 播出日期」匹配集号。 综艺文件名通常没有 SxxEyy,只有日期;正片与特典(加更 / 会员版 / 超前企划) 也常放在同一目录。因此这里: 1. 从文件名提取日期(多种格式,含无年份时用季年份补全); 2. 拉取该剧全季(含 Season 00)的播出日期,建立 {日期: [(季, 集, 集名)]} 索引; 3. 按日期分组做「一对一分配」,靠排除法消歧(不依赖加更/特别这类关键词); 4. 产出三类动作: - rename:能对上的,改名为 标题.SxxEyy.年份.技术标签.期名 - extras:TMDB 没有对应条目的,移到剧集根目录 extras/(不改名) - delete:同一集的重复下载 / 低码率版本(按拍板:只留最高码率) """ from __future__ import annotations import json import re from datetime import datetime from collections import defaultdict from pathlib import Path from core.logger import log from core import config from core import tmdb_store as store from core.utils import StringUtil from services.mediainfo import MediaInfoService from services.tmdb import TMDBService # 2026-04-04 / 2026.04.04 / 2026年4月4日 / 20260404 _DATE_FULL = [ re.compile(r"(20\d{2})[-._年/](\d{1,2})[-._月/](\d{1,2})"), re.compile(r"(? re.Pattern: """词表 → 「任一命中」的正则;空表用永不匹配的表达式兜底。""" if not words: return re.compile(r"(?!)") return re.compile("|".join(sorted(re.escape(word) for word in words))) _SPECIAL_WORDS = _words_pattern(config.VARIETY_SPECIAL_WORDS) _EP_NAME_SPECIAL = _words_pattern(config.VARIETY_EP_NAME_SPECIAL_WORDS) class VarietyService: # 扫描用的视频扩展名(比 [Media] supported_exts 宽,含 .ts/.m2ts/.mov) VIDEO_EXTS = config.VIDEO_EXTS # ---------------------------------------------------------------- 日期与季 @staticmethod def extract_date(name: str) -> tuple[str | None, bool]: """返回 (YYYY-MM-DD, 是否完整含年份)。找不到返回 (None, False)。""" for pattern in _DATE_FULL: match = pattern.search(name) if match: year, month, day = match.groups() try: return f"{int(year):04d}-{int(month):02d}-{int(day):02d}", True except ValueError: continue match = _DATE_SHORT.search(name) if match: month, day = int(match.group(1)), int(match.group(2)) # 只接受合法的月/日,避免把集号、分辨率之类的数字当成日期 if 1 <= month <= 12 and 1 <= day <= 31: return f"????-{month:02d}-{day:02d}", False return None, False @staticmethod def season_hint(path: Path) -> str | None: """从目录名推断季号:Season 04 / 第六季。""" for part in reversed(path.parts): match = re.search(r"[Ss]eason\s*0*(\d{1,2})", part) if match: return str(int(match.group(1))).zfill(2) match = re.search(r"第\s*([0-9一二三四五六七八九十]+)\s*季", part) if match: raw = match.group(1) cn = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10} if raw in cn: return str(cn[raw]).zfill(2) if raw.isdigit(): return str(int(raw)).zfill(2) return None # ---------------------------------------------------------------- TMDB 索引 # TMDB 单集数据缓存有效期见 config.ini [Advanced] variety_cache_hours: # 综艺周更,超过这个时间必须重拉,否则新一期不会出现在索引里。 @classmethod def _fresh(cls, stamp: str) -> bool: try: when = datetime.fromisoformat(stamp) except (TypeError, ValueError): return False if when.tzinfo is None: when = when.replace(tzinfo=datetime.now().astimezone().tzinfo) age = datetime.now().astimezone() - when return age.total_seconds() <= config.VARIETY_CACHE_HOURS * 3600 @classmethod def _index_from_cache(cls, payload: dict) -> dict: index: dict[str, list[dict]] = defaultdict(list) for season, episodes in payload.items(): for item in episodes: date = item.get("date") or "" if len(date) < 10: continue index[date].append({ "season": season, "ep": int(item.get("ep") or 0), "name": item.get("name") or "", "air_year": date[:4], "air_date": date, }) return dict(index) @classmethod def _save_index(cls, show_id: int, index: dict, show: dict) -> None: payload: dict[str, list[dict]] = defaultdict(list) for date, candidates in index.items(): for cand in candidates: payload[cand["season"]].append( {"ep": cand["ep"], "date": date, "name": cand["name"]}) for season in payload: payload[season].sort(key=lambda item: item["ep"]) key = store.entity_key("tv", show_id) try: with store.transaction(config.TMDB_CACHE_PATH) as db: entity = db["entities"].get(key) if entity is None: entity = store.build_entity("tv", show_id, show) db["entities"][key] = entity entity["episode_air_dates"] = dict(payload) entity["episodes_fetched_at"] = store.now_iso() except OSError as exc: log.warning(f"⚠️ 单集数据缓存写入失败: {exc}") @classmethod def build_index(cls, show_id: int) -> dict: """{date: [{'season','ep','name','air_year','air_date'}]},含 Season 00。 优先用缓存里的单集数据(24 小时有效),过期或没有才回源 TMDB。 """ key = store.entity_key("tv", show_id) snapshot = store.snapshot(config.TMDB_CACHE_PATH) entity = snapshot["entities"].get(key) if entity: cached = entity.get("episode_air_dates") or {} if cached and cls._fresh(entity.get("episodes_fetched_at") or ""): index = cls._index_from_cache(cached) log.info(f"📅 TMDB 索引命中缓存({config.VARIETY_CACHE_HOURS}h 内,{len(index)} 个播出日期)") return index session = TMDBService._get_session() show = TMDBService._fetch_details(session, "tv", show_id) if not show: return {} index: dict[str, list[dict]] = defaultdict(list) seasons = show.get("seasons") or [] for season in seasons: try: number = int(season.get("season_number")) except (TypeError, ValueError): continue payload = TMDBService._fetch_season(session, "tv", show_id, number) if not payload: continue for episode in payload.get("episodes") or []: air = (episode.get("air_date") or "").strip() if len(air) < 10: continue try: ep_no = int(episode.get("episode_number")) except (TypeError, ValueError): continue index[air].append({ "season": str(number).zfill(2), "ep": ep_no, "name": episode.get("name") or "", "air_year": air[:4], "air_date": air, }) result = dict(index) log.info(f"📅 TMDB 索引: {len(result)} 个播出日期({len(seasons)} 季,已写入缓存)") cls._save_index(show_id, result, show) return result # ---------------------------------------------------------------- 打分与分配 # 归一化用:去掉分隔符与空白,方便做「集名 ↔ 文件名」重合判断 _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: score += 3 elif ep_special and not file_special: score -= 1 if hint: if candidate["season"] == hint: score += 2 elif candidate["season"] != "00": score -= 2 if hint == "00" and candidate["season"] == "00": score += 1 return score @classmethod def _assign(cls, files: list[Path], candidates: list[dict], hint: str | None) -> tuple[list, list]: """一对一贪心分配。返回 (已分配 [(file, cand)], 剩余文件)。""" pairs = [] for file in files: date, _ = cls.extract_date(file.name) compact = (date or "").replace("-", "") for candidate in candidates: pairs.append((cls._score(candidate, file.name, hint, compact), file, candidate)) pairs.sort(key=lambda item: -item[0]) used_files, used_eps, result = set(), set(), [] for score, file, candidate in pairs: key = (candidate["season"], candidate["ep"]) if file in used_files or key in used_eps: continue used_files.add(file) used_eps.add(key) result.append((file, candidate, score)) leftover = [f for f in files if f not in used_files] return result, leftover # ---------------------------------------------------------------- 主流程 @classmethod 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 and not (set(part.lower() for part in p.relative_to(folder).parts[:-1]) & set(config.EXTRAS_DIRS))] # 按日期分组;无日期的先放着 groups: dict[str, list[Path]] = defaultdict(list) undated: list[Path] = [] # 反查表:(季, 集) → 播出日期。库里已整理过的文件名没有日期, # 但带着 SxxEyy,可以用它反查日期,进而补上「-日期.期名」尾巴。 ep_index: dict[tuple[str, int], str] = {} for air, candidates in index.items(): 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: 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 "", "") if year: date = f"{year}-{date[5:]}" else: undated.append(file) continue if not date: undated.append(file) continue groups[date].append(file) plan = {"show_id": show_id, "show": show_name, "folder": folder, "show_year": show_year, "renames": [], "extras": [], "deletes": [], "undated": undated, # file → 目标路径(计划阶段算一次,预览/执行直接复用); # normalized = 目标路径与现路径完全一致、无需改动的条目数 "targets": {}, "normalized": 0} for date, files in sorted(groups.items()): candidates = index.get(date) or [] if not candidates: plan["extras"].extend(files) continue hint = cls.season_hint(files[0].relative_to(folder)) or cls.season_hint(folder) # ① 先按「文件自称的集号」锁定,一集只锁一个文件 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] # ② 剩下的文件再按日期/关键词打分分配 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) order = {"2160p": 4, "1440p": 3, "1080p": 2, "720p": 1} return (order.get(tags.get("res"), 0), path.stat().st_size) @staticmethod def _period_of(name: str) -> str | None: match = re.search(r"第\s*(\d+)\s*期", name) return match.group(1) if match else None _TYPE_WORDS = _words_pattern(config.VARIETY_TYPE_WORDS) @classmethod def _signature(cls, name: str) -> tuple: """同一集的指纹:期数 + 类型关键词。不同指纹 = 不同内容。""" return (cls._period_of(name), tuple(sorted(set(cls._TYPE_WORDS.findall(name))))) # ---------------------------------------------------------------- 预览与执行 @staticmethod def _target_name(file: Path, candidate: dict, media_title: str, season_years: dict) -> str: tags = MediaInfoService.get_scene_tags(file) source = MediaInfoService.detect_source(file.name, tags) extra = '.'.join(p for p in (tags.get('hdr'), tags.get('fps')) if p) tech = '.'.join(p for p in (tags['res'], source, tags['v_codec'], tags['bits'], extra, tags['a_info']) if p) season = candidate["season"] # S00(特别篇)按「本集」播出年份,其余按季年份 —— 与常规整理保持一致 year = (candidate.get("air_year") if season == "00" else season_years.get(season)) or "" parts = [media_title, f"S{season}E{candidate['ep']:02d}"] if year: parts.append(str(year)) parts.append(tech) stem = ".".join(parts) # 期名用「-」接在技术标签之后:`-<播出日期>.<期名>` # 日期写成 YYYYMMDD,既能一眼看出播出时间,也让常规整理识别为已规范。 ep_name = StringUtil.sanitize_title(candidate["name"])[:config.EPISODE_LABEL_CHARS].strip(".") air_date = (candidate.get("air_date") or "").replace("-", "") tail = ".".join(part for part in (air_date, ep_name) if part) if tail: stem = f"{stem}-{tail}" return stem + file.suffix.lower() @classmethod def preview(cls, plan: dict, season_years: dict, media_title: str) -> None: log.info("=" * 60) log.info(f"📺 综艺整理:{plan['show']}(tv/{plan['show_id']})") 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 = 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}") for file, reason in plan["deletes"][:5]: log.info(f" [删除] {file.name} ← {reason}") log.info("=" * 60) @classmethod def _follow_sidecars(cls, src_video: Path, dst_video: Path, moved: bool = False) -> int: """让附属文件跟着视频走:<旧名>.xxx → <新名>.xxx。返回处理数量。""" count = 0 for side in list(src_video.parent.iterdir()): if not side.is_file() or side.suffix.lower() not in config.SIDECAR_EXTS: continue if not side.name.startswith(src_video.stem): continue rest = side.name[len(src_video.stem):] if rest and rest[0].isalnum(): continue target_side = dst_video.parent / f"{dst_video.stem}{rest}" if target_side == side: continue try: target_side.parent.mkdir(parents=True, exist_ok=True) side.rename(target_side) count += 1 except OSError as exc: log.warning(f"⚠️ 附属文件改名失败 {side.name}: {exc}") return count @classmethod def adopt_orphan_sidecars(cls, folder: Path, stats: dict) -> int: """兜底认领:老名字的附属文件(视频早已改名)按「同一日期」认领到对应视频。 典型场景:花儿与少年的 .nfo 还叫 花儿与少年.S01E20220610.nfo, 而视频已经变成 …-20220610.第四季…,两者共享同一个 YYYYMMDD。 """ videos = [p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() in cls.VIDEO_EXTS] by_date: dict[str, Path] = {} for video in videos: match = re.search(r"-(\d{8})\.", video.name) if match: by_date.setdefault(match.group(1), video) video_stems = {p.stem for p in videos} adopted = 0 for side in list(folder.rglob("*")): if not side.is_file() or side.suffix.lower() not in config.SIDECAR_EXTS: continue if side.stem in video_stems or side.stem in {"season", "tvshow"}: continue match = re.search(r"(\d{8})", side.name) if not match: continue video = by_date.get(match.group(1)) if not video or video.parent != side.parent: continue # 已经跟着视频名了(<视频名>-thumb.jpg 这种),不要再认领一次, # 否则会把尾巴反复拼接到超长路径 if side.name == video.stem or side.name.startswith(f"{video.stem}.") \ or side.name.startswith(f"{video.stem}-"): continue rest = re.sub(r"^.*?\d{8}", "", side.stem) target = video.with_name(f"{video.stem}{rest}{side.suffix.lower()}") if target == side: continue try: if target.exists(): continue side.rename(target) adopted += 1 except OSError as exc: log.warning(f"⚠️ 附属文件认领失败 {side.name}: {exc}") if adopted: stats["sidecars"] = stats.get("sidecars", 0) + adopted return adopted @classmethod def execute(cls, plan: dict, season_years: dict, media_title: str) -> dict: """执行改名 / 移入 extras / 删除。返回统计。""" folder: Path = plan["folder"] 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"]: # 目标路径在 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 if target.exists(): log.warning(f"⚠️ 目标已存在,跳过: {target.name}") stats["skipped"] += 1 continue target.parent.mkdir(parents=True, exist_ok=True) file.rename(target) log.info(f"✅ 改名: {file.name} → {target.relative_to(folder)}") stats["renamed"] += 1 stats["sidecars"] = stats.get("sidecars", 0) + cls._follow_sidecars(file, target, moved=True) for file in plan["extras"]: extras_dir.mkdir(parents=True, exist_ok=True) target = extras_dir / file.name if target.exists(): log.warning(f"⚠️ extras 里已有同名文件,跳过: {file.name}") stats["skipped"] += 1 continue file.rename(target) log.info(f"📦 移入 extras: {file.name}") stats["extras"] += 1 for file, reason in plan["deletes"]: try: file.unlink() log.info(f"🗑 删除: {file.name}({reason})") stats["deleted"] += 1 except OSError as exc: log.warning(f"⚠️ 删除失败 {file.name}: {exc}") stats["skipped"] += 1 # 老名字的附属文件按日期兜底认领 cls.adopt_orphan_sidecars(folder, stats) # 根目录规范化:<标题> (<首播年>) [tmdbid-XXX],与「媒体整理」阶段 5 一致 folder_title = (plan.get("show") or media_title).replace(".", " ") parts = [folder_title] if plan.get("show_year"): parts.append(f"({plan['show_year']})") target_folder_name = " ".join(parts) + f" [tmdbid-{plan['show_id']}]" if folder.name != target_folder_name: target_folder = folder.parent / target_folder_name if target_folder.exists(): log.warning(f"⚠️ 目标目录已存在,跳过根目录改名: {target_folder_name}") else: try: folder.rename(target_folder) log.info(f"📁 根目录: {folder.name} → {target_folder_name}") stats["folder"] = target_folder_name except OSError as exc: log.warning(f"⚠️ 根目录改名失败: {exc}") return stats