|
| 1 | +""" |
| 2 | +animethemes.moe API client: search, theme fetching, episode-aware theme selection. |
| 3 | +""" |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import json |
| 7 | +import re |
| 8 | +import urllib.parse |
| 9 | +import urllib.request |
| 10 | +from typing import Callable, Optional |
| 11 | + |
| 12 | +from constants import API_BASE, API_HEADERS, API_TIMEOUT |
| 13 | +from models import Theme |
| 14 | + |
| 15 | + |
| 16 | +def api_request(url: str, timeout: int = API_TIMEOUT) -> dict: |
| 17 | + """Make API request and return JSON response""" |
| 18 | + request = urllib.request.Request(url, headers=API_HEADERS) |
| 19 | + with urllib.request.urlopen(request, timeout=timeout) as response: |
| 20 | + return json.loads(response.read().decode("utf-8")) |
| 21 | + |
| 22 | + |
| 23 | +def search_anime(query: str) -> list[dict]: |
| 24 | + """Search for anime by name""" |
| 25 | + encoded_query = urllib.parse.quote(query) |
| 26 | + url = f"{API_BASE}/anime?q={encoded_query}&fields[anime]=name,slug,year&page[size]=10" |
| 27 | + data = api_request(url) |
| 28 | + return data.get("anime", []) |
| 29 | + |
| 30 | + |
| 31 | +def parse_episode_set(episodes_str: str) -> set[int]: |
| 32 | + """Parse episode string like '1-3, 5, 7-9' into set of integers""" |
| 33 | + if not episodes_str or not episodes_str.strip(): |
| 34 | + return set() |
| 35 | + |
| 36 | + episodes: set[int] = set() |
| 37 | + |
| 38 | + for part in re.split(r"[,،]", episodes_str): |
| 39 | + part = part.strip() |
| 40 | + |
| 41 | + # Range like "1-3" or "1–3" |
| 42 | + range_match = re.match(r"^(\d+)\s*[-–]\s*(\d+)$", part) |
| 43 | + if range_match: |
| 44 | + start, end = int(range_match.group(1)), int(range_match.group(2)) |
| 45 | + episodes.update(range(start, end + 1)) |
| 46 | + continue |
| 47 | + |
| 48 | + # Open-ended like "1-" |
| 49 | + open_match = re.match(r"^(\d+)\s*[-–]$", part) |
| 50 | + if open_match: |
| 51 | + start = int(open_match.group(1)) |
| 52 | + episodes.update(range(start, 1000)) # Arbitrary upper limit |
| 53 | + continue |
| 54 | + |
| 55 | + # Single episode |
| 56 | + single_match = re.match(r"^(\d+)$", part) |
| 57 | + if single_match: |
| 58 | + episodes.add(int(single_match.group(1))) |
| 59 | + |
| 60 | + return episodes |
| 61 | + |
| 62 | + |
| 63 | +def get_anime_themes(slug: str, log_func: Optional[Callable] = None) -> list[Theme]: |
| 64 | + """ |
| 65 | + Fetch all theme songs for an anime. |
| 66 | +
|
| 67 | + Returns list of Theme objects with: |
| 68 | + - label: "OP1", "ED1", "ED1v2", etc. |
| 69 | + - type: "OP" | "ED" |
| 70 | + - title: Song title |
| 71 | + - video_url: Direct video link |
| 72 | + - duration_ms: Duration (filled later with ffprobe) |
| 73 | + - episode_set: Episodes this theme applies to |
| 74 | + """ |
| 75 | + url = ( |
| 76 | + f"{API_BASE}/anime/{slug}" |
| 77 | + "?include=animethemes.animethemeentries.videos,animethemes.song" |
| 78 | + "&fields[animetheme]=type,sequence" |
| 79 | + "&fields[animethemeentry]=episodes,version" |
| 80 | + "&fields[video]=link" |
| 81 | + "&fields[song]=title" |
| 82 | + ) |
| 83 | + |
| 84 | + data = api_request(url) |
| 85 | + themes_data = data.get("anime", {}).get("animethemes", []) |
| 86 | + themes: list[Theme] = [] |
| 87 | + |
| 88 | + for theme in themes_data: |
| 89 | + theme_type = theme.get("type", "OP") |
| 90 | + sequence = theme.get("sequence") or 1 |
| 91 | + song_title = (theme.get("song") or {}).get("title", "Unknown") |
| 92 | + |
| 93 | + for entry in theme.get("animethemeentries", []): |
| 94 | + version = entry.get("version") or 1 |
| 95 | + episode_set = parse_episode_set(entry.get("episodes") or "") |
| 96 | + videos = entry.get("videos") or [] |
| 97 | + |
| 98 | + if not videos: |
| 99 | + continue |
| 100 | + |
| 101 | + video_url = videos[0].get("link") |
| 102 | + if not video_url: |
| 103 | + continue |
| 104 | + |
| 105 | + theme_obj = Theme( |
| 106 | + label=f"{theme_type}{sequence}" + (f"v{version}" if version > 1 else ""), |
| 107 | + type=theme_type, |
| 108 | + sequence=sequence, |
| 109 | + version=version, |
| 110 | + title=song_title, |
| 111 | + video_url=video_url, |
| 112 | + duration_ms=None, |
| 113 | + episode_set=episode_set, |
| 114 | + ) |
| 115 | + themes.append(theme_obj) |
| 116 | + |
| 117 | + return themes |
| 118 | + |
| 119 | + |
| 120 | +def select_theme_for_episode( |
| 121 | + themes: list[Theme], |
| 122 | + theme_type: str, |
| 123 | + episode: Optional[int], |
| 124 | + log_func: Optional[Callable] = None |
| 125 | +) -> Optional[Theme]: |
| 126 | + """ |
| 127 | + Select the appropriate theme version for a specific episode. |
| 128 | +
|
| 129 | + Selection priority: |
| 130 | + 1. Theme whose episode_set explicitly contains the episode |
| 131 | + 2. Theme without episode restrictions (applies to all) |
| 132 | + 3. Theme with highest sequence whose min_episode <= current episode |
| 133 | + 4. Fallback to last theme (most recent) |
| 134 | + """ |
| 135 | + candidates = [t for t in themes if t.type == theme_type] |
| 136 | + |
| 137 | + if not candidates: |
| 138 | + return None |
| 139 | + |
| 140 | + if episode is None: |
| 141 | + if log_func: |
| 142 | + log_func(f" [{theme_type}] No episode number, using first theme: {candidates[0].label}\n", "dim") |
| 143 | + return candidates[0] |
| 144 | + |
| 145 | + # First, try to find a theme that specifically includes this episode |
| 146 | + for theme in candidates: |
| 147 | + if theme.episode_set and episode in theme.episode_set: |
| 148 | + if log_func: |
| 149 | + eps = sorted(theme.episode_set) if theme.episode_set else [] |
| 150 | + log_func(f" [{theme_type}] Selected {theme.label}: ep {episode} in {eps}\n", "dim") |
| 151 | + return theme |
| 152 | + |
| 153 | + # Then, try themes without episode restrictions (applies to all) |
| 154 | + for theme in candidates: |
| 155 | + if not theme.episode_set: |
| 156 | + if log_func: |
| 157 | + log_func(f" [{theme_type}] Selected {theme.label}: no episode restriction\n", "dim") |
| 158 | + return theme |
| 159 | + |
| 160 | + # If episode not in any set, pick theme with highest sequence whose min_episode <= episode |
| 161 | + # This handles cases like ED2 with eps=[3] meaning "from episode 3 onwards" |
| 162 | + best_theme: Optional[Theme] = None |
| 163 | + best_min_ep = -1 |
| 164 | + |
| 165 | + for theme in candidates: |
| 166 | + if theme.episode_set: |
| 167 | + min_ep = min(theme.episode_set) |
| 168 | + # Theme applies if its range starts at or before current episode |
| 169 | + if min_ep <= episode: |
| 170 | + # Prefer higher sequence or later starting episode |
| 171 | + if best_theme is None or theme.sequence > best_theme.sequence or min_ep > best_min_ep: |
| 172 | + best_theme = theme |
| 173 | + best_min_ep = min_ep |
| 174 | + |
| 175 | + if best_theme: |
| 176 | + if log_func: |
| 177 | + eps = sorted(best_theme.episode_set) if best_theme.episode_set else [] |
| 178 | + log_func( |
| 179 | + f" [{theme_type}] Selected {best_theme.label}: " |
| 180 | + f"min_ep={best_min_ep} <= ep{episode} (fallback logic)\n", |
| 181 | + "dim" |
| 182 | + ) |
| 183 | + return best_theme |
| 184 | + |
| 185 | + # Ultimate fallback: use the last theme (most recent sequence) |
| 186 | + result = candidates[-1] |
| 187 | + if log_func: |
| 188 | + log_func( |
| 189 | + f" [{theme_type}] No matching theme found for ep {episode}, " |
| 190 | + f"using last: {result.label}\n", |
| 191 | + "err" |
| 192 | + ) |
| 193 | + return result |
0 commit comments