summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/src/meshbay_node/indexer/title_parse.py
blob: ef522ad72e9ca77f4ba607eeb63a51124b51d9f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""
Filename -> title/year/season/episode parsing for the Videos group app.

Wraps `guessit` and layers the fixes from docs/mediacenter.md §3.3/§3.4 on
top of it: none of them are per-title hacks, each is a generic rule found
by validating guessit's raw output against real TMDB search results over a
~1950-file library (movies, TV shows, and a small franchise set).

Scope is deliberately narrow (§3.5): title, year, season, episode. Technical
facts (resolution, codec, duration) come from ffprobe, never the filename —
a mislabeled `1080p` tag is a real, observed failure mode.

This module never touches the filesystem or the network. The orchestration
that decides *which* file supplies a show's title (a representative episode
filename, not the folder name — §3.4) lives in the indexer, which has the
directory listing; this module only parses strings it's handed.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field

from guessit import guessit

# French edition/release vocabulary guessit's (English-centric) edition list
# doesn't recognize — left stuck to the title instead of stripped as a tag.
_EDITION_PHRASES = (
    r"version\s+longue",
    r"version\s+int[ée]grale",
    r"remasteris[ée]e?",
    r"non[\s._-]*censur[ée]e?",
    r"original\s+version",
)
_EDITION_RE = re.compile("|".join(_EDITION_PHRASES), re.IGNORECASE)

# A season-like ancestor folder: the English/French words plus a number or
# Roman numeral. Vocabulary is a plain tuple so a deployment can extend it
# per locale without touching the regex-building logic.
SEASON_WORDS = ("season", "saison")
_SEASON_RE = re.compile(
    r"(?:" + "|".join(SEASON_WORDS) + r")\s*([0-9]+|[ivxlc]+)\b",
    re.IGNORECASE,
)
_SPECIALS_RE = re.compile(r"\b(?:bonus|extras?|specials?)\b", re.IGNORECASE)

_ROMAN_NUMERALS = {
    2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI",
    7: "VII", 8: "VIII", 9: "IX", 10: "X",
}


def _roman_to_int(s: str) -> int | None:
    values = {"i": 1, "v": 5, "x": 10, "l": 50, "c": 100}
    s = s.lower()
    if not s or any(c not in values for c in s):
        return None
    total = 0
    prev = 0
    for c in reversed(s):
        v = values[c]
        total += v if v >= prev else -v
        prev = v
    return total or None


def _strip_editions(title: str) -> str:
    return re.sub(r"\s+", " ", _EDITION_RE.sub(" ", title)).strip()


def naive_title(filename: str) -> str:
    """
    The mandated fallback (§3.6, §4.1): strip the extension, replace every
    `.`/`_`/`-` with a space, drop a trailing parenthesized year, collapse
    whitespace. Always computable, never fails, used both as the flat-mode
    display name of last resort and as a second TMDB query candidate.
    """
    stem = filename.rsplit(".", 1)[0] if "." in filename else filename
    stem = re.sub(r"[._-]+", " ", stem)
    stem = re.sub(r"\(\s*(19|20)\d{2}\s*\)", " ", stem)
    stem = _strip_editions(stem)
    return re.sub(r"\s+", " ", stem).strip()


def sequel_variants(title: str) -> list[str]:
    """
    A trailing sequel digit sometimes has no equivalent in the real TMDB
    title, or the real title uses a Roman numeral instead (§3.3 row 4).
    Returns extra candidates to try — empty if `title` has no trailing digit.
    """
    m = re.match(r"^(.*\S)\s+([2-9])$", title)
    if not m:
        return []
    base, digit = m.group(1), int(m.group(2))
    variants = [base]
    roman = _ROMAN_NUMERALS.get(digit)
    if roman:
        variants.append(f"{base} {roman}")
    return variants


def season_from_folder_name(name: str) -> int | None:
    """
    §3.4: a season-like ancestor folder, vocabulary-driven rather than
    assuming a numeric convention everywhere. A specials/bonus/extras
    folder maps to season 0 (matching TMDB's own `season_number: 0`).
    Returns None if `name` doesn't look like a season folder at all.
    """
    if _SPECIALS_RE.search(name):
        return 0
    m = _SEASON_RE.search(name)
    if not m:
        return None
    token = m.group(1)
    if token.isdigit():
        return int(token)
    return _roman_to_int(token)


@dataclass
class ParsedName:
    display_title: str | None   # None => caller must supply from elsewhere (e.g. a sibling file)
    alt_title: str | None = None    # guessit's alternative_title, a second query candidate (§3.3 row 1)
    naive_title: str = ""           # always available, fully punctuation-normalized fallback
    year: int | None = None
    season: int | None = None
    episode: int | None = None
    confidence: bool = False        # True only when display_title is set and structurally corroborated


def parse_movie_filename(filename: str) -> ParsedName:
    """Parse a standalone movie filename."""
    g = guessit(filename)
    title = g.get("title")
    title = str(title).strip() if title else None
    if title:
        title = _strip_editions(title)
    alt = g.get("alternative_title")
    alt = _strip_editions(str(alt).strip()) if alt else None
    year = g.get("year")
    nt = naive_title(filename)
    confidence = bool(title) and len(title) >= 2 and year is not None
    return ParsedName(
        display_title=title or None, alt_title=alt, naive_title=nt,
        year=year, confidence=confidence,
    )


def parse_episode_filename(filename: str) -> ParsedName:
    """
    Parse an episode filename. `display_title` may come back None (e.g.
    `S08E02.SUBFRENCH.720p.mkv` carries no show name at all, §3.2) — the
    indexer then supplies the show title from a representative sibling
    filename in the same folder rather than the folder name itself (§3.4).
    """
    g = guessit(filename)
    title = g.get("title")
    title = str(title).strip() if title else None
    if title:
        title = _strip_editions(title)
    season = g.get("season")
    episode = g.get("episode")
    # guessit returns a list when it finds more than one candidate (e.g. a
    # multi-episode file); take the first as the representative one.
    if isinstance(season, list):
        season = season[0] if season else None
    if isinstance(episode, list):
        episode = episode[0] if episode else None
    nt = naive_title(filename)
    confidence = bool(title) and len(title) >= 2 and season is not None and episode is not None
    return ParsedName(
        display_title=title or None, naive_title=nt,
        season=season, episode=episode, confidence=confidence,
    )