forked from kenzuya/unshackle
refactor(core)!: drop leading underscores from internal definitions
Renames 314 defs and 41 module/class-level constants. Keeps 11 names underscored where the stripped form collides in scope, plus 5.5.0 shims for the three symbols external service repos call.
This commit is contained in:
@@ -95,7 +95,7 @@ def search_metadata(
|
||||
continue
|
||||
cached = title_cacher.get_cached_provider(p.NAME, cache_title_id, kind, cache_region, cache_account_hash)
|
||||
if cached:
|
||||
result = _cached_to_result(cached, p.NAME, kind)
|
||||
result = cached_to_result(cached, p.NAME, kind)
|
||||
if result and result.title and fuzzy_match(result.title, title):
|
||||
log.debug("Using cached %s data for %r", p.NAME, title)
|
||||
return result
|
||||
@@ -120,7 +120,7 @@ def search_metadata(
|
||||
if result.external_ids.tmdb_id or result.external_ids.tvdb_id:
|
||||
cache_data = {
|
||||
**result.raw,
|
||||
"_enriched_ids": _external_ids_to_dict(result.external_ids),
|
||||
"_enriched_ids": external_ids_to_dict(result.external_ids),
|
||||
}
|
||||
title_cacher.cache_provider(
|
||||
p.NAME, cache_title_id, cache_data, kind, cache_region, cache_account_hash
|
||||
@@ -165,7 +165,7 @@ def get_title_by_id(
|
||||
title_cacher.cache_provider(
|
||||
"tmdb",
|
||||
cache_title_id,
|
||||
{"detail": result.raw, "external_ids": _external_ids_to_dict(ext_ids)},
|
||||
{"detail": result.raw, "external_ids": external_ids_to_dict(ext_ids)},
|
||||
kind,
|
||||
cache_region,
|
||||
cache_account_hash,
|
||||
@@ -210,7 +210,7 @@ def get_year_by_id(
|
||||
title_cacher.cache_provider(
|
||||
"tmdb",
|
||||
cache_title_id,
|
||||
{"detail": result.raw, "external_ids": _external_ids_to_dict(ext_ids)},
|
||||
{"detail": result.raw, "external_ids": external_ids_to_dict(ext_ids)},
|
||||
kind,
|
||||
cache_region,
|
||||
cache_account_hash,
|
||||
@@ -282,7 +282,7 @@ def fetch_external_ids(
|
||||
title_cacher.cache_provider(
|
||||
"tmdb",
|
||||
cache_title_id,
|
||||
{"detail": detail, "external_ids": _external_ids_to_dict(ext)},
|
||||
{"detail": detail, "external_ids": external_ids_to_dict(ext)},
|
||||
kind,
|
||||
cache_region,
|
||||
cache_account_hash,
|
||||
@@ -378,13 +378,13 @@ def resolve_by_ids(
|
||||
|
||||
# trust ranking for cross-validating enrichments; `metadata_providers` filters this
|
||||
# set but sets search order only, not the ranking
|
||||
_ENRICHMENT_AUTHORITY: tuple[str, ...] = ("tmdb", "simkl", "tvdb")
|
||||
ENRICHMENT_AUTHORITY: tuple[str, ...] = ("tmdb", "simkl", "tvdb")
|
||||
|
||||
|
||||
def _enrichment_providers(kind: Optional[str] = None) -> list[str]:
|
||||
def enrichment_providers(kind: Optional[str] = None) -> list[str]:
|
||||
"""Names of configured providers that can resolve an IMDB ID, most trusted first."""
|
||||
configured = {cls.NAME for cls in provider_order(kind) if hasattr(cls, "find_by_imdb_id")}
|
||||
return [name for name in _ENRICHMENT_AUTHORITY if name in configured]
|
||||
return [name for name in ENRICHMENT_AUTHORITY if name in configured]
|
||||
|
||||
|
||||
def enrich_ids(result: MetadataResult) -> None:
|
||||
@@ -403,7 +403,7 @@ def enrich_ids(result: MetadataResult) -> None:
|
||||
kind = result.kind or "movie"
|
||||
|
||||
# Step 1: Collect enrichment results from all available providers
|
||||
authority = {name: i for i, name in enumerate(_enrichment_providers(kind))}
|
||||
authority = {name: i for i, name in enumerate(enrichment_providers(kind))}
|
||||
enrichments: list[tuple[str, ExternalIds]] = []
|
||||
for provider_name in authority:
|
||||
p = get_provider(provider_name)
|
||||
@@ -421,7 +421,7 @@ def enrich_ids(result: MetadataResult) -> None:
|
||||
return
|
||||
|
||||
# Step 2: Cross-validate using tmdb_id as anchor — drop providers that disagree
|
||||
validated = _validate_enrichments(enrichments, authority)
|
||||
validated = validate_enrichments(enrichments, authority)
|
||||
|
||||
# Step 3: Merge validated data (fill gaps only)
|
||||
for _provider_name, ext in validated:
|
||||
@@ -432,7 +432,7 @@ def enrich_ids(result: MetadataResult) -> None:
|
||||
ids.tvdb_id = ext.tvdb_id
|
||||
|
||||
|
||||
def _validate_enrichments(
|
||||
def validate_enrichments(
|
||||
enrichments: list[tuple[str, ExternalIds]],
|
||||
authority: dict[str, int],
|
||||
) -> list[tuple[str, ExternalIds]]:
|
||||
@@ -484,7 +484,7 @@ def _validate_enrichments(
|
||||
return validated
|
||||
|
||||
|
||||
def _external_ids_to_dict(ext: ExternalIds) -> dict:
|
||||
def external_ids_to_dict(ext: ExternalIds) -> dict:
|
||||
"""Convert ExternalIds to a dict for caching."""
|
||||
result: dict = {}
|
||||
if ext.imdb_id:
|
||||
@@ -500,7 +500,7 @@ def _external_ids_to_dict(ext: ExternalIds) -> dict:
|
||||
return result
|
||||
|
||||
|
||||
def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[MetadataResult]:
|
||||
def cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[MetadataResult]:
|
||||
"""Convert a cached provider dict back to a MetadataResult."""
|
||||
if provider_name == "tmdb":
|
||||
detail = cached.get("detail", {})
|
||||
@@ -566,10 +566,10 @@ def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[M
|
||||
raw=cached,
|
||||
)
|
||||
elif provider_name == "tvdb":
|
||||
from unshackle.core.providers.tvdb import _ids_from_remote, _parse_int
|
||||
from unshackle.core.providers.tvdb import ids_from_remote, parse_int
|
||||
|
||||
tvdb_id = _parse_int(cached.get("tvdb_id") or cached.get("id"))
|
||||
ext = _ids_from_remote(cached.get("remote_ids") or cached.get("remoteIds"), tvdb_id)
|
||||
tvdb_id = parse_int(cached.get("tvdb_id") or cached.get("id"))
|
||||
ext = ids_from_remote(cached.get("remote_ids") or cached.get("remoteIds"), tvdb_id)
|
||||
# restore IDs that enrichment filled in beyond the raw remote_ids
|
||||
enriched = cached.get("_enriched_ids", {})
|
||||
ext.imdb_id = ext.imdb_id or enriched.get("imdb_id")
|
||||
@@ -578,14 +578,14 @@ def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[M
|
||||
ext.tmdb_kind = kind
|
||||
return MetadataResult(
|
||||
title=cached.get("name"),
|
||||
year=_parse_int(cached.get("year")),
|
||||
year=parse_int(cached.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
source="tvdb",
|
||||
raw=cached,
|
||||
)
|
||||
elif provider_name == "anilist":
|
||||
return AniListProvider()._to_result(cached)
|
||||
return AniListProvider().to_result(cached)
|
||||
elif provider_name == "imdb":
|
||||
from unshackle.core.providers.imdb import primary_language
|
||||
|
||||
|
||||
@@ -86,15 +86,15 @@ class MetadataProvider(metaclass=ABCMeta):
|
||||
"""Fetch external IDs for a title by this provider's native ID."""
|
||||
|
||||
|
||||
def _clean(s: str) -> str:
|
||||
def clean(s: str) -> str:
|
||||
return STRIP_RE.sub("", s).lower()
|
||||
|
||||
|
||||
def _strip_year(s: str) -> str:
|
||||
def strip_year(s: str) -> str:
|
||||
return YEAR_RE.sub("", s).strip()
|
||||
|
||||
|
||||
def fuzzy_match(a: str, b: str, threshold: float = 0.8) -> bool:
|
||||
"""Return True if ``a`` and ``b`` are a close match."""
|
||||
ratio = SequenceMatcher(None, _clean(a), _clean(b)).ratio()
|
||||
ratio = SequenceMatcher(None, clean(a), clean(b)).ratio()
|
||||
return ratio >= threshold
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Optional, Union
|
||||
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean
|
||||
|
||||
GRAPHQL_URL = "https://graphql.anilist.co"
|
||||
|
||||
@@ -55,7 +55,7 @@ class AniListProvider(MetadataProvider):
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
def _graphql(self, query: str, variables: dict) -> Optional[dict]:
|
||||
def graphql(self, query: str, variables: dict) -> Optional[dict]:
|
||||
try:
|
||||
r = self.session.post(GRAPHQL_URL, json={"query": query, "variables": variables}, timeout=30)
|
||||
body = r.json()
|
||||
@@ -69,7 +69,7 @@ class AniListProvider(MetadataProvider):
|
||||
return None
|
||||
return body.get("data")
|
||||
|
||||
def _title_variant(self, titles: dict) -> Optional[str]:
|
||||
def title_variant(self, titles: dict) -> Optional[str]:
|
||||
from unshackle.core.config import config
|
||||
|
||||
configured = (config.anilist_title_language or "english").lower()
|
||||
@@ -79,8 +79,8 @@ class AniListProvider(MetadataProvider):
|
||||
return str(value)
|
||||
return None
|
||||
|
||||
def _to_result(self, node: dict) -> Optional[MetadataResult]:
|
||||
title = self._title_variant(node.get("title") or {})
|
||||
def to_result(self, node: dict) -> Optional[MetadataResult]:
|
||||
title = self.title_variant(node.get("title") or {})
|
||||
if not title:
|
||||
return None
|
||||
return MetadataResult(
|
||||
@@ -96,7 +96,7 @@ class AniListProvider(MetadataProvider):
|
||||
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
|
||||
self.log.debug("Searching AniList for %r (%s, %s)", title, kind, year)
|
||||
|
||||
data = self._graphql(SEARCH_QUERY, {"search": title})
|
||||
data = self.graphql(SEARCH_QUERY, {"search": title})
|
||||
nodes = ((data or {}).get("Page") or {}).get("media") or []
|
||||
if not nodes:
|
||||
self.log.debug("AniList returned no results for %r", title)
|
||||
@@ -110,8 +110,8 @@ class AniListProvider(MetadataProvider):
|
||||
dated = [n for n in nodes if (n.get("startDate") or {}).get("year") == year]
|
||||
nodes = dated or nodes
|
||||
|
||||
best = max(nodes, key=lambda n: _match_ratio(n, title))
|
||||
result = self._to_result(best)
|
||||
best = max(nodes, key=lambda n: match_ratio(n, title))
|
||||
result = self.to_result(best)
|
||||
if result:
|
||||
self.log.debug("AniList -> %s (ID %s)", result.title, result.external_ids.anilist_id)
|
||||
return result
|
||||
@@ -126,14 +126,14 @@ class AniListProvider(MetadataProvider):
|
||||
namespace, number = ref
|
||||
self.log.debug("Fetching AniList media %s:%d", namespace, number)
|
||||
if namespace == "mal":
|
||||
data = self._graphql(MAL_QUERY, {"idMal": number})
|
||||
data = self.graphql(MAL_QUERY, {"idMal": number})
|
||||
else:
|
||||
data = self._graphql(MEDIA_QUERY, {"id": number})
|
||||
data = self.graphql(MEDIA_QUERY, {"id": number})
|
||||
|
||||
node = (data or {}).get("Media")
|
||||
if not node:
|
||||
return None
|
||||
return self._to_result(node)
|
||||
return self.to_result(node)
|
||||
|
||||
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
|
||||
"""Return external IDs. AniList knows no western IDs, so only its own."""
|
||||
@@ -147,6 +147,6 @@ class AniListProvider(MetadataProvider):
|
||||
return result.external_ids if result else ExternalIds()
|
||||
|
||||
|
||||
def _match_ratio(node: dict, title: str) -> float:
|
||||
def match_ratio(node: dict, title: str) -> float:
|
||||
names = (node.get("title") or {}).values()
|
||||
return max((SequenceMatcher(None, _clean(title), _clean(n)).ratio() for n in names if n), default=0.0)
|
||||
return max((SequenceMatcher(None, clean(title), clean(n)).ratio() for n in names if n), default=0.0)
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Optional, Union
|
||||
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, fuzzy_match
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, fuzzy_match
|
||||
|
||||
GRAPHQL_URL = "https://caching.graphql.imdb.com/"
|
||||
|
||||
@@ -41,7 +41,7 @@ def primary_language(data: dict) -> Optional[str]:
|
||||
return langs[0].get("id") if langs else None
|
||||
|
||||
|
||||
def _title_to_result(node: dict, kind: str) -> Optional[MetadataResult]:
|
||||
def title_to_result(node: dict, kind: str) -> Optional[MetadataResult]:
|
||||
title = (node.get("titleText") or {}).get("text") or (node.get("originalTitleText") or {}).get("text")
|
||||
if not title:
|
||||
return None
|
||||
@@ -66,7 +66,7 @@ class IMDBProvider(MetadataProvider):
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
def _graphql(self, operation: str, query: str) -> Optional[dict]:
|
||||
def graphql(self, operation: str, query: str) -> Optional[dict]:
|
||||
"""Run a persisted query, registering it with one POST the first time it is seen."""
|
||||
extensions = {"persistedQuery": {"version": 1, "sha256Hash": hashlib.sha256(query.encode()).hexdigest()}}
|
||||
# IMDb's GraphQL gateway decodes "+" literally, so these JSON params must carry no spaces
|
||||
@@ -79,7 +79,7 @@ class IMDBProvider(MetadataProvider):
|
||||
try:
|
||||
r = self.session.get(GRAPHQL_URL, params=params, headers=GRAPHQL_HEADERS, timeout=30)
|
||||
body = r.json()
|
||||
if _persisted_query_missing(body):
|
||||
if persisted_query_missing(body):
|
||||
self.log.debug("Registering persisted query %s", operation)
|
||||
payload = {"operationName": operation, "variables": {}, "query": query, "extensions": extensions}
|
||||
r = self.session.post(GRAPHQL_URL, json=payload, headers=GRAPHQL_HEADERS, timeout=30)
|
||||
@@ -110,15 +110,15 @@ class IMDBProvider(MetadataProvider):
|
||||
"{ edges { node { title { %s } } } } }" % (", ".join(constraints), TITLE_FIELDS)
|
||||
)
|
||||
|
||||
data = self._graphql("UnshackleTitleSearch", query)
|
||||
data = self.graphql("UnshackleTitleSearch", query)
|
||||
edges = ((data or {}).get("advancedTitleSearch") or {}).get("edges") or []
|
||||
nodes = [edge["node"]["title"] for edge in edges if (edge.get("node") or {}).get("title")]
|
||||
if not nodes:
|
||||
self.log.debug("IMDb returned no results for %r", title)
|
||||
return None
|
||||
|
||||
best = max(nodes, key=lambda n: _match_ratio(n, title))
|
||||
result = _title_to_result(best, kind)
|
||||
best = max(nodes, key=lambda n: match_ratio(n, title))
|
||||
result = title_to_result(best, kind)
|
||||
if not result or not result.title or not fuzzy_match(result.title, title):
|
||||
self.log.debug("IMDb title mismatch: searched %r, got %r", title, result.title if result else None)
|
||||
return None
|
||||
@@ -132,23 +132,23 @@ class IMDBProvider(MetadataProvider):
|
||||
self.log.debug("Fetching IMDb title %s", imdb_id)
|
||||
|
||||
query = 'query UnshackleTitle { title(id: "%s") { %s } }' % (escape_graphql(imdb_id), TITLE_FIELDS)
|
||||
data = self._graphql("UnshackleTitle", query)
|
||||
data = self.graphql("UnshackleTitle", query)
|
||||
node = (data or {}).get("title")
|
||||
if not node:
|
||||
return None
|
||||
return _title_to_result(node, kind)
|
||||
return title_to_result(node, kind)
|
||||
|
||||
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
|
||||
"""Return external IDs. For IMDB, the provider_id IS the IMDB ID."""
|
||||
return ExternalIds(imdb_id=str(provider_id))
|
||||
|
||||
|
||||
def _match_ratio(node: dict, title: str) -> float:
|
||||
def match_ratio(node: dict, title: str) -> float:
|
||||
names = [(node.get("titleText") or {}).get("text"), (node.get("originalTitleText") or {}).get("text")]
|
||||
return max((SequenceMatcher(None, _clean(title), _clean(n)).ratio() for n in names if n), default=0.0)
|
||||
return max((SequenceMatcher(None, clean(title), clean(n)).ratio() for n in names if n), default=0.0)
|
||||
|
||||
|
||||
def _persisted_query_missing(body: dict) -> bool:
|
||||
def persisted_query_missing(body: dict) -> bool:
|
||||
for error in body.get("errors") or []:
|
||||
code = (error.get("extensions") or {}).get("code")
|
||||
if code == "PERSISTED_QUERY_NOT_FOUND" or error.get("message") == "PersistedQueryNotFound":
|
||||
|
||||
@@ -7,7 +7,7 @@ import requests
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, fuzzy_match
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, fuzzy_match
|
||||
|
||||
# Mapping from our kind ("movie"/"tv") to OMDb title types
|
||||
KIND_TO_TYPE: dict[str, str] = {
|
||||
@@ -27,7 +27,7 @@ def primary_language(data: dict) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_year(value: Optional[str]) -> Optional[int]:
|
||||
def parse_year(value: Optional[str]) -> Optional[int]:
|
||||
# OMDb years look like "2017", "2008–2013" or "2023–"
|
||||
if value and len(value) >= 4 and value[:4].isdigit():
|
||||
return int(value[:4])
|
||||
@@ -46,12 +46,12 @@ class OMDBProvider(MetadataProvider):
|
||||
return bool(config.omdb_api_key)
|
||||
|
||||
@property
|
||||
def _api_key(self) -> str:
|
||||
def api_key(self) -> str:
|
||||
return config.omdb_api_key
|
||||
|
||||
def _get(self, params: dict[str, str]) -> Optional[dict]:
|
||||
def api_get(self, params: dict[str, str]) -> Optional[dict]:
|
||||
try:
|
||||
r = self.session.get(self.BASE_URL, params={"apikey": self._api_key, **params}, timeout=30)
|
||||
r = self.session.get(self.BASE_URL, params={"apikey": self.api_key, **params}, timeout=30)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
@@ -72,11 +72,11 @@ class OMDBProvider(MetadataProvider):
|
||||
if year is not None:
|
||||
params["y"] = str(year)
|
||||
|
||||
data = self._get(params)
|
||||
data = self.api_get(params)
|
||||
if not data and year is not None:
|
||||
# OMDb's year filter is exact; retry without it for off-by-one metadata
|
||||
del params["y"]
|
||||
data = self._get(params)
|
||||
data = self.api_get(params)
|
||||
if not data:
|
||||
return None
|
||||
|
||||
@@ -88,9 +88,9 @@ class OMDBProvider(MetadataProvider):
|
||||
name = candidate.get("Title") or ""
|
||||
if not name:
|
||||
continue
|
||||
ratio = SequenceMatcher(None, _clean(title), _clean(name)).ratio()
|
||||
ratio = SequenceMatcher(None, clean(title), clean(name)).ratio()
|
||||
if ratio > best_ratio:
|
||||
candidate_year = _parse_year(candidate.get("Year"))
|
||||
candidate_year = parse_year(candidate.get("Year"))
|
||||
if year and candidate_year and abs(year - candidate_year) > 1:
|
||||
continue
|
||||
best_ratio = ratio
|
||||
@@ -109,11 +109,11 @@ class OMDBProvider(MetadataProvider):
|
||||
self.log.debug("OMDb -> %s (ID %s)", result_title, imdb_id)
|
||||
|
||||
# Fetch full detail so raw carries ratings, genre, rating cert, etc.
|
||||
detail = self._get({"i": imdb_id}) if imdb_id else None
|
||||
detail = self.api_get({"i": imdb_id}) if imdb_id else None
|
||||
|
||||
return MetadataResult(
|
||||
title=result_title,
|
||||
year=_parse_year(best_match.get("Year")),
|
||||
year=parse_year(best_match.get("Year")),
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(imdb_id=imdb_id),
|
||||
original_language=primary_language(detail or best_match),
|
||||
@@ -126,13 +126,13 @@ class OMDBProvider(MetadataProvider):
|
||||
imdb_id = str(provider_id)
|
||||
self.log.debug("Fetching OMDb title %s", imdb_id)
|
||||
|
||||
data = self._get({"i": imdb_id})
|
||||
data = self.api_get({"i": imdb_id})
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return MetadataResult(
|
||||
title=data.get("Title"),
|
||||
year=_parse_year(data.get("Year")),
|
||||
year=parse_year(data.get("Year")),
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(imdb_id=data.get("imdbID")),
|
||||
original_language=primary_language(data),
|
||||
|
||||
@@ -47,7 +47,7 @@ class SimklProvider(MetadataProvider):
|
||||
self.log.debug("Simkl returned list (no matches) for %r", filename)
|
||||
return None
|
||||
|
||||
return self._parse_response(data, title, year, kind)
|
||||
return self.parse_response(data, title, year, kind)
|
||||
|
||||
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
|
||||
return None # SIMKL has no direct ID lookup used here
|
||||
@@ -115,7 +115,7 @@ class SimklProvider(MetadataProvider):
|
||||
tvdb_id=tvdb_id,
|
||||
)
|
||||
|
||||
def _parse_response(
|
||||
def parse_response(
|
||||
self, data: dict, search_title: str, search_year: Optional[int], kind: str
|
||||
) -> Optional[MetadataResult]:
|
||||
"""Parse a SIMKL response into a MetadataResult."""
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Optional, Union
|
||||
import requests
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, _strip_year
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, strip_year
|
||||
|
||||
|
||||
class TMDBProvider(MetadataProvider):
|
||||
@@ -21,14 +21,14 @@ class TMDBProvider(MetadataProvider):
|
||||
return bool(config.tmdb_api_key)
|
||||
|
||||
@property
|
||||
def _api_key(self) -> str:
|
||||
def api_key(self) -> str:
|
||||
return config.tmdb_api_key
|
||||
|
||||
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
|
||||
search_title = _strip_year(title)
|
||||
search_title = strip_year(title)
|
||||
self.log.debug("Searching TMDB for %r (%s, %s)", search_title, kind, year)
|
||||
|
||||
params: dict[str, str | int] = {"api_key": self._api_key, "query": search_title}
|
||||
params: dict[str, str | int] = {"api_key": self.api_key, "query": search_title}
|
||||
if year is not None:
|
||||
params["year" if kind == "movie" else "first_air_date_year"] = year
|
||||
|
||||
@@ -56,7 +56,7 @@ class TMDBProvider(MetadataProvider):
|
||||
candidates = [c for c in candidates if c]
|
||||
|
||||
for candidate in candidates:
|
||||
ratio = SequenceMatcher(None, _clean(search_title), _clean(candidate)).ratio()
|
||||
ratio = SequenceMatcher(None, clean(search_title), clean(candidate)).ratio()
|
||||
if ratio > best_ratio:
|
||||
best_ratio = ratio
|
||||
best_id = result.get("id")
|
||||
@@ -73,8 +73,8 @@ class TMDBProvider(MetadataProvider):
|
||||
return None
|
||||
|
||||
# Fetch full detail for caching
|
||||
detail = self._fetch_detail(best_id, kind)
|
||||
ext_raw = self._fetch_external_ids_raw(best_id, kind)
|
||||
detail = self.fetch_detail(best_id, kind)
|
||||
ext_raw = self.fetch_external_ids_raw(best_id, kind)
|
||||
|
||||
date = (detail or {}).get("release_date") or (detail or {}).get("first_air_date")
|
||||
result_year = int(date[:4]) if date and len(date) >= 4 and date[:4].isdigit() else None
|
||||
@@ -97,7 +97,7 @@ class TMDBProvider(MetadataProvider):
|
||||
)
|
||||
|
||||
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
|
||||
detail = self._fetch_detail(int(provider_id), kind)
|
||||
detail = self.fetch_detail(int(provider_id), kind)
|
||||
if not detail:
|
||||
return None
|
||||
|
||||
@@ -116,7 +116,7 @@ class TMDBProvider(MetadataProvider):
|
||||
)
|
||||
|
||||
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
|
||||
raw = self._fetch_external_ids_raw(int(provider_id), kind)
|
||||
raw = self.fetch_external_ids_raw(int(provider_id), kind)
|
||||
if not raw:
|
||||
return ExternalIds(tmdb_id=int(provider_id), tmdb_kind=kind)
|
||||
return ExternalIds(
|
||||
@@ -132,7 +132,7 @@ class TMDBProvider(MetadataProvider):
|
||||
try:
|
||||
r = self.session.get(
|
||||
f"{self.BASE_URL}/find/{imdb_id}",
|
||||
params={"api_key": self._api_key, "external_source": "imdb_id"},
|
||||
params={"api_key": self.api_key, "external_source": "imdb_id"},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
@@ -166,7 +166,7 @@ class TMDBProvider(MetadataProvider):
|
||||
self.log.debug("TMDB find -> ID %s (%s) for IMDB %s", tmdb_id, kind, imdb_id)
|
||||
|
||||
# Now fetch the full external IDs from TMDB to get TVDB etc.
|
||||
ext_raw = self._fetch_external_ids_raw(tmdb_id, kind)
|
||||
ext_raw = self.fetch_external_ids_raw(tmdb_id, kind)
|
||||
|
||||
return ExternalIds(
|
||||
imdb_id=imdb_id,
|
||||
@@ -175,11 +175,11 @@ class TMDBProvider(MetadataProvider):
|
||||
tvdb_id=ext_raw.get("tvdb_id") if ext_raw else None,
|
||||
)
|
||||
|
||||
def _fetch_detail(self, tmdb_id: int, kind: str) -> Optional[dict]:
|
||||
def fetch_detail(self, tmdb_id: int, kind: str) -> Optional[dict]:
|
||||
try:
|
||||
r = self.session.get(
|
||||
f"{self.BASE_URL}/{kind}/{tmdb_id}",
|
||||
params={"api_key": self._api_key},
|
||||
params={"api_key": self.api_key},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
@@ -188,11 +188,11 @@ class TMDBProvider(MetadataProvider):
|
||||
self.log.debug("Failed to fetch TMDB detail: %s", exc)
|
||||
return None
|
||||
|
||||
def _fetch_external_ids_raw(self, tmdb_id: int, kind: str) -> Optional[dict]:
|
||||
def fetch_external_ids_raw(self, tmdb_id: int, kind: str) -> Optional[dict]:
|
||||
try:
|
||||
r = self.session.get(
|
||||
f"{self.BASE_URL}/{kind}/{tmdb_id}/external_ids",
|
||||
params={"api_key": self._api_key},
|
||||
params={"api_key": self.api_key},
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Any, Optional, Union
|
||||
import requests
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, _strip_year
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, strip_year
|
||||
|
||||
|
||||
def primary_language(data: dict) -> Optional[str]:
|
||||
@@ -26,14 +26,14 @@ AIRED_ORDER = "official"
|
||||
_token: Optional[str] = None
|
||||
|
||||
|
||||
def _parse_int(value: Optional[str]) -> Optional[int]:
|
||||
def parse_int(value: Optional[str]) -> Optional[int]:
|
||||
try:
|
||||
return int(value) # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _ids_from_remote(remote_ids: Optional[list], tvdb_id: Optional[int]) -> ExternalIds:
|
||||
def ids_from_remote(remote_ids: Optional[list], tvdb_id: Optional[int]) -> ExternalIds:
|
||||
"""Build ExternalIds from a TVDB remote_ids/remoteIds list."""
|
||||
ext = ExternalIds(tvdb_id=tvdb_id)
|
||||
for entry in remote_ids or []:
|
||||
@@ -42,11 +42,11 @@ def _ids_from_remote(remote_ids: Optional[list], tvdb_id: Optional[int]) -> Exte
|
||||
if source == "imdb":
|
||||
ext.imdb_id = value
|
||||
elif source.startswith("themoviedb"):
|
||||
ext.tmdb_id = _parse_int(value)
|
||||
ext.tmdb_id = parse_int(value)
|
||||
return ext
|
||||
|
||||
|
||||
def _pick_match(
|
||||
def pick_match(
|
||||
results: list[dict], search_title: str, year: Optional[int]
|
||||
) -> tuple[Optional[dict], Optional[str], float]:
|
||||
"""Best title match among results, ignoring any whose year is more than a year out."""
|
||||
@@ -54,13 +54,13 @@ def _pick_match(
|
||||
best_title: Optional[str] = None
|
||||
best_ratio = 0.0
|
||||
for result in results:
|
||||
result_year = _parse_int(result.get("year"))
|
||||
result_year = parse_int(result.get("year"))
|
||||
if year and result_year and abs(result_year - year) > 1:
|
||||
continue
|
||||
for candidate in [result.get("name"), *(result.get("aliases") or [])]:
|
||||
if not candidate:
|
||||
continue
|
||||
ratio = SequenceMatcher(None, _clean(search_title), _clean(candidate)).ratio()
|
||||
ratio = SequenceMatcher(None, clean(search_title), clean(candidate)).ratio()
|
||||
if ratio > best_ratio:
|
||||
best, best_title, best_ratio = result, candidate, ratio
|
||||
return best, best_title, best_ratio
|
||||
@@ -81,7 +81,7 @@ class TVDBProvider(MetadataProvider):
|
||||
def is_available(self) -> bool:
|
||||
return bool(config.tvdb_api_key)
|
||||
|
||||
def _login(self) -> Optional[str]:
|
||||
def login(self) -> Optional[str]:
|
||||
global _token
|
||||
payload: dict[str, str] = {"apikey": config.tvdb_api_key}
|
||||
if config.tvdb_pin:
|
||||
@@ -95,10 +95,10 @@ class TVDBProvider(MetadataProvider):
|
||||
_token = None
|
||||
return _token
|
||||
|
||||
def _get(self, path: str, params: Optional[dict] = None) -> Any:
|
||||
def api_get(self, path: str, params: Optional[dict] = None) -> Any:
|
||||
"""The `data` payload of a TVDB response: a dict for entities, a list for searches."""
|
||||
global _token
|
||||
token = _token or self._login()
|
||||
token = _token or self.login()
|
||||
if not token:
|
||||
return None
|
||||
for _ in range(2):
|
||||
@@ -111,7 +111,7 @@ class TVDBProvider(MetadataProvider):
|
||||
)
|
||||
if r.status_code == 401:
|
||||
_token = None
|
||||
token = self._login()
|
||||
token = self.login()
|
||||
if not token:
|
||||
return None
|
||||
continue
|
||||
@@ -123,7 +123,7 @@ class TVDBProvider(MetadataProvider):
|
||||
return None
|
||||
|
||||
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
|
||||
search_title = _strip_year(title)
|
||||
search_title = strip_year(title)
|
||||
self.log.debug("Searching TVDB for %r (%s, %s)", search_title, kind, year)
|
||||
|
||||
params: dict[str, str | int] = {"query": search_title, "limit": 10}
|
||||
@@ -133,23 +133,23 @@ class TVDBProvider(MetadataProvider):
|
||||
if year is not None:
|
||||
params["year"] = year
|
||||
|
||||
results = self._get("/search", params)
|
||||
results = self.api_get("/search", params)
|
||||
if not results and year is not None:
|
||||
del params["year"]
|
||||
results = self._get("/search", params)
|
||||
results = self.api_get("/search", params)
|
||||
if not results:
|
||||
self.log.debug("No TVDB results for %r", search_title)
|
||||
return None
|
||||
|
||||
# year first, so an identically named remake cannot win on title alone
|
||||
best, best_title, best_ratio = _pick_match(results, search_title, year)
|
||||
best, best_title, best_ratio = pick_match(results, search_title, year)
|
||||
if best is None:
|
||||
best, best_title, best_ratio = _pick_match(results, search_title, None)
|
||||
best, best_title, best_ratio = pick_match(results, search_title, None)
|
||||
if best is None:
|
||||
best, best_title = results[0], results[0].get("name")
|
||||
|
||||
tvdb_id = _parse_int(best.get("tvdb_id"))
|
||||
ext = _ids_from_remote(best.get("remote_ids"), tvdb_id)
|
||||
tvdb_id = parse_int(best.get("tvdb_id"))
|
||||
ext = ids_from_remote(best.get("remote_ids"), tvdb_id)
|
||||
if ext.tmdb_id:
|
||||
ext.tmdb_kind = kind
|
||||
|
||||
@@ -157,7 +157,7 @@ class TVDBProvider(MetadataProvider):
|
||||
|
||||
return MetadataResult(
|
||||
title=best_title or best.get("name"),
|
||||
year=_parse_int(best.get("year")),
|
||||
year=parse_int(best.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=primary_language(best),
|
||||
@@ -165,23 +165,23 @@ class TVDBProvider(MetadataProvider):
|
||||
raw=best,
|
||||
)
|
||||
|
||||
def _fetch_extended(self, tvdb_id: int, kind: str) -> Optional[dict]:
|
||||
def fetch_extended(self, tvdb_id: int, kind: str) -> Optional[dict]:
|
||||
path = KIND_TO_PATH.get(kind, "series")
|
||||
return self._get(f"/{path}/{tvdb_id}/extended", {"short": "true"})
|
||||
return self.api_get(f"/{path}/{tvdb_id}/extended", {"short": "true"})
|
||||
|
||||
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
|
||||
tvdb_id = int(provider_id)
|
||||
detail = self._fetch_extended(tvdb_id, kind)
|
||||
detail = self.fetch_extended(tvdb_id, kind)
|
||||
if not detail:
|
||||
return None
|
||||
|
||||
ext = _ids_from_remote(detail.get("remoteIds"), tvdb_id)
|
||||
ext = ids_from_remote(detail.get("remoteIds"), tvdb_id)
|
||||
if ext.tmdb_id:
|
||||
ext.tmdb_kind = kind
|
||||
|
||||
return MetadataResult(
|
||||
title=detail.get("name"),
|
||||
year=_parse_int(detail.get("year")),
|
||||
year=parse_int(detail.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=primary_language(detail),
|
||||
@@ -191,10 +191,10 @@ class TVDBProvider(MetadataProvider):
|
||||
|
||||
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
|
||||
tvdb_id = int(provider_id)
|
||||
detail = self._fetch_extended(tvdb_id, kind)
|
||||
detail = self.fetch_extended(tvdb_id, kind)
|
||||
if not detail:
|
||||
return ExternalIds(tvdb_id=tvdb_id)
|
||||
ext = _ids_from_remote(detail.get("remoteIds"), tvdb_id)
|
||||
ext = ids_from_remote(detail.get("remoteIds"), tvdb_id)
|
||||
if ext.tmdb_id:
|
||||
ext.tmdb_kind = kind
|
||||
return ext
|
||||
@@ -207,7 +207,7 @@ class TVDBProvider(MetadataProvider):
|
||||
|
||||
episodes: list[dict] = []
|
||||
for page in range(20): # ponytail: hard page cap, 500 eps/page covers any real series
|
||||
data = self._get(f"/series/{tvdb_id}/episodes/{order}", {"page": page})
|
||||
data = self.api_get(f"/series/{tvdb_id}/episodes/{order}", {"page": page})
|
||||
if data is None and page:
|
||||
# a partial listing would renumber episodes wrongly
|
||||
self.log.warning("TVDB %s order listing for series %s failed at page %d", order, tvdb_id, page)
|
||||
@@ -232,7 +232,7 @@ class TVDBProvider(MetadataProvider):
|
||||
episodes = self.get_episodes(tvdb_id, order)
|
||||
if not episodes:
|
||||
continue
|
||||
slots = {(_parse_int(e.get("seasonNumber")), _parse_int(e.get("number"))) for e in episodes}
|
||||
slots = {(parse_int(e.get("seasonNumber")), parse_int(e.get("number"))) for e in episodes}
|
||||
score = sum(1 for key in keys if key in slots)
|
||||
self.log.debug("TVDB order %s matches %d/%d of the service's episodes", order, score, len(keys))
|
||||
if score > best_score:
|
||||
@@ -264,8 +264,8 @@ class TVDBProvider(MetadataProvider):
|
||||
match = by_id.get(ep.get("id"))
|
||||
if not match:
|
||||
continue
|
||||
src_season, src_number = _parse_int(ep.get("seasonNumber")), _parse_int(ep.get("number"))
|
||||
dst_season, dst_number = _parse_int(match.get("seasonNumber")), _parse_int(match.get("number"))
|
||||
src_season, src_number = parse_int(ep.get("seasonNumber")), parse_int(ep.get("number"))
|
||||
dst_season, dst_number = parse_int(match.get("seasonNumber")), parse_int(match.get("number"))
|
||||
if src_season is None or src_number is None or dst_season is None or dst_number is None:
|
||||
continue
|
||||
mapping[(src_season, src_number)] = (dst_season, dst_number, match.get("name"))
|
||||
@@ -275,7 +275,7 @@ class TVDBProvider(MetadataProvider):
|
||||
|
||||
def find_by_imdb_id(self, imdb_id: str, kind: str) -> Optional[ExternalIds]:
|
||||
"""Resolve a TVDB ID from an IMDb ID via /search/remoteid."""
|
||||
results = self._get(f"/search/remoteid/{imdb_id}")
|
||||
results = self.api_get(f"/search/remoteid/{imdb_id}")
|
||||
if not results:
|
||||
self.log.debug("No TVDB results for IMDB ID %s", imdb_id)
|
||||
return None
|
||||
@@ -290,6 +290,6 @@ class TVDBProvider(MetadataProvider):
|
||||
if not entity:
|
||||
return None
|
||||
|
||||
tvdb_id = _parse_int(entity.get("id"))
|
||||
tvdb_id = parse_int(entity.get("id"))
|
||||
self.log.debug("TVDB find -> TVDB %s for IMDB %s", tvdb_id, imdb_id)
|
||||
return ExternalIds(imdb_id=imdb_id, tvdb_id=tvdb_id)
|
||||
|
||||
Reference in New Issue
Block a user