feat(variety): 新增综艺整理模式,按日期匹配 TMDB 播出日期定集号
- 新增 services/variety.py:日期提取(多格式/无年份补全)、TMDB 全季索引 (含 Season 00)、按日期分组的一对一分配、三类动作(改名/extras/删除) - 消歧不依赖「加更/特别」这类关键词:集名里含该日期 +6、类型关键词命中 +3、 季提示 +2,再靠一对一约束用排除法定 - 删除判定:期数 + 类型关键词都相同才算同一集的重复(保留体积最大的), 避免把「加更版第1期」误当成「正片第1期」删掉 - 命名:标题.SxxEyy.年份.技术标签.TMDB期名(期名放最后,按拍板) - main.py 新增 variety 模式与 --show 参数;pipeline 增加 run_variety - docs/variety-plan.md 补记拍板结果与实现状态 预览结果(未执行): 花儿与少年 特典 改名 70 / extras 3 / 删除 0 你好星期六 改名 284 / extras 31 / 删除 49 5.哈 第六季 改名 48 / extras 16 / 删除 0
This commit is contained in:
@@ -0,0 +1,314 @@
|
||||
# src/services/variety.py
|
||||
"""综艺整理:按「文件名日期 ↔ TMDB 播出日期」匹配集号。
|
||||
|
||||
综艺文件名通常没有 SxxEyy,只有日期;正片与特典(加更 / 会员版 / 超前企划)
|
||||
也常放在同一目录。因此这里:
|
||||
|
||||
1. 从文件名提取日期(多种格式,含无年份时用季年份补全);
|
||||
2. 拉取该剧全季(含 Season 00)的播出日期,建立 {日期: [(季, 集, 集名)]} 索引;
|
||||
3. 按日期分组做「一对一分配」,靠排除法消歧(不依赖加更/特别这类关键词);
|
||||
4. 产出三类动作:
|
||||
- rename:能对上的,改名为 标题.SxxEyy.年份.技术标签.期名
|
||||
- extras:TMDB 没有对应条目的,移到剧集根目录 extras/(不改名)
|
||||
- delete:同一集的重复下载 / 低码率版本(按拍板:只留最高码率)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from core.logger import log
|
||||
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出发
|
||||
_DATE_SHORT = re.compile(r"(?<!\d)(\d{1,2})[.\-_/](\d{1,2})(?!\d)")
|
||||
|
||||
# 特典类关键词:仅用于「同日期多个候选」时的排序,不用于判定归属
|
||||
_SPECIAL_WORDS = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋|先导|前瞻|精编|回顾|纯享|未播")
|
||||
_EP_NAME_SPECIAL = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋|精编|回顾|纯享|未播")
|
||||
|
||||
|
||||
class VarietyService:
|
||||
VIDEO_EXTS = {".mkv", ".mp4", ".avi", ".ts", ".m2ts", ".mov"}
|
||||
|
||||
# ---------------------------------------------------------------- 日期与季
|
||||
|
||||
@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 = match.groups()
|
||||
return f"????-{int(month):02d}-{int(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 索引
|
||||
|
||||
@classmethod
|
||||
def build_index(cls, show_id: int) -> dict:
|
||||
"""{date: [{'season','ep','name'}]},含 Season 00。按需拉取,失败静默跳过。"""
|
||||
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 "",
|
||||
})
|
||||
log.info(f"📅 TMDB 索引: {len(index)} 个播出日期({len(seasons)} 季)")
|
||||
return dict(index)
|
||||
|
||||
# ---------------------------------------------------------------- 打分与分配
|
||||
|
||||
@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) -> 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]
|
||||
|
||||
# 按日期分组;无日期的先放着
|
||||
groups: dict[str, list[Path]] = defaultdict(list)
|
||||
undated: list[Path] = []
|
||||
for file in videos:
|
||||
date, complete = cls.extract_date(file.name)
|
||||
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,
|
||||
"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 = re.compile(r"加更|会员|特别|特辑|企划|花絮|彩蛋|先导|前瞻|精编|回顾|纯享|未播|超前|探班")
|
||||
|
||||
@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)
|
||||
tech = f"{tags['res']}.WEB-DL.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||
season = candidate["season"]
|
||||
year = season_years.get(season) or ""
|
||||
ep_name = StringUtil.sanitize_title(candidate["name"])[:40].strip(".")
|
||||
parts = [media_title, f"S{season}E{candidate['ep']:02d}"]
|
||||
if year:
|
||||
parts.append(str(year))
|
||||
parts.append(tech)
|
||||
if ep_name:
|
||||
parts.append(ep_name)
|
||||
return ".".join(parts) + 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 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}
|
||||
|
||||
for file, candidate in plan["renames"]:
|
||||
target = file.with_name(cls._target_name(file, candidate, media_title, season_years))
|
||||
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.name}")
|
||||
stats["renamed"] += 1
|
||||
|
||||
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
|
||||
return stats
|
||||
Reference in New Issue
Block a user