feat(tmdb): 缓存库重构为 entities + lookups(schema 2)

- 新增 core/tmdb_store.py:{type}_{tmdb_id} 实体 + 标题/年份索引,fcntl.flock
  串行化 + 临时文件原子替换,容器内 pipeline 与宿主机 media-archive 共用
- 命中优先级:目录名里的 [tmdbid-xxx] → 缓存 lookup → 在线搜索
- 搜索先去掉年份条件;精确标题匹配后仍有多条才交互选择(非 TTY 取第一条
  并告警),解决「苍兰诀」真人版/动漫版同名同年歧义
- 未给年份的搜索在解析出实体后,同时补写空年份桶与带年份桶
- tmdb_original_title 保留原文;新增 media_title(白名单清洗 + 120 字符截断)
  专供拼文件名,清洗规则改为只保留字母/数字/下划线/连字符
- 年份三级兜底:目录名 → TMDB 实体 → 省略年份段;取消阻塞式年份追问
- Season 00 年份统一取 Season 01
- media-archive 改用同一 store,删除自带的 details_ 缓存
- 迁移 415 条旧记录 → 411 实体 / 409 标题索引(4 个 TMDB id 已失效跳过)
- 移除不再使用的 core/cache.py
This commit is contained in:
ali
2026-11-19 17:24:20 +08:00
parent ab5bbe54e9
commit 2c76863c16
6 changed files with 525 additions and 197 deletions
-42
View File
@@ -1,42 +0,0 @@
# src/core/cache.py
import json
from pathlib import Path
from core.logger import log
class JsonCacheManager:
"""全局无状态 JSON 缓存管理器"""
_caches = {}
@classmethod
def _load_if_needed(cls, cache_path: Path):
path_str = str(cache_path)
if path_str not in cls._caches:
if cache_path.exists():
try:
cls._caches[path_str] = json.loads(cache_path.read_text('utf-8'))
except Exception as e:
log.warning(f"⚠️ 读取缓存失败 {cache_path}: {e}")
cls._caches[path_str] = {}
else:
cls._caches[path_str] = {}
return cls._caches[path_str]
@classmethod
def get(cls, cache_path: Path, key: str, default=None):
cache_dict = cls._load_if_needed(cache_path)
return cache_dict.get(key, default)
@classmethod
def set(cls, cache_path: Path, key: str, value):
cache_dict = cls._load_if_needed(cache_path)
cache_dict[key] = value
@classmethod
def save(cls, cache_path: Path):
path_str = str(cache_path)
if path_str in cls._caches:
try:
cache_path.write_text(json.dumps(cls._caches[path_str], ensure_ascii=False, indent=2), 'utf-8')
except Exception as e:
log.error(f"❌ 保存缓存落盘失败 {cache_path}: {e}")
+205
View File
@@ -0,0 +1,205 @@
# src/core/tmdb_store.py
"""TMDB 缓存库(schema 2)。
结构::
{
"_meta": {"schema": 2, "updated_at": "..."},
"entities": {"movie_9007": {...}, "tv_231620": {...}},
"lookups": {"movie": {"标题": {"年份或空串": ["movie_9007"]}}, "tv": {...}}
}
- entities 以 ``{type}_{tmdb_id}`` 为主键,一条记录即一个 TMDB 实体
- lookups 是「标题(+年份) → 实体键列表」的索引,列表长度 >1 表示搜索结果并列
- 文件级访问用 fcntl.flock 串行化,写入走临时文件 + os.replace,供容器内 pipeline
与宿主机 media-archive 两个进程并发使用
"""
from __future__ import annotations
import fcntl
import json
import os
import unicodedata
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from core.utils import StringUtil
SCHEMA = 2
TYPES = ("movie", "tv")
# 详情里我们关心的字段(写进 details 段)
DETAIL_KEYS = ("original_language", "origin_country")
# ------------------------------------------------------------------ 时间/字符串
def now_iso() -> str:
"""本地时区(东八区)ISO8601,精确到秒。"""
return datetime.now().astimezone().isoformat(timespec="seconds")
def normalize_title(title: str) -> str:
"""lookup 键归一化:NFKC + 去首尾空白 + 连续空白压成一个空格。"""
if not title:
return ""
return " ".join(unicodedata.normalize("NFKC", str(title)).strip().split())
def entity_key(mtype: str, tmdb_id) -> str:
return f"{mtype}_{int(tmdb_id)}"
# ------------------------------------------------------------------ 读写与锁
def empty_db() -> dict:
return {"_meta": {"schema": SCHEMA}, "entities": {}, "lookups": {t: {} for t in TYPES}}
@contextmanager
def _lock(path: Path):
lock_path = path.with_name(path.name + ".lock")
path.parent.mkdir(parents=True, exist_ok=True)
with open(lock_path, "a+") as fh:
fcntl.flock(fh, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(fh, fcntl.LOCK_UN)
def _read(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return empty_db()
if not isinstance(data, dict) or "entities" not in data or "lookups" not in data:
# 旧扁平结构或损坏:运行期当空库用,转换交给迁移脚本
return empty_db()
for t in TYPES:
data["lookups"].setdefault(t, {})
data.setdefault("_meta", {}).setdefault("schema", SCHEMA)
return data
def _write(path: Path, db: dict) -> None:
db.setdefault("_meta", {})["schema"] = SCHEMA
db["_meta"]["updated_at"] = now_iso()
tmp = path.with_name(f"{path.name}.tmp{os.getpid()}")
tmp.write_text(json.dumps(db, ensure_ascii=False, indent=2), encoding="utf-8")
os.replace(tmp, path)
@contextmanager
def transaction(path: Path):
"""持锁完成一次「读-改-写」;块内抛异常则不写回。"""
with _lock(path):
db = _read(path)
yield db
_write(path, db)
def snapshot(path: Path) -> dict:
"""只读快照(同样持锁,避免读到半个文件)。"""
with _lock(path):
return _read(path)
# ------------------------------------------------------------------ 实体
def get_entity(db: dict, mtype: str, tmdb_id) -> dict | None:
try:
return db["entities"].get(entity_key(mtype, tmdb_id))
except (TypeError, ValueError):
return None
def put_entity(db: dict, entity: dict) -> str:
key = entity_key(entity["type"], entity["tmdb_id"])
entity["updated_at"] = now_iso()
db["entities"][key] = entity
return key
def _first(payload: dict, *names):
for name in names:
value = payload.get(name)
if value:
return value
return None
def _year_of(payload: dict) -> int | None:
date = _first(payload, "release_date", "first_air_date", "air_date") or ""
return int(date[:4]) if len(date) >= 4 and date[:4].isdigit() else None
def season_years_from(payload: dict) -> dict[str, str]:
"""从 /tv/{id} 的 seasons 数组生成 {"01": "2023"}。
特别季 Season 00 的 air_date 通常散落各年,统一取 Season 01 的年份。
"""
out: dict[str, str] = {}
for season in payload.get("seasons") or []:
try:
num = str(int(season.get("season_number", 0))).zfill(2)
except (TypeError, ValueError):
continue
air = (season.get("air_date") or "").strip()
if len(air) >= 4 and air[:4].isdigit():
out[num] = air[:4]
if "00" in out and "01" in out:
out["00"] = out["01"]
return out
def build_entity(mtype: str, tmdb_id, payload: dict) -> dict:
"""把 TMDB 详情响应映射成本库的记录结构。"""
localized = _first(payload, "title", "name") or ""
original = _first(payload, "original_title", "original_name") or localized
genres = [
{"id": int(g.get("id")), "name": g.get("name") or ""}
for g in (payload.get("genres") or [])
if isinstance(g, dict) and g.get("id")
]
record = {
"type": mtype,
"tmdb_id": int(tmdb_id),
"title": localized,
"tmdb_original_title": original,
"media_title": StringUtil.media_title(original, fallback=localized),
"year": _year_of(payload),
"details": {
"genres": genres,
"original_language": (payload.get("original_language") or "").lower(),
"origin_country": [str(c).upper() for c in (payload.get("origin_country") or []) if c],
},
"updated_at": now_iso(),
}
if mtype == "tv":
record["season_years"] = season_years_from(payload)
return record
# ------------------------------------------------------------------ 索引
def lookup(db: dict, mtype: str, title: str, year) -> list[str]:
bucket = db["lookups"].get(mtype, {}).get(normalize_title(title))
if not bucket:
return []
return list(bucket.get(str(year or ""), []))
def merge_candidates(db: dict, mtype: str, title: str, years, keys) -> None:
"""把 keys 写进 title 的若干年份桶(年份为空串表示「未给年份的搜索」)。"""
key_title = normalize_title(title)
if not key_title or not keys:
return
bucket = db["lookups"].setdefault(mtype, {}).setdefault(key_title, {})
for year in years:
slot = bucket.setdefault(str(year), [])
for key in keys:
if key not in slot:
slot.append(key)
+27 -2
View File
@@ -1,18 +1,43 @@
# src/core/utils.py # src/core/utils.py
import json import json
import re
import subprocess import subprocess
import unicodedata
from pathlib import Path from pathlib import Path
from core.constants import RegexPatterns from core.constants import RegexPatterns
class StringUtil: class StringUtil:
"""字符串与文件命名安全处理工具""" """字符串与文件命名安全处理工具"""
# media_title 允许的最大字符数(留足技术标签,避免触碰文件系统 255 字节上限)
MAX_MEDIA_TITLE = 120
@staticmethod @staticmethod
def sanitize_title(title: str) -> str: def sanitize_title(title: str) -> str:
"""白名单清洗:只保留字母/数字/下划线/连字符。
路径特殊字符(\\ / * ? : " < > |)、空格、各类中英文标点一律转成点,
中日韩文字与带重音的拉丁字母属于 \\w,会原样保留。
"""
if not title: if not title:
return "" return ""
# 接入核心正则 s = unicodedata.normalize("NFKC", str(title))
return RegexPatterns.FILE_SANITIZE.sub('.', title.replace("'", "").replace("’", "")).strip('.') s = re.sub(r"[^\w\-]+", ".", s, flags=re.UNICODE)
s = re.sub(r"\.{2,}", ".", s).strip(".")
return s
@staticmethod
def media_title(title: str, fallback: str = "") -> str:
"""生成可直接用作文件名的标题:白名单清洗 + 超长截断。
title 为空或清洗后为空时退回 fallback(一般是 TMDB 本地化标题)。
"""
for candidate in (title, fallback):
s = StringUtil.sanitize_title(candidate)
if s:
return s[:StringUtil.MAX_MEDIA_TITLE].strip(".")
return ""
class FFprobeUtil: class FFprobeUtil:
"""FFprobe 探针调用与 JSON 解析工具""" """FFprobe 探针调用与 JSON 解析工具"""
+45 -21
View File
@@ -1,5 +1,6 @@
# src/services/parser.py # src/services/parser.py
import re
from pathlib import Path from pathlib import Path
from core import config from core import config
from core.logger import log from core.logger import log
@@ -59,48 +60,71 @@ class ParserService:
title, year = clean_name.strip().replace(' ', '.'), "" title, year = clean_name.strip().replace(' ', '.'), ""
if not year: if not year:
context_path = " / ".join(file_path.parts[-3:]) # 不再阻塞式追问:年份稍后由 TMDB 实体补全,实在查不到就省略年份段
log.warning(f"目录命名不规范: {root_dir_path.name}") log.debug(f"目录名无年份,将由 TMDB 结果补全: {root_dir_path.name}")
log.warning(f"📁 案发现场: {context_path}")
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
if user_title: title = user_title.replace(' ', '.')
while not RegexPatterns.YEAR_EXACT.match(year):
year = input(f" ➤ 请输入 4 位年份: ").strip()
context_cache[root_key] = (title, year) context_cache[root_key] = (title, year)
title, year = context_cache[root_key] title, year = context_cache[root_key]
return m_type, title, year, season_num, target_season_folder, root_dir_path, f"{title.replace('.', ' ')} ({year})" 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] 时直接返回,避免重复搜索与歧义。"""
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)
return None
@staticmethod @staticmethod
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False): 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) tags = MediaInfoService.get_scene_tags(f_path)
tmdb = TMDBService.search_media(title, year, m_type, season_num) tmdb = TMDBService.search_media(
title, year, m_type, season_num,
known_tmdb_id=ParserService._known_tmdb_id(f_path, m_type),
)
orig = tmdb['original_title'] if tmdb else "" # 文件名主名:优先用媒体库里的安全标题(白名单清洗 + 截断)
if orig: media_name = (tmdb or {}).get("media_title") or ""
display_name = orig if not media_name:
else: media_name = StringUtil.media_title(title) or "Unknown"
display_name = StringUtil.sanitize_title(title)
# 年份三级兜底:目录名 → 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 "" tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL" source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}" tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip() folder_title = title.replace('.', ' ')
target_folder = f"{folder_title} ({fit_year})" if fit_year else folder_title
if tid:
target_folder = f"{target_folder} {tid}"
target_folder = target_folder.strip()
if m_type == "movie": if m_type == "movie":
if is_multi_version: if is_multi_version:
return f"{title} ({year}) - {tech}", target_folder stem = f"{folder_title} ({fit_year})" if fit_year else folder_title
return f"{display_name}.{year}.{tech}", target_folder 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: else:
match = RegexPatterns.TARGET_EP.search(f_path.stem) match = RegexPatterns.TARGET_EP.search(f_path.stem)
ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01" ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01"
episode_year = year episode_year = fit_year
if tmdb and "season_years" in tmdb: season_years = (tmdb or {}).get("season_years") or {}
episode_year = tmdb["season_years"].get(season_num, year) if season_years:
episode_year = season_years.get(season_num, fit_year)
return f"{display_name}.S{season_num}E{ep}.{episode_year}.{tech}", target_folder prefix = f"{media_name}.S{season_num}E{ep}"
if episode_year:
prefix = f"{prefix}.{episode_year}"
return f"{prefix}.{tech}", target_folder
+203 -75
View File
@@ -1,112 +1,240 @@
# src/services/tmdb.py # src/services/tmdb.py
"""TMDB 查询:优先用目录名里的 tmdbid,其次查本地缓存库,最后才发请求。"""
import sys
import requests import requests
from requests.adapters import HTTPAdapter from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry from urllib3.util.retry import Retry
from core import config from core import config
from core import tmdb_store as store
from core.logger import log from core.logger import log
from core.utils import StringUtil
from core.cache import JsonCacheManager # 💡 接入统一缓存层
class TMDBService: class TMDBService:
_notified_cache_hits = set() _notified_cache_hits = set()
# ------------------------------------------------------------ HTTP
@staticmethod @staticmethod
def _get_session(): def _get_session():
s = requests.Session() s = requests.Session()
retries = Retry(total=config.TMDB_MAX_RETRIES, backoff_factor=1, status_forcelist=[429, 502, 503, 504]) retries = Retry(total=config.TMDB_MAX_RETRIES, backoff_factor=1,
status_forcelist=[429, 502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retries)) s.mount('https://', HTTPAdapter(max_retries=retries))
return s return s
@classmethod
def _fetch_season_years(cls, session, tmdb_id):
details_url = f"https://api.themoviedb.org/3/tv/{tmdb_id}"
season_years = {}
try:
resp = session.get(details_url, params={"api_key": config.TMDB_API_KEY.strip()}, timeout=config.TMDB_TIMEOUT)
if resp.status_code == 200:
for season in resp.json().get('seasons', []):
s_num = str(season.get('season_number', 0)).zfill(2)
air_date = season.get('air_date')
if air_date and len(air_date) >= 4:
season_years[s_num] = air_date[:4]
except Exception as e:
log.warning(f"获取剧集详情年份失败 [ID:{tmdb_id}]: {e}")
return season_years
@staticmethod @staticmethod
def search_media(title, year=None, m_type="movie", season_num=None): def _params(extra: dict | None = None) -> dict:
params = {"api_key": config.TMDB_API_KEY.strip(), "language": config.TMDB_LANGUAGE}
if extra:
params.update(extra)
return params
@classmethod
def _fetch_details(cls, session, mtype: str, tmdb_id) -> dict | None:
endpoint = "tv" if mtype == "tv" else "movie"
try:
resp = session.get(f"https://api.themoviedb.org/3/{endpoint}/{tmdb_id}",
params=cls._params(), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001
log.warning(f"⚠️ TMDB 详情请求异常 [{mtype}/{tmdb_id}]: {exc}")
return None
if resp.status_code != 200:
log.warning(f"⚠️ TMDB 详情获取失败 [{mtype}/{tmdb_id}]: HTTP {resp.status_code}")
return None
return resp.json()
@classmethod
def _search(cls, session, title: str, year_s: str, mtype: str) -> list[dict]:
endpoint = "tv" if mtype == "tv" else "movie"
extra = {"query": title}
if year_s:
extra["first_air_date_year" if mtype == "tv" else "year"] = year_s
try:
resp = session.get(f"https://api.themoviedb.org/3/search/{endpoint}",
params=cls._params(extra), timeout=config.TMDB_TIMEOUT)
except Exception as exc: # noqa: BLE001
log.warning(f"⚠️ TMDB 搜索异常 [{title}]: {exc}")
return []
if resp.status_code != 200:
log.warning(f"⚠️ TMDB 搜索失败 [{title}]: HTTP {resp.status_code}")
return []
return resp.json().get("results") or []
# ------------------------------------------------------------ 对外入口
@classmethod
def search_media(cls, title, year=None, m_type="movie", season_num=None, known_tmdb_id=None):
"""取 TMDB 实体,失败返回 None。
优先级:目录名里的 tmdbid → 缓存 lookup → 在线搜索。
返回的实体字段见 core.tmdb_store.build_entity。
"""
if not config.TMDB_API_KEY: if not config.TMDB_API_KEY:
return None return None
cache_path = config.TMDB_CACHE_PATH year_s = str(year).strip() if year else ""
cache_key = f"{m_type}_{title}_{year}" path = config.TMDB_CACHE_PATH
# 💡 利用解耦的缓存管理器 entity = None
cached_data = JsonCacheManager.get(cache_path, cache_key) if known_tmdb_id:
entity = cls._from_id(path, m_type, known_tmdb_id, title, year_s)
if entity is None:
entity = cls._from_lookup(path, m_type, title, year_s)
if entity is None:
entity = cls._from_search(path, m_type, title, year_s)
if entity is None:
return None
return cls._ensure_season(entity, season_num, year_s)
if cached_data: # ------------------------------------------------------------ 三条来源
if m_type == "tv" and season_num:
if season_num not in cached_data.get("season_years", {}):
log.info(f"🔄 {title} 缓存缺失新季数 (S{season_num}) 的年份,触发按需增量更新...")
tmdb_id = cached_data.get("tmdb_id")
if tmdb_id:
session = TMDBService._get_session()
new_sy = TMDBService._fetch_season_years(session, tmdb_id)
if "season_years" not in cached_data: @classmethod
cached_data["season_years"] = {} def _from_id(cls, path, mtype, tmdb_id, title, year_s):
key = store.entity_key(mtype, tmdb_id)
db = store.snapshot(path)
entity = db["entities"].get(key)
if entity is not None:
log.debug(f"⚡ TMDB 命中(目录名 tmdbid): {key}")
return entity
if new_sy: session = cls._get_session()
cached_data["season_years"].update(new_sy) payload = cls._fetch_details(session, mtype, tmdb_id)
if not payload:
return None
entity = store.build_entity(mtype, tmdb_id, payload)
cls._save(path, [entity], title, year_s, chosen=entity)
return entity
if season_num not in cached_data["season_years"]: @classmethod
cached_data["season_years"][season_num] = year def _from_lookup(cls, path, mtype, title, year_s):
log.debug(f"⚠️ TMDB 暂无 S{season_num} 年份记录,已使用首播年份 ({year}) 兜底并锁定缓存。") db = store.snapshot(path)
keys = store.lookup(db, mtype, title, year_s)
entities = [db["entities"][k] for k in keys if k in db["entities"]]
if not entities:
return None
JsonCacheManager.set(cache_path, cache_key, cached_data) if len(entities) == 1:
JsonCacheManager.save(cache_path) mark = (mtype, store.normalize_title(title), year_s)
if mark not in cls._notified_cache_hits:
log.debug(f"⚡ TMDB 缓存命中: {title} ({year_s or '无年份'})")
cls._notified_cache_hits.add(mark)
return entities[0]
if cache_key not in TMDBService._notified_cache_hits: log.info(f"🔀 缓存里「{title}」({year_s or '无年份'}) 有 {len(entities)} 个候选")
log.debug(f"⚡ TMDB 缓存命中: {title} ({year})") return cls._choose(entities, title, year_s)
TMDBService._notified_cache_hits.add(cache_key)
return cached_data
endpoint = "tv" if m_type == "tv" else "movie" @classmethod
url = f"https://api.themoviedb.org/3/search/{endpoint}" def _from_search(cls, path, mtype, title, year_s):
params = {"api_key": config.TMDB_API_KEY.strip(), "query": title, "language": config.TMDB_LANGUAGE} session = cls._get_session()
log.debug(f"🌐 请求 TMDB 搜索: {title} ({year_s or '无年份'})")
results = cls._search(session, title, year_s, mtype)
if not results:
log.warning(f"⚠️ TMDB 未搜到: {title}")
return None
if year: target = store.normalize_title(title)
if m_type == "tv": params["first_air_date_year"] = year exact = [
else: params["year"] = year r for r in results
if store.normalize_title(r.get("title") or r.get("name") or "") == target
or store.normalize_title(r.get("original_title") or r.get("original_name") or "") == target
]
pool = (exact or results)[:5]
entities = []
for result in pool:
payload = cls._fetch_details(session, mtype, result.get("id"))
if not payload:
continue
entities.append(store.build_entity(mtype, result["id"], payload))
if not entities:
return None
if len(entities) == 1:
chosen = entities[0]
elif exact:
# 精确标题匹配后仍有多条(如「苍兰诀」真人版 + 动漫版)→ 才问
log.info(f"🔀 「{title}」精确匹配到 {len(entities)} 个候选,需要确认")
chosen = cls._choose(entities, title, year_s)
else:
log.warning(f"⚠️ 「{title}」没有精确匹配,{len(entities)} 个候选取热度最高者"
f"(tmdbid-{entities[0]['tmdb_id']}),如有误请核对")
chosen = entities[0]
cls._save(path, entities, title, year_s, chosen)
return chosen
# ------------------------------------------------------------ 选择与落库
@classmethod
def _choose(cls, entities, title, year_s):
"""候选并列时才走到这里:交互模式让用户选,否则取第一个(搜索热度顺序)。"""
for idx, ent in enumerate(entities, 1):
genres = "/".join(g["name"] for g in ent["details"].get("genres", [])[:3]) or "-"
seasons = len(ent.get("season_years") or {})
tail = f" {seasons} 季" if ent["type"] == "tv" and seasons else ""
print(f" {idx}. {ent['type']}/{ent['tmdb_id']} {ent['title']} "
f"({ent.get('year') or '?'}) {genres}{tail}")
if sys.stdin.isatty():
try:
raw = input(f" ➤ 选择编号(1-{len(entities)},回车默认 1): ").strip()
if raw.isdigit() and 1 <= int(raw) <= len(entities):
return entities[int(raw) - 1]
except (EOFError, KeyboardInterrupt):
pass
log.warning(f"⚠️ 未选择,取热度最高者({title} {year_s or '无年份'} → "
f"tmdbid-{entities[0]['tmdb_id']})")
return entities[0]
@classmethod
def _save(cls, path, entities, title, year_s, chosen):
keys = [store.entity_key(e["type"], e["tmdb_id"]) for e in entities]
years = set()
if year_s:
years.add(year_s)
chosen_year = str(chosen.get("year") or "")
if chosen_year:
years.add(chosen_year)
if not year_s:
years.add("") # 未给年份的搜索:同时维护空年份桶
try: try:
session = TMDBService._get_session() with store.transaction(path) as db:
log.debug(f"🌐 请求 TMDB [{endpoint.upper()}]: {title}") for entity in entities:
resp = session.get(url, params=params, timeout=config.TMDB_TIMEOUT) store.put_entity(db, entity)
data = resp.json() store.merge_candidates(db, chosen["type"], title, years, keys)
except OSError as exc:
log.warning(f"⚠️ TMDB 缓存写入失败(不影响本次处理): {exc}")
if resp.status_code == 200 and data.get('results'): # ------------------------------------------------------------ 季年份
res = data['results'][0]
orig = res.get('original_name') if m_type == "tv" else res.get('original_title')
clean_orig = StringUtil.sanitize_title(orig) @classmethod
tmdb_id = res.get('id') def _ensure_season(cls, entity, season_num, year_s):
"""剧集缺某一季的年份时按需补拉(旧行为保留),并写入缓存。"""
if entity.get("type") != "tv" or not season_num:
return entity
result = { season_years = entity.setdefault("season_years", {})
"original_title": clean_orig, if season_num in season_years:
"tmdb_id": tmdb_id return entity
}
if m_type == "tv" and tmdb_id: log.info(f"🔄 缓存缺少 S{season_num} 的年份,按需补拉剧集详情...")
result["season_years"] = TMDBService._fetch_season_years(session, tmdb_id) session = cls._get_session()
if season_num and season_num not in result["season_years"]: payload = cls._fetch_details(session, "tv", entity["tmdb_id"])
result["season_years"][season_num] = year if payload:
merged = store.season_years_from(payload)
JsonCacheManager.set(cache_path, cache_key, result) merged.update({k: v for k, v in season_years.items() if v})
JsonCacheManager.save(cache_path) entity["season_years"] = merged
return result season_years = merged
except Exception as e: if season_num not in season_years and year_s:
log.error(f"TMDB 异常 [{title}]: {e}") season_years[season_num] = year_s
return None
try:
with store.transaction(config.TMDB_CACHE_PATH) as db:
store.put_entity(db, entity)
except OSError as exc:
log.warning(f"⚠️ 补季写入失败: {exc}")
return entity
+27 -39
View File
@@ -56,15 +56,13 @@ GENRE_TALK = 10767
CHINESE = {"zh", "cn", "cmn", "yue"} CHINESE = {"zh", "cn", "cmn", "yue"}
HK_TW = {"TW", "HK"} HK_TW = {"TW", "HK"}
# 详情缓存与「片名→id」缓存共用 media/src/tmdb_data.json(已 gitignore), # 与 pipeline 共用的 TMDB 缓存库(entities + lookups,已 gitignore)
# 键加 details_ 前缀与 pipeline 的 <type>_<title>_<year> 区分开。
TMDB_CACHE_PATH = Path( TMDB_CACHE_PATH = Path(
os.environ.get( os.environ.get(
"SCENERENAME_TMDB_CACHE", "SCENERENAME_TMDB_CACHE",
"/home/ali/docker/tools/python/media/src/tmdb_data.json", "/home/ali/docker/tools/python/media/src/tmdb_data.json",
) )
) )
DETAILS_PREFIX = "details_"
# --------------------------------------------------------------------- 基础 # --------------------------------------------------------------------- 基础
@@ -122,42 +120,29 @@ def tmdb_id_of(name: str) -> str | None:
return m.group(1) if m else None return m.group(1) if m else None
def cache_load() -> dict: def _store():
try: """延迟导入共享缓存模块(本脚本跑在宿主机,需把 media/src 加进 sys.path)。"""
return json.loads(TMDB_CACHE_PATH.read_text(encoding="utf-8")) src = str(CONFIG_PATH.parent)
except (OSError, ValueError): if src not in sys.path:
return {} sys.path.insert(0, src)
from core import tmdb_store # noqa: PLC0415 (延迟导入,避免脚本启动就依赖容器代码树)
return tmdb_store
def cache_store(key: str, value: dict) -> None:
"""写入详情缓存。
与 pipeline 的 JsonCacheManager 共用同一个文件,而那是「整文件读改写」的做法,
所以这里写前重新读一次、再用临时文件 + 原子替换,尽量避免覆盖对方刚写入的条目。
"""
data = cache_load()
data[key] = value
tmp = TMDB_CACHE_PATH.with_name(TMDB_CACHE_PATH.name + ".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
os.replace(tmp, TMDB_CACHE_PATH)
# 分类真正用到的字段;name/title 只用于回显
DETAIL_FIELDS = ("name", "title", "genres", "original_language", "origin_country")
def tmdb_info(tmdb_id: str, kind: str, cfg: configparser.ConfigParser) -> dict | None: def tmdb_info(tmdb_id: str, kind: str, cfg: configparser.ConfigParser) -> dict | None:
"""取 TMDB 实体(含 details);命中缓存则不回源。"""
if not cfg.has_section("TMDB"): if not cfg.has_section("TMDB"):
return None return None
api_key = (cfg.get("TMDB", "api_key", fallback="") or "").strip() api_key = (cfg.get("TMDB", "api_key", fallback="") or "").strip()
if not api_key: if not api_key:
return None return None
cache_key = f"{DETAILS_PREFIX}{kind}_{tmdb_id}" store = _store()
cached = cache_load().get(cache_key) key = store.entity_key(kind, tmdb_id)
if isinstance(cached, dict) and "genres" in cached: entity = store.snapshot(TMDB_CACHE_PATH)["entities"].get(key)
print(f"⚡ TMDB 详情缓存命中: {cache_key}") if entity and (entity.get("details") or {}).get("genres") is not None:
return cached print(f"⚡ TMDB 详情命中缓存: {key}")
return entity
language = cfg.get("TMDB", "language", fallback="zh-CN").strip() or "zh-CN" language = cfg.get("TMDB", "language", fallback="zh-CN").strip() or "zh-CN"
endpoint = "tv" if kind == "tv" else "movie" endpoint = "tv" if kind == "tv" else "movie"
@@ -170,17 +155,19 @@ def tmdb_info(tmdb_id: str, kind: str, cfg: configparser.ConfigParser) -> dict |
if not data: if not data:
return None return None
trimmed = {k: data[k] for k in DETAIL_FIELDS if k in data} entity = store.build_entity(kind, tmdb_id, data)
try: try:
cache_store(cache_key, trimmed) with store.transaction(TMDB_CACHE_PATH) as db:
store.put_entity(db, entity)
except OSError as exc: except OSError as exc:
print(f"⚠️ TMDB 详情缓存写入失败(不影响本次归档): {exc}") print(f"⚠️ TMDB 缓存写入失败(不影响本次归档): {exc}")
return trimmed return entity
def region_of(info: dict) -> str: def region_of(entity: dict) -> str:
lang = (info.get("original_language") or "").lower() details = entity.get("details") or {}
countries = {str(c).upper() for c in (info.get("origin_country") or []) if c} lang = (details.get("original_language") or "").lower()
countries = {str(c).upper() for c in (details.get("origin_country") or []) if c}
if lang in CHINESE or "CN" in countries or "HK" in countries or "TW" in countries: if lang in CHINESE or "CN" in countries or "HK" in countries or "TW" in countries:
return "港台" if countries & HK_TW else "华语" return "港台" if countries & HK_TW else "华语"
if lang in {"ja", "ko"}: if lang in {"ja", "ko"}:
@@ -191,7 +178,8 @@ def region_of(info: dict) -> str:
def suggest_category(kind: str, info: dict | None) -> str | None: def suggest_category(kind: str, info: dict | None) -> str | None:
if not info: if not info:
return None return None
genres = {int(g.get("id", 0)) for g in info.get("genres", []) if isinstance(g, dict)} genres = {int(g.get("id", 0)) for g in (info.get("details") or {}).get("genres", [])
if isinstance(g, dict)}
region = region_of(info) region = region_of(info)
if genres & {GENRE_REALITY, GENRE_TALK}: if genres & {GENRE_REALITY, GENRE_TALK}:
@@ -423,7 +411,7 @@ def main() -> int:
files, size = count_media(src) files, size = count_media(src)
label = "剧集" if kind == "tv" else "电影" label = "剧集" if kind == "tv" else "电影"
title = (info or {}).get("name") or (info or {}).get("title") or src.name title = (info or {}).get("title") or src.name
print(f"📁 源目录 : {src}") print(f"📁 源目录 : {src}")
print(f"🎬 识别 : {label} | {title}" + (f" | tmdbid-{tmdb_id}" if tmdb_id else " | 无 tmdbid")) print(f"🎬 识别 : {label} | {title}" + (f" | tmdbid-{tmdb_id}" if tmdb_id else " | 无 tmdbid"))
if tmdb_id and info is None: if tmdb_id and info is None: