# 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"(?