Files
SceneMarshal/media/src/services/tmdb.py
T
ali d22a21a29a perf(tmdb): 目录名 tmdbid 命中改为每进程只记一次,并加进程内实体缓存
- 原来每集都打一行「⚡ TMDB 命中(目录名 tmdbid)」,且每次都重新读取
  并解析 320KB 的 tmdb_data.json(snapshot 加锁),40 集就是 40 次
- 现在同一 id 在本进程内只记一次日志;实体本身也缓存,后续集数直接复用
- 实测:我的三体 40 集 → 1 行;苍兰诀动漫 50 集 → 1 行
2026-11-19 21:00:29 +08:00

321 lines
13 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/tmdb.py
"""TMDB 查询:优先用目录名里的 tmdbid,其次查本地缓存库,最后才发请求。"""
import sys
from pathlib import Path
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from core import config
from core import tmdb_store as store
from core.logger import log
class TMDBService:
_notified_cache_hits = set()
# 本进程内的「负缓存」:同一个目录的每一集都会重复调用 search_media,
# 失败结果不记住的话,一个 60 集的剧会白跑 180 次请求。
_dead_ids = set() # 详情 404 的 tmdb id
_failed_searches = set() # (类型, 归一化标题, 年份) 搜索无结果
_id_hits_notified = set() # 目录名 tmdbid 命中:每个 id 只记一次日志
_id_entity_cache = {} # 进程内实体缓存,避免每集重读缓存文件
# ------------------------------------------------------------ HTTP
@staticmethod
def _get_session():
s = requests.Session()
retries = Retry(total=config.TMDB_MAX_RETRIES, backoff_factor=1,
status_forcelist=[429, 502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retries))
return s
@staticmethod
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:
try:
cache_key = (mtype, int(tmdb_id))
except (TypeError, ValueError):
return None
if cache_key in cls._dead_ids:
log.debug(f"⏭ 跳过已确认失效的 TMDB id: {mtype}/{tmdb_id}")
return 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 == 404:
# 目录名里的 tmdbid 已失效(TMDB 侧删除/合并),本次运行不再重试
cls._dead_ids.add(cache_key)
log.warning(f"⚠️ TMDB id 已失效(404),本次运行不再重试: {mtype}/{tmdb_id}")
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,
media_path=None):
"""取 TMDB 实体,失败返回 None。
优先级:目录名里的 tmdbid → 缓存 lookup → 在线搜索。
media_path 是待整理的媒体文件路径,仅用于「动漫/真人」分类消歧。
返回的实体字段见 core.tmdb_store.build_entity。
"""
if not config.TMDB_API_KEY:
return None
year_s = str(year).strip() if year else ""
path = config.TMDB_CACHE_PATH
entity = None
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, media_path)
if entity is None:
entity = cls._from_search(path, m_type, title, year_s, media_path)
if entity is None:
return None
return cls._ensure_season(entity, season_num, year_s)
# ------------------------------------------------------------ 三条来源
@classmethod
def _from_id(cls, path, mtype, tmdb_id, title, year_s):
key = store.entity_key(mtype, tmdb_id)
# 同一目录的每一集都会走这里,进程内记住即可:
# 既不用每集重读 320KB 的缓存文件,日志也只留一行。
cached = cls._id_entity_cache.get(key)
if cached is not None:
return cached
db = store.snapshot(path)
entity = db["entities"].get(key)
if entity is not None:
if key not in cls._id_hits_notified:
log.debug(f"⚡ TMDB 命中(目录名 tmdbid): {key}")
cls._id_hits_notified.add(key)
cls._id_entity_cache[key] = entity
return entity
session = cls._get_session()
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)
cls._id_entity_cache[key] = entity
return entity
@classmethod
def _from_lookup(cls, path, mtype, title, year_s, media_path=None):
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
# 同名作品可能有多条(苍兰诀动漫版/真人版),缓存命中也要按所在分类过滤
narrowed = cls._prefer_by_category(media_path, entities)
if narrowed:
entities = narrowed
if len(entities) == 1:
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]
log.info(f"🔀 缓存里「{title}」({year_s or '无年份'}) 有 {len(entities)} 个候选")
return cls._choose(entities, title, year_s)
@classmethod
def _from_search(cls, path, mtype, title, year_s, media_path=None):
search_key = (mtype, store.normalize_title(title), year_s)
if search_key in cls._failed_searches:
log.debug(f"⏭ 跳过本进程内已失败过的搜索: {title} ({year_s or '无年份'})")
return None
session = cls._get_session()
log.debug(f"🌐 请求 TMDB 搜索: {title} ({year_s or '无年份'})")
results = cls._search(session, title, year_s, mtype)
if not results:
cls._failed_searches.add(search_key)
log.warning(f"⚠️ TMDB 未搜到(本次运行不再重试): {title}")
return None
target = store.normalize_title(title)
exact = [
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:
cls._failed_searches.add(search_key)
return None
if len(entities) == 1:
chosen = entities[0]
elif exact:
# 精确标题匹配后仍有多条(如「苍兰诀」真人版 tv/130368 + 动漫版 tv/206534)
# 先用库里的分类目录消歧,剩下的才需要问
narrowed = cls._prefer_by_category(media_path, entities)
if narrowed and len(narrowed) == 1:
log.info(f"🔀 「{title}」有 {len(entities)} 个同名候选,按所在分类锁定 "
f"tmdbid-{narrowed[0]['tmdb_id']}")
chosen = narrowed[0]
else:
pool_entities = narrowed or entities
log.info(f"🔀 「{title}」精确匹配到 {len(pool_entities)} 个候选,需要确认")
chosen = cls._choose(pool_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
# ------------------------------------------------------------ 选择与落库
# 库里按「动漫 / 真人」分目录,同名候选可用所在分类消歧:
# 苍兰诀就是典型——动漫版 tv/206534(2 季 50 集)与真人版 tv/130368(1 季 36 集)同名。
ANIME_DIRS = {"动漫节目", "动漫电影"}
LIVE_DIRS = {"电视节目", "电影", "综艺"}
ANIME_GENRE_ID = 16
@classmethod
def _prefer_by_category(cls, path, entities):
"""按文件所在分类目录偏好动画/真人;判断不出返回 None。"""
try:
parts = set(Path(path).parts)
except (TypeError, ValueError):
return None
if parts & cls.ANIME_DIRS:
want_anime = True
elif parts & cls.LIVE_DIRS:
want_anime = False
else:
return None
def is_anime(entity):
genres = entity.get("details", {}).get("genres") or []
return cls.ANIME_GENRE_ID in {g.get("id") for g in genres}
picked = [e for e in entities if is_anime(e) == want_anime]
return picked or None
@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:
with store.transaction(path) as db:
for entity in entities:
store.put_entity(db, entity)
store.merge_candidates(db, chosen["type"], title, years, keys)
except OSError as exc:
log.warning(f"⚠️ TMDB 缓存写入失败(不影响本次处理): {exc}")
# ------------------------------------------------------------ 季年份
@classmethod
def _ensure_season(cls, entity, season_num, year_s):
"""剧集缺某一季的年份时按需补拉(旧行为保留),并写入缓存。"""
if entity.get("type") != "tv" or not season_num:
return entity
season_years = entity.setdefault("season_years", {})
if season_num in season_years:
return entity
log.info(f"🔄 缓存缺少 S{season_num} 的年份,按需补拉剧集详情...")
session = cls._get_session()
payload = cls._fetch_details(session, "tv", entity["tmdb_id"])
if payload:
merged = store.season_years_from(payload)
merged.update({k: v for k, v in season_years.items() if v})
entity["season_years"] = merged
season_years = merged
if season_num not in season_years and year_s:
season_years[season_num] = year_s
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