Files
SceneMarshal/src/services/variety.py
T

527 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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"(?<!\d)(20\d{2})(\d{2})(\d{2})(?!\d)"),
]
# 只有 月.日(无年份),例如 S00E017.02.24出发。
# 必须位于开头或分隔符之后——否则 "S01E02.2020" 里的 02.20 会被误当成 2 月 20 日。
_DATE_SHORT = re.compile(
r"(?:^|(?<=[.\s_\-()\[\]]))(\d{1,2})[.\-_/](\d{1,2})(?![0-9])")
# 特典类关键词:仅用于「同日期多个候选」时的排序,不用于判定归属。
# 词表见 config.ini [Variety] special_words / filename_only_words / extra_type_words。
def _words_pattern(words) -> 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
# ---------------------------------------------------------------- 打分与分配
@staticmethod
def _score(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 集名里直接写了这个日期
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 = "") -> dict:
index = cls.build_index(show_id)
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
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))))
if by_ep:
date, complete = by_ep, True
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}
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)
# 文件数多于候选数 → 同一天多份,按码率取前 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)
for file, candidate, _score in assigned:
plan["renames"].append((file, candidate))
# 无日期的一律进 extras(无法定位)
plan["extras"].extend(plan.pop("undated"))
return plan
@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']})")
log.info(f" 改名 {len(plan['renames'])} | 进 extras {len(plan['extras'])} | 删除 {len(plan['deletes'])}")
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]}")
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]}")
for file, reason in plan["deletes"][:5]:
log.info(f" [删除] {file.name[:60]} ← {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}
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
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