fix(providers): match a later season's year and TVDB translated names in metadata searches

This commit is contained in:
imSp4rky
2026-11-29 11:18:48 -07:00
parent 1571236991
commit d2eea0c4c5
8 changed files with 194 additions and 26 deletions
+2 -1
View File
@@ -565,7 +565,7 @@ def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataRes
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, result_names
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)
@@ -582,6 +582,7 @@ def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataRes
external_ids=ext,
source="tvdb",
raw=cached,
names=result_names(cached),
)
elif provider_name in ("anilist", "imdb"):
result = AniListProvider().to_result(cached) if provider_name == "anilist" else title_to_result(cached, kind)
+4 -2
View File
@@ -97,8 +97,10 @@ def clean(s: str) -> str:
return unicodedata.normalize("NFC", "".join(c for c in s if c.isalnum() or unicodedata.category(c)[0] == "M"))
def strip_year(s: str) -> str:
return YEAR_RE.sub("", s).strip()
def strip_year(s: str, year: int | None = None) -> str:
"""`s` without a trailing year (only `year`, when given), or `s` itself when it is only a year."""
pattern = re.compile(rf"\s*\(?(?<!\d){year}\)?$") if year else YEAR_RE
return pattern.sub("", s).strip() or s
def title_ratio(a: str, b: str) -> float:
+33 -10
View File
@@ -5,7 +5,14 @@ import json
import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio, result_matches
from unshackle.core.providers._base import (
ExternalIds,
MetadataProvider,
MetadataResult,
best_ratio,
result_matches,
strip_year,
)
GRAPHQL_URL = "https://caching.graphql.imdb.com/"
@@ -99,19 +106,31 @@ class IMDBProvider(MetadataProvider):
return body.get("data")
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
self.log.debug("Searching IMDb for %r (%s, %s)", title, kind, year)
"""Find a title released in `year`, then on a miss the one title of that name released in or before it.
constraints = [f'titleTextConstraint: {{searchTerm: "{escape_graphql(title)}"}}']
A service can give the year of a later season, which is after the year that IMDb lists for the series.
"""
search_title = strip_year(title, year) if year else title
self.log.debug("Searching IMDb for %r (%s, %s)", search_title, kind, year)
result = self.search_range(title, search_title, kind, year)
if not result and year:
result = self.search_range(title, search_title, kind, year, wide=True)
return result
def search_range(
self, title: str, search_title: str, kind: str, year: int | None, wide: bool = False
) -> MetadataResult | None:
constraints = [f'titleTextConstraint: {{searchTerm: "{escape_graphql(search_title)}"}}']
if year:
constraints.append(
f'releaseDateConstraint: {{releaseDateRange: {{start: "{year}-01-01", end: "{year}-12-31"}}}}'
)
start = "" if wide else f'start: "{year}-01-01", '
constraints.append(f'releaseDateConstraint: {{releaseDateRange: {{{start}end: "{year}-12-31"}}}}')
types = KIND_TO_TYPES.get(kind)
if types:
constraints.append(f"titleTypeConstraint: {{anyTitleTypeIds: {json.dumps(types)}}}")
first = 10 if wide else 5
query = (
f"query UnshackleTitleSearch {{ advancedTitleSearch(first: 5, constraints: {{{', '.join(constraints)}}}) "
f"query UnshackleTitleSearch {{ advancedTitleSearch(first: {first}, constraints: {{{', '.join(constraints)}}}) "
f"{{ edges {{ node {{ title {{ {TITLE_FIELDS} }} }} }} }} }}"
)
@@ -119,11 +138,15 @@ class IMDBProvider(MetadataProvider):
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)
self.log.debug("IMDb returned no results for %r (%s, wide %s)", search_title, year, wide)
return None
best = max(nodes, key=lambda n: best_ratio(title, node_names(n)))
result = title_to_result(best, kind)
scores = [best_ratio(search_title, node_names(n)) for n in nodes]
top = max(scores)
if wide and scores.count(top) > 1:
self.log.debug("IMDb has %d titles named like %r up to %s", scores.count(top), search_title, year)
return None
result = title_to_result(nodes[scores.index(top)], kind)
if not result or not result_matches(result, title):
self.log.debug("IMDb title mismatch: searched %r, got %r", title, result.title if result else None)
return None
+13 -6
View File
@@ -22,12 +22,17 @@ class TMDBProvider(MetadataProvider):
return config.tmdb_api_key
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
"""Find a title by name; a title first out in `year` wins a tie.
On /search/tv, `year` matches every episode air date and `first_air_date_year` only the first one,
so `year` finds a series from a service that gives the year of a later season.
"""
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}
if year is not None:
params["year" if kind == "movie" else "first_air_date_year"] = year
params["year"] = year
try:
r = self.session.get(f"{self.BASE_URL}/search/{kind}", params=params, timeout=30)
@@ -40,10 +45,12 @@ class TMDBProvider(MetadataProvider):
self.log.warning("Failed to search TMDB for %s: %s", title, exc)
return None
best_ratio = 0.0
best_key = (0.0, False)
best_id: int | None = None
best_title: str | None = None
for result in results:
first_aired = result.get("release_date") or result.get("first_air_date") or ""
year_matches = first_aired[:4] == str(year)
candidates = [
result.get("title"),
result.get("name"),
@@ -53,13 +60,13 @@ class TMDBProvider(MetadataProvider):
candidates = [c for c in candidates if c]
for candidate in candidates:
ratio = title_ratio(search_title, candidate)
if ratio > best_ratio:
best_ratio = ratio
key = (title_ratio(search_title, candidate), year_matches)
if key > best_key:
best_key = key
best_id = result.get("id")
best_title = candidate
self.log.debug("Best candidate ratio %.2f for %r (ID %s)", best_ratio, best_title, best_id)
self.log.debug("Best candidate ratio %.2f for %r (ID %s)", best_key[0], best_title, best_id)
if best_id is None:
first = results[0]
+8 -3
View File
@@ -45,6 +45,12 @@ def ids_from_remote(remote_ids: list | None, tvdb_id: int | None) -> ExternalIds
return ext
def result_names(data: dict) -> tuple[str, ...]:
"""The name, aliases and translated names of a TVDB search result, each once."""
names = [data.get("name"), *(data.get("aliases") or []), *(data.get("translations") or {}).values()]
return tuple(dict.fromkeys(n for n in names if isinstance(n, str) and n))
def pick_match(results: list[dict], search_title: str, year: int | None) -> tuple[dict | None, str | None, float]:
"""The result whose title matches best, ignoring any whose year is more than a year out."""
best: dict | None = None
@@ -54,9 +60,7 @@ def pick_match(results: list[dict], search_title: str, year: int | None) -> tupl
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
for candidate in result_names(result):
ratio = title_ratio(search_title, candidate)
if ratio > best_ratio:
best, best_title, best_ratio = result, candidate, ratio
@@ -160,6 +164,7 @@ class TVDBProvider(MetadataProvider):
original_language=primary_language(best),
source="tvdb",
raw=best,
names=result_names(best),
)
def fetch_extended(self, tvdb_id: int, kind: str) -> dict | None: