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
+42 -2
View File
@@ -154,7 +154,8 @@ def test_search_picks_the_closest_title_not_the_first(monkeypatch: pytest.Monkey
def test_search_rejects_a_title_that_is_not_a_close_match(monkeypatch: pytest.MonkeyPatch) -> None: def test_search_rejects_a_title_that_is_not_a_close_match(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [edges(node(imdb_id="tt999", text="Something Else Entirely"))]) other = node(imdb_id="tt999", text="Something Else Entirely")
p, _ = _provider(monkeypatch, [edges(other), edges(other)])
assert p.search("The Last of Us", 2023, "tv") is None assert p.search("The Last of Us", 2023, "tv") is None
@@ -165,8 +166,47 @@ def test_search_survives_a_null_language_block(monkeypatch: pytest.MonkeyPatch)
def test_search_returns_none_when_nothing_comes_back(monkeypatch: pytest.MonkeyPatch) -> None: def test_search_returns_none_when_nothing_comes_back(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [edges()]) p, session = _provider(monkeypatch, [edges(), edges()])
assert p.search("The Last of Us", 2023, "tv") is None assert p.search("The Last of Us", 2023, "tv") is None
assert len(session.gets) == 2
def test_a_miss_in_the_year_retries_with_any_earlier_start(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, edges(), NOT_FOUND, edges(node())])
result = p.search("The Last of Us", 2025, "tv")
assert result is not None and result.external_ids.imdb_id == "tt3581920"
assert 'start: "2025-01-01", end: "2025-12-31"' in session.posts[0]["query"]
assert 'releaseDateRange: {end: "2025-12-31"}' in session.posts[1]["query"]
def test_the_wider_search_misses_on_two_titles_of_the_same_name(monkeypatch: pytest.MonkeyPatch) -> None:
older, newer = node(imdb_id="tt1", year=1997), node(imdb_id="tt2", year=2016)
p, _ = _provider(monkeypatch, [edges(node(imdb_id="tt9", text="OTHER")), edges(older, newer)])
assert p.search("The Last of Us", 2017, "tv") is None
def test_the_year_search_keeps_the_first_of_two_titles_of_the_same_name(monkeypatch: pytest.MonkeyPatch) -> None:
p, _ = _provider(monkeypatch, [edges(node(imdb_id="tt1"), node(imdb_id="tt2"))])
result = p.search("The Last of Us", 2023, "tv")
assert result is not None and result.external_ids.imdb_id == "tt1"
def test_a_trailing_number_that_is_not_the_year_stays_in_the_search_term(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node(text="EXAMPLE 2049"))])
assert p.search("EXAMPLE 2049", 2017, "movie") is not None
assert 'searchTerm: "EXAMPLE 2049"' in session.posts[0]["query"]
def test_a_hit_in_the_year_does_not_retry(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [edges(node())])
assert p.search("The Last of Us", 2023, "tv") is not None
assert len(session.gets) == 1
def test_search_term_drops_a_year_suffix(monkeypatch: pytest.MonkeyPatch) -> None:
p, session = _provider(monkeypatch, [NOT_FOUND, edges(node())])
assert p.search("The Last of Us (2023)", 2023, "tv") is not None
assert 'searchTerm: "The Last of Us"' in session.posts[0]["query"]
def test_escape_graphql_closes_the_string_injection() -> None: def test_escape_graphql_closes_the_string_injection() -> None:
+62 -1
View File
@@ -3,9 +3,10 @@ import pytest
from unshackle.core import providers from unshackle.core import providers
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.providers import MetadataResult, fuzzy_match, result_matches from unshackle.core.providers import MetadataResult, fuzzy_match, result_matches
from unshackle.core.providers._base import clean, title_ratio from unshackle.core.providers._base import clean, strip_year, title_ratio
from unshackle.core.providers.anilist import AniListProvider from unshackle.core.providers.anilist import AniListProvider
from unshackle.core.providers.imdb import IMDBProvider from unshackle.core.providers.imdb import IMDBProvider
from unshackle.core.providers.tmdb import TMDBProvider
IMDB_NODE = { IMDB_NODE = {
"id": "tt2560140", "id": "tt2560140",
@@ -135,3 +136,63 @@ def test_search_metadata_accepts_an_anilist_result_found_by_another_title_varian
result = providers.search_metadata("Shingeki no Kyojin", None, "tv", anime=True) result = providers.search_metadata("Shingeki no Kyojin", None, "tv", anime=True)
assert result is not None and (result.title, result.external_ids.anilist_id) == ("Attack on Titan", 16498) assert result is not None and (result.title, result.external_ids.anilist_id) == ("Attack on Titan", 16498)
@pytest.mark.parametrize(
("title", "year", "expected"),
[
("EXAMPLE (2019)", None, "EXAMPLE"),
("EXAMPLE 2011", 2011, "EXAMPLE"),
("1917", None, "1917"),
("EXAMPLE 2049", 2017, "EXAMPLE 2049"),
("EXAMPLE 12023", 2023, "EXAMPLE 12023"),
],
)
def test_strip_year_keeps_a_title_that_is_only_a_year_or_ends_in_another_number(
title: str, year: int | None, expected: str
) -> None:
assert strip_year(title, year) == expected
class TMDBResponse:
def __init__(self, results: list[dict]) -> None:
self.results = results
def raise_for_status(self) -> None:
pass
def json(self) -> dict:
return {"results": self.results}
def tmdb_search(monkeypatch: pytest.MonkeyPatch, results: list[dict], year: int | None) -> tuple[int | None, dict]:
sent: dict = {}
def get(url: str, params: dict, timeout: int) -> TMDBResponse:
sent.update(params)
return TMDBResponse(results)
p = TMDBProvider()
monkeypatch.setattr(config, "tmdb_api_key", "key")
monkeypatch.setattr(p, "_session", type("S", (), {"get": staticmethod(get)})())
monkeypatch.setattr(p, "fetch_detail", lambda tmdb_id, kind: None)
monkeypatch.setattr(p, "fetch_external_ids_raw", lambda tmdb_id, kind: None)
result = p.search("EXAMPLE", year, "tv")
return (result.external_ids.tmdb_id if result else None), sent
def test_tmdb_tv_search_matches_the_year_on_any_air_date(monkeypatch: pytest.MonkeyPatch) -> None:
_, sent = tmdb_search(monkeypatch, [{"id": 1, "name": "EXAMPLE", "first_air_date": "2016-04-04"}], 2020)
assert sent["year"] == 2020 and "first_air_date_year" not in sent
@pytest.mark.parametrize(("year", "expected"), [(2023, 2), (1999, 1), (2024, 1), (None, 1)])
def test_tmdb_prefers_the_series_that_first_aired_in_the_year_on_a_title_tie(
monkeypatch: pytest.MonkeyPatch, year: int | None, expected: int
) -> None:
results = [
{"id": 1, "name": "EXAMPLE", "first_air_date": "1999-10-20"},
{"id": 2, "name": "EXAMPLE", "first_air_date": "2023-08-31"},
{"id": 3, "name": "EXAMPLE OTHER", "first_air_date": "2024-01-01"},
]
assert tmdb_search(monkeypatch, results, year)[0] == expected
+30 -1
View File
@@ -6,7 +6,8 @@ import pytest
from unshackle.core import providers from unshackle.core import providers
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.providers.tvdb import TVDBProvider, ids_from_remote, pick_match from unshackle.core.providers import result_matches
from unshackle.core.providers.tvdb import TVDBProvider, ids_from_remote, pick_match, result_names
from unshackle.core.utils.tags import build_tags_from_ids from unshackle.core.utils.tags import build_tags_from_ids
REMOTE_IDS = [ REMOTE_IDS = [
@@ -109,6 +110,34 @@ def test_pick_match_returns_nothing_when_no_year_fits() -> None:
assert pick_match(BSG, "Battlestar Galactica", 1995)[0] is None assert pick_match(BSG, "Battlestar Galactica", 1995)[0] is None
EXAMPLE_HIT = {
"name": "エグザンプル",
"aliases": ["Eguzanpuru", "Eguzanpuru"],
"translations": {"eng": "EXAMPLE Show", "jpn": "エグザンプル"},
"year": "2020",
"tvdb_id": "101",
}
def test_result_names_lists_each_name_once() -> None:
assert result_names(EXAMPLE_HIT) == ("エグザンプル", "Eguzanpuru", "EXAMPLE Show")
assert result_names({"name": "EXAMPLE", "aliases": [{"language": "eng", "name": "x"}, ""]}) == ("EXAMPLE",)
def test_search_matches_on_a_translated_name(monkeypatch: pytest.MonkeyPatch) -> None:
p = TVDBProvider()
monkeypatch.setattr(p, "api_get", lambda path, params=None: [EXAMPLE_HIT])
result = p.search("EXAMPLE Show", 2020, "tv")
assert result is not None and result.external_ids.tvdb_id == 101
assert result_matches(result, "EXAMPLE Show")
assert not result_matches(result, "OTHER Show")
def test_cached_tvdb_result_matches_on_a_translated_name() -> None:
result = providers.cached_to_result(EXAMPLE_HIT, "tvdb", "tv")
assert result is not None and result_matches(result, "EXAMPLE Show")
def test_tvdb2_tag_follows_the_matroska_spec() -> None: def test_tvdb2_tag_follows_the_matroska_spec() -> None:
# TVDB2 IDs are prefixed by entity type: matroska.org/technical/tagging.html # TVDB2 IDs are prefixed by entity type: matroska.org/technical/tagging.html
from unshackle.core.providers import ExternalIds from unshackle.core.providers import ExternalIds
+2 -1
View File
@@ -565,7 +565,7 @@ def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataRes
raw=cached, raw=cached,
) )
elif provider_name == "tvdb": 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")) 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) 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, external_ids=ext,
source="tvdb", source="tvdb",
raw=cached, raw=cached,
names=result_names(cached),
) )
elif provider_name in ("anilist", "imdb"): elif provider_name in ("anilist", "imdb"):
result = AniListProvider().to_result(cached) if provider_name == "anilist" else title_to_result(cached, kind) 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")) 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: def strip_year(s: str, year: int | None = None) -> str:
return YEAR_RE.sub("", s).strip() """`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: def title_ratio(a: str, b: str) -> float:
+33 -10
View File
@@ -5,7 +5,14 @@ import json
import requests 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/" GRAPHQL_URL = "https://caching.graphql.imdb.com/"
@@ -99,19 +106,31 @@ class IMDBProvider(MetadataProvider):
return body.get("data") return body.get("data")
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None: 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: if year:
constraints.append( start = "" if wide else f'start: "{year}-01-01", '
f'releaseDateConstraint: {{releaseDateRange: {{start: "{year}-01-01", end: "{year}-12-31"}}}}' constraints.append(f'releaseDateConstraint: {{releaseDateRange: {{{start}end: "{year}-12-31"}}}}')
)
types = KIND_TO_TYPES.get(kind) types = KIND_TO_TYPES.get(kind)
if types: if types:
constraints.append(f"titleTypeConstraint: {{anyTitleTypeIds: {json.dumps(types)}}}") constraints.append(f"titleTypeConstraint: {{anyTitleTypeIds: {json.dumps(types)}}}")
first = 10 if wide else 5
query = ( 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} }} }} }} }} }}" f"{{ edges {{ node {{ title {{ {TITLE_FIELDS} }} }} }} }} }}"
) )
@@ -119,11 +138,15 @@ class IMDBProvider(MetadataProvider):
edges = ((data or {}).get("advancedTitleSearch") or {}).get("edges") or [] edges = ((data or {}).get("advancedTitleSearch") or {}).get("edges") or []
nodes = [edge["node"]["title"] for edge in edges if (edge.get("node") or {}).get("title")] nodes = [edge["node"]["title"] for edge in edges if (edge.get("node") or {}).get("title")]
if not nodes: 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 return None
best = max(nodes, key=lambda n: best_ratio(title, node_names(n))) scores = [best_ratio(search_title, node_names(n)) for n in nodes]
result = title_to_result(best, kind) 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): 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) self.log.debug("IMDb title mismatch: searched %r, got %r", title, result.title if result else None)
return None return None
+13 -6
View File
@@ -22,12 +22,17 @@ class TMDBProvider(MetadataProvider):
return config.tmdb_api_key return config.tmdb_api_key
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None: 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) search_title = strip_year(title)
self.log.debug("Searching TMDB for %r (%s, %s)", search_title, kind, year) 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: if year is not None:
params["year" if kind == "movie" else "first_air_date_year"] = year params["year"] = year
try: try:
r = self.session.get(f"{self.BASE_URL}/search/{kind}", params=params, timeout=30) 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) self.log.warning("Failed to search TMDB for %s: %s", title, exc)
return None return None
best_ratio = 0.0 best_key = (0.0, False)
best_id: int | None = None best_id: int | None = None
best_title: str | None = None best_title: str | None = None
for result in results: 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 = [ candidates = [
result.get("title"), result.get("title"),
result.get("name"), result.get("name"),
@@ -53,13 +60,13 @@ class TMDBProvider(MetadataProvider):
candidates = [c for c in candidates if c] candidates = [c for c in candidates if c]
for candidate in candidates: for candidate in candidates:
ratio = title_ratio(search_title, candidate) key = (title_ratio(search_title, candidate), year_matches)
if ratio > best_ratio: if key > best_key:
best_ratio = ratio best_key = key
best_id = result.get("id") best_id = result.get("id")
best_title = candidate 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: if best_id is None:
first = results[0] 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 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]: 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.""" """The result whose title matches best, ignoring any whose year is more than a year out."""
best: dict | None = None 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")) result_year = parse_int(result.get("year"))
if year and result_year and abs(result_year - year) > 1: if year and result_year and abs(result_year - year) > 1:
continue continue
for candidate in [result.get("name"), *(result.get("aliases") or [])]: for candidate in result_names(result):
if not candidate:
continue
ratio = title_ratio(search_title, candidate) ratio = title_ratio(search_title, candidate)
if ratio > best_ratio: if ratio > best_ratio:
best, best_title, best_ratio = result, candidate, ratio best, best_title, best_ratio = result, candidate, ratio
@@ -160,6 +164,7 @@ class TVDBProvider(MetadataProvider):
original_language=primary_language(best), original_language=primary_language(best),
source="tvdb", source="tvdb",
raw=best, raw=best,
names=result_names(best),
) )
def fetch_extended(self, tvdb_id: int, kind: str) -> dict | None: def fetch_extended(self, tvdb_id: int, kind: str) -> dict | None: