diff --git a/tests/core/test_provider_title_match.py b/tests/core/test_provider_title_match.py new file mode 100644 index 00000000..46a25d91 --- /dev/null +++ b/tests/core/test_provider_title_match.py @@ -0,0 +1,69 @@ +import pytest + +from unshackle.core.providers import fuzzy_match +from unshackle.core.providers._base import clean, title_ratio + + +@pytest.mark.parametrize( + ("title", "expected"), + [ + ("The Matrix (1999)", "thematrix1999"), + ("Spider-Man: No Way Home", "spidermannowayhome"), + ("Léon", "leon"), + ("Straße", "strasse"), + ("XYZ 12", "xyz12"), + ("进击的巨人", "进击的巨人"), + ("Брат 2", "брат2"), + ("İstanbul", "istanbul"), + ("Title™", "titletm"), + ("사랑의 불시착", "사랑의불시착"), + ("がっこうぐらし", "がっこうぐらし"), + ("เป็นต่อ", "เป็นต่อ"), + ("진격의 거인", "진격의거인"), + ("進撃の巨人", "進撃の巨人"), + ], +) +def test_clean_keeps_letters_and_digits_of_every_script(title: str, expected: str) -> None: + assert clean(title) == expected + + +@pytest.mark.parametrize("title", ["เป็นต่อ", "हिंदी", "进击的巨人", "Война и мир", "The Matrix"]) +def test_fuzzy_match_a_title_with_itself(title: str) -> None: + assert fuzzy_match(title, title) + + +@pytest.mark.parametrize( + ("a", "b"), + [ + ("เป็นต่อ", "हिंदी"), + ("进击的巨人", "鬼灭之刃"), + ("Война и мир", "Преступление и наказание"), + ("เป็นต่อ", "The Matrix"), + ("사랑", "사람"), + ("슬기로운 의사생활", "슬기로운 감빵생활"), + ("がっこうぐらし", "かっこうくらし"), + ("ガンダム", "カンタム"), + ("कहानी", "कहना"), + ], +) +def test_fuzzy_match_rejects_different_non_latin_titles(a: str, b: str) -> None: + assert not fuzzy_match(a, b) + + +@pytest.mark.parametrize(("a", "b"), [("!!!", "!!!"), ("", ""), ("---", "The Matrix")]) +def test_a_title_with_no_letters_or_digits_matches_nothing(a: str, b: str) -> None: + assert title_ratio(a, b) == 0.0 + assert not fuzzy_match(a, b) + + +@pytest.mark.parametrize( + ("a", "b", "expected"), + [ + ("The Matrix", "the matrix", True), + ("Spider-Man: No Way Home", "Spider Man No Way Home", True), + ("Leon", "Léon", True), + ("The Matrix", "The Godfather", False), + ], +) +def test_fuzzy_match_latin_titles(a: str, b: str, expected: bool) -> None: + assert fuzzy_match(a, b) is expected diff --git a/unshackle/core/providers/_base.py b/unshackle/core/providers/_base.py index f8c6dc8e..9d5b37c3 100644 --- a/unshackle/core/providers/_base.py +++ b/unshackle/core/providers/_base.py @@ -2,6 +2,7 @@ from __future__ import annotations import logging import re +import unicodedata from abc import ABCMeta, abstractmethod from dataclasses import dataclass, field from difflib import SequenceMatcher @@ -13,7 +14,7 @@ log = logging.getLogger("METADATA") HEADERS = {"User-Agent": "unshackle-tags/1.0"} -STRIP_RE = re.compile(r"[^a-z0-9]+", re.I) +LATIN_ACCENT_RE = re.compile(r"[\u0300-\u036f]") YEAR_RE = re.compile(r"\s*\(?[12][0-9]{3}\)?$") @@ -87,14 +88,24 @@ class MetadataProvider(metaclass=ABCMeta): def clean(s: str) -> str: - return STRIP_RE.sub("", s).lower() + """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 fuzzy_match(a: str, b: str, threshold: float = 0.8) -> bool: """Return True if ``a`` and ``b`` match closely.""" - ratio = SequenceMatcher(None, clean(a), clean(b)).ratio() - return ratio >= threshold + return title_ratio(a, b) >= threshold diff --git a/unshackle/core/providers/anilist.py b/unshackle/core/providers/anilist.py index a7ae918f..c584fa10 100644 --- a/unshackle/core/providers/anilist.py +++ b/unshackle/core/providers/anilist.py @@ -1,10 +1,8 @@ from __future__ import annotations -from difflib import SequenceMatcher - import requests -from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean +from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, title_ratio GRAPHQL_URL = "https://graphql.anilist.co" @@ -148,4 +146,4 @@ class AniListProvider(MetadataProvider): 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) + return max((title_ratio(title, n) for n in names if n), default=0.0) diff --git a/unshackle/core/providers/imdb.py b/unshackle/core/providers/imdb.py index 6fb1fbbd..267ed6eb 100644 --- a/unshackle/core/providers/imdb.py +++ b/unshackle/core/providers/imdb.py @@ -2,11 +2,10 @@ from __future__ import annotations import hashlib import json -from difflib import SequenceMatcher import requests -from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, fuzzy_match +from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, title_ratio GRAPHQL_URL = "https://caching.graphql.imdb.com/" @@ -144,7 +143,7 @@ class IMDBProvider(MetadataProvider): def match_ratio(node: dict, title: str) -> float: names = [(node.get("titleText") or {}).get("text"), (node.get("originalTitleText") or {}).get("text")] - return max((SequenceMatcher(None, clean(title), clean(n)).ratio() for n in names if n), default=0.0) + return max((title_ratio(title, n) for n in names if n), default=0.0) def persisted_query_missing(body: dict) -> bool: diff --git a/unshackle/core/providers/omdb.py b/unshackle/core/providers/omdb.py index afc412e0..7185dc9f 100644 --- a/unshackle/core/providers/omdb.py +++ b/unshackle/core/providers/omdb.py @@ -1,12 +1,10 @@ from __future__ import annotations -from difflib import SequenceMatcher - import requests from langcodes import Language from unshackle.core.config import config -from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, fuzzy_match +from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, title_ratio KIND_TO_TYPE: dict[str, str] = { "movie": "movie", @@ -86,7 +84,7 @@ class OMDBProvider(MetadataProvider): name = candidate.get("Title") or "" if not name: continue - ratio = SequenceMatcher(None, clean(title), clean(name)).ratio() + ratio = title_ratio(title, name) if ratio > best_ratio: candidate_year = parse_year(candidate.get("Year")) if year and candidate_year and abs(year - candidate_year) > 1: diff --git a/unshackle/core/providers/tmdb.py b/unshackle/core/providers/tmdb.py index af5eea56..15bbc139 100644 --- a/unshackle/core/providers/tmdb.py +++ b/unshackle/core/providers/tmdb.py @@ -1,11 +1,9 @@ from __future__ import annotations -from difflib import SequenceMatcher - import requests from unshackle.core.config import config -from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, strip_year +from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, strip_year, title_ratio class TMDBProvider(MetadataProvider): @@ -55,7 +53,7 @@ class TMDBProvider(MetadataProvider): candidates = [c for c in candidates if c] for candidate in candidates: - ratio = SequenceMatcher(None, clean(search_title), clean(candidate)).ratio() + ratio = title_ratio(search_title, candidate) if ratio > best_ratio: best_ratio = ratio best_id = result.get("id") diff --git a/unshackle/core/providers/tvdb.py b/unshackle/core/providers/tvdb.py index c32ada56..9fa673dc 100644 --- a/unshackle/core/providers/tvdb.py +++ b/unshackle/core/providers/tvdb.py @@ -1,13 +1,12 @@ from __future__ import annotations from collections.abc import Collection -from difflib import SequenceMatcher from typing import Any import requests from unshackle.core.config import config -from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, strip_year +from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, strip_year, title_ratio def primary_language(data: dict) -> str | None: @@ -58,7 +57,7 @@ def pick_match(results: list[dict], search_title: str, year: int | None) -> tupl for candidate in [result.get("name"), *(result.get("aliases") or [])]: if not candidate: continue - ratio = SequenceMatcher(None, clean(search_title), clean(candidate)).ratio() + ratio = title_ratio(search_title, candidate) if ratio > best_ratio: best, best_title, best_ratio = result, candidate, ratio return best, best_title, best_ratio