diff --git a/docs/guide/downloading.md b/docs/guide/downloading.md index b886d1bce..fe880ca85 100644 --- a/docs/guide/downloading.md +++ b/docs/guide/downloading.md @@ -1148,6 +1148,15 @@ yourself. IDs of the whole series, also for a later season. When the map cannot download, the match keeps only its AniList ID. + The map also works in the other direction. A TMDB or TVDB match of an anime title has no + AniList ID, so unshackle looks its TMDB or TVDB ID up in the map. It does this only for an + anime service, or for a match whose original language is Japanese, Korean or Chinese, so + other downloads never download the map. One series often has an AniList entry for each season. + unshackle then uses the season number of each episode, and writes no AniList tag when no + single entry has that season. It reads the season number in the TMDB numbering and in the TVDB + numbering, and when the two give different entries, it writes no AniList tag. A TMDB movie ID takes only the AniList entry of that movie. + An AniList ID that you give with `--anilist` always wins over the map. + The ID you give must have a metadata provider that can find it, so unshackle makes sure of that before it downloads anything. `--tmdb` without `tmdb_api_key`, or an ID whose metadata providers your `metadata_providers` list leaves out, fails immediately with a message naming diff --git a/tests/core/test_anilist_provider.py b/tests/core/test_anilist_provider.py index 32d09824e..b239af770 100644 --- a/tests/core/test_anilist_provider.py +++ b/tests/core/test_anilist_provider.py @@ -364,3 +364,87 @@ def test_western_ids_never_cross_the_kind( id_map: list[str], anilist_id: int, kind: str, expected: anilist.ExternalIds ) -> None: assert anilist.western_ids(anilist_id, kind) == expected + + +def test_a_map_entry_keeps_its_season_numbers() -> None: + entry = {"themoviedb_id": {"tv": 1429}, "tvdb_id": 267440, "season": {"tvdb": 0, "tmdb": 2}} + + assert anilist.reduce_map_entry(entry) == {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 2, "tvdb_season": 0} + assert anilist.reduce_map_entry({"season": {"tvdb": 1}}) == {} + + +REVERSE_MAP = { + "21": {"imdb": "tt0388629", "tmdb_tv": 37854, "tvdb": 81797}, + "459": {"tmdb_movie": 19576, "tvdb": 81797, "tvdb_season": 0}, + "460": {"tmdb_movie": 23446, "tvdb": 81797}, + "527": {"tmdb_tv": 60572}, + "1564": {"tmdb_tv": 60572, "tmdb_season": 6}, + "700": {"tmdb_tv": 7, "tvdb": 8, "tmdb_season": 1, "tvdb_season": 1}, + "701": {"tmdb_tv": 7, "tvdb": 8, "tmdb_season": 1, "tvdb_season": 2}, + "900": {"tmdb_tv": 9, "tvdb": 10, "tmdb_season": 2, "tvdb_season": 1}, + "901": {"tmdb_tv": 9, "tvdb": 10, "tmdb_season": 1, "tvdb_season": 2}, + "16498": {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 1, "tvdb_season": 1}, + "20958": {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 2, "tvdb_season": 2}, + "99147": {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 3, "tvdb_season": 3}, + "104578": {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 3, "tvdb_season": 3}, + "199": {"imdb": "tt0245429", "tmdb_movie": 129}, +} + + +@pytest.mark.parametrize( + ("ids", "kind", "season", "expected"), + [ + (anilist.ExternalIds(tmdb_id=37854), "tv", None, 21), + (anilist.ExternalIds(tvdb_id=81797), "tv", 1, 21), + (anilist.ExternalIds(tmdb_id=1429, tvdb_id=267440), "tv", 2, 20958), + (anilist.ExternalIds(tmdb_id=1429), "tv", None, None), + (anilist.ExternalIds(tmdb_id=1429), "tv", 3, None), + (anilist.ExternalIds(tmdb_id=1429), "tv", 5, None), + (anilist.ExternalIds(tmdb_id=37854, tvdb_id=1), "tv", None, None), + (anilist.ExternalIds(imdb_id="tt9", tmdb_id=37854), "tv", None, None), + (anilist.ExternalIds(tmdb_id=129), "movie", None, 199), + (anilist.ExternalIds(tmdb_id=37854), "movie", None, None), + (anilist.ExternalIds(tmdb_id=129), "tv", None, None), + (anilist.ExternalIds(tvdb_id=81797), "movie", None, None), + (anilist.ExternalIds(tvdb_id=81797), "tv", None, 21), + (anilist.ExternalIds(tmdb_id=19576), "movie", None, 459), + (anilist.ExternalIds(tmdb_id=60572), "tv", None, None), + (anilist.ExternalIds(tmdb_id=60572), "tv", 6, 1564), + (anilist.ExternalIds(tmdb_id=60572), "tv", 3, None), + (anilist.ExternalIds(tmdb_id=7, tvdb_id=8), "tv", 1, 700), + (anilist.ExternalIds(tmdb_id=7, tvdb_id=8), "tv", 2, 701), + (anilist.ExternalIds(tmdb_id=7), "tv", 1, None), + (anilist.ExternalIds(tmdb_id=9, tvdb_id=10), "tv", 1, None), + (anilist.ExternalIds(tmdb_id=9), "tv", 1, 901), + ], + ids=[ + "series-entry", + "movie-entries-on-the-same-tvdb-drop-out", + "season-picks-one", + "several-seasons-without-a-season", + "two-entries-for-one-season", + "no-entry-for-the-season", + "tvdb-disagrees", + "imdb-disagrees", + "movie", + "tv-id-for-a-movie", + "movie-id-for-a-series", + "tvdb-id-for-a-movie", + "movie-entries-without-a-season-drop-out", + "movie-entry-with-a-season", + "whole-series-entry-beside-season-entries", + "season-entry-beside-a-whole-series-entry", + "whole-series-entry-of-a-split-series", + "tvdb-numbering-picks-season-1", + "tvdb-numbering-picks-season-2", + "tmdb-numbering-alone-is-ambiguous", + "tmdb-and-tvdb-numbering-disagree", + "tmdb-numbering-picks", + ], +) +def test_a_western_match_takes_the_one_anilist_entry_that_fits( + monkeypatch: pytest.MonkeyPatch, ids: anilist.ExternalIds, kind: str, season: int | None, expected: int | None +) -> None: + monkeypatch.setattr(anilist, "western_id_map", lambda: REVERSE_MAP) + + assert anilist.anilist_id_for(ids, kind, season) == expected diff --git a/tests/core/test_resolve_by_ids.py b/tests/core/test_resolve_by_ids.py index 9c9799bc1..a01d88670 100644 --- a/tests/core/test_resolve_by_ids.py +++ b/tests/core/test_resolve_by_ids.py @@ -16,6 +16,8 @@ search_metadata = providers.search_metadata ANIME_MAP = { "21": {"imdb": "tt0388629", "tmdb_tv": 37854, "tvdb": 81797}, "199": {"imdb": "tt0245429", "tmdb_movie": 129}, + "16498": {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 1, "tvdb_season": 1}, + "20958": {"tmdb_tv": 1429, "tvdb": 267440, "tmdb_season": 2, "tvdb_season": 2}, } @@ -415,18 +417,117 @@ def test_a_supplied_western_id_wins_over_the_map(monkeypatch: pytest.MonkeyPatch assert result.external_ids == ExternalIds(tvdb_id=1, anilist_id=21) -class AniListHit(FakeProvider): +class SearchHit(FakeProvider): def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None: - return anilist_hit() + return self._result def test_a_search_hit_on_anilist_takes_the_mapped_western_ids( monkeypatch: pytest.MonkeyPatch, anime_map: list[bool] ) -> None: monkeypatch.setattr(config, "disable_metadata", False) - monkeypatch.setattr(providers, "provider_order", lambda *a: [lambda: AniListHit("anilist")]) + monkeypatch.setattr(providers, "provider_order", lambda *a: [lambda: SearchHit("anilist", anilist_hit())]) result = search_metadata("One Piece", None, "tv") assert result is not None assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21) + + +def western_hit(language: str | None = "ja", kind: str = "tv", **ids: Any) -> MetadataResult: + ids = {"tmdb_id": 37854, "tmdb_kind": kind, **ids} + return MetadataResult(title="One Piece", kind=kind, original_language=language, external_ids=ExternalIds(**ids)) + + +@pytest.mark.parametrize( + ("hit", "kind", "anime", "season", "expected"), + [ + (western_hit(), "tv", False, None, 21), + (western_hit("jpn"), "tv", False, None, 21), + (western_hit(None), "tv", True, None, 21), + (western_hit(tmdb_id=1429), "tv", False, 2, 20958), + (western_hit(tmdb_id=1429), "tv", False, None, None), + (western_hit(tmdb_id=129, kind="movie"), "movie", False, None, 199), + (western_hit(tmdb_kind="movie"), "tv", False, None, None), + ( + MetadataResult(kind="movie", original_language="ja", external_ids=ExternalIds(tmdb_id=37854)), + "tv", + False, + None, + None, + ), + (western_hit(anilist_id=7), "tv", False, None, 7), + ], + ids=[ + "ja", + "alpha-3", + "anime-run", + "season", + "no-season", + "movie", + "movie-id-on-tv", + "movie-match-for-tv", + "own-anilist-id-kept", + ], +) +def test_a_western_match_takes_its_mapped_anilist_id( + anime_map: list[bool], hit: MetadataResult, kind: str, anime: bool, season: int | None, expected: int | None +) -> None: + providers.fill_anilist_id(hit, kind, anime, season) + + assert hit.external_ids.anilist_id == expected + + +@pytest.mark.parametrize( + "hit", + [western_hit("en"), western_hit(None), western_hit(anilist_id=7), western_hit(tmdb_id=None, tmdb_kind=None)], + ids=["english", "no-language", "has-anilist-id", "no-western-id"], +) +def test_a_match_outside_anime_never_reads_the_map(anime_map: list[bool], hit: MetadataResult) -> None: + providers.fill_anilist_id(hit, "tv") + + assert anime_map == [] + + +def test_the_tagging_lookup_picks_the_anilist_entry_of_the_season( + monkeypatch: pytest.MonkeyPatch, anime_map: list[bool] +) -> None: + patch_providers(monkeypatch, {"tmdb": FakeProvider("tmdb", western_hit(tmdb_id=1429))}) + + result = providers.resolve_by_ids(1429, kind="tv", prefer="tmdb", season=2) + + assert result is not None + assert result.external_ids.anilist_id == 20958 + + +def test_a_supplied_anilist_id_wins_over_the_mapped_one(monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]) -> None: + patch_providers(monkeypatch, {"tmdb": FakeProvider("tmdb", western_hit(tmdb_id=1429))}) + + result = providers.resolve_by_ids(1429, anilist_id=16498, kind="tv", prefer="tmdb", season=2) + + assert result is not None + assert result.external_ids.anilist_id == 16498 + + +def test_a_search_hit_on_tmdb_takes_the_mapped_anilist_id( + monkeypatch: pytest.MonkeyPatch, anime_map: list[bool] +) -> None: + monkeypatch.setattr(config, "disable_metadata", False) + monkeypatch.setattr(providers, "provider_order", lambda *a: [lambda: SearchHit("tmdb", western_hit())]) + monkeypatch.setattr(providers, "search_metadata", search_metadata) + + result = providers.resolve_by_ids(title="One Piece", kind="tv") + + assert result is not None + assert result.external_ids == ExternalIds(None, 37854, "tv", None, 21) + + +def test_the_tagging_search_picks_the_anilist_entry_of_the_season( + monkeypatch: pytest.MonkeyPatch, anime_map: list[bool] +) -> None: + monkeypatch.setattr(providers, "search_metadata", lambda *a, **kw: western_hit(tmdb_id=1429)) + + result = providers.resolve_by_ids(title="EXAMPLE", kind="tv", season=2) + + assert result is not None + assert result.external_ids.anilist_id == 20958 diff --git a/tests/core/test_tag_file_dispatch.py b/tests/core/test_tag_file_dispatch.py index 3754afa73..f368b511f 100644 --- a/tests/core/test_tag_file_dispatch.py +++ b/tests/core/test_tag_file_dispatch.py @@ -152,3 +152,24 @@ def test_the_tag_lookup_passes_the_service_provider(calls: Calls, monkeypatch: p ) assert seen and seen[0]["prefer"] == "tmdb" + + +@pytest.mark.parametrize( + ("title", "season"), + [ + (Episode(id_="episode-0001", service=DummyService, title="Some Show", season=3, number=2), 3), + (Movie(id_="movie-0001", service=DummyService, name="Some Movie"), None), + ], + ids=["episode", "movie"], +) +def test_the_tag_lookup_passes_the_season( + calls: Calls, monkeypatch: pytest.MonkeyPatch, title: Any, season: int | None +) -> None: + seen: list[dict[str, Any]] = [] + monkeypatch.setattr(config, "tag_imdb_tmdb", True) + monkeypatch.setattr(tags_module, "get_available_providers", lambda: [object()]) + monkeypatch.setattr(tags_module, "resolve_by_ids", lambda *a, **kw: seen.append(kw) or None) + + tags_module.tag_file(Path("Some Title.mkv"), title) + + assert seen and seen[0]["season"] == season diff --git a/unshackle/core/providers/__init__.py b/unshackle/core/providers/__init__.py index 59885de3a..a14299bf8 100644 --- a/unshackle/core/providers/__init__.py +++ b/unshackle/core/providers/__init__.py @@ -12,12 +12,19 @@ from unshackle.core.providers._base import ( log, result_matches, ) -from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref, western_ids +from unshackle.core.providers.anilist import ( + COUNTRY_TO_LANGUAGE, + AniListProvider, + anilist_id_for, + parse_anilist_ref, + western_ids, +) from unshackle.core.providers.imdb import IMDBProvider, title_to_result from unshackle.core.providers.omdb import OMDBProvider from unshackle.core.providers.simkl import SimklProvider from unshackle.core.providers.tmdb import TMDBProvider from unshackle.core.providers.tvdb import TVDBProvider +from unshackle.core.utilities import spoken_language if TYPE_CHECKING: from unshackle.core.title_cacher import TitleCacher @@ -292,6 +299,7 @@ def resolve_by_ids( cache_account_hash: str | None = None, anime: bool = False, prefer: str | None = None, + season: int | None = None, ) -> MetadataResult | None: """Get metadata from user-supplied external IDs, and find the title by name only without them. @@ -313,9 +321,12 @@ def resolve_by_ids( if not supplied: if not title: return None - return search_metadata( + found = search_metadata( title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash, anime, prefer=prefer ) + if found: + fill_anilist_id(found, kind, anime, season) + return found result: MetadataResult | None = None for cls in provider_order(kind, anime, prefer): @@ -357,6 +368,7 @@ def resolve_by_ids( ids.tvdb_id = ext.tvdb_id fill_anime_ids(result, kind) enrich_ids(result) + fill_anilist_id(result, kind, anime, season) return result @@ -392,6 +404,19 @@ def fill_anime_ids(result: MetadataResult, kind: str) -> None: ids.tvdb_id = ids.tvdb_id or mapped.tvdb_id +def fill_anilist_id(result: MetadataResult, kind: str, anime: bool = False, season: int | None = None) -> None: + """Fill the AniList ID that a TMDB or TVDB match of ``kind`` lacks from the AniList ID map. + + Only an anime lookup, or a match in Japanese, Korean or Chinese, reads the map, so a run outside them never downloads it. + """ + ids = result.external_ids + if ids.anilist_id or not (ids.tmdb_id or ids.tvdb_id) or (result.kind or kind) != kind: + return + if not anime and spoken_language(result.original_language) not in COUNTRY_TO_LANGUAGE.values(): + return + ids.anilist_id = anilist_id_for(ids, kind, season) + + def enrich_ids(result: MetadataResult) -> None: """Enrich a MetadataResult by cross-referencing IMDB ID with the available metadata providers. diff --git a/unshackle/core/providers/anilist.py b/unshackle/core/providers/anilist.py index 50452d72f..2ca9055b4 100644 --- a/unshackle/core/providers/anilist.py +++ b/unshackle/core/providers/anilist.py @@ -1,5 +1,6 @@ from __future__ import annotations +import dataclasses import functools import re @@ -21,8 +22,9 @@ MAL_QUERY = f"query UnshackleAniListMal($idMal: Int) {{ Media(idMal: $idMal, typ TITLE_LANGUAGES: tuple[str, ...] = ("english", "romaji", "native") ID_MAP_URL = "https://raw.githubusercontent.com/Fribb/anime-lists/master/anime-list-mini.json" -ID_MAP_CACHE_KEY = "anilist_id_map" +ID_MAP_CACHE_KEY = "anilist_id_map_v2" ID_MAP_LIFETIME = 7 * 24 * 3600 +SEASON_KEYS = ("tmdb_season", "tvdb_season") # AniList records where a title was produced, not what it is spoken in; these are the # production countries whose anime output is reliably in the country's own language @@ -152,9 +154,9 @@ class AniListProvider(MetadataProvider): return result.external_ids if result else ExternalIds() -def as_id(value: object) -> int | None: - """A positive integer ID, or None for anything else.""" - return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None +def as_id(value: object, low: int = 1) -> int | None: + """An integer of at least ``low``, or None for anything else.""" + return value if isinstance(value, int) and not isinstance(value, bool) and value >= low else None def single(values: object) -> object: @@ -163,17 +165,22 @@ def single(values: object) -> object: def reduce_map_entry(entry: dict) -> dict[str, int | str]: - """The western IDs that one anime-lists entry sets; a list that holds several IDs gives none.""" + """The western IDs and season numbers that one anime-lists entry sets; a list that holds several IDs gives none.""" tmdb = entry.get("themoviedb_id") tmdb = tmdb if isinstance(tmdb, dict) else {} + season = entry.get("season") + season = season if isinstance(season, dict) else {} imdb = single(entry.get("imdb_id")) - ids = { + ids: dict[str, int | str | None] = { "imdb": imdb if isinstance(imdb, str) and re.fullmatch(r"tt\d+", imdb) else None, "tmdb_tv": as_id(tmdb.get("tv")), "tmdb_movie": as_id(single(tmdb.get("movie"))), "tvdb": as_id(entry.get("tvdb_id")), } - return {key: value for key, value in ids.items() if value} + if not any(ids.values()): + return {} + ids |= {"tmdb_season": as_id(season.get("tmdb"), 0), "tvdb_season": as_id(season.get("tvdb"), 0)} + return {key: value for key, value in ids.items() if value is not None} @functools.cache @@ -223,6 +230,61 @@ def western_ids(anilist_id: int, kind: str) -> ExternalIds: ) +def fits(entry: dict, ids: ExternalIds, kind: str) -> bool: + """Whether a map entry is the entry of a western match of ``kind`` whose IDs all agree with it. + + A movie entry fits only from its TMDB movie ID, and a series entry from its TMDB TV or TVDB ID. + """ + if kind == "movie": + keys: tuple[tuple[object, str], ...] = ((ids.tmdb_id, "tmdb_movie"),) + elif "tmdb_movie" in entry: + return False + else: + keys = ((ids.tmdb_id, "tmdb_tv"), (ids.tvdb_id, "tvdb")) + if not any(have and entry.get(key) == have for have, key in keys): + return False + return not any(have and entry.get(key, have) != have for have, key in ((ids.imdb_id, "imdb"), *keys)) + + +def season_hits(hits: dict[str, dict], ids: ExternalIds, season: int | None) -> dict[str, dict]: + """The series entries that the TMDB or the TVDB season numbering picks for ``season`` on its own. + + An entry without a season covers every season only when no entry of the series names a season past 0, + since anime-lists also leaves out the season of an entry in absolute numbering. + """ + split = any(entry.get(key) for entry in hits.values() for key in SEASON_KEYS) + + def covers(entry: dict, season_key: str) -> bool: + if season_key in entry: + return bool(entry[season_key] == season) + return not split and not any(key in entry for key in SEASON_KEYS) + + picks: dict[str, dict] = {} + for have, id_key, season_key in ((ids.tmdb_id, "tmdb_tv", "tmdb_season"), (ids.tvdb_id, "tvdb", "tvdb_season")): + fit = { + key: entry + for key, entry in hits.items() + if have and entry.get(id_key) == have and covers(entry, season_key) + } + if len(fit) == 1: + picks |= fit + return picks + + +def anilist_id_for(ids: ExternalIds, kind: str, season: int | None = None) -> int | None: + """The AniList ID that the ID map gives a western match of ``kind``, or None unless exactly one entry fits. + + When the TMDB and the TVDB numbering each pick an entry, they must agree. Without a ``season``, a series + takes an ID only when the map holds one entry for it. + """ + if ids.tmdb_kind not in (None, kind): + ids = dataclasses.replace(ids, tmdb_id=None, tmdb_kind=None) + hits = {key: entry for key, entry in western_id_map().items() if fits(entry, ids, kind)} + if kind != "movie": + hits = season_hits(hits, ids, season) if season is not None or len(hits) == 1 else {} + return int(next(iter(hits))) if len(hits) == 1 else None + + def media_names(node: dict) -> tuple[str, ...]: """Every title variant of an AniList media node that is set.""" return tuple(str(n) for n in (node.get("title") or {}).values() if n) diff --git a/unshackle/core/utils/tags.py b/unshackle/core/utils/tags.py index 70fc9f741..b75e6eaee 100644 --- a/unshackle/core/utils/tags.py +++ b/unshackle/core/utils/tags.py @@ -147,7 +147,16 @@ def tag_file( return result = resolve_by_ids( - tmdb_id, imdb_id, tvdb_id, anilist_id, title=name, year=year, kind=kind, anime=anime, prefer=prefer + tmdb_id, + imdb_id, + tvdb_id, + anilist_id, + title=name, + year=year, + kind=kind, + anime=anime, + prefer=prefer, + season=title.season if isinstance(title, Episode) else None, ) if result and result.external_ids: