Files
unshackle/unshackle/core/providers/_base.py
T

123 lines
4.1 KiB
Python

from __future__ import annotations
import logging
import re
import unicodedata
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, field
from difflib import SequenceMatcher
import requests
from requests.adapters import HTTPAdapter, Retry
log = logging.getLogger("METADATA")
HEADERS = {"User-Agent": "unshackle-tags/1.0"}
LATIN_ACCENT_RE = re.compile(r"[\u0300-\u036f]")
YEAR_RE = re.compile(r"\s*\(?[12][0-9]{3}\)?$")
@dataclass
class ExternalIds:
"""Normalized external IDs across providers."""
imdb_id: str | None = None
tmdb_id: int | None = None
tmdb_kind: str | None = None # "movie" or "tv"
tvdb_id: int | None = None
anilist_id: int | None = None
@dataclass
class MetadataResult:
"""Unified metadata result from any metadata provider."""
title: str | None = None
year: int | None = None
kind: str | None = None # "movie" or "tv"
external_ids: ExternalIds = field(default_factory=ExternalIds)
original_language: str | None = None # alpha-2 or alpha-3, whichever the provider speaks
source: str = ""
raw: dict | None = None
names: tuple[str, ...] = ()
class MetadataProvider(metaclass=ABCMeta):
"""Abstract base for metadata providers."""
NAME: str = ""
REQUIRES_KEY: bool = True
ID_KIND: str | None = None
def __init__(self) -> None:
self.log = logging.getLogger(f"METADATA.{self.NAME.upper()}")
self._session: requests.Session | None = None
@property
def session(self) -> requests.Session:
if self._session is None:
self._session = requests.Session()
self._session.headers.update(HEADERS)
retry = Retry(
total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504],
allowed_methods=["GET", "POST"],
respect_retry_after_header=False,
)
adapter = HTTPAdapter(max_retries=retry)
self._session.mount("https://", adapter)
self._session.mount("http://", adapter)
return self._session
@abstractmethod
def is_available(self) -> bool:
"""Return True if this metadata provider has the credentials/keys it needs."""
@abstractmethod
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
"""Find a title and return its metadata, or None on failure or when nothing matches."""
@abstractmethod
def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
"""Fetch metadata by this provider's native ID."""
@abstractmethod
def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Fetch external IDs for a title by this provider's native ID."""
def clean(s: str) -> str:
"""Fold case and Latin accents, and keep the letters, digits and combining marks of any script.
Marks outside the Latin accent block stay, so kana voicing and Thai or Indic vowel signs still tell titles apart.
"""
s = LATIN_ACCENT_RE.sub("", unicodedata.normalize("NFKD", s).casefold())
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:
return YEAR_RE.sub("", s).strip()
def title_ratio(a: str, b: str) -> float:
"""Similarity of two cleaned titles from 0 to 1; a title with no letters or digits scores 0."""
a, b = clean(a), clean(b)
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:
"""Return True if ``a`` and ``b`` match closely."""
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)