forked from kenzuya/unshackle
feat(metadata)!: replace animeapi with a first-class anilist provider
--anilist supersedes --animeapi (REST: anilist_id); the keyless AniList GraphQL provider joins the registry with title search, mal: ID lookup, an ANILIST mkv tag, and the anilist_title_language config option. Services mark anime via Service.ANIME / Title.anime for anilist-first metadata resolution with fall-through.
This commit is contained in:
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Optional, Union
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, log
|
||||
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref
|
||||
from unshackle.core.providers.imdb import IMDBProvider
|
||||
from unshackle.core.providers.omdb import OMDBProvider
|
||||
from unshackle.core.providers.simkl import SimklProvider
|
||||
@@ -15,21 +16,24 @@ if TYPE_CHECKING:
|
||||
from unshackle.core.title_cacher import TitleCacher
|
||||
|
||||
REGISTRY: dict[str, type[MetadataProvider]] = {
|
||||
cls.NAME: cls for cls in (IMDBProvider, OMDBProvider, SimklProvider, TMDBProvider, TVDBProvider)
|
||||
cls.NAME: cls for cls in (AniListProvider, IMDBProvider, OMDBProvider, SimklProvider, TMDBProvider, TVDBProvider)
|
||||
}
|
||||
|
||||
# legacy `metadata_providers` names, still accepted
|
||||
ALIASES: dict[str, str] = {"imdbapi": "imdb"}
|
||||
|
||||
# used when `metadata_providers` is unset
|
||||
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb")
|
||||
# used when `metadata_providers` is unset; anilist answers for anime only, so it costs
|
||||
# nothing at the end of the order
|
||||
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb", "anilist")
|
||||
|
||||
|
||||
def provider_order(kind: Optional[str] = None) -> list[type[MetadataProvider]]:
|
||||
def provider_order(kind: Optional[str] = None, anime: bool = False) -> list[type[MetadataProvider]]:
|
||||
"""Provider classes in the order configured by `metadata_providers`.
|
||||
|
||||
`metadata_providers` is either a flat list applying to both kinds, or a mapping of
|
||||
kind ("tv"/"movie") to its own list. A kind the mapping omits uses `DEFAULT_ORDER`.
|
||||
An `anime` title puts anilist first; the rest of the order stays behind it to
|
||||
fall back on.
|
||||
"""
|
||||
from unshackle.core.config import config
|
||||
|
||||
@@ -37,6 +41,8 @@ def provider_order(kind: Optional[str] = None) -> list[type[MetadataProvider]]:
|
||||
selected = (configured.get(kind) if kind else None) if isinstance(configured, dict) else configured
|
||||
|
||||
names = [ALIASES.get(str(n).lower(), str(n).lower()) for n in (selected or DEFAULT_ORDER)]
|
||||
if anime and AniListProvider.NAME in names:
|
||||
names = [AniListProvider.NAME, *names]
|
||||
unknown = [n for n in names if n not in REGISTRY]
|
||||
if unknown:
|
||||
log.warning("Ignoring unknown metadata_providers entries: %s", ", ".join(unknown))
|
||||
@@ -68,6 +74,7 @@ def search_metadata(
|
||||
cache_title_id: Optional[str] = None,
|
||||
cache_region: Optional[str] = None,
|
||||
cache_account_hash: Optional[str] = None,
|
||||
anime: bool = False,
|
||||
) -> Optional[MetadataResult]:
|
||||
"""Search all available providers for metadata. Returns best match."""
|
||||
from unshackle.core.config import config
|
||||
@@ -78,7 +85,7 @@ def search_metadata(
|
||||
log.debug("Metadata lookups are disabled by config; not searching for %r", title)
|
||||
return None
|
||||
|
||||
ordered = provider_order(kind)
|
||||
ordered = provider_order(kind, anime)
|
||||
|
||||
# Check cache first
|
||||
if title_cacher and cache_title_id:
|
||||
@@ -290,6 +297,7 @@ def resolve_by_ids(
|
||||
tmdb_id: Optional[int] = None,
|
||||
imdb_id: Optional[str] = None,
|
||||
tvdb_id: Optional[int] = None,
|
||||
anilist_id: Optional[Union[int, str]] = None,
|
||||
*,
|
||||
title: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
@@ -298,6 +306,7 @@ def resolve_by_ids(
|
||||
cache_title_id: Optional[str] = None,
|
||||
cache_region: Optional[str] = None,
|
||||
cache_account_hash: Optional[str] = None,
|
||||
anime: bool = False,
|
||||
) -> Optional[MetadataResult]:
|
||||
"""Resolve metadata from user-supplied external IDs, falling back to search only without them.
|
||||
|
||||
@@ -313,14 +322,16 @@ def resolve_by_ids(
|
||||
supplied["imdb"] = imdb_id
|
||||
if tvdb_id is not None:
|
||||
supplied["tvdb"] = tvdb_id
|
||||
if anilist_id is not None:
|
||||
supplied["anilist"] = anilist_id
|
||||
|
||||
if not supplied:
|
||||
if not title:
|
||||
return None
|
||||
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash, anime)
|
||||
|
||||
result: Optional[MetadataResult] = None
|
||||
for cls in provider_order(kind):
|
||||
for cls in provider_order(kind, anime):
|
||||
provider_id = supplied.get(cls.ID_KIND or "")
|
||||
if provider_id is None:
|
||||
continue
|
||||
@@ -346,6 +357,10 @@ def resolve_by_ids(
|
||||
ids.imdb_id = imdb_id
|
||||
if tvdb_id is not None:
|
||||
ids.tvdb_id = tvdb_id
|
||||
if anilist_id is not None and ids.anilist_id is None:
|
||||
ref = parse_anilist_ref(anilist_id)
|
||||
if ref and ref[0] == "id":
|
||||
ids.anilist_id = ref[1]
|
||||
|
||||
if ids.tmdb_id and not (ids.imdb_id and ids.tvdb_id):
|
||||
ext = fetch_external_ids(ids.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
@@ -480,6 +495,8 @@ def _external_ids_to_dict(ext: ExternalIds) -> dict:
|
||||
result["tmdb_kind"] = ext.tmdb_kind
|
||||
if ext.tvdb_id:
|
||||
result["tvdb_id"] = ext.tvdb_id
|
||||
if ext.anilist_id:
|
||||
result["anilist_id"] = ext.anilist_id
|
||||
return result
|
||||
|
||||
|
||||
@@ -567,6 +584,8 @@ def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[M
|
||||
source="tvdb",
|
||||
raw=cached,
|
||||
)
|
||||
elif provider_name == "anilist":
|
||||
return AniListProvider()._to_result(cached)
|
||||
elif provider_name == "imdb":
|
||||
from unshackle.core.providers.imdb import primary_language
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ class ExternalIds:
|
||||
tmdb_id: Optional[int] = None
|
||||
tmdb_kind: Optional[str] = None # "movie" or "tv"
|
||||
tvdb_id: Optional[int] = None
|
||||
anilist_id: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Optional, Union
|
||||
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean
|
||||
|
||||
GRAPHQL_URL = "https://graphql.anilist.co"
|
||||
|
||||
MEDIA_FIELDS = "id idMal title { romaji english native } format startDate { year } countryOfOrigin"
|
||||
|
||||
SEARCH_QUERY = (
|
||||
"query UnshackleAniListSearch($search: String) { Page(perPage: 10) "
|
||||
"{ media(search: $search, type: ANIME, sort: SEARCH_MATCH) { %s } } }" % MEDIA_FIELDS
|
||||
)
|
||||
MEDIA_QUERY = "query UnshackleAniListMedia($id: Int) { Media(id: $id, type: ANIME) { %s } }" % MEDIA_FIELDS
|
||||
MAL_QUERY = "query UnshackleAniListMal($idMal: Int) { Media(idMal: $idMal, type: ANIME) { %s } }" % MEDIA_FIELDS
|
||||
|
||||
TITLE_LANGUAGES: tuple[str, ...] = ("english", "romaji", "native")
|
||||
|
||||
# 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"}
|
||||
|
||||
|
||||
def parse_anilist_ref(value: Union[int, str]) -> Optional[tuple[str, int]]:
|
||||
"""Split an AniList reference into its namespace and number.
|
||||
|
||||
A bare number is an AniList ID; ``mal:12345`` is a MyAnimeList ID, which AniList
|
||||
resolves natively. Returns None for anything else.
|
||||
"""
|
||||
text = str(value).strip().lower()
|
||||
namespace = "id"
|
||||
if ":" in text:
|
||||
prefix, _, text = text.partition(":")
|
||||
if prefix != "mal":
|
||||
return None
|
||||
namespace = "mal"
|
||||
# isdecimal, not isdigit: superscripts pass isdigit but crash int()
|
||||
if not text.isdecimal():
|
||||
return None
|
||||
number = int(text)
|
||||
return (namespace, number) if number > 0 else None
|
||||
|
||||
|
||||
class AniListProvider(MetadataProvider):
|
||||
"""Anime metadata provider using AniList's public GraphQL API (no API key)."""
|
||||
|
||||
NAME = "anilist"
|
||||
REQUIRES_KEY = False
|
||||
ID_KIND = "anilist"
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
def _graphql(self, query: str, variables: dict) -> Optional[dict]:
|
||||
try:
|
||||
r = self.session.post(GRAPHQL_URL, json={"query": query, "variables": variables}, timeout=30)
|
||||
body = r.json()
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
self.log.debug("AniList GraphQL request failed: %s", exc)
|
||||
return None
|
||||
|
||||
if body.get("errors"):
|
||||
# a miss is a 404 with an error body, not an empty result
|
||||
self.log.debug("AniList GraphQL errors: %s", [e.get("message") for e in body["errors"]][:3])
|
||||
return None
|
||||
return body.get("data")
|
||||
|
||||
def _title_variant(self, titles: dict) -> Optional[str]:
|
||||
from unshackle.core.config import config
|
||||
|
||||
configured = (config.anilist_title_language or "english").lower()
|
||||
for variant in [configured, *(v for v in TITLE_LANGUAGES if v != configured)]:
|
||||
value = titles.get(variant)
|
||||
if value:
|
||||
return str(value)
|
||||
return None
|
||||
|
||||
def _to_result(self, node: dict) -> Optional[MetadataResult]:
|
||||
title = self._title_variant(node.get("title") or {})
|
||||
if not title:
|
||||
return None
|
||||
return MetadataResult(
|
||||
title=title,
|
||||
year=(node.get("startDate") or {}).get("year"),
|
||||
kind="movie" if node.get("format") == "MOVIE" else "tv",
|
||||
external_ids=ExternalIds(anilist_id=node.get("id")),
|
||||
original_language=COUNTRY_TO_LANGUAGE.get(node.get("countryOfOrigin") or ""),
|
||||
source="anilist",
|
||||
raw=node,
|
||||
)
|
||||
|
||||
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
|
||||
self.log.debug("Searching AniList for %r (%s, %s)", title, kind, year)
|
||||
|
||||
data = self._graphql(SEARCH_QUERY, {"search": title})
|
||||
nodes = ((data or {}).get("Page") or {}).get("media") or []
|
||||
if not nodes:
|
||||
self.log.debug("AniList returned no results for %r", title)
|
||||
return None
|
||||
|
||||
# soft filters with fallback: other providers search kind-scoped endpoints, here
|
||||
# one ANIME search covers both kinds, so a TV hit must not shadow a movie search
|
||||
matching = [n for n in nodes if (n.get("format") == "MOVIE") == (kind == "movie")]
|
||||
nodes = matching or nodes
|
||||
if year:
|
||||
dated = [n for n in nodes if (n.get("startDate") or {}).get("year") == year]
|
||||
nodes = dated or nodes
|
||||
|
||||
best = max(nodes, key=lambda n: _match_ratio(n, title))
|
||||
result = self._to_result(best)
|
||||
if result:
|
||||
self.log.debug("AniList -> %s (ID %s)", result.title, result.external_ids.anilist_id)
|
||||
return result
|
||||
|
||||
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
|
||||
"""Fetch metadata by AniList ID, or by MyAnimeList ID when given as 'mal:12345'."""
|
||||
ref = parse_anilist_ref(provider_id)
|
||||
if not ref:
|
||||
self.log.debug("Not an AniList reference: %r", provider_id)
|
||||
return None
|
||||
|
||||
namespace, number = ref
|
||||
self.log.debug("Fetching AniList media %s:%d", namespace, number)
|
||||
if namespace == "mal":
|
||||
data = self._graphql(MAL_QUERY, {"idMal": number})
|
||||
else:
|
||||
data = self._graphql(MEDIA_QUERY, {"id": number})
|
||||
|
||||
node = (data or {}).get("Media")
|
||||
if not node:
|
||||
return None
|
||||
return self._to_result(node)
|
||||
|
||||
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
|
||||
"""Return external IDs. AniList knows no western IDs, so only its own."""
|
||||
ref = parse_anilist_ref(provider_id)
|
||||
if not ref:
|
||||
return ExternalIds()
|
||||
namespace, number = ref
|
||||
if namespace == "id":
|
||||
return ExternalIds(anilist_id=number)
|
||||
result = self.get_by_id(provider_id, kind)
|
||||
return result.external_ids if result else ExternalIds()
|
||||
|
||||
|
||||
def _match_ratio(node: dict, title: str) -> float:
|
||||
names = (node.get("title") or {}).values()
|
||||
return max((SequenceMatcher(None, _clean(title), _clean(n)).ratio() for n in names if n), default=0.0)
|
||||
Reference in New Issue
Block a user