Files
SceneMarshal/media/src/services/parser.py
T
ali 3a8e1d1583 fix(variety): 期名用「-」后缀并与常规整理互不干扰
- 命名改为 标题.SxxEyy.年份.技术标签-期名,S00 年份取每集播出年
  (与常规整理一致,避免两边各改一次)
- renamer.scan_rename 把「<目标名>-说明」视为已规范,整库扫描不再改回去
- 新增 .variety.json 标识:综艺目录名常常不规范(「花儿与少年」会被
  误匹配到衍生剧「同心季」),常规扫描据此按记录的 tmdb_id 识别
- 剧集根目录年份改用「首播年」而不是某集年份(综艺各集年份不同,
  否则根目录会随扫描顺序乱变)
- 附带把 花儿与少年 已整理的 70 个文件按集号重建为最终格式
2026-11-19 23:03:30 +08:00

230 lines
10 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/parser.py
import json
import re
from pathlib import Path
from core import config
from core.logger import log
from core.constants import RegexPatterns
from core.utils import StringUtil
from services.mediainfo import MediaInfoService
from services.tmdb import TMDBService
class ParserService:
"""纯业务计算与媒体结构解析器 (无状态)"""
@staticmethod
def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None):
parent_name = file_path.parent.name
grandparent_name = file_path.parent.parent.name
season_match = RegexPatterns.SEASON_DIR.match(parent_name)
flat_tv_match = RegexPatterns.FLAT_TV.search(file_path.stem)
pure_number_match = RegexPatterns.PURE_NUMBER.fullmatch(file_path.stem)
if forced_type == "tv" or (not forced_type and season_match):
m_type = "tv"
if season_match:
season_num = season_match.group(1).zfill(2)
target_season_folder = f"Season {season_num}"
target_name, root_dir_path = grandparent_name, file_path.parent.parent
else:
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
target_season_folder = None
target_name, root_dir_path = parent_name, file_path.parent
elif forced_type == "movie" or (not forced_type and not season_match and not (flat_tv_match or pure_number_match)):
m_type = "movie"
season_num = "01"
target_season_folder = None
if season_match:
target_name, root_dir_path = grandparent_name, file_path.parent.parent
else:
target_name, root_dir_path = parent_name, file_path.parent
elif not forced_type and (flat_tv_match or pure_number_match):
m_type = "tv"
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
target_season_folder = None
target_name, root_dir_path = parent_name, file_path.parent
else:
return None
root_key = str(root_dir_path)
if root_key not in context_cache:
clean_name = RegexPatterns.TMDB_CLEAN.sub('', target_name).strip()
tm = RegexPatterns.TMDB_CLEAN.search(target_name)
if tm:
title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2)
else:
title, year = clean_name.strip().replace(' ', '.'), ""
if not year:
# 目录名没写年份时,先从文件名里找(如 ...Last.Row.2026.S01E05...)
year_in_name = re.search(r"[.\s_\-\[\(]((?:19|20)\d{2})[.\s_\-\[\]\)]", file_path.stem)
if year_in_name:
year = year_in_name.group(1)
else:
log.debug(f"目录名与文件名都没有年份: {root_dir_path.name}")
context_cache[root_key] = (title, year)
title, year = context_cache[root_key]
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})"
@staticmethod
def _known_tmdb_id(f_path: Path, m_type: str) -> str | None:
"""目录名里已带 [tmdbid-xxx] 时直接返回,避免重复搜索与歧义。
另外检查「综艺整理」留下的 .variety.json 标识:综艺目录名常常不规范
(如「花儿与少年」会误匹配到衍生剧「同心季」),有了标识就按记录的 id 走。
"""
names = [f_path.parent.name]
if m_type == "tv" and f_path.parent.parent is not None:
names.append(f_path.parent.parent.name)
for name in names:
match = re.search(r"tmdbid-(\d+)", name, re.I)
if match:
return match.group(1)
marker_id = ParserService._variety_marker_id(f_path)
if marker_id is None:
return None
return str(marker_id)
@staticmethod
def _variety_marker_id(f_path: Path) -> int | None:
"""读取综艺整理留下的 .variety.json(向上最多找 3 层)。"""
folder = f_path.parent
for _ in range(3):
marker = folder / ".variety.json"
if marker.is_file():
try:
data = json.loads(marker.read_text(encoding="utf-8"))
return int(data.get("tmdb_id")) if data.get("tmdb_id") else None
except (OSError, ValueError, TypeError):
return None
if folder.parent == folder:
break
folder = folder.parent
return None
@staticmethod
def _title_from_filename(stem: str) -> str:
"""从文件名里推出一个可搜索的标题(用于中文目录名搜不到时的兜底)。
例:Notes.from.the.Last.Row.2026.S01E05.2160p.NF.WEB-DL... → "Notes from the Last Row"
"""
head = re.split(r"[.\s_]+S\d{1,2}E\d{1,4}", stem, maxsplit=1, flags=re.I)[0]
head = re.sub(r"[.\s_\-]+", " ", head).strip()
head = re.sub(r"\s*[\[\(]?(?:19|20)\d{2}[\]\)]?\s*$", "", head).strip()
return head
@staticmethod
def _episode_of(stem: str) -> str:
"""取集号,按可靠性依次尝试:
1. SxxEyy —— 标准写法
2. EPxx / Exx —— 很多国漫/网剧用 Love.Between.Fairy.and.Devil.2022.E01
3. 第x集/话/期 —— 中文写法
4. 裸数字兜底 —— 排除年份(19xx/20xx)、分辨率/编码(720/1080/265…)、
以及 AAC.2.0 / DDP5.1 这类声道写法
不能直接用 TARGET_EP 的第一个分组:它会先命中靠左的年份。
"""
sxe = re.search(r"S(\d{1,2})E(\d{1,4})", stem, re.I)
if sxe:
return sxe.group(2).zfill(2)
epx = re.search(r"(?<![a-zA-Z])(?:EP|E)[\s._-]?(\d{1,4})(?!\d)", stem, re.I)
if epx:
return epx.group(1).zfill(2)
cn = re.search(r"第\s*(\d{1,4})\s*[集话期]", stem)
if cn:
return cn.group(1).zfill(2)
for match in re.finditer(r"(?<![a-zA-Z0-9])(\d{1,4})(?![a-zA-Z0-9])", stem):
value = match.group(1)
number = int(value)
if len(value) == 4 and value[:2] in ("19", "20"): # 年份
continue
if value in {"480", "576", "720", "1080", "2160", "4320", "264", "265"}:
continue
if not 1 <= number <= 999:
continue
if re.match(r"\.[01](?![0-9])", stem[match.end():]): # 2.0 / 5.1 声道
continue
return value.zfill(2)
return "01"
@staticmethod
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
tags = MediaInfoService.get_scene_tags(f_path)
tmdb = TMDBService.search_media(
title, year, m_type, season_num,
known_tmdb_id=ParserService._known_tmdb_id(f_path, m_type),
media_path=f_path,
)
# 中文目录名搜不到时,用文件名里的英文原名再试一次
if tmdb is None:
alt_title = ParserService._title_from_filename(f_path.stem)
plain_title = title.replace(".", " ").strip()
if alt_title and alt_title.lower() != plain_title.lower():
log.info(f"🔁 中文标题未命中,改用文件名标题重试: {alt_title}")
tmdb = TMDBService.search_media(alt_title, year, m_type, season_num, media_path=f_path)
# 文件名主名:优先用媒体库里的安全标题(白名单清洗 + 截断)
media_name = (tmdb or {}).get("media_title") or ""
if not media_name:
media_name = StringUtil.media_title(title) or "Unknown"
# 年份三级兜底:目录名 → TMDB 实体 → 省略年份段
fit_year = str(year or "").strip()
if not fit_year and tmdb and tmdb.get("year"):
fit_year = str(tmdb["year"])
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
folder_title = title.replace('.', ' ')
# 剧集根目录年份用「剧集首播年」:综艺每集年份不同(2022~2025),
# 若用某一集的年份,根目录就会随扫描顺序乱变。
root_year = fit_year
if m_type == "tv":
in_name = re.search(r"(?:19|20)\d{2}", folder_title)
root_year = in_name.group(0) if in_name else str((tmdb or {}).get("year") or "")
target_folder = f"{folder_title} ({root_year})" if root_year else folder_title
if tid:
target_folder = f"{target_folder} {tid}"
target_folder = target_folder.strip()
if m_type == "movie":
if is_multi_version:
stem = f"{folder_title} ({fit_year})" if fit_year else folder_title
return f"{stem} - {tech}", target_folder
stem = f"{media_name}.{fit_year}" if fit_year else media_name
return f"{stem}.{tech}", target_folder
else:
ep = ParserService._episode_of(f_path.stem)
episode_year = fit_year
season_years = (tmdb or {}).get("season_years") or {}
if season_years:
episode_year = season_years.get(season_num, fit_year)
# 特别篇按「本集」的播出年份:Season 00 的整体 air_date 往往是第一篇的年份。
# 注意必须限定在 S00,否则正片集号会撞上特别篇集号(S03E10 撞上特别篇第 10 集)。
special_years = (tmdb or {}).get("special_years") or {}
if str(season_num).zfill(2) == "00" and special_years.get(ep):
episode_year = special_years[ep]
prefix = f"{media_name}.S{season_num}E{ep}"
if episode_year:
prefix = f"{prefix}.{episode_year}"
return f"{prefix}.{tech}", target_folder