forked from kenzuya/unshackle
feat(providers): fill the western IDs of an AniList match from the anime-lists ID map
This commit is contained in:
@@ -1178,7 +1178,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
oneOf:
|
||||
- type: integer
|
||||
- type: string
|
||||
description: AniList ID for tagging instead of a title search, or a MyAnimeList ID as the string mal:21. Combines with one of tmdb_id, imdb_id and tvdb_id, which AniList does not know (default - None)
|
||||
description: AniList ID for tagging instead of a title search, or a MyAnimeList ID as the string mal:21. Combines with one of tmdb_id, imdb_id and tvdb_id, which wins over the IDs mapped from AniList (default - None)
|
||||
enrich:
|
||||
type: boolean
|
||||
description: Overwrite show title, year and original language with the external source's. Requires one of tmdb_id, imdb_id, tvdb_id or anilist_id (default - false)
|
||||
|
||||
@@ -12,7 +12,7 @@ from unshackle.core.providers._base import (
|
||||
log,
|
||||
result_matches,
|
||||
)
|
||||
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref
|
||||
from unshackle.core.providers.anilist import AniListProvider, 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
|
||||
@@ -125,11 +125,12 @@ def search_metadata(
|
||||
log.debug("%s search failed: %s", p.NAME, exc)
|
||||
continue
|
||||
if result and result_matches(result, title):
|
||||
fill_anime_ids(result, kind)
|
||||
enrich_ids(result)
|
||||
if title_cacher and cache_title_id and result.raw:
|
||||
try:
|
||||
cache_data = result.raw
|
||||
if result.external_ids.tmdb_id or result.external_ids.tvdb_id:
|
||||
if result.external_ids.tmdb_id or result.external_ids.imdb_id or result.external_ids.tvdb_id:
|
||||
cache_data = {
|
||||
**result.raw,
|
||||
"_enriched_ids": external_ids_to_dict(result.external_ids),
|
||||
@@ -354,6 +355,7 @@ def resolve_by_ids(
|
||||
ids.imdb_id = ext.imdb_id
|
||||
if ext.tvdb_id and not ids.tvdb_id:
|
||||
ids.tvdb_id = ext.tvdb_id
|
||||
fill_anime_ids(result, kind)
|
||||
enrich_ids(result)
|
||||
|
||||
return result
|
||||
@@ -370,6 +372,26 @@ def enrichment_providers(kind: str | None = None) -> list[str]:
|
||||
return [name for name in ENRICHMENT_AUTHORITY if name in configured]
|
||||
|
||||
|
||||
def fill_anime_ids(result: MetadataResult, kind: str) -> None:
|
||||
"""Fill the western IDs that an AniList match of ``kind`` lacks from the AniList ID map.
|
||||
|
||||
The map is used only when every western ID the match already has agrees with it, and never
|
||||
when AniList gives the match another kind, so a mapped ID never replaces or mixes with another one.
|
||||
"""
|
||||
ids = result.external_ids
|
||||
complete = ids.tmdb_id and ids.imdb_id and (ids.tvdb_id or kind == "movie")
|
||||
if not ids.anilist_id or complete or (result.kind or kind) != kind:
|
||||
return
|
||||
mapped = western_ids(ids.anilist_id, kind)
|
||||
pairs = ((ids.imdb_id, mapped.imdb_id), (ids.tmdb_id, mapped.tmdb_id), (ids.tvdb_id, mapped.tvdb_id))
|
||||
if any(have and have != got for have, got in pairs):
|
||||
return
|
||||
ids.imdb_id = ids.imdb_id or mapped.imdb_id
|
||||
ids.tmdb_id = ids.tmdb_id or mapped.tmdb_id
|
||||
ids.tmdb_kind = ids.tmdb_kind or mapped.tmdb_kind
|
||||
ids.tvdb_id = ids.tvdb_id or mapped.tvdb_id
|
||||
|
||||
|
||||
def enrich_ids(result: MetadataResult) -> None:
|
||||
"""Enrich a MetadataResult by cross-referencing IMDB ID with the available metadata providers.
|
||||
|
||||
@@ -561,12 +583,11 @@ def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataRes
|
||||
source="tvdb",
|
||||
raw=cached,
|
||||
)
|
||||
elif provider_name == "anilist":
|
||||
return AniListProvider().to_result(cached)
|
||||
elif provider_name == "imdb":
|
||||
result = title_to_result(cached, kind)
|
||||
elif provider_name in ("anilist", "imdb"):
|
||||
result = AniListProvider().to_result(cached) if provider_name == "anilist" else title_to_result(cached, kind)
|
||||
if result:
|
||||
enriched = cached.get("_enriched_ids", {})
|
||||
result.external_ids.imdb_id = result.external_ids.imdb_id or enriched.get("imdb_id")
|
||||
result.external_ids.tmdb_id = enriched.get("tmdb_id")
|
||||
result.external_ids.tmdb_kind = enriched.get("tmdb_kind")
|
||||
result.external_ids.tvdb_id = enriched.get("tvdb_id")
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import re
|
||||
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio, log
|
||||
|
||||
GRAPHQL_URL = "https://graphql.anilist.co"
|
||||
|
||||
@@ -17,6 +20,10 @@ 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_LIFETIME = 7 * 24 * 3600
|
||||
|
||||
# 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
|
||||
COUNTRY_TO_LANGUAGE: dict[str, str] = {"JP": "ja", "KR": "ko", "CN": "zh", "TW": "zh", "HK": "zh"}
|
||||
@@ -134,7 +141,7 @@ class AniListProvider(MetadataProvider):
|
||||
return self.to_result(node)
|
||||
|
||||
def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
|
||||
"""Return external IDs. AniList knows no western IDs, so only its own."""
|
||||
"""Return the AniList ID only; ``fill_anime_ids`` adds the western IDs from the AniList ID map."""
|
||||
ref = parse_anilist_ref(provider_id)
|
||||
if not ref:
|
||||
return ExternalIds()
|
||||
@@ -145,6 +152,77 @@ 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 single(values: object) -> object:
|
||||
"""The one item of a list, or None for an empty or ambiguous list."""
|
||||
return values[0] if isinstance(values, list) and len(values) == 1 else None
|
||||
|
||||
|
||||
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."""
|
||||
tmdb = entry.get("themoviedb_id")
|
||||
tmdb = tmdb if isinstance(tmdb, dict) else {}
|
||||
imdb = single(entry.get("imdb_id"))
|
||||
ids = {
|
||||
"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}
|
||||
|
||||
|
||||
@functools.cache
|
||||
def western_id_map() -> dict[str, dict]:
|
||||
"""The anime-lists map from AniList ID to western IDs, downloaded once a week; empty when it cannot load."""
|
||||
from unshackle.core.cacher import Cacher
|
||||
|
||||
cache = Cacher("global", ID_MAP_CACHE_KEY)
|
||||
try:
|
||||
cache = cache.get(ID_MAP_CACHE_KEY)
|
||||
except (ValueError, KeyError, TypeError, AttributeError, OSError) as exc:
|
||||
log.debug("Ignoring the unreadable AniList ID map cache: %s", exc)
|
||||
if cache.data and not cache.expired:
|
||||
return cache.data
|
||||
|
||||
try:
|
||||
r = AniListProvider().session.get(ID_MAP_URL, timeout=30)
|
||||
r.raise_for_status()
|
||||
id_map: dict[str, dict] = {}
|
||||
for entry in r.json():
|
||||
anilist_id = as_id(entry.get("anilist_id"))
|
||||
ids = reduce_map_entry(entry)
|
||||
if anilist_id and ids:
|
||||
id_map[str(anilist_id)] = ids
|
||||
except (requests.RequestException, ValueError, TypeError, AttributeError) as exc:
|
||||
log.debug("AniList ID map download failed: %s", exc)
|
||||
return cache.data or {}
|
||||
try:
|
||||
cache.set(id_map, expiration=ID_MAP_LIFETIME)
|
||||
except OSError as exc:
|
||||
log.debug("AniList ID map not cached: %s", exc)
|
||||
return id_map
|
||||
|
||||
|
||||
def western_ids(anilist_id: int, kind: str) -> ExternalIds:
|
||||
"""The TMDB, IMDb and TVDB IDs that the ID map gives an AniList ID of ``kind`` ("movie" or "tv").
|
||||
|
||||
A movie takes only a TMDB movie ID, and a series only a TMDB TV ID and the TVDB series ID.
|
||||
"""
|
||||
entry = western_id_map().get(str(anilist_id)) or {}
|
||||
tmdb_id = entry.get("tmdb_movie") if kind == "movie" else entry.get("tmdb_tv")
|
||||
return ExternalIds(
|
||||
imdb_id=entry.get("imdb"),
|
||||
tmdb_id=tmdb_id,
|
||||
tmdb_kind=kind if tmdb_id else None,
|
||||
tvdb_id=None if kind == "movie" else entry.get("tvdb"),
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -69,8 +69,8 @@ def validate_metadata_ids(
|
||||
) -> None:
|
||||
"""Reject ID flags that conflict, or that no configured metadata provider could ever find.
|
||||
|
||||
--anilist stays outside the mutual exclusion: AniList knows no western IDs, so pairing
|
||||
it with one of the other three is how an anime title gets both.
|
||||
--anilist stays outside the mutual exclusion: a western ID given with it wins over the
|
||||
IDs mapped from AniList.
|
||||
"""
|
||||
if anilist_id and not parse_anilist_ref(anilist_id):
|
||||
raise PlanError("--anilist takes an AniList ID like 21, or a MyAnimeList ID like mal:21.")
|
||||
|
||||
@@ -175,6 +175,7 @@ class TitleMetadata:
|
||||
self.tmdb_id = result.external_ids.tmdb_id
|
||||
elif providers.result_matches(result, title.title):
|
||||
self.tmdb_id = result.external_ids.tmdb_id
|
||||
self.anilist_id = result.external_ids.anilist_id
|
||||
tmdb_title = result.title
|
||||
self.search_source = result.source
|
||||
if listing:
|
||||
|
||||
Reference in New Issue
Block a user