mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 18:08:07 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47c6691823 | ||
|
|
d59b5bf3bd | ||
|
|
bb01e9e36a | ||
|
|
c133b64c7d | ||
|
|
cd11088be5 |
No files matched your search
@@ -103,3 +103,43 @@ async def search_tracks(query: str, artist: str | None = None, limit: int = 10)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to search tracks from karaoke-decide: {e}")
|
||||
return []
|
||||
|
||||
|
||||
SPOTIFY_SEARCH_TIMEOUT = 6 # seconds; decide's own Spotify call is capped at 4 s
|
||||
SPOTIFY_CACHE_TTL_SECONDS = 600
|
||||
|
||||
|
||||
async def spotify_search(query: str, limit: int = 10) -> list[dict] | None:
|
||||
"""Live Spotify track search via karaoke-decide (partner route, X-Partner-Secret).
|
||||
|
||||
Lets the match judge confirm a song our BigQuery catalogue doesn't know (it's a July 2025
|
||||
Spotify snapshot + MusicBrainz, so 2025+ releases and small artists are missing). Returns
|
||||
track dicts with ``artist_name`` / ``track_name`` (the catalogue candidate shape), or
|
||||
**None when there's no evidence either way**: secret unset, decide down, or decide's
|
||||
Spotify breaker open. Never raises.
|
||||
"""
|
||||
secret = getattr(settings, "decide_partner_secret", "") or ""
|
||||
q = " ".join((query or "").split())
|
||||
if not secret or len(q) < 2:
|
||||
return None
|
||||
cache_key = f"spotify:{q.casefold()}:{limit}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
url = f"{_get_base_url()}/api/partner/gen/spotify-search"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=SPOTIFY_SEARCH_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url, params={"q": q[:300], "limit": min(limit, 10)},
|
||||
headers={"X-Partner-Secret": secret},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning(f"Spotify search via karaoke-decide failed: {e}")
|
||||
return None
|
||||
if not isinstance(data, dict) or not data.get("available"):
|
||||
return None
|
||||
tracks = [t for t in data.get("tracks") or [] if isinstance(t, dict)]
|
||||
_cache_set(cache_key, tracks, SPOTIFY_CACHE_TTL_SECONDS)
|
||||
return tracks
|
||||
@@ -9,6 +9,12 @@ verdict shape (kind cosmetic/content/ambiguous/none) plus the typed split.
|
||||
:func:`judge_match` catalog pass, so the singer gets exactly the canonical
|
||||
artist/title gen's AudioSourceStep would "tidy" to (the catalog can't parse a
|
||||
one-line query itself — the AI only does the split + typo fix).
|
||||
|
||||
Live Spotify (2026-11-06, see ``service.py``'s grounding rule): before Gemini, the
|
||||
raw query goes to a live Spotify search. A result whose artist + title IS the query
|
||||
(either order, after normalising) answers it without Gemini. Otherwise Gemini gets
|
||||
those results as candidates, and a confident answer that neither the catalogue nor
|
||||
Spotify can confirm is returned with ``confident: false``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -26,6 +32,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
Judge = Callable[[str, str], Awaitable[MatchVerdict]]
|
||||
SpotifySearch = Callable[[str], Awaitable[Optional[list[dict]]]]
|
||||
|
||||
_VALID_KINDS = {"cosmetic", "content", "ambiguous"}
|
||||
|
||||
@@ -45,6 +52,10 @@ GEMINI_ATTEMPT_TIMEOUT_S = 8.0
|
||||
GEMINI_MIN_DEADLINE_MS = 10000 # the API's minimum request deadline
|
||||
GEMINI_ATTEMPTS = 2
|
||||
CATALOG_TIDY_TIMEOUT_S = 4.0
|
||||
# Live Spotify lookup before Gemini. Kept short so the worst case still fits decide's
|
||||
# 25 s wait: 3 + 2 x 8 (Gemini) + 4 (tidy) = 23 s. A miss just means no candidates.
|
||||
SPOTIFY_TIMEOUT_S = 3.0
|
||||
SPOTIFY_CANDIDATES_FOR_AI = 8
|
||||
|
||||
# In-flight catalog searches. One the tidy gave up on keeps running (warming decide and
|
||||
# the catalog proxy's cache for the next ask); strong refs so it isn't GC'd mid-flight.
|
||||
@@ -75,7 +86,10 @@ _SYSTEM_PROMPT = (
|
||||
" 'ambiguous' – several real songs are plausible; list them in alternatives.\n"
|
||||
" 'none' – not a recognisable song, or you are not sure.\n"
|
||||
"confident: true only when you are sure which released song is meant. Never "
|
||||
"invent songs; prefer kind='none' when unsure. canonical_artist/canonical_title "
|
||||
"invent songs; prefer kind='none' when unsure. When live Spotify results are "
|
||||
"listed, they are real released songs: if one is the song meant, use its exact "
|
||||
"artist and title. Never 'correct' a query to a different, more familiar title "
|
||||
"when a listed result matches what was typed. canonical_artist/canonical_title "
|
||||
"must use official formatting. alternatives is a list of {artist,title} (max 4)."
|
||||
)
|
||||
|
||||
@@ -167,8 +181,18 @@ def _retryable(exc: BaseException) -> bool:
|
||||
return not (isinstance(code, int) and 400 <= code < 500 and code != 429)
|
||||
|
||||
|
||||
def _user_prompt(query: str, candidates: Optional[list[dict]]) -> str:
|
||||
lines = [f'Singer typed: "{query}"']
|
||||
if candidates:
|
||||
lines.append("Live Spotify search results for this query (real released songs):")
|
||||
lines += [f'- {c.get("artist_name", "")} — {c.get("track_name", "")}'
|
||||
for c in candidates[:SPOTIFY_CANDIDATES_FOR_AI]]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
|
||||
model: Optional[str] = None) -> dict:
|
||||
model: Optional[str] = None,
|
||||
candidates: Optional[list[dict]] = None) -> dict:
|
||||
"""Split + correct a free-text song query. Never raises: failures → kind 'none'.
|
||||
|
||||
Each Gemini attempt is bounded by GEMINI_ATTEMPT_TIMEOUT_S; a transient failure
|
||||
@@ -180,7 +204,7 @@ async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
|
||||
for attempt in range(1, GEMINI_ATTEMPTS + 1):
|
||||
try:
|
||||
data = await asyncio.wait_for(
|
||||
gen(model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"'),
|
||||
gen(model or _model(), _SYSTEM_PROMPT, _user_prompt(query, candidates)),
|
||||
GEMINI_ATTEMPT_TIMEOUT_S)
|
||||
except Exception as e:
|
||||
reason = f"timed out after {GEMINI_ATTEMPT_TIMEOUT_S:g}s" if isinstance(e, asyncio.TimeoutError) else str(e)
|
||||
@@ -192,8 +216,49 @@ async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
|
||||
return _none(query, "unavailable") # pragma: no cover - loop always returns
|
||||
|
||||
|
||||
def _split_like_query(query: str, artist: str, title: str) -> tuple[str, str]:
|
||||
"""The query's own words as (typed_artist, typed_title), given the song it names."""
|
||||
words = query.split()
|
||||
n_artist = len(artist.split())
|
||||
if normalize_for_match(" ".join(words[:n_artist])) == normalize_for_match(artist):
|
||||
return " ".join(words[:n_artist]), " ".join(words[n_artist:])
|
||||
n_title = len(title.split())
|
||||
if normalize_for_match(" ".join(words[:n_title])) == normalize_for_match(title):
|
||||
return " ".join(words[n_title:]), " ".join(words[:n_title])
|
||||
return artist, title
|
||||
|
||||
|
||||
def _spotify_exact(query: str, live: list[dict]) -> Optional[dict]:
|
||||
"""A live result whose artist + title is exactly the query (either order) → its verdict."""
|
||||
typed = normalize_for_match(query)
|
||||
if not typed:
|
||||
return None
|
||||
for c in live:
|
||||
ca, ct = (c.get("artist_name") or "").strip(), (c.get("track_name") or "").strip()
|
||||
if not (ca and ct):
|
||||
continue
|
||||
if typed in (normalize_for_match(f"{ca} {ct}"), normalize_for_match(f"{ct} {ca}")):
|
||||
typed_artist, typed_title = _split_like_query(query, ca, ct)
|
||||
return {
|
||||
"kind": KIND_COSMETIC, "confident": True,
|
||||
"typed_artist": typed_artist, "typed_title": typed_title,
|
||||
"canonical_artist": ca, "canonical_title": ct, "alternatives": [],
|
||||
"engine": "catalog", "reason": "live Spotify match",
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
async def _live_spotify(spotify: SpotifySearch, query: str) -> list[dict]:
|
||||
try:
|
||||
return list(await asyncio.wait_for(spotify(query), SPOTIFY_TIMEOUT_S) or [])
|
||||
except Exception as e: # timeout / decide down: no evidence, carry on as before
|
||||
logger.warning(f"resolve_and_tidy live Spotify search failed: {e!r}")
|
||||
return []
|
||||
|
||||
|
||||
async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
|
||||
judge: Optional[Judge] = None, model: Optional[str] = None) -> dict:
|
||||
judge: Optional[Judge] = None, model: Optional[str] = None,
|
||||
spotify: Optional[SpotifySearch] = None) -> dict:
|
||||
"""Free-text split/correct, then gen's catalog tidy (the job flow's fast pass).
|
||||
|
||||
The AI verdict's song — its canonical pick when confident, else the typed
|
||||
@@ -201,9 +266,17 @@ async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
|
||||
"fast": catalog only, no second AI call). A confident catalog match wins:
|
||||
its formatting becomes the canonical artist/title, kind "cosmetic" when the
|
||||
query already named that song (only casing/punctuation/word order differ),
|
||||
else "content". No catalog match → the AI verdict unchanged. Never raises.
|
||||
else "content". No catalog match → the AI verdict, but a confident answer
|
||||
that live Spotify didn't list either comes back ``confident: False``
|
||||
(grounding rule). A timed-out tidy keeps the AI verdict as "unavailable"
|
||||
(transient, not cached). A live Spotify result that IS the query answers
|
||||
before Gemini runs. Never raises.
|
||||
"""
|
||||
verdict = await resolve_free_text(query, generate=generate, model=model)
|
||||
live = await _live_spotify(spotify or _default_spotify, query)
|
||||
exact = _spotify_exact(query, live)
|
||||
if exact is not None:
|
||||
return exact
|
||||
verdict = await resolve_free_text(query, generate=generate, model=model, candidates=live)
|
||||
kind = verdict.get("kind")
|
||||
if kind in ("cosmetic", "content") and verdict.get("confident"):
|
||||
artist, title = verdict["canonical_artist"], verdict["canonical_title"]
|
||||
@@ -231,6 +304,14 @@ async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
|
||||
return {**verdict, "reason": "unavailable"}
|
||||
if not (cat.confident and cat.engine == "catalog" and cat.kind in (KIND_COSMETIC, KIND_NONE)
|
||||
and cat.canonical_artist and cat.canonical_title):
|
||||
if verdict.get("confident") and kind in ("cosmetic", "content"):
|
||||
from backend.services.match_judge.service import names_song
|
||||
if not names_song(live, artist, title):
|
||||
# Grounding rule: neither the catalogue nor live Spotify has the song the
|
||||
# AI named, so it's a guess. Offer it at most ("Did you mean…?").
|
||||
logger.info(f"resolve_and_tidy: AI answer {artist!r} / {title!r} unconfirmed; not confident")
|
||||
return {**verdict, "confident": False,
|
||||
"reason": f"{verdict.get('reason') or ''} [unconfirmed: not in catalog or Spotify]".strip()}
|
||||
return verdict
|
||||
ca, ct = cat.canonical_artist, cat.canonical_title
|
||||
typed = normalize_for_match(query)
|
||||
@@ -252,6 +333,11 @@ async def _default_judge(artist: str, title: str) -> MatchVerdict:
|
||||
return await judge_match(artist, title, stage="fast")
|
||||
|
||||
|
||||
async def _default_spotify(query: str) -> Optional[list[dict]]:
|
||||
from backend.services.catalog_proxy_service import spotify_search
|
||||
return await spotify_search(query)
|
||||
|
||||
|
||||
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
|
||||
|
||||
|
||||
@@ -3,14 +3,26 @@
|
||||
Composes the deterministic+catalog classifier with the AI judge. The AI judge
|
||||
runs ONLY when the classifier can't confidently decide, and never blocks or
|
||||
errors the caller — any failure degrades to "no suggestion".
|
||||
|
||||
Evidence comes from two places: decide's BigQuery catalogue (a July 2025 Spotify
|
||||
snapshot + MusicBrainz) and, when that can't confirm the typed song, a **live
|
||||
Spotify search** (via decide's partner route). The live search is what knows 2025+
|
||||
releases and small artists.
|
||||
|
||||
**Grounding rule** (2026-11-06, "Cole Phillips – Roll of Dice" became "Roll of the
|
||||
Dice"): a confident AI correction must name a song the catalogue or live Spotify
|
||||
actually has. Otherwise it is downgraded to ``confident=False``, which both clients
|
||||
show as "Did you mean…?" and never apply.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Literal, Optional
|
||||
|
||||
from backend.services.match_judge.classifier import classify_catalog_match
|
||||
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
|
||||
from dataclasses import replace
|
||||
|
||||
from backend.services.match_judge.classifier import classify_catalog_match, normalize_for_match
|
||||
from backend.services.match_judge.verdict import KIND_CONTENT, KIND_COSMETIC, KIND_NONE, MatchVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -25,6 +37,8 @@ WEAK_TIER = 3
|
||||
|
||||
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
|
||||
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
|
||||
# Live Spotify track search: candidate dicts, or None when there's no evidence either way.
|
||||
SpotifySearch = Callable[[str], Awaitable[Optional[list[dict]]]]
|
||||
|
||||
|
||||
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
|
||||
@@ -32,6 +46,72 @@ async def _default_search_tracks(query: str, artist: Optional[str], limit: int)
|
||||
return await search_tracks(query, artist, limit)
|
||||
|
||||
|
||||
async def _default_spotify_search(query: str) -> Optional[list[dict]]:
|
||||
from backend.services.catalog_proxy_service import spotify_search
|
||||
return await spotify_search(query)
|
||||
|
||||
|
||||
async def _safe_spotify(spotify: SpotifySearch, query: str) -> list[dict]:
|
||||
try:
|
||||
return list(await spotify(query) or [])
|
||||
except Exception:
|
||||
logger.warning("match-judge Spotify search failed; continuing without it", exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
def _merge(*groups: list[dict]) -> list[dict]:
|
||||
"""Concatenate candidate lists, dropping repeats of the same artist/title."""
|
||||
seen: set[tuple[str, str]] = set()
|
||||
out: list[dict] = []
|
||||
for group in groups:
|
||||
for c in group:
|
||||
key = (normalize_for_match(c.get("artist_name") or ""), normalize_for_match(c.get("track_name") or ""))
|
||||
if key in seen or not all(key):
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
def _names(candidate: dict) -> list[str]:
|
||||
names = [candidate.get("artist_name") or ""] + list(candidate.get("artist_names") or [])
|
||||
return [n for n in names if n]
|
||||
|
||||
|
||||
def names_song(candidates: list[dict], artist: str, title: str) -> bool:
|
||||
"""True when a candidate is this artist/title, after normalising. Any credited artist counts."""
|
||||
key_artist, key_title = normalize_for_match(artist), normalize_for_match(title)
|
||||
if not key_artist or not key_title:
|
||||
return False
|
||||
return any(
|
||||
normalize_for_match(c.get("track_name") or "") == key_title
|
||||
and any(normalize_for_match(n) == key_artist for n in _names(c))
|
||||
for c in candidates
|
||||
)
|
||||
|
||||
|
||||
async def ground_verdict(
|
||||
verdict: MatchVerdict, candidates: list[dict], spotify: SpotifySearch
|
||||
) -> MatchVerdict:
|
||||
"""Apply the grounding rule to an AI verdict (see module docstring).
|
||||
|
||||
A confident cosmetic/content verdict is kept only when its canonical song is
|
||||
among ``candidates``, or turns up in one live Spotify search for it.
|
||||
"""
|
||||
if not (verdict.confident and verdict.kind in (KIND_COSMETIC, KIND_CONTENT)):
|
||||
return verdict
|
||||
artist, title = verdict.canonical_artist, verdict.canonical_title
|
||||
if names_song(candidates, artist, title):
|
||||
return verdict
|
||||
if names_song(await _safe_spotify(spotify, f"{artist} {title}"), artist, title):
|
||||
return verdict
|
||||
logger.info(
|
||||
f"match-judge: AI suggestion {artist!r} / {title!r} not found in catalog or Spotify; "
|
||||
"downgraded to not confident"
|
||||
)
|
||||
return replace(verdict, confident=False, reason=f"{verdict.reason} [unconfirmed: not in catalog or Spotify]".strip())
|
||||
|
||||
|
||||
async def _default_ai_judge(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> MatchVerdict:
|
||||
@@ -55,6 +135,7 @@ async def judge_match(
|
||||
stage: Stage = "full",
|
||||
search_tracks: Optional[SearchTracks] = None,
|
||||
ai_judge: Optional[AiJudge] = None,
|
||||
spotify_search: Optional[SpotifySearch] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
) -> MatchVerdict:
|
||||
"""Return a :class:`MatchVerdict` for the typed artist/title.
|
||||
@@ -73,6 +154,7 @@ async def judge_match(
|
||||
"""
|
||||
search = search_tracks or _default_search_tracks
|
||||
ai = ai_judge or _default_ai_judge
|
||||
spotify = spotify_search or _default_spotify_search
|
||||
if enabled is None:
|
||||
enabled = _default_enabled()
|
||||
|
||||
@@ -86,6 +168,14 @@ async def judge_match(
|
||||
candidates = []
|
||||
|
||||
catalog_verdict = classify_catalog_match(artist, title, candidates)
|
||||
if catalog_verdict is None:
|
||||
# The snapshot doesn't have it: ask live Spotify. An exact (normalised) hit
|
||||
# confirms the typed song, e.g. "Roll of dice" -> "Roll of Dice".
|
||||
live = await _safe_spotify(spotify, f"{artist} {title}")
|
||||
spotify_verdict = classify_catalog_match(artist, title, live)
|
||||
if spotify_verdict is not None:
|
||||
catalog_verdict = replace(spotify_verdict, reason=f"{spotify_verdict.reason} (live Spotify)")
|
||||
candidates = _merge(candidates, live)
|
||||
|
||||
# Fast pass: catalog only. Never touches the AI layer.
|
||||
if stage == "fast":
|
||||
@@ -115,6 +205,7 @@ async def judge_match(
|
||||
exc_info=True,
|
||||
)
|
||||
return catalog_verdict
|
||||
ai_verdict = await ground_verdict(ai_verdict, candidates, spotify)
|
||||
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
|
||||
return ai_verdict
|
||||
return catalog_verdict
|
||||
@@ -125,7 +216,7 @@ async def judge_match(
|
||||
)
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
ai_verdict = await ai(artist, title, candidates, audio_tier)
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
@@ -139,3 +230,4 @@ async def judge_match(
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
|
||||
)
|
||||
return await ground_verdict(ai_verdict, candidates, spotify)
|
||||
@@ -49,6 +49,30 @@ TimedLine = Tuple[str, Optional[float]]
|
||||
|
||||
_LRC_RE = re.compile(r"\[(\d+):(\d+(?:\.\d+)?)\]")
|
||||
|
||||
# A synced LRCLIB result found under a *cleaned* title is often a different
|
||||
# recording (studio vs "Live From ..."), so its timing is only trusted when the
|
||||
# lengths agree this closely; otherwise its words scroll at a constant pace.
|
||||
CLEAN_TITLE_SYNC_TOLERANCE_S = 4.0
|
||||
|
||||
# Trailing "(...)" / "[...]" groups and " - Live at ..." style suffixes that stop
|
||||
# LRCLIB matching the plain song (kjbox quick_lyrics.clean_title mirrors this).
|
||||
_TRAILING_GROUP_RE = re.compile(r"\s*[\(\[][^\(\)\[\]]*[\)\]]\s*$")
|
||||
_DASH_SUFFIX_RE = re.compile(
|
||||
r"\s+-\s+.*\b(live|version|remaster(ed)?|mix|edit|acoustic|orchestral|session|demo|mono|stereo)\b.*$",
|
||||
re.IGNORECASE)
|
||||
|
||||
|
||||
def clean_title(title: str) -> str:
|
||||
"""'Song (Live From X) [HD]' / 'Song - 2011 Remaster' → 'Song' (never empty)."""
|
||||
t = (title or "").strip()
|
||||
while True:
|
||||
stripped = _TRAILING_GROUP_RE.sub("", t)
|
||||
if stripped == t or not stripped.strip():
|
||||
break
|
||||
t = stripped
|
||||
t = _DASH_SUFFIX_RE.sub("", t)
|
||||
return t.strip() or (title or "").strip()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Lyrics:
|
||||
@@ -151,9 +175,46 @@ def fetch_lrclib_lyrics(
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
logger.warning(f"LRCLIB search failed: {exc}")
|
||||
|
||||
# Decorated titles ("My Song (Orchestral Version Live From X)") rarely match
|
||||
# on LRCLIB: retry once with the plain title. Exact-title plain lyrics still
|
||||
# win over this looser match.
|
||||
cleaned = clean_title(title)
|
||||
if exact_plain is None and cleaned and cleaned.casefold() != (title or "").strip().casefold():
|
||||
exact_plain = _search_cleaned_title(artist, cleaned, duration, timeout, session)
|
||||
|
||||
return exact_plain
|
||||
|
||||
|
||||
def _search_cleaned_title(artist: str, cleaned: str, duration: Optional[float], timeout: float,
|
||||
session: requests.Session) -> Optional[Lyrics]:
|
||||
"""Search LRCLIB with a cleaned title. Synced timing is kept only for a hit
|
||||
whose length matches the audio; any other hit is used as plain lyrics."""
|
||||
try:
|
||||
r = lrclib_client.get(f"{LRCLIB_BASE}/search", {"q": f"{artist} {cleaned}"}, user_agent=USER_AGENT,
|
||||
timeout=timeout, session=session, retry=False)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
hits = [h for h in (r.json() or []) if isinstance(h, dict)]
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
logger.warning(f"LRCLIB cleaned-title search failed: {exc}")
|
||||
return None
|
||||
fallback: Optional[Lyrics] = None
|
||||
for hit in sorted(hits, key=lambda h: 0 if h.get("syncedLyrics") else 1):
|
||||
got = lyrics_from_lrclib_payload(hit)
|
||||
if got is None:
|
||||
continue
|
||||
hit_duration = hit.get("duration")
|
||||
if (got.kind == "synced" and duration and isinstance(hit_duration, (int, float))
|
||||
and abs(hit_duration - duration) <= CLEAN_TITLE_SYNC_TOLERANCE_S):
|
||||
logger.info(f"Quick lyrics: synced match via cleaned title {cleaned!r}")
|
||||
return got
|
||||
if fallback is None and got.plain.strip():
|
||||
fallback = Lyrics("plain", got.plain)
|
||||
if fallback is not None:
|
||||
logger.info(f"Quick lyrics: plain lyrics via cleaned title {cleaned!r} (no length-matched sync)")
|
||||
return fallback
|
||||
|
||||
|
||||
def resolve_timed_lines(lyrics: Optional[Lyrics]) -> Tuple[List[TimedLine], str]:
|
||||
"""Lyrics → (line, anchor|None) pairs + tier label (synced / constant / none)."""
|
||||
if lyrics is None:
|
||||
@@ -326,15 +387,19 @@ def render_quick_video(
|
||||
workdir: str,
|
||||
lyrics: Optional[Lyrics] = None,
|
||||
fetch_lyrics: bool = True,
|
||||
lyrics_artist: Optional[str] = None,
|
||||
lyrics_title: Optional[str] = None,
|
||||
settings: Optional[RenderSettings] = None,
|
||||
ffmpeg_timeout: float = 600.0,
|
||||
) -> RenderResult:
|
||||
"""Render the quick video. ``lyrics`` overrides the LRCLIB fetch."""
|
||||
"""Render the quick video. ``lyrics`` overrides the LRCLIB fetch;
|
||||
``lyrics_artist``/``lyrics_title`` (the job's lyrics-search overrides) are
|
||||
what LRCLIB is searched with, while ``artist``/``title`` are displayed."""
|
||||
s = settings or RenderSettings()
|
||||
duration = probe_duration(instrumental_path)
|
||||
|
||||
if lyrics is None and fetch_lyrics:
|
||||
lyrics = fetch_lrclib_lyrics(artist, title, duration)
|
||||
lyrics = fetch_lrclib_lyrics(lyrics_artist or artist, lyrics_title or title, duration)
|
||||
|
||||
timed_lines, tier = resolve_timed_lines(lyrics)
|
||||
if tier == "synced":
|
||||
|
||||
@@ -29,6 +29,7 @@ from typing import Any, Callable, Dict, Optional, Tuple
|
||||
|
||||
from backend.services.job_notification_service import is_kjbox_job
|
||||
from backend.services.quick_version.renderer import render_quick_video
|
||||
from backend.services.tempo_label import strip_tempo_suffix
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -161,10 +162,13 @@ class QuickVersionRender:
|
||||
|
||||
def __init__(self, job_id: str, artist: str, title: str, instrumental: str, vocals: Optional[str],
|
||||
workdir: str, job_manager: Any, storage: Any, job_log: Any = None,
|
||||
started_monotonic: Optional[float] = None, separation_seconds: Optional[float] = None):
|
||||
started_monotonic: Optional[float] = None, separation_seconds: Optional[float] = None,
|
||||
lyrics_artist: Optional[str] = None, lyrics_title: Optional[str] = None):
|
||||
self.job_id = job_id
|
||||
self.artist = artist or "Unknown"
|
||||
self.title = title or "Unknown"
|
||||
self.lyrics_artist = lyrics_artist
|
||||
self.lyrics_title = lyrics_title
|
||||
self.instrumental = instrumental
|
||||
self.vocals = vocals
|
||||
self.workdir = workdir
|
||||
@@ -195,6 +199,7 @@ class QuickVersionRender:
|
||||
result = render_quick_video(
|
||||
instrumental_path=self.instrumental, vocals_path=self.vocals,
|
||||
artist=self.artist, title=self.title, out_path=out_path, workdir=render_dir,
|
||||
lyrics_artist=self.lyrics_artist, lyrics_title=self.lyrics_title,
|
||||
)
|
||||
render_seconds = time.monotonic() - t0
|
||||
gcs_path = f"jobs/{self.job_id}/quick/quick.mp4"
|
||||
@@ -259,6 +264,9 @@ def start_quick_version(
|
||||
return QuickVersionRender(
|
||||
job_id, job.artist, job.title, inst, vocals, workdir, job_manager, storage, job_log,
|
||||
started_monotonic=started, separation_seconds=sep_seconds,
|
||||
# Same lyrics-search names the review page uses (never a tempo label).
|
||||
lyrics_artist=getattr(job, "lyrics_artist", None) or job.artist,
|
||||
lyrics_title=getattr(job, "lyrics_title", None) or strip_tempo_suffix(job.title),
|
||||
).start()
|
||||
except Exception as exc:
|
||||
logger.warning(f"[job:{job_id}] Quick version skipped after error (non-fatal): {exc}", exc_info=True)
|
||||
|
||||
@@ -26,6 +26,22 @@ def _ai_never(*_a, **_k):
|
||||
raise AssertionError("AI judge must not be called")
|
||||
|
||||
|
||||
def _spotify(*pairs, calls=None):
|
||||
async def _search(query):
|
||||
if calls is not None:
|
||||
calls.append(query)
|
||||
return [{"artist_name": a, "track_name": t} for a, t in pairs]
|
||||
return _search
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_live_spotify(monkeypatch):
|
||||
"""Tests that don't inject a Spotify search get "no evidence" (never the network)."""
|
||||
async def none(query):
|
||||
return None
|
||||
monkeypatch.setattr("backend.services.match_judge.service._default_spotify_search", none)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_cosmetic_match_skips_ai():
|
||||
calls = {"ai": 0}
|
||||
@@ -68,12 +84,17 @@ async def test_no_catalog_match_calls_ai():
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=ai,
|
||||
spotify_search=_spotify(("Queen", "Bohemian Rhapsody")),
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.engine == "ai"
|
||||
assert verdict.confident is True # grounded: live Spotify lists the AI's song
|
||||
assert seen["tier"] == 3
|
||||
assert seen["candidates"] == [{"artist_name": "Queen", "track_name": "Radio Ga Ga"}]
|
||||
assert seen["candidates"] == [
|
||||
{"artist_name": "Queen", "track_name": "Radio Ga Ga"},
|
||||
{"artist_name": "Queen", "track_name": "Bohemian Rhapsody"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -165,7 +186,7 @@ async def test_weak_tier_catalog_match_is_verified_and_overridden_by_ai():
|
||||
verdict = await judge_match(
|
||||
"Queen", "Bohemian Rapsody",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody"), ("Queen", "Bohemian Rhapsody")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
@@ -174,6 +195,23 @@ async def test_weak_tier_catalog_match_is_verified_and_overridden_by_ai():
|
||||
assert verdict.engine == "ai"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_unconfirmed_ai_override_keeps_catalog_verdict():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_CONTENT, True, "Queen", "Bohemian Rhapsody", engine="ai")
|
||||
|
||||
verdict = await judge_match(
|
||||
"Queen", "Bohemian Rapsody",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
|
||||
ai_judge=ai,
|
||||
spotify_search=_spotify(),
|
||||
enabled=True,
|
||||
)
|
||||
# The AI's song is in neither source, so it can't override the catalog match.
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strong_tier_catalog_match_still_skips_ai():
|
||||
verdict = await judge_match(
|
||||
@@ -270,3 +308,128 @@ async def test_catalog_search_failure_still_lets_ai_run():
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.engine == "ai"
|
||||
|
||||
|
||||
# --- Live Spotify + grounding (2026-11-06: "Cole Phillips – Roll of Dice" became "Roll of the Dice") ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stage", ["fast", "full"])
|
||||
async def test_live_spotify_confirms_typed_song_missing_from_catalog(stage):
|
||||
calls = []
|
||||
verdict = await judge_match(
|
||||
"Cole Phillips", "Roll of dice",
|
||||
audio_tier=2, stage=stage,
|
||||
search_tracks=_candidates(), # the July 2025 snapshot doesn't have it
|
||||
spotify_search=_spotify(("Cole Phillips", "Roll of Dice"), ("Bruce Springsteen", "Roll of the Dice"),
|
||||
calls=calls),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC and verdict.confident is True
|
||||
assert (verdict.canonical_artist, verdict.canonical_title) == ("Cole Phillips", "Roll of Dice")
|
||||
assert verdict.engine == "catalog" and "live Spotify" in verdict.reason
|
||||
assert verdict.needs_ai is False
|
||||
assert calls == ["Cole Phillips Roll of dice"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_hit_never_calls_spotify():
|
||||
calls = []
|
||||
await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
spotify_search=_spotify(calls=calls), ai_judge=_ai_never, enabled=True,
|
||||
)
|
||||
assert calls == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unconfirmed_ai_correction_is_downgraded():
|
||||
"""The incident: no source has the song the AI named, so it must not be applied."""
|
||||
calls = []
|
||||
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_CONTENT, True, "Cole Phillips", "Roll of the Dice", engine="ai", reason="typo")
|
||||
|
||||
verdict = await judge_match(
|
||||
"Cole Phillips", "Roll of dice",
|
||||
audio_tier=2,
|
||||
search_tracks=_candidates(),
|
||||
spotify_search=_spotify(("Bruce Springsteen", "Roll of the Dice"), calls=calls),
|
||||
ai_judge=ai, enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT and verdict.confident is False
|
||||
assert verdict.canonical_title == "Roll of the Dice" # still offered as "Did you mean…?"
|
||||
assert "unconfirmed" in verdict.reason
|
||||
# One search for what was typed, one for the AI's song.
|
||||
assert calls == ["Cole Phillips Roll of dice", "Cole Phillips Roll of the Dice"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_correction_confirmed_by_second_spotify_lookup():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_CONTENT, True, "The Strokes", "Machu Picchu", engine="ai")
|
||||
|
||||
async def spotify(query):
|
||||
return [{"artist_name": "The Strokes", "track_name": "Machu Picchu"}] if "Machu" in query else []
|
||||
|
||||
verdict = await judge_match(
|
||||
"the stokes", "max picu", audio_tier=3,
|
||||
search_tracks=_candidates(), spotify_search=spotify, ai_judge=ai, enabled=True,
|
||||
)
|
||||
assert verdict.confident is True and verdict.canonical_title == "Machu Picchu"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_grounding_accepts_any_credited_artist():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_CONTENT, True, "Sean Paul", "Breathe", engine="ai")
|
||||
|
||||
async def spotify(query):
|
||||
return [{"artist_name": "Blu Cantrell", "artist_names": ["Blu Cantrell", "Sean Paul"],
|
||||
"track_name": "Breathe"}]
|
||||
|
||||
verdict = await judge_match(
|
||||
"sean pual", "breath", audio_tier=3,
|
||||
search_tracks=_candidates(), spotify_search=spotify, ai_judge=ai, enabled=True,
|
||||
)
|
||||
assert verdict.confident is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spotify_unavailable_or_failing_means_no_evidence():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_CONTENT, True, "Queen", "Bohemian Rhapsody", engine="ai")
|
||||
|
||||
async def broken(query):
|
||||
raise RuntimeError("decide down")
|
||||
|
||||
for spotify in (broken, None):
|
||||
verdict = await judge_match(
|
||||
"queen", "bohemian rapsody", audio_tier=3,
|
||||
search_tracks=_candidates(), spotify_search=spotify, ai_judge=ai, enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT and verdict.confident is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ambiguous_and_none_ai_verdicts_are_not_grounded():
|
||||
calls = []
|
||||
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_AMBIGUOUS, True, artist, title,
|
||||
alternatives=[{"artist": "A", "title": "T"}], engine="ai")
|
||||
|
||||
verdict = await judge_match(
|
||||
"x", "y", search_tracks=_candidates(), spotify_search=_spotify(calls=calls), ai_judge=ai, enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_AMBIGUOUS and verdict.confident is True
|
||||
assert calls == ["x y"] # only the typed-song lookup
|
||||
|
||||
|
||||
def test_merge_drops_repeats_and_blanks():
|
||||
from backend.services.match_judge.service import _merge
|
||||
a = [{"artist_name": "Queen", "track_name": "Radio Ga Ga"}, {"artist_name": "", "track_name": "x"}]
|
||||
b = [{"artist_name": "queen", "track_name": "radio ga ga!"}, {"artist_name": "Queen", "track_name": "Innuendo"}]
|
||||
assert [c["track_name"] for c in _merge(a, b)] == ["Radio Ga Ga", "Innuendo"]
|
||||
@@ -0,0 +1,81 @@
|
||||
"""catalog_proxy_service.spotify_search: gen -> decide's partner Spotify search."""
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from backend.services import catalog_proxy_service as proxy
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean(monkeypatch):
|
||||
proxy._cache.clear()
|
||||
monkeypatch.setattr(proxy.settings, "decide_partner_secret", "s3cret", raising=False)
|
||||
monkeypatch.setattr(proxy.settings, "karaoke_decide_api_url", "https://decide.test", raising=False)
|
||||
yield
|
||||
proxy._cache.clear()
|
||||
|
||||
|
||||
def _mock(monkeypatch, handler):
|
||||
real = httpx.AsyncClient
|
||||
seen = []
|
||||
|
||||
def wrapped(request):
|
||||
seen.append(request)
|
||||
return handler(request)
|
||||
|
||||
monkeypatch.setattr(proxy.httpx, "AsyncClient",
|
||||
lambda **kw: real(transport=httpx.MockTransport(wrapped), **kw))
|
||||
return seen
|
||||
|
||||
|
||||
_BODY = {"available": True, "tracks": [{"artist_name": "Cole Phillips", "track_name": "Roll of Dice"}]}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sends_secret_and_returns_tracks(monkeypatch):
|
||||
seen = _mock(monkeypatch, lambda r: httpx.Response(200, json=_BODY))
|
||||
tracks = await proxy.spotify_search(" Cole Phillips Roll of dice ")
|
||||
assert tracks == _BODY["tracks"]
|
||||
req = seen[0]
|
||||
assert req.url.path == "/api/partner/gen/spotify-search"
|
||||
assert req.url.params["q"] == "Cole Phillips Roll of dice"
|
||||
assert req.url.params["limit"] == "10"
|
||||
assert req.headers["X-Partner-Secret"] == "s3cret"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_results_are_cached(monkeypatch):
|
||||
seen = _mock(monkeypatch, lambda r: httpx.Response(200, json=_BODY))
|
||||
await proxy.spotify_search("Cole Phillips Roll of dice")
|
||||
await proxy.spotify_search("cole phillips roll of dice")
|
||||
assert len(seen) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("response", [
|
||||
httpx.Response(200, json={"available": False, "tracks": []}), # decide's breaker open
|
||||
httpx.Response(401, json={"detail": "partner_auth"}),
|
||||
httpx.Response(503, json={"detail": "partner_disabled"}),
|
||||
httpx.Response(200, json=["not", "a", "dict"]),
|
||||
])
|
||||
async def test_no_evidence_is_none_and_not_cached(monkeypatch, response):
|
||||
seen = _mock(monkeypatch, lambda r: response)
|
||||
assert await proxy.spotify_search("some song") is None
|
||||
assert await proxy.spotify_search("some song") is None
|
||||
assert len(seen) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_network_error_is_none(monkeypatch):
|
||||
def boom(request):
|
||||
raise httpx.ConnectError("down", request=request)
|
||||
_mock(monkeypatch, boom)
|
||||
assert await proxy.spotify_search("some song") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_secret_or_short_query_skips_the_call(monkeypatch):
|
||||
seen = _mock(monkeypatch, lambda r: httpx.Response(200, json=_BODY))
|
||||
assert await proxy.spotify_search("x") is None
|
||||
monkeypatch.setattr(proxy.settings, "decide_partner_secret", "", raising=False)
|
||||
assert await proxy.spotify_search("some song") is None
|
||||
assert seen == []
|
||||
@@ -53,11 +53,18 @@ def test_ambiguous_keeps_up_to_four_alternatives():
|
||||
assert v["kind"] == "ambiguous" and len(v["alternatives"]) == 4
|
||||
|
||||
|
||||
async def _no_spotify(q):
|
||||
return None
|
||||
|
||||
|
||||
# ---- resolve_and_tidy: AI split → the job flow's judge_match catalog pass
|
||||
|
||||
def _tidy(query, ai, judge_result=None, judge_exc=None):
|
||||
def _tidy(query, ai, judge_result=None, judge_exc=None, live=None):
|
||||
seen = []
|
||||
|
||||
async def spotify(q):
|
||||
return live
|
||||
|
||||
async def gen(model, system_prompt, user_prompt):
|
||||
return ai
|
||||
|
||||
@@ -66,7 +73,7 @@ def _tidy(query, ai, judge_result=None, judge_exc=None):
|
||||
if judge_exc:
|
||||
raise judge_exc
|
||||
return judge_result
|
||||
v = asyncio.run(resolve_and_tidy(query, generate=gen, judge=judge, model="m"))
|
||||
v = asyncio.run(resolve_and_tidy(query, generate=gen, judge=judge, model="m", spotify=spotify))
|
||||
return v, seen
|
||||
|
||||
|
||||
@@ -125,6 +132,87 @@ def test_no_catalog_match_keeps_ai_verdict(judge_result, judge_exc):
|
||||
assert v["engine"] == "ai" and v["canonical_title"] == "Push Up on Me"
|
||||
# A failed catalog pass is transient — the route must not cache it.
|
||||
assert (v["reason"] == "unavailable") is (judge_exc is not None)
|
||||
# Grounding: a check that ran and found nothing makes the AI answer unconfirmed;
|
||||
# a check that never ran (decide down) leaves it as it was.
|
||||
assert v["confident"] is (judge_exc is not None)
|
||||
|
||||
|
||||
# ---- live Spotify (2026-11-06: "Cole Phillips – Roll of Dice" became "Roll of the Dice")
|
||||
|
||||
_COLE = [{"artist_name": "Cole Phillips", "track_name": "Roll of Dice"},
|
||||
{"artist_name": "Bruce Springsteen", "track_name": "Roll of the Dice"}]
|
||||
|
||||
|
||||
def test_live_spotify_exact_answers_without_gemini():
|
||||
v, seen = _tidy("Roll of dice Cole Phillips", None, live=_COLE) # ai=None: Gemini must not matter
|
||||
assert v["kind"] == "cosmetic" and v["confident"] is True and v["engine"] == "catalog"
|
||||
assert (v["canonical_artist"], v["canonical_title"]) == ("Cole Phillips", "Roll of Dice")
|
||||
assert (v["typed_artist"], v["typed_title"]) == ("Cole Phillips", "Roll of dice")
|
||||
assert seen == []
|
||||
|
||||
|
||||
def test_live_spotify_exact_artist_first():
|
||||
v, _ = _tidy("cole phillips roll of dice", None, live=_COLE)
|
||||
assert (v["typed_artist"], v["typed_title"]) == ("cole phillips", "roll of dice")
|
||||
assert v["canonical_title"] == "Roll of Dice"
|
||||
|
||||
|
||||
def test_unconfirmed_ai_correction_is_not_confident():
|
||||
"""The incident: Gemini 'corrects' to a more familiar title no source has for this artist."""
|
||||
ai = {"kind": "content", "confident": True, "typed_artist": "Cole Philips",
|
||||
"typed_title": "Roll of dice", "canonical_artist": "Cole Phillips",
|
||||
"canonical_title": "Roll of the Dice"}
|
||||
inconclusive = MatchVerdict("none", False, "Cole Phillips", "Roll of the Dice",
|
||||
engine="catalog", needs_ai=True)
|
||||
v, _ = _tidy("Roll of dice Cole Philips", ai, inconclusive, live=[])
|
||||
assert v["kind"] == "content" and v["confident"] is False
|
||||
assert "unconfirmed" in v["reason"]
|
||||
|
||||
|
||||
def test_ai_pick_from_live_results_is_kept():
|
||||
ai = {"kind": "content", "confident": True, "typed_artist": "Cole Philips",
|
||||
"typed_title": "Roll of dice", "canonical_artist": "Cole Phillips",
|
||||
"canonical_title": "Roll of Dice"}
|
||||
inconclusive = MatchVerdict("none", False, "Cole Phillips", "Roll of Dice",
|
||||
engine="catalog", needs_ai=True)
|
||||
v, _ = _tidy("Roll of dice Cole Philips", ai, inconclusive, live=_COLE)
|
||||
assert v["confident"] is True and v["canonical_title"] == "Roll of Dice"
|
||||
|
||||
|
||||
def test_live_results_are_handed_to_gemini():
|
||||
prompts = []
|
||||
|
||||
async def gen(model, system_prompt, user_prompt):
|
||||
prompts.append(user_prompt)
|
||||
return {"kind": "none", "confident": False}
|
||||
|
||||
async def spotify(q):
|
||||
return _COLE
|
||||
|
||||
asyncio.run(resolve_and_tidy("Roll of dice Cole Philips", generate=gen, model="m", spotify=spotify))
|
||||
assert "Live Spotify search results" in prompts[0]
|
||||
assert "- Cole Phillips — Roll of Dice" in prompts[0]
|
||||
|
||||
|
||||
def test_live_spotify_failure_falls_back_to_gemini(monkeypatch):
|
||||
import backend.services.match_judge.free_text as ft
|
||||
monkeypatch.setattr(ft, "SPOTIFY_TIMEOUT_S", 0.05)
|
||||
prompts = []
|
||||
|
||||
async def gen(model, system_prompt, user_prompt):
|
||||
prompts.append(user_prompt)
|
||||
return {"kind": "none", "confident": False}
|
||||
|
||||
async def slow(q):
|
||||
await asyncio.sleep(1)
|
||||
|
||||
async def broken(q):
|
||||
raise RuntimeError("decide down")
|
||||
|
||||
for spotify in (slow, broken):
|
||||
v = asyncio.run(resolve_and_tidy("some query", generate=gen, model="m", spotify=spotify))
|
||||
assert v["kind"] == "none"
|
||||
assert prompts == ['Singer typed: "some query"'] * 2
|
||||
|
||||
|
||||
def test_ambiguous_and_failures_skip_the_catalog():
|
||||
@@ -208,7 +296,8 @@ def test_slow_catalog_tidy_answers_with_ai_verdict_and_keeps_searching(monkeypat
|
||||
return MatchVerdict("cosmetic", True, "Céline Dion", "My Heart Will Go On", engine="catalog")
|
||||
|
||||
async def main():
|
||||
v = await resolve_and_tidy("song from titanic", generate=gen, judge=judge, model="m")
|
||||
v = await resolve_and_tidy("song from titanic", generate=gen, judge=judge, model="m",
|
||||
spotify=_no_spotify)
|
||||
assert finished == [] # answered before the catalog search finished
|
||||
await asyncio.sleep(0.3) # ...which kept running in the background
|
||||
return v
|
||||
|
||||
@@ -12,6 +12,20 @@ from backend.services.quick_version import renderer as r
|
||||
from backend.services.quick_version import service as qs
|
||||
|
||||
|
||||
class TestCleanTitle:
|
||||
@pytest.mark.parametrize("raw,clean", [
|
||||
("My Body Isn't Ready (Orchestral Version Live From Sound City)", "My Body Isn't Ready"),
|
||||
("Creep (Acoustic) [Remastered 2009]", "Creep"),
|
||||
("Song - Live at Wembley", "Song"),
|
||||
("Song - 2011 Remaster", "Song"),
|
||||
("Rock - Paper - Scissors", "Rock - Paper - Scissors"),
|
||||
("(Intro)", "(Intro)"),
|
||||
("", ""),
|
||||
])
|
||||
def test_clean_title(self, raw, clean):
|
||||
assert r.clean_title(raw) == clean
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Lyrics parsing / tiers
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -70,6 +84,56 @@ class TestFetchLrclib:
|
||||
got = r.fetch_lrclib_lyrics("A", "T", None)
|
||||
assert got.kind == "plain" and got.plain == "plain words"
|
||||
|
||||
def test_decorated_title_retries_cleaned_with_length_matched_sync(self):
|
||||
sess = self._session([
|
||||
_resp(404, {}),
|
||||
_resp(200, []),
|
||||
_resp(200, [
|
||||
{"syncedLyrics": "[00:01.00]studio", "duration": 217},
|
||||
{"syncedLyrics": "[00:02.00]live", "duration": 223},
|
||||
]),
|
||||
])
|
||||
with patch.object(r.requests, "Session", return_value=sess):
|
||||
got = r.fetch_lrclib_lyrics("Sombr", "My Body Isn't Ready (Orchestral Version Live From X)", 224.5)
|
||||
assert got.kind == "synced" and got.timed == [(2.0, "live")]
|
||||
assert sess.get.call_args.kwargs["params"] == {"q": "Sombr My Body Isn't Ready"}
|
||||
|
||||
def test_cleaned_title_sync_with_wrong_length_becomes_plain(self):
|
||||
sess = self._session([
|
||||
_resp(404, {}),
|
||||
_resp(200, []),
|
||||
_resp(200, [{"syncedLyrics": "[00:01.00]a\n[00:02.00]b", "duration": 180}]),
|
||||
])
|
||||
with patch.object(r.requests, "Session", return_value=sess):
|
||||
got = r.fetch_lrclib_lyrics("A", "Song (Live)", 224.5)
|
||||
assert got.kind == "plain" and got.plain == "a\nb" and got.timed is None
|
||||
|
||||
def test_cleaned_title_without_duration_never_trusts_sync(self):
|
||||
sess = self._session([_resp(404, {}), _resp(200, []),
|
||||
_resp(200, [{"syncedLyrics": "[00:01.00]a", "duration": 200}])])
|
||||
with patch.object(r.requests, "Session", return_value=sess):
|
||||
assert r.fetch_lrclib_lyrics("A", "Song (Live)", None).kind == "plain"
|
||||
|
||||
def test_exact_plain_beats_cleaned_retry(self):
|
||||
sess = self._session([_resp(200, {"plainLyrics": "exact"}), _resp(200, [])])
|
||||
with patch.object(r.requests, "Session", return_value=sess):
|
||||
got = r.fetch_lrclib_lyrics("A", "Song (Live)", 200)
|
||||
assert got.plain == "exact" and sess.get.call_count == 2
|
||||
|
||||
def test_cleaned_retry_failures_return_none(self):
|
||||
err = r.requests.RequestException("down")
|
||||
for third in (err, _resp(500, {}), _resp(200, [{"plainLyrics": " "}, "junk"])):
|
||||
sess = self._session([_resp(404, {}), _resp(200, []), third])
|
||||
with patch.object(r.requests, "Session", return_value=sess):
|
||||
assert r.fetch_lrclib_lyrics("A", "Song (Live)", 200) is None
|
||||
assert sess.get.call_count == 3
|
||||
|
||||
def test_undecorated_title_does_not_retry(self):
|
||||
sess = self._session([_resp(404, {}), _resp(200, [])])
|
||||
with patch.object(r.requests, "Session", return_value=sess):
|
||||
assert r.fetch_lrclib_lyrics("A", "Song", 200) is None
|
||||
assert sess.get.call_count == 2
|
||||
|
||||
def test_network_errors_return_none(self):
|
||||
err = r.requests.RequestException("down")
|
||||
sess = self._session([err, err])
|
||||
@@ -289,6 +353,30 @@ class TestStartQuickVersion:
|
||||
ready = jm.update_state_data.call_args_list[-1].args[2]
|
||||
assert ready["lyrics_tier"] == "synced" and ready["line_count"] == 42 and "ready_at" in ready
|
||||
|
||||
@pytest.mark.parametrize("overrides,expected", [
|
||||
({}, ("Artist", "Song")),
|
||||
({"title": "Song (90% Tempo)"}, ("Artist", "Song")),
|
||||
({"lyrics_artist": "LA", "lyrics_title": "LT"}, ("LA", "LT")),
|
||||
])
|
||||
def test_lyrics_search_names(self, tmp_path, overrides, expected):
|
||||
seen = {}
|
||||
|
||||
def fake_render(**kw):
|
||||
seen.update(kw)
|
||||
open(kw["out_path"], "wb").write(b"x")
|
||||
return r.RenderResult(kw["out_path"], "synced", 1, 1.0)
|
||||
|
||||
job = _job()
|
||||
job.artist, job.title = "Artist", "Song"
|
||||
for k, v in overrides.items():
|
||||
setattr(job, k, v)
|
||||
with patch.object(qs, "render_quick_video", side_effect=fake_render):
|
||||
run = qs.start_quick_version(job, "a.flac", str(tmp_path), "/m", Mock(), Mock(),
|
||||
separator_factory=_FakeSeparator)
|
||||
assert run.join(10)
|
||||
assert (seen["lyrics_artist"], seen["lyrics_title"]) == expected
|
||||
assert seen["title"] == job.title # display title untouched
|
||||
|
||||
def test_separation_failure_is_non_fatal(self, tmp_path):
|
||||
jm = Mock()
|
||||
|
||||
|
||||
+25
-1
@@ -1093,6 +1093,22 @@ the AI layer with `MATCH_JUDGE_ENABLED=false` (deterministic+catalog still run).
|
||||
> is designing an on-device typo-tolerant matcher that uses Gemini only as a fallback. Read
|
||||
> `kjbox/docs/SONG-IDENTIFICATION.md` before reusing this judge for free-text search.
|
||||
|
||||
**Live Spotify + grounding (v0.294.0).** When the catalogue can't confirm the typed song, the judge
|
||||
(both stages) runs a live Spotify search through decide's partner route
|
||||
(`GET /api/partner/gen/spotify-search`, `X-Partner-Secret`, via
|
||||
`catalog_proxy_service.spotify_search`). The catalogue is a July 2025 snapshot, so new releases are
|
||||
missing from it.
|
||||
- An exact match after normalisation is a confident `catalog` verdict with reason
|
||||
"… (live Spotify)" and **no Gemini call**. Example: "Cole Phillips" / "Roll of dice" → "Roll of Dice".
|
||||
- Gemini also gets the Spotify results as candidates.
|
||||
- **Grounding rule:** a confident AI `cosmetic` / `content` verdict must name a song that is in the
|
||||
candidates or in one more Spotify lookup of the AI's song. Otherwise it comes back
|
||||
`confident: false` with reason "… [unconfirmed: not in catalog or Spotify]". Clients show that as
|
||||
"Did you mean…?" and never apply it.
|
||||
- Every live result is kept forever by decide (Firestore query cache + BigQuery `spotify_live_tracks`), and kn-data-sync adds those songs to the daily song-id export. So a song looked up once is known to the kjbox on-device matcher, decide's song search and the mobile app's offline index from the next build on (v0.294.2).
|
||||
- Spotify unavailable means no evidence, so AI corrections aren't confident. That is conservative on
|
||||
purpose. Incident: kjbox 2026-11-05, job `f01c9997`, "Roll of Dice" became "Roll of the Dice".
|
||||
|
||||
`stage` (optional, `"fast"` | `"full"`, default `"full"`) supports a two-call
|
||||
pattern the frontend uses to keep the tidy off the critical path:
|
||||
|
||||
@@ -3461,7 +3477,15 @@ AudioSourceStep ("Tidied to …" / "Corrected to …"). Two steps
|
||||
`judge_match(stage="fast")`. A confident catalog match wins: its formatting
|
||||
becomes `canonical_*`, `engine: "catalog"`, kind `cosmetic` when the query
|
||||
already named that song (only casing/punctuation/word order differ), else
|
||||
`content`. No catalog match → the AI verdict unchanged.
|
||||
`content`. No catalog match → the AI verdict, but a confident answer that neither the
|
||||
catalogue nor live Spotify confirms comes back `confident: false` (grounding rule, above).
|
||||
A tidy that timed out keeps the AI verdict with reason `unavailable` (not cached).
|
||||
|
||||
**Step 0 (v0.294.0): live Spotify.** Before Gemini, the raw query goes to live Spotify (3 s cap).
|
||||
A result whose artist + title *is* the query (either order, after normalising) is answered
|
||||
directly: `cosmetic`, `engine: "catalog"`, reason `live Spotify match`. Otherwise the results go to
|
||||
Gemini as candidates ("use the listed song's exact artist and title; never 'correct' to a more
|
||||
familiar title").
|
||||
|
||||
kind `none` keeps the AI's `typed_artist`/`typed_title` split when it has one
|
||||
(kjbox pre-fills its make-it form with it). kjbox calls this only when its own
|
||||
|
||||
@@ -827,6 +827,13 @@ full NOMAD version. Code: `backend/services/quick_version/` (a port of kjbox `fa
|
||||
crawl PNG + one ffmpeg `overlay` pass, 854×480, vocals mixed back in at 30% as a guide. Every
|
||||
ffmpeg input and the output are bounded with `-t <duration>`: the GPU image's ffmpeg 4.4 never
|
||||
ends on `-shortest` alone once `amix` is involved (first prod job ran into the 300 s join timeout).
|
||||
LRCLIB is searched with the job's `lyrics_artist`/`lyrics_title` overrides (else artist + title
|
||||
without a tempo label). If the exact title finds nothing, it retries once with the title's
|
||||
decorations stripped (`clean_title`: trailing `(…)`/`[…]`, `- Live …`/`- Remaster` suffixes). A
|
||||
synced hit from that retry keeps its timing only when its length is within 4 s of the audio
|
||||
(otherwise it is likely another recording, e.g. studio vs live), and anything else becomes a constant
|
||||
crawl. Added after a "… (Orchestral Version Live From Sound City)" draft rendered with no lyrics
|
||||
(2026-11-06). kjbox can also add lyrics to a lyric-less draft on the box (kjbox v0.150.0).
|
||||
3. Uploads `jobs/{id}/quick/quick.mp4` → `file_urls.quick.video_mp4`, and records
|
||||
`state_data.quick_version = {status: separating|rendering|ready|failed, lyrics_tier, ready_at, …}`.
|
||||
4. The worker joins the render (≤300 s) before cleaning up its temp dir — even when the ensemble
|
||||
|
||||
@@ -96,9 +96,10 @@ Notifications are sent when:
|
||||
| Variable | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
|
||||
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
|
||||
| `NOTIFY_ON_SUCCESS` | `false` (prod) | Send an "all clear" email on every clean run; off in prod because the post-job trigger runs after every job |
|
||||
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
|
||||
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
|
||||
| `IN_FLIGHT_GRACE_MINUTES` | `30` (default) | Tracks with any file created in Drive this recently count as still uploading and are left out of the gap check |
|
||||
|
||||
### Secrets (Cloud Function)
|
||||
|
||||
@@ -202,6 +203,16 @@ The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-q
|
||||
|
||||
**IMPORTANT: Never add new entries to `KNOWN_GAPS`.** The existing known gaps are historical (pre-generator era, over a year old). Every new gap is a real bug that must be investigated and fixed.
|
||||
|
||||
**Tracks still uploading are not gaps.** A job's packaging step uploads MP4, then
|
||||
MP4-720p, then CDG over ~2 minutes, and another job's post-job trigger can run in that
|
||||
window. On 2026-11-07 NOMAD-1871's check ran at 12:24:47 UTC while NOMAD-1872 was
|
||||
uploading (12:23:39–12:25:40) and emailed "CDG/MP4-720p: missing 1872"; the files were
|
||||
all there a minute later. Since then the validator reads each file's Drive `createdTime`
|
||||
and leaves out of the gap check any track with a file created in the last
|
||||
`IN_FLIGHT_GRACE_MINUTES` (30). That track is still checked by its own post-job trigger
|
||||
(which names its `brand_code`) and by the daily 9 PM run. If you get a gap alert for the
|
||||
newest track, first check whether that job was in `packaging` at the alert time.
|
||||
|
||||
**Investigation steps:**
|
||||
|
||||
1. **Identify the missing brand code(s)** from the alert (e.g., "MP4: missing 1295")
|
||||
|
||||
@@ -6,6 +6,23 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## An AI "correction" nothing can confirm is a guess: ground it in real data (Nov 2026, v0.294.0)
|
||||
|
||||
At a live kjbox night a singer typed "Cole Phillips – Roll of Dice", a 2025 release missing from the
|
||||
July 2025 Spotify snapshot, from MusicBrainz and from KaraokeNerds. Gemini "corrected" it to the
|
||||
more familiar phrase "Roll of the Dice", and `resolve_and_tidy` shipped that as confident:
|
||||
"No catalog match → AI verdict unchanged". After the singer tapped "keep what I typed", the make
|
||||
wizard's full judge did it again. The job came out titled wrong (`f01c9997`) even though the audio
|
||||
search had found the real track on Spotify at score 1.0.
|
||||
|
||||
The LLM is weakest exactly where our data is thinnest: new releases and small artists. So silence
|
||||
from the catalogue is not evidence for the AI's answer. Fix: a live Spotify search (decide partner
|
||||
route, client-credentials, cached, 429 circuit breaker) confirms the typed song before Gemini. Any
|
||||
AI correction must name a song the catalogue or Spotify actually has, otherwise it is
|
||||
`confident: false` (offered, never applied). When a real data source is cheap and fresh, ask it
|
||||
before asking a model, and check what the model says against it.
|
||||
|
||||
## A lazy import on the loop can stall it for 15s: the image had no precompiled bytecode (Oct 2026, v0.282.1)
|
||||
|
||||
The hourly `process-stale-reviews` cron stalled the API loop 10–15s, 4 times in 2 days. The culprit was `internal.py:670`: a lazy `from backend.services.conversion_emails import ...` inside an `async def`. The stall stack ended in `importlib … _write_atomic`. The backend Dockerfile never ran `compileall`, so the first import on each instance compiled the module and wrote a `.pyc` on the event loop, on a CPU-throttled instance.
|
||||
|
||||
@@ -1835,7 +1835,7 @@ function AdminJobsPageContent() {
|
||||
{/* YouTube */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.youtube.status === "deleted"
|
||||
deleteOutputsResult.deleted_services.youtube.status === "success"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.youtube.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
@@ -1844,7 +1844,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">YouTube</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "deleted" && (
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "success" && (
|
||||
<>Deleted video: <code className="text-xs bg-muted px-1 rounded">{deleteOutputsResult.deleted_services.youtube.video_id}</code></>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "skipped" && (
|
||||
@@ -1853,6 +1853,9 @@ function AdminJobsPageContent() {
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "error" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.youtube.error}</span>
|
||||
)}
|
||||
{(deleteOutputsResult.deleted_services.youtube.status === "failed" || deleteOutputsResult.deleted_services.youtube.status === "partial") && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.youtube.reason || deleteOutputsResult.deleted_services.youtube.error || "Delete failed, check the job logs"}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1860,7 +1863,7 @@ function AdminJobsPageContent() {
|
||||
{/* Dropbox */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.dropbox.status === "deleted"
|
||||
deleteOutputsResult.deleted_services.dropbox.status === "success"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.dropbox.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
@@ -1869,7 +1872,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">Dropbox</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "deleted" && (
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "success" && (
|
||||
<>Deleted folder: <code className="text-xs bg-muted px-1 rounded break-all">{deleteOutputsResult.deleted_services.dropbox.path}</code></>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "skipped" && (
|
||||
@@ -1878,6 +1881,9 @@ function AdminJobsPageContent() {
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "error" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.dropbox.error}</span>
|
||||
)}
|
||||
{(deleteOutputsResult.deleted_services.dropbox.status === "failed" || deleteOutputsResult.deleted_services.dropbox.status === "partial") && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.dropbox.reason || deleteOutputsResult.deleted_services.dropbox.error || "Delete failed, check the job logs"}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1885,7 +1891,7 @@ function AdminJobsPageContent() {
|
||||
{/* Google Drive */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.gdrive.status === "deleted"
|
||||
deleteOutputsResult.deleted_services.gdrive.status === "success"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.gdrive.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
@@ -1894,7 +1900,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">Google Drive</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "deleted" && deleteOutputsResult.deleted_services.gdrive.files && (
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "success" && deleteOutputsResult.deleted_services.gdrive.files && (
|
||||
<>Deleted {Object.keys(deleteOutputsResult.deleted_services.gdrive.files).length} file(s)</>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "skipped" && (
|
||||
@@ -1903,6 +1909,14 @@ function AdminJobsPageContent() {
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "error" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.gdrive.error}</span>
|
||||
)}
|
||||
{(deleteOutputsResult.deleted_services.gdrive.status === "failed" || deleteOutputsResult.deleted_services.gdrive.status === "partial") && (
|
||||
<span className="text-red-500">{
|
||||
deleteOutputsResult.deleted_services.gdrive.files &&
|
||||
Object.values(deleteOutputsResult.deleted_services.gdrive.files).some((ok) => !ok)
|
||||
? `Not deleted: ${Object.entries(deleteOutputsResult.deleted_services.gdrive.files).filter(([, ok]) => !ok).map(([k]) => k).join(", ")}`
|
||||
: deleteOutputsResult.deleted_services.gdrive.reason || deleteOutputsResult.deleted_services.gdrive.error || "Delete failed, check the job logs"
|
||||
}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -581,8 +581,8 @@ test.describe('Admin Job Detail Page', () => {
|
||||
job_id: 'test-job-123',
|
||||
message: 'All outputs deleted successfully',
|
||||
deleted_services: {
|
||||
youtube: { status: 'deleted', video_id: 'xyz789' },
|
||||
dropbox: { status: 'deleted', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
youtube: { status: 'success', video_id: 'xyz789' },
|
||||
dropbox: { status: 'success', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
gdrive: { status: 'skipped', reason: 'No Google Drive files found' },
|
||||
},
|
||||
cleared_state_data: ['youtube_url', 'youtube_video_id', 'dropbox_link', 'brand_code'],
|
||||
@@ -653,8 +653,8 @@ test.describe('Admin Job Detail Page', () => {
|
||||
message: 'Some outputs could not be deleted',
|
||||
deleted_services: {
|
||||
youtube: { status: 'error', error: 'Video not found or already deleted' },
|
||||
dropbox: { status: 'deleted', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
gdrive: { status: 'skipped', reason: 'No Google Drive files found' },
|
||||
dropbox: { status: 'success', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
gdrive: { status: 'partial', files: { mp4: true, cdg: false } },
|
||||
},
|
||||
cleared_state_data: ['dropbox_link', 'brand_code'],
|
||||
outputs_deleted_at: '2026-01-15T10:00:00Z',
|
||||
@@ -693,6 +693,9 @@ test.describe('Admin Job Detail Page', () => {
|
||||
|
||||
// Should show Dropbox success
|
||||
await expect(page.getByText(/NK001.*Test Artist.*Test Song/)).toBeVisible();
|
||||
|
||||
// A partial Drive delete names the file(s) left behind
|
||||
await expect(page.getByText('Not deleted: cdg')).toBeVisible();
|
||||
});
|
||||
|
||||
test('delete outputs button is disabled when outputs already deleted', async ({ page }) => {
|
||||
|
||||
@@ -53,7 +53,7 @@ gcloud functions deploy "${FUNCTION_NAME}" \
|
||||
--min-instances=0 \
|
||||
--max-instances=1 \
|
||||
--service-account="gdrive-validator@${PROJECT_ID}.iam.gserviceaccount.com" \
|
||||
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=true" \
|
||||
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=false,LOG_EXECUTION_ID=true" \
|
||||
--set-secrets="PUSHBULLET_API_KEY=pushbullet-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest" \
|
||||
--project="${PROJECT_ID}"
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import re
|
||||
import json
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Union
|
||||
import functions_framework
|
||||
import requests
|
||||
@@ -38,6 +39,21 @@ EMAIL_FROM = os.environ.get("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
# Set to "false" to only receive notifications when issues are detected
|
||||
NOTIFY_ON_SUCCESS = os.environ.get("NOTIFY_ON_SUCCESS", "true").lower() == "true"
|
||||
|
||||
# A track whose newest file landed in Drive this recently is treated as still
|
||||
# uploading: a job's packaging step uploads MP4, then MP4-720p, then CDG over a
|
||||
# couple of minutes, and the post-job trigger for an earlier job can fire right
|
||||
# in the middle (2026-11-07: NOMAD-1871's check flagged NOMAD-1872 mid-upload).
|
||||
# Gaps for such tracks are held back; the track's own post-job trigger (which
|
||||
# names its brand_code) and the daily run still check it once the upload ends.
|
||||
def _grace_minutes() -> int:
|
||||
try:
|
||||
return int(os.environ.get("IN_FLIGHT_GRACE_MINUTES", "30"))
|
||||
except ValueError:
|
||||
return 30
|
||||
|
||||
|
||||
IN_FLIGHT_GRACE_MINUTES = _grace_minutes()
|
||||
|
||||
# Known gaps configuration - matches the local validate_and_sync.py script
|
||||
# These are HISTORICAL ONLY (pre-generator era, before Dec 2024). Do NOT add new entries.
|
||||
# New gaps are bugs — see docs/GDRIVE-VALIDATOR.md § "Sequence Gap Detected" for fix procedure.
|
||||
@@ -93,7 +109,9 @@ def get_drive_service():
|
||||
return build('drive', 'v3', credentials=credentials)
|
||||
|
||||
|
||||
def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
|
||||
def list_folder_contents(
|
||||
service, folder_id: str, created_times: dict[str, str] | None = None
|
||||
) -> dict[str, list[str]]:
|
||||
"""
|
||||
List all files in a Google Drive folder and its subfolders.
|
||||
|
||||
@@ -102,6 +120,9 @@ def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
|
||||
- CDG/ (contains .zip files)
|
||||
- MP4/ (contains .mp4 files)
|
||||
- MP4-720p/ (contains .mp4 files)
|
||||
|
||||
If ``created_times`` is given, it is filled with ``{filename: createdTime}``
|
||||
(RFC 3339) so the caller can tell which tracks are still being uploaded.
|
||||
"""
|
||||
results = {}
|
||||
|
||||
@@ -134,12 +155,15 @@ def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
|
||||
query = f"'{folder_id_inner}' in parents and trashed=false and mimeType!='application/vnd.google-apps.folder'"
|
||||
response = service.files().list(
|
||||
q=query,
|
||||
fields="nextPageToken, files(name)",
|
||||
fields="nextPageToken, files(name, createdTime)",
|
||||
pageSize=1000,
|
||||
pageToken=page_token
|
||||
).execute()
|
||||
|
||||
files.extend([f['name'] for f in response.get('files', [])])
|
||||
for f in response.get('files', []):
|
||||
files.append(f['name'])
|
||||
if created_times is not None and f.get('createdTime'):
|
||||
created_times[f['name']] = f['createdTime']
|
||||
page_token = response.get('nextPageToken')
|
||||
|
||||
if not page_token:
|
||||
@@ -187,10 +211,39 @@ def get_sequence_number(filename: str) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
|
||||
def recently_uploaded_sequences(
|
||||
created_times: dict[str, str],
|
||||
now: datetime | None = None,
|
||||
grace_minutes: int = IN_FLIGHT_GRACE_MINUTES,
|
||||
) -> set[int]:
|
||||
"""Sequence numbers that have any file created within the grace window."""
|
||||
now = now or datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(minutes=grace_minutes)
|
||||
recent = set()
|
||||
for filename, created in created_times.items():
|
||||
seq = get_sequence_number(filename)
|
||||
if seq is None:
|
||||
continue
|
||||
try:
|
||||
ts = datetime.fromisoformat(created.replace("Z", "+00:00"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ts >= cutoff:
|
||||
recent.add(seq)
|
||||
return recent
|
||||
|
||||
|
||||
def validate_files(
|
||||
files_by_folder: dict[str, list[str]], in_flight: set[int] | None = None
|
||||
) -> dict:
|
||||
"""
|
||||
Validate all files and return a dict of issues found.
|
||||
|
||||
``in_flight`` sequence numbers (tracks still uploading) are not reported
|
||||
as gaps.
|
||||
|
||||
Returns:
|
||||
{
|
||||
'duplicates': {'MP4': {1107: ['file1.mp4', 'file2.mp4']}, ...},
|
||||
@@ -255,7 +308,7 @@ def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
|
||||
min_num = min(sequence_numbers)
|
||||
expected_range = set(range(min_num, global_max + 1))
|
||||
excluded = EXCLUDED_NUMBERS.get(folder_name, set())
|
||||
missing = sorted(expected_range - sequence_numbers - excluded)
|
||||
missing = sorted(expected_range - sequence_numbers - excluded - (in_flight or set()))
|
||||
|
||||
if missing:
|
||||
issues['gaps'][folder_name] = missing
|
||||
@@ -501,7 +554,8 @@ def validate_gdrive(request):
|
||||
service = get_drive_service()
|
||||
|
||||
# List all files
|
||||
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID)
|
||||
created_times: dict[str, str] = {}
|
||||
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID, created_times)
|
||||
|
||||
if not files_by_folder:
|
||||
logger.warning("No folders found in Google Drive")
|
||||
@@ -511,7 +565,10 @@ def validate_gdrive(request):
|
||||
}), 200, {"Content-Type": "application/json"}
|
||||
|
||||
# Validate files
|
||||
issues = validate_files(files_by_folder)
|
||||
in_flight = recently_uploaded_sequences(created_times)
|
||||
if in_flight:
|
||||
logger.info("Holding back gap checks for tracks still uploading: %s", sorted(in_flight))
|
||||
issues = validate_files(files_by_folder, in_flight=in_flight)
|
||||
|
||||
# Targeted same-run completeness for the just-published track.
|
||||
if brand_code:
|
||||
|
||||
@@ -31,6 +31,7 @@ from main import ( # noqa: E402
|
||||
expand_gaps,
|
||||
has_issues,
|
||||
check_track_completeness,
|
||||
recently_uploaded_sequences,
|
||||
)
|
||||
|
||||
|
||||
@@ -333,3 +334,35 @@ class TestHasIssues:
|
||||
|
||||
def test_has_gaps(self):
|
||||
assert has_issues({"duplicates": {}, "invalid_filenames": {}, "gaps": {"MP4": [3]}})
|
||||
|
||||
|
||||
class TestInFlightUploads:
|
||||
"""2026-11-07: NOMAD-1871's post-job check ran while NOMAD-1872 was mid-upload
|
||||
(MP4 done, 720p + CDG not yet) and emailed a false sequence-gap alert."""
|
||||
|
||||
NOW = __import__("datetime").datetime(2026, 11, 7, 12, 24, 47, tzinfo=__import__("datetime").timezone.utc)
|
||||
|
||||
def _files(self):
|
||||
return {
|
||||
"MP4": [make_mp4(i) for i in range(100, 106)],
|
||||
"MP4-720p": [make_mp4(i) for i in range(100, 105)],
|
||||
"CDG": [make_cdg(i) for i in range(100, 105)],
|
||||
}
|
||||
|
||||
def test_track_still_uploading_is_not_a_gap(self):
|
||||
created = {make_mp4(105): "2026-11-07T12:24:30.000Z", make_mp4(104): "2026-11-06T09:00:00.000Z"}
|
||||
in_flight = recently_uploaded_sequences(created, now=self.NOW, grace_minutes=30)
|
||||
assert in_flight == {105}
|
||||
issues = validate_files(self._files(), in_flight=in_flight)
|
||||
assert issues["gaps"] == {}
|
||||
|
||||
def test_old_track_missing_is_still_a_gap(self):
|
||||
created = {make_mp4(105): "2026-11-07T10:00:00.000Z"}
|
||||
in_flight = recently_uploaded_sequences(created, now=self.NOW, grace_minutes=30)
|
||||
assert in_flight == set()
|
||||
issues = validate_files(self._files(), in_flight=in_flight)
|
||||
assert issues["gaps"] == {"MP4-720p": [105], "CDG": [105]}
|
||||
|
||||
def test_bad_timestamps_and_non_track_files_ignored(self):
|
||||
created = {"desktop.ini": "2026-11-07T12:24:00Z", make_mp4(105): "garbage"}
|
||||
assert recently_uploaded_sequences(created, now=self.NOW) == set()
|
||||
@@ -36,7 +36,7 @@ DATASET_ID = "karaoke_decide"
|
||||
|
||||
# kjbox song-identification index: every song a singer might mean, exported daily
|
||||
# after the KN refresh and downloaded by the NomadPC's nomad-catalog-sync. Design:
|
||||
# kjbox docs/SONG-IDENTIFICATION.md. Rows from three sources, merged/deduped on the
|
||||
# kjbox docs/SONG-IDENTIFICATION.md. Rows from these sources, merged/deduped on the
|
||||
# device (scripts/build_song_id_db.py keeps the highest popularity per song):
|
||||
# - MusicBrainz recordings (weekly-refreshed by karaoke-decide's mb-refresh — the
|
||||
# source that keeps NEW songs coming). Kept when Spotify track popularity >= 30
|
||||
@@ -48,6 +48,7 @@ DATASET_ID = "karaoke_decide"
|
||||
# (an estimate must not outrank a measured score).
|
||||
# - the static July 2025 Spotify snapshot (popularity >= 30)
|
||||
# - every KaraokeNerds song (daily; karaoke = 1)
|
||||
# - every song a live Spotify search returned (SPOTIFY_LIVE_UNION below)
|
||||
# ListenBrainz (karaoke-decide's lb-refresh, fortnightly dumps) is mapped onto Spotify's
|
||||
# 0-100 scale per stats range: score = offset + slope * log10(listeners), fitted to the
|
||||
# median Spotify popularity of songs that have both (2026-09-29; e.g. 100 this_year
|
||||
@@ -119,6 +120,26 @@ UNION ALL SELECT sp.best.a, sp.best.t, sp.p, 0 FROM sp
|
||||
UNION ALL SELECT a, t, CAST(NULL AS INT64), 1 FROM kn
|
||||
"""
|
||||
|
||||
# Every song a live Spotify search ever returned (karaoke-decide keeps them forever in
|
||||
# `spotify_live_tracks`, 2026-11-08), so a song someone looked up once, e.g. a 2025 release
|
||||
# missing from the July 2025 snapshot and MusicBrainz, is in the index from then on. The API
|
||||
# has no popularity, so the estimate is the D5a one: 0.8 x the artist's popularity capped at 50,
|
||||
# else 30. Appended only when the table exists (decide creates it on the first live search).
|
||||
SPOTIFY_LIVE_TABLE = "spotify_live_tracks"
|
||||
SPOTIFY_LIVE_UNION = r"""
|
||||
UNION ALL
|
||||
SELECT sl.a, sl.t, COALESCE(CAST(LEAST(art.apop * 0.8, 50) AS INT64), 30), 0
|
||||
FROM (
|
||||
SELECT ANY_VALUE(artist_name) a, ANY_VALUE(track_name) t,
|
||||
TRIM(REGEXP_REPLACE(REGEXP_REPLACE(la, r'[^a-z0-9 ]', ' '), r' +', ' ')) na
|
||||
FROM (SELECT artist_name, track_name, LOWER(artist_name) la, LOWER(track_name) lt
|
||||
FROM `{project}.{dataset}.spotify_live_tracks`
|
||||
WHERE artist_name IS NOT NULL AND track_name IS NOT NULL
|
||||
AND TRIM(artist_name) != '' AND TRIM(track_name) != '')
|
||||
GROUP BY la, lt) sl
|
||||
LEFT JOIN art ON art.name_normalized = sl.na
|
||||
"""
|
||||
|
||||
# API endpoints
|
||||
SONGS_URL = "https://karaokenerds.com/Data/Songs"
|
||||
COMMUNITY_URL = "https://karaokenerds.com/Data/Community"
|
||||
@@ -256,6 +277,15 @@ def _load_community_to_bigquery(raw_bytes: bytes) -> int:
|
||||
return load_job.output_rows
|
||||
|
||||
|
||||
def _table_exists(client, table: str) -> bool:
|
||||
from google.api_core.exceptions import NotFound
|
||||
try:
|
||||
client.get_table(f"{GCP_PROJECT_ID}.{DATASET_ID}.{table}")
|
||||
return True
|
||||
except NotFound:
|
||||
return False
|
||||
|
||||
|
||||
def _export_song_id_index() -> dict:
|
||||
"""EXPORT DATA the song-identification index to GCS + write the manifest.
|
||||
|
||||
@@ -267,6 +297,10 @@ def _export_song_id_index() -> dict:
|
||||
folder = f"{SONG_ID_PREFIX}/{run}"
|
||||
client = bigquery.Client(project=GCP_PROJECT_ID)
|
||||
select = SONG_ID_SQL.format(project=GCP_PROJECT_ID, dataset=DATASET_ID)
|
||||
if _table_exists(client, SPOTIFY_LIVE_TABLE):
|
||||
select = select.rstrip() + "\n" + SPOTIFY_LIVE_UNION.format(project=GCP_PROJECT_ID, dataset=DATASET_ID)
|
||||
else:
|
||||
logger.info("song-id export: %s not created yet, skipping live Spotify songs", SPOTIFY_LIVE_TABLE)
|
||||
export = (
|
||||
f"EXPORT DATA OPTIONS(uri='gs://{GCS_BUCKET}/{folder}/songs-*.tsv.gz', format='CSV', "
|
||||
"field_delimiter='\t', header=false, compression='GZIP', overwrite=true) AS " + select
|
||||
|
||||
@@ -137,3 +137,27 @@ def test_song_id_sql_uses_listenbrainz_and_keeps_the_four_columns():
|
||||
assert f"`p.d.{table}`" in sql
|
||||
# the device's build_song_id_db.py reads exactly these columns, in this order
|
||||
assert "SELECT artist, title, popularity, karaoke FROM mb_kept" in sql
|
||||
|
||||
|
||||
def test_export_adds_live_spotify_songs_when_the_table_exists(clients):
|
||||
bq, _gcs = clients
|
||||
bq.get_table.return_value = object()
|
||||
main._export_song_id_index()
|
||||
sql = bq.query.call_args[0][0]
|
||||
assert "`nomadkaraoke.karaoke_decide.spotify_live_tracks`" in sql
|
||||
assert sql.rstrip().endswith("LEFT JOIN art ON art.name_normalized = sl.na")
|
||||
assert "{" not in sql.split(" AS ", 1)[1].replace("{project}", "") # placeholders filled
|
||||
|
||||
|
||||
def test_export_skips_live_spotify_songs_before_the_table_exists(clients):
|
||||
from google.api_core.exceptions import NotFound
|
||||
bq, _gcs = clients
|
||||
bq.get_table.side_effect = NotFound("no table")
|
||||
main._export_song_id_index()
|
||||
assert "spotify_live_tracks" not in bq.query.call_args[0][0]
|
||||
|
||||
|
||||
def test_live_union_keeps_the_four_columns_and_estimates_popularity():
|
||||
union = main.SPOTIFY_LIVE_UNION.format(project="p", dataset="d")
|
||||
assert "{" not in union and "`p.d.spotify_live_tracks`" in union
|
||||
assert union.strip().startswith("UNION ALL\nSELECT sl.a, sl.t, COALESCE(CAST(LEAST(art.apop * 0.8, 50) AS INT64), 30), 0")
|
||||
@@ -504,6 +504,11 @@ class KaraokeFinalise:
|
||||
self.logger.info(f"Successfully deleted YouTube video with ID: {video_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# 404 = the video is already gone (e.g. removed in YouTube Studio).
|
||||
# The goal of the delete is met, so report success, not failure.
|
||||
if getattr(getattr(e, "resp", None), "status", None) == 404:
|
||||
self.logger.warning(f"YouTube video {video_id} not found; treating as already deleted")
|
||||
return True
|
||||
self.logger.error(f"Failed to delete YouTube video with ID {video_id}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.293.1"
|
||||
version = "0.294.3"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -472,6 +472,25 @@ def test_delete_youtube_video_failure(mock_auth, finaliser_for_yt, mock_youtube_
|
||||
mock_youtube_service.videos().delete.assert_called_once_with(id=video_id)
|
||||
finaliser_for_yt.logger.error.assert_any_call(f"Failed to delete YouTube video with ID {video_id}: API Error")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_already_gone_404_counts_as_deleted(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""A 404 means the video was already removed (e.g. in YouTube Studio): success, not failure."""
|
||||
from googleapiclient.errors import HttpError
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
resp = MagicMock(status=404, reason="Not Found")
|
||||
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = HttpError(resp, b"{}")
|
||||
assert finaliser_for_yt.delete_youtube_video("gone_video") is True
|
||||
finaliser_for_yt.logger.error.assert_not_called()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_403_still_fails(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Other HTTP errors (e.g. 403 wrong channel) are still failures."""
|
||||
from googleapiclient.errors import HttpError
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
resp = MagicMock(status=403, reason="Forbidden")
|
||||
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = HttpError(resp, b"{}")
|
||||
assert finaliser_for_yt.delete_youtube_video("other_video") is False
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_dry_run(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test video deletion dry run."""
|
||||
|
||||
Reference in new issue
Block a user