fix(providers): accept an IMDb or AniList match on any title the ranker used

This commit is contained in:
imSp4rky
2026-11-28 17:42:44 -07:00
parent ed743a81b9
commit 94d0b67d20
8 changed files with 132 additions and 46 deletions
+3
View File
@@ -61,6 +61,9 @@ each metadata provider can answer with, see
side, unshackle falls back in the order english → romaji → native. It takes the first one side, unshackle falls back in the order english → romaji → native. It takes the first one
that is set, so you always get a title. that is set, so you always get a title.
A title search compares your query with all three titles. A romaji query thus finds a work
when the title that this option picks is the English one.
!!! note "What `disable_metadata` turns off" !!! note "What `disable_metadata` turns off"
With `disable_metadata: true`, unshackle never contacts a metadata provider on its own. With `disable_metadata: true`, unshackle never contacts a metadata provider on its own.
The title search is dead, and that includes the keyless `imdb` metadata provider. Titles, years and The title search is dead, and that includes the keyless `imdb` metadata provider. Titles, years and
+69 -1
View File
@@ -1,7 +1,26 @@
import pytest import pytest
from unshackle.core.providers import fuzzy_match from unshackle.core import providers
from unshackle.core.config import config
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, title_ratio
from unshackle.core.providers.anilist import AniListProvider
from unshackle.core.providers.imdb import IMDBProvider
IMDB_NODE = {
"id": "tt2560140",
"titleText": {"text": "Attack on Titan"},
"originalTitleText": {"text": "Shingeki no Kyojin"},
"releaseYear": {"year": 2013},
}
ANILIST_NODE = {
"id": 16498,
"title": {"romaji": "Shingeki no Kyojin", "english": "Attack on Titan", "native": "進撃の巨人"},
"format": "TV",
"startDate": {"year": 2013},
"countryOfOrigin": "JP",
}
@pytest.mark.parametrize( @pytest.mark.parametrize(
@@ -67,3 +86,52 @@ def test_a_title_with_no_letters_or_digits_matches_nothing(a: str, b: str) -> No
) )
def test_fuzzy_match_latin_titles(a: str, b: str, expected: bool) -> None: def test_fuzzy_match_latin_titles(a: str, b: str, expected: bool) -> None:
assert fuzzy_match(a, b) is expected assert fuzzy_match(a, b) is expected
def test_a_result_matches_on_any_of_its_names() -> None:
result = MetadataResult(title="Attack on Titan", names=("Attack on Titan", "Shingeki no Kyojin"))
assert result_matches(result, "Shingeki no Kyojin")
assert not result_matches(result, "The Matrix")
def test_a_result_with_no_names_matches_on_its_title_only() -> None:
assert result_matches(MetadataResult(title="Attack on Titan"), "attack on titan")
assert not result_matches(MetadataResult(title="Attack on Titan"), "Shingeki no Kyojin")
assert not result_matches(MetadataResult(), "Shingeki no Kyojin")
def test_imdb_search_accepts_a_result_that_matches_on_its_original_title(monkeypatch: pytest.MonkeyPatch) -> None:
p = IMDBProvider()
edges = {"advancedTitleSearch": {"edges": [{"node": {"title": IMDB_NODE}}]}}
monkeypatch.setattr(p, "graphql", lambda operation, query: edges)
result = p.search("Shingeki no Kyojin", 2013, "tv")
assert result is not None and result.title == "Attack on Titan"
class FakeCacher:
def get_cached_provider(self, provider_name: str, *args: object) -> dict:
return IMDB_NODE
def test_search_metadata_uses_a_cached_imdb_result_that_matches_on_its_original_title(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(config, "disable_metadata", False)
monkeypatch.setattr(providers, "provider_order", lambda *args: [IMDBProvider])
monkeypatch.setattr(IMDBProvider, "search", lambda *args: pytest.fail("a cache hit must not search again"))
result = providers.search_metadata("Shingeki no Kyojin", None, "tv", FakeCacher(), "show-1") # type: ignore[arg-type]
assert result is not None and result.external_ids.imdb_id == "tt2560140"
def test_search_metadata_accepts_an_anilist_result_found_by_another_title_variant(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(config, "disable_metadata", False)
monkeypatch.setattr(config, "anilist_title_language", "english")
monkeypatch.setattr(providers, "provider_order", lambda *args: [AniListProvider])
monkeypatch.setattr(providers, "enrich_ids", lambda result: None)
monkeypatch.setattr(AniListProvider, "graphql", lambda self, query, variables: {"Page": {"media": [ANILIST_NODE]}})
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)
+10 -3
View File
@@ -128,7 +128,7 @@ def test_the_tvdb_order_resolves_a_tvdb_id_and_keeps_it_for_the_tags(monkeypatch
def test_a_series_is_searched_once_and_each_title_fetches_its_external_ids(monkeypatch: pytest.MonkeyPatch) -> None: def test_a_series_is_searched_once_and_each_title_fetches_its_external_ids(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, found(title="The Show")) calls = Providers(monkeypatch, found(title="The Show"))
monkeypatch.setattr(providers, "fuzzy_match", lambda a, b: a == b) monkeypatch.setattr(providers, "result_matches", lambda result, title: result.title == title)
metadata = TitleMetadata(cache=CACHE) metadata = TitleMetadata(cache=CACHE)
metadata.search(episode(1, 1)) metadata.search(episode(1, 1))
metadata.search(episode(1, 2)) metadata.search(episode(1, 2))
@@ -141,12 +141,19 @@ def test_a_series_is_searched_once_and_each_title_fetches_its_external_ids(monke
def test_a_search_that_matches_another_show_sets_no_id(monkeypatch: pytest.MonkeyPatch) -> None: def test_a_search_that_matches_another_show_sets_no_id(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, found(title="Another Show")) calls = Providers(monkeypatch, found(title="Another Show"))
monkeypatch.setattr(providers, "fuzzy_match", lambda a, b: a == b) monkeypatch.setattr(providers, "result_matches", lambda result, title: result.title == title)
metadata = TitleMetadata() metadata = TitleMetadata()
metadata.search(episode(1, 1)) metadata.search(episode(1, 1))
assert (metadata.tmdb_id, metadata.searched, calls.fetched) == (None, True, []) assert (metadata.tmdb_id, metadata.searched, calls.fetched) == (None, True, [])
def test_a_search_matches_on_another_name_of_the_result(monkeypatch: pytest.MonkeyPatch) -> None:
Providers(monkeypatch, found(title="Another Show", names=("Another Show", "The Show")))
metadata = TitleMetadata()
metadata.search(episode(1, 1))
assert metadata.tmdb_id == 1396
def test_a_given_tmdb_id_is_kept(monkeypatch: pytest.MonkeyPatch) -> None: def test_a_given_tmdb_id_is_kept(monkeypatch: pytest.MonkeyPatch) -> None:
Providers(monkeypatch, found(tmdb_id=1, title="Other")) Providers(monkeypatch, found(tmdb_id=1, title="Other"))
metadata = TitleMetadata(tmdb_id=5) metadata = TitleMetadata(tmdb_id=5)
@@ -224,7 +231,7 @@ def test_enrich_fills_the_air_dates_of_a_daily_series(monkeypatch: pytest.Monkey
def test_a_listing_prints_the_search_match(monkeypatch: pytest.MonkeyPatch) -> None: def test_a_listing_prints_the_search_match(monkeypatch: pytest.MonkeyPatch) -> None:
Providers(monkeypatch, found(title="The Show")) Providers(monkeypatch, found(title="The Show"))
monkeypatch.setattr(providers, "fuzzy_match", lambda a, b: a == b) monkeypatch.setattr(providers, "result_matches", lambda result, title: result.title == title)
with console.capture() as captured: with console.capture() as captured:
TitleMetadata().search(episode(1, 1), listing=True) TitleMetadata().search(episode(1, 1), listing=True)
assert "Search -> The Show (ID 1396)" in captured.get() assert "Search -> The Show (ID 1396)" in captured.get()
+19 -25
View File
@@ -4,9 +4,16 @@ from typing import TYPE_CHECKING
import requests import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, log from unshackle.core.providers._base import (
ExternalIds,
MetadataProvider,
MetadataResult,
fuzzy_match,
log,
result_matches,
)
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref
from unshackle.core.providers.imdb import IMDBProvider from unshackle.core.providers.imdb import IMDBProvider, title_to_result
from unshackle.core.providers.omdb import OMDBProvider from unshackle.core.providers.omdb import OMDBProvider
from unshackle.core.providers.simkl import SimklProvider from unshackle.core.providers.simkl import SimklProvider
from unshackle.core.providers.tmdb import TMDBProvider from unshackle.core.providers.tmdb import TMDBProvider
@@ -92,7 +99,7 @@ def search_metadata(
cached = title_cacher.get_cached_provider(p.NAME, cache_title_id, kind, cache_region, cache_account_hash) cached = title_cacher.get_cached_provider(p.NAME, cache_title_id, kind, cache_region, cache_account_hash)
if cached: 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): if result and result_matches(result, title):
log.debug("Using cached %s data for %r", p.NAME, title) log.debug("Using cached %s data for %r", p.NAME, title)
return result return result
@@ -105,7 +112,7 @@ def search_metadata(
except (requests.RequestException, ValueError, KeyError) as exc: except (requests.RequestException, ValueError, KeyError) as exc:
log.debug("%s search failed: %s", p.NAME, exc) log.debug("%s search failed: %s", p.NAME, exc)
continue continue
if result and result.title and fuzzy_match(result.title, title): if result and result_matches(result, title):
enrich_ids(result) enrich_ids(result)
if title_cacher and cache_title_id and result.raw: if title_cacher and cache_title_id and result.raw:
try: try:
@@ -542,27 +549,13 @@ def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataRes
elif provider_name == "anilist": elif provider_name == "anilist":
return AniListProvider().to_result(cached) return AniListProvider().to_result(cached)
elif provider_name == "imdb": elif provider_name == "imdb":
from unshackle.core.providers.imdb import primary_language result = title_to_result(cached, kind)
if result:
title = (cached.get("titleText") or {}).get("text") or (cached.get("originalTitleText") or {}).get("text") enriched = cached.get("_enriched_ids", {})
year = (cached.get("releaseYear") or {}).get("year") result.external_ids.tmdb_id = enriched.get("tmdb_id")
imdb_id = cached.get("id") result.external_ids.tmdb_kind = enriched.get("tmdb_kind")
# Restore enriched IDs that were saved alongside the raw data result.external_ids.tvdb_id = enriched.get("tvdb_id")
enriched = cached.get("_enriched_ids", {}) return result
return MetadataResult(
title=title,
year=year,
kind=kind,
external_ids=ExternalIds(
imdb_id=imdb_id,
tmdb_id=enriched.get("tmdb_id"),
tmdb_kind=enriched.get("tmdb_kind"),
tvdb_id=enriched.get("tvdb_id"),
),
original_language=primary_language(cached),
source="imdb",
raw=cached,
)
return None return None
@@ -581,5 +574,6 @@ __all__ = [
"get_year_by_id", "get_year_by_id",
"provider_order", "provider_order",
"resolve_by_ids", "resolve_by_ids",
"result_matches",
"search_metadata", "search_metadata",
] ]
+11
View File
@@ -40,6 +40,7 @@ class MetadataResult:
original_language: str | None = None # alpha-2 or alpha-3, whichever the provider speaks original_language: str | None = None # alpha-2 or alpha-3, whichever the provider speaks
source: str = "" source: str = ""
raw: dict | None = None raw: dict | None = None
names: tuple[str, ...] = ()
class MetadataProvider(metaclass=ABCMeta): class MetadataProvider(metaclass=ABCMeta):
@@ -106,6 +107,16 @@ def title_ratio(a: str, b: str) -> float:
return SequenceMatcher(None, a, b).ratio() if a and b else 0.0 return SequenceMatcher(None, a, b).ratio() if a and b else 0.0
def best_ratio(title: str, names: tuple[str, ...]) -> float:
"""The highest ``title_ratio`` of ``title`` against one of ``names``; 0 when there is no name."""
return max((title_ratio(title, n) for n in names), default=0.0)
def fuzzy_match(a: str, b: str, threshold: float = 0.8) -> bool: def fuzzy_match(a: str, b: str, threshold: float = 0.8) -> bool:
"""Return True if ``a`` and ``b`` match closely.""" """Return True if ``a`` and ``b`` match closely."""
return title_ratio(a, b) >= threshold return title_ratio(a, b) >= threshold
def result_matches(result: MetadataResult, title: str) -> bool:
"""Return True if ``title`` matches the title of ``result`` or one of its ``names``."""
return any(fuzzy_match(name, title) for name in (result.title, *result.names) if name)
+6 -5
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import requests import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, title_ratio from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio
GRAPHQL_URL = "https://graphql.anilist.co" GRAPHQL_URL = "https://graphql.anilist.co"
@@ -88,6 +88,7 @@ class AniListProvider(MetadataProvider):
original_language=COUNTRY_TO_LANGUAGE.get(node.get("countryOfOrigin") or ""), original_language=COUNTRY_TO_LANGUAGE.get(node.get("countryOfOrigin") or ""),
source="anilist", source="anilist",
raw=node, raw=node,
names=media_names(node),
) )
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None: def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
@@ -107,7 +108,7 @@ class AniListProvider(MetadataProvider):
dated = [n for n in nodes if (n.get("startDate") or {}).get("year") == year] dated = [n for n in nodes if (n.get("startDate") or {}).get("year") == year]
nodes = dated or nodes nodes = dated or nodes
best = max(nodes, key=lambda n: match_ratio(n, title)) best = max(nodes, key=lambda n: best_ratio(title, media_names(n)))
result = self.to_result(best) result = self.to_result(best)
if result: if result:
self.log.debug("AniList -> %s (ID %s)", result.title, result.external_ids.anilist_id) self.log.debug("AniList -> %s (ID %s)", result.title, result.external_ids.anilist_id)
@@ -144,6 +145,6 @@ class AniListProvider(MetadataProvider):
return result.external_ids if result else ExternalIds() return result.external_ids if result else ExternalIds()
def match_ratio(node: dict, title: str) -> float: def media_names(node: dict) -> tuple[str, ...]:
names = (node.get("title") or {}).values() """Every title variant of an AniList media node that is set."""
return max((title_ratio(title, n) for n in names if n), default=0.0) return tuple(str(n) for n in (node.get("title") or {}).values() if n)
+13 -11
View File
@@ -5,7 +5,7 @@ import json
import requests import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, title_ratio from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio, result_matches
GRAPHQL_URL = "https://caching.graphql.imdb.com/" GRAPHQL_URL = "https://caching.graphql.imdb.com/"
@@ -39,18 +39,25 @@ def primary_language(data: dict) -> str | None:
return langs[0].get("id") if langs else None return langs[0].get("id") if langs else None
def node_names(node: dict) -> tuple[str, ...]:
"""The display title, then the original title, of an IMDb title node."""
names = ((node.get("titleText") or {}).get("text"), (node.get("originalTitleText") or {}).get("text"))
return tuple(n for n in names if n)
def title_to_result(node: dict, kind: str) -> MetadataResult | None: def title_to_result(node: dict, kind: str) -> MetadataResult | None:
title = (node.get("titleText") or {}).get("text") or (node.get("originalTitleText") or {}).get("text") names = node_names(node)
if not title: if not names:
return None return None
return MetadataResult( return MetadataResult(
title=title, title=names[0],
year=(node.get("releaseYear") or {}).get("year"), year=(node.get("releaseYear") or {}).get("year"),
kind=kind, kind=kind,
external_ids=ExternalIds(imdb_id=node.get("id")), external_ids=ExternalIds(imdb_id=node.get("id")),
original_language=primary_language(node), original_language=primary_language(node),
source="imdb", source="imdb",
raw=node, raw=node,
names=names,
) )
@@ -115,9 +122,9 @@ class IMDBProvider(MetadataProvider):
self.log.debug("IMDb returned no results for %r", title) self.log.debug("IMDb returned no results for %r", title)
return None return None
best = max(nodes, key=lambda n: match_ratio(n, title)) best = max(nodes, key=lambda n: best_ratio(title, node_names(n)))
result = title_to_result(best, kind) result = title_to_result(best, kind)
if not result or not result.title or not fuzzy_match(result.title, 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
@@ -141,11 +148,6 @@ class IMDBProvider(MetadataProvider):
return ExternalIds(imdb_id=str(provider_id)) return ExternalIds(imdb_id=str(provider_id))
def match_ratio(node: dict, title: str) -> float:
names = [(node.get("titleText") or {}).get("text"), (node.get("originalTitleText") or {}).get("text")]
return max((title_ratio(title, n) 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 []: for error in body.get("errors") or []:
code = (error.get("extensions") or {}).get("code") code = (error.get("extensions") or {}).get("code")
+1 -1
View File
@@ -166,7 +166,7 @@ class TitleMetadata:
tmdb_title = result.title tmdb_title = result.title
if not self.tmdb_id: if not self.tmdb_id:
self.tmdb_id = result.external_ids.tmdb_id self.tmdb_id = result.external_ids.tmdb_id
elif result.title and providers.fuzzy_match(result.title, title.title): elif providers.result_matches(result, title.title):
self.tmdb_id = result.external_ids.tmdb_id self.tmdb_id = result.external_ids.tmdb_id
tmdb_title = result.title tmdb_title = result.title
self.search_source = result.source self.search_source = result.source