mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 01:48:08 +09:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5222be688a | ||
|
|
42c6874257 | ||
|
|
2cc68a0bba |
No files matched your search
+1
-10
@@ -36,16 +36,7 @@ class Settings(BaseSettings):
|
||||
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
|
||||
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
|
||||
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
|
||||
|
||||
# KaraokeNerds community catalog: our own daily-refreshed copy of KN's community
|
||||
# (web-only, directly-playable) tracks, written by the authorized `kn-data-sync`
|
||||
# export job. The community-version check reads THIS, never scrapes karaokenerds.com.
|
||||
# Source of truth is BigQuery `karaoke_decide.karaokenerds_community`; the export job
|
||||
# also mirrors it to this gzipped-JSON GCS object, which the backend loads in-process.
|
||||
kn_community_bucket: str = os.getenv("KN_COMMUNITY_BUCKET", "nomadkaraoke-kn-data")
|
||||
kn_community_blob: str = os.getenv("KN_COMMUNITY_BLOB", "community/community-data-latest.json.gz")
|
||||
kn_community_ttl_seconds: int = int(os.getenv("KN_COMMUNITY_TTL_SECONDS", "21600")) # 6h
|
||||
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
|
||||
|
||||
@@ -1,208 +1,249 @@
|
||||
"""
|
||||
KaraokeNerds community version detection service.
|
||||
|
||||
Checks whether a song already has community-approved karaoke versions (free,
|
||||
directly-playable, on YouTube). This reads OUR OWN daily-refreshed copy of the
|
||||
KaraokeNerds community catalog — it does NOT scrape or live-query
|
||||
karaokenerds.com. The catalog is populated by the authorized `kn-data-sync`
|
||||
export job (the only thing permitted to hit karaokenerds.com) into BigQuery
|
||||
`karaoke_decide.karaokenerds_community` and mirrored to a gzipped-JSON object in
|
||||
GCS, which this module loads into an in-process index.
|
||||
|
||||
Public API (`check_community_versions` / `check_community_versions_batch`) and
|
||||
its return shapes are unchanged from the previous scraping implementation, so
|
||||
callers and the frontend need no changes.
|
||||
Scrapes karaokenerds.com to check if a song already has community-approved
|
||||
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from google.cloud import storage
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from backend.config import settings
|
||||
from backend.services.kn_brand_names import brand_name_for
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Extract a YouTube video id from any of KaraokeNerds' stored watch-URL forms
|
||||
# (youtu.be/<id>, /watch?v=<id>, /embed/<id>, /shorts/<id>) so we can emit the
|
||||
# canonical https://www.youtube.com/watch?v=<id> the old scrape produced.
|
||||
_YT_ID_RE = re.compile(
|
||||
r"(?:youtu\.be/|youtube\.com/(?:watch\?(?:[^&]*&)*v=|embed/|shorts/|v/))"
|
||||
r"([A-Za-z0-9_-]{11})"
|
||||
)
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# karaokenerds.com's search silently returns zero results once a query exceeds
|
||||
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
|
||||
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
|
||||
# artist blow past this, so the song is falsely reported as having no community
|
||||
# version. When that happens we retry with the title alone (the highest-signal
|
||||
# term) and keep only results whose artist matches.
|
||||
MAX_RELIABLE_QUERY_TERMS = 10
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
|
||||
|
||||
def _normalize_youtube_url(watch: str | None) -> str | None:
|
||||
"""Canonicalize a KaraokeNerds watch URL to youtube.com/watch?v=<id>.
|
||||
|
||||
Returns the canonical URL, or the stripped original if no 11-char id can be
|
||||
parsed (never fabricates), or None when empty.
|
||||
"""
|
||||
watch = (watch or "").strip()
|
||||
if not watch:
|
||||
return None
|
||||
m = _YT_ID_RE.search(watch)
|
||||
if m:
|
||||
return f"https://www.youtube.com/watch?v={m.group(1)}"
|
||||
return watch
|
||||
|
||||
# Every row in the community catalog is, by definition, a community/web track, so
|
||||
# entries surfaced from it are always flagged as community versions.
|
||||
_IS_COMMUNITY = True
|
||||
|
||||
# In-process index built from the community export, refreshed on a TTL. Structure:
|
||||
# { "<norm-artist>\x1f<norm-title>": {"title", "artist", "community_tracks": [...]} }
|
||||
_index: dict[str, dict[str, Any]] | None = None
|
||||
_index_expiry: float = 0.0
|
||||
_index_lock = asyncio.Lock()
|
||||
|
||||
# Separator for the (artist, title) match key — a control char that survives
|
||||
# normalization stripping so it can never appear inside a normalized value.
|
||||
_KEY_SEP = "\x1f"
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
|
||||
|
||||
def _match_key(artist: str, title: str) -> str:
|
||||
return f"{normalize_for_match(artist)}{_KEY_SEP}{normalize_for_match(title)}"
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
|
||||
|
||||
def _build_index(items: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
"""Build the (artist, title) -> song lookup from raw community rows.
|
||||
|
||||
Each raw row carries ``Artist, Title, Brand, Watch`` (YouTube URL). Rows for
|
||||
the same normalized (artist, title) are grouped; their community tracks are
|
||||
deduped by (brand, url).
|
||||
"""
|
||||
index: dict[str, dict[str, Any]] = {}
|
||||
for row in items:
|
||||
artist = (row.get("Artist") or "").strip()
|
||||
title = (row.get("Title") or "").strip()
|
||||
if not artist or not title:
|
||||
continue
|
||||
# The export stores the brand *code* (e.g. "NOMAD"); resolve the human
|
||||
# name for display and keep the code, matching the old scrape's output.
|
||||
brand_code = (row.get("Brand") or "").strip()
|
||||
youtube_url = _normalize_youtube_url(row.get("Watch"))
|
||||
|
||||
key = _match_key(artist, title)
|
||||
song = index.get(key)
|
||||
if song is None:
|
||||
# Keep the first-seen display casing for artist/title.
|
||||
song = {"title": title, "artist": artist, "community_tracks": [], "_seen": set()}
|
||||
index[key] = song
|
||||
|
||||
dedup = (brand_code, youtube_url)
|
||||
if dedup in song["_seen"]:
|
||||
continue
|
||||
song["_seen"].add(dedup)
|
||||
song["community_tracks"].append({
|
||||
"brand_name": brand_name_for(brand_code),
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": _IS_COMMUNITY,
|
||||
})
|
||||
|
||||
# Drop the internal dedup bookkeeping before returning.
|
||||
for song in index.values():
|
||||
song.pop("_seen", None)
|
||||
return index
|
||||
def _clean_youtube_url(url: str) -> str:
|
||||
"""Strip playlist params from YouTube URLs, keep just the video URL."""
|
||||
return re.sub(r"&list=[^&]*", "", url)
|
||||
|
||||
|
||||
def _load_index() -> dict[str, dict[str, Any]]:
|
||||
"""Download and parse the community export gzip from GCS (blocking)."""
|
||||
client = storage.Client(project=settings.google_cloud_project)
|
||||
bucket = client.bucket(settings.kn_community_bucket)
|
||||
blob = bucket.blob(settings.kn_community_blob)
|
||||
raw = blob.download_as_bytes()
|
||||
data = json.loads(gzip.decompress(raw))
|
||||
if isinstance(data, dict) and "Items" in data:
|
||||
items = data["Items"]
|
||||
elif isinstance(data, list):
|
||||
items = data
|
||||
else:
|
||||
raise ValueError(f"Unexpected community export shape: {type(data).__name__}")
|
||||
index = _build_index(items)
|
||||
logger.info(
|
||||
"Loaded KaraokeNerds community index: %d songs from gs://%s/%s",
|
||||
len(index), settings.kn_community_bucket, settings.kn_community_blob,
|
||||
)
|
||||
return index
|
||||
def _parse_single_track(li) -> dict | None:
|
||||
"""Parse a single track <li> element from karaokenerds search results."""
|
||||
# Brand name: first <a> in the li
|
||||
brand_link = li.find("a")
|
||||
brand_name = brand_link.get_text(strip=True) if brand_link else ""
|
||||
|
||||
# Brand code: text inside .badge span
|
||||
badge = li.find("span", class_="badge")
|
||||
brand_code = ""
|
||||
if badge:
|
||||
brand_code = badge.get_text(strip=True)
|
||||
|
||||
async def _get_index() -> dict[str, dict[str, Any]]:
|
||||
"""Return the community index, refreshing from GCS when the TTL has expired.
|
||||
|
||||
Failures are non-fatal: a stale index keeps serving; if there is no index
|
||||
yet, an empty one is returned (every song reads as "no community version",
|
||||
which keeps tracks selectable — the same fail-open behaviour the scraper had).
|
||||
"""
|
||||
global _index, _index_expiry
|
||||
if _index is not None and time.monotonic() < _index_expiry:
|
||||
return _index
|
||||
|
||||
async with _index_lock:
|
||||
# Re-check after acquiring the lock — another coroutine may have loaded it.
|
||||
if _index is not None and time.monotonic() < _index_expiry:
|
||||
return _index
|
||||
try:
|
||||
fresh = await asyncio.to_thread(_load_index)
|
||||
_index = fresh
|
||||
_index_expiry = time.monotonic() + max(60, settings.kn_community_ttl_seconds)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to load KaraokeNerds community index: %s", e)
|
||||
if _index is None:
|
||||
# No prior data — serve empty until the short retry window elapses.
|
||||
_index = {}
|
||||
# Retry soon whether we're serving empty or a stale index, so an
|
||||
# outage doesn't make every request re-attempt the load immediately.
|
||||
_index_expiry = time.monotonic() + 60
|
||||
return _index
|
||||
|
||||
|
||||
def _lookup(index: dict[str, dict[str, Any]], artist: str, title: str) -> dict:
|
||||
"""Build a check result for one (artist, title) from the index."""
|
||||
song = index.get(_match_key(artist, title))
|
||||
if not song or not song.get("community_tracks"):
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
best_youtube_url = None
|
||||
for track in song["community_tracks"]:
|
||||
if track.get("youtube_url"):
|
||||
best_youtube_url = track["youtube_url"]
|
||||
# YouTube URL: link containing youtube.com
|
||||
youtube_url = None
|
||||
for a in li.find_all("a", href=True):
|
||||
href = a["href"]
|
||||
if "youtube.com" in href:
|
||||
youtube_url = _clean_youtube_url(href)
|
||||
break
|
||||
|
||||
# Community: presence of img.check
|
||||
is_community = bool(li.find("img", class_="check"))
|
||||
|
||||
if not youtube_url:
|
||||
return None
|
||||
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [{
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": song["community_tracks"],
|
||||
}],
|
||||
"best_youtube_url": best_youtube_url,
|
||||
"brand_name": brand_name,
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": is_community,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tracks(details_row) -> list[dict]:
|
||||
"""Parse track list items from a details row."""
|
||||
tracks = []
|
||||
for li in details_row.find_all("li", class_="track"):
|
||||
track = _parse_single_track(li)
|
||||
if track:
|
||||
tracks.append(track)
|
||||
return tracks
|
||||
|
||||
|
||||
def parse_results(html: str) -> list[dict]:
|
||||
"""Parse karaokenerds.com search results HTML into structured data."""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
table = soup.find("table")
|
||||
if not table:
|
||||
return []
|
||||
|
||||
tbody = table.find("tbody")
|
||||
if not tbody:
|
||||
return []
|
||||
|
||||
songs = []
|
||||
rows = tbody.find_all("tr", recursive=False)
|
||||
|
||||
i = 0
|
||||
while i < len(rows):
|
||||
row = rows[i]
|
||||
|
||||
# Song rows have class "group"
|
||||
if "group" not in row.get("class", []):
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Extract title and artist from the song row
|
||||
cells = row.find_all("td")
|
||||
if len(cells) < 3:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
title_link = cells[0].find("a")
|
||||
artist_link = cells[1].find("a")
|
||||
title = title_link.get_text(strip=True) if title_link else ""
|
||||
artist = artist_link.get_text(strip=True) if artist_link else ""
|
||||
|
||||
# The next row should be the details row with tracks
|
||||
tracks = []
|
||||
if i + 1 < len(rows):
|
||||
details_row = rows[i + 1]
|
||||
if "details" in details_row.get("class", []):
|
||||
tracks = _parse_tracks(details_row)
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
if title:
|
||||
songs.append({
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": tracks,
|
||||
})
|
||||
|
||||
return songs
|
||||
|
||||
|
||||
async def _search_songs(query: str) -> list[dict] | None:
|
||||
"""Run a single karaokenerds search and parse the results.
|
||||
|
||||
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
|
||||
caller can distinguish "search errored" from "search returned nothing").
|
||||
"""
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
return None
|
||||
return parse_results(resp.text)
|
||||
|
||||
|
||||
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
|
||||
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
|
||||
community_songs: list[dict] = []
|
||||
best_youtube_url: str | None = None
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
return community_songs, best_youtube_url
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions.
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
|
||||
Reads our own community catalog (never karaokenerds.com). Returns a dict with:
|
||||
Returns a dict with:
|
||||
- has_community: bool
|
||||
- songs: list of matched songs with community tracks
|
||||
- best_youtube_url: URL of the top community version (if any)
|
||||
"""
|
||||
artist = (artist or "").strip()
|
||||
title = (title or "").strip()
|
||||
if not artist or not title:
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
index = await _get_index()
|
||||
return _lookup(index, artist, title)
|
||||
query = f"{artist} {title}"
|
||||
cache_key = f"community:{query.lower().strip()}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
songs = await _search_songs(query)
|
||||
if songs is None:
|
||||
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
|
||||
# site, matching prior behaviour.
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
# karaokenerds chokes on overlong queries and returns nothing. If the
|
||||
# combined "artist title" query was too long AND came back empty, retry with
|
||||
# the title alone, then keep only results whose artist matches (title-only is
|
||||
# broader, so this guards against same-titled songs by other artists).
|
||||
if (
|
||||
not songs
|
||||
and title.strip()
|
||||
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
|
||||
):
|
||||
fallback = await _search_songs(title)
|
||||
if fallback:
|
||||
key_artist = normalize_for_match(artist)
|
||||
songs = [
|
||||
s for s in fallback
|
||||
if normalize_for_match(s.get("artist") or "") == key_artist
|
||||
]
|
||||
|
||||
community_songs, best_youtube_url = _extract_community_songs(songs)
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
"songs": community_songs,
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
|
||||
async def check_community_versions_batch(
|
||||
@@ -215,20 +256,20 @@ async def check_community_versions_batch(
|
||||
"brand_count": int, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
|
||||
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
|
||||
uses to render clickable links; ``brands``/``brand_count`` are retained for
|
||||
back-compat. Lookups hit our in-process community index (no network per song), so
|
||||
``concurrency`` is accepted for back-compat but no longer meaningful. A missing
|
||||
catalog degrades to ``available=False`` (the track simply stays selectable).
|
||||
back-compat. Bounded concurrency keeps us polite to karaokenerds.com; per-song
|
||||
results reuse the existing 1h cache. A failed lookup degrades to
|
||||
``available=False`` (the track simply stays selectable) — never raises.
|
||||
"""
|
||||
_ = concurrency # retained for call-site compatibility; lookups are in-memory now
|
||||
index = await _get_index()
|
||||
sem = asyncio.Semaphore(max(1, concurrency))
|
||||
|
||||
def _one(song: dict) -> dict:
|
||||
async def _one(song: dict) -> dict:
|
||||
artist = (song.get("artist") or "").strip()
|
||||
title = (song.get("title") or "").strip()
|
||||
if not artist or not title:
|
||||
return {"artist": artist, "title": title, "available": False,
|
||||
"brands": [], "brand_count": 0, "versions": []}
|
||||
res = _lookup(index, artist, title)
|
||||
async with sem:
|
||||
res = await check_community_versions(artist, title)
|
||||
versions: list[dict] = []
|
||||
versioned_brands: set[str] = set()
|
||||
brands: list[str] = []
|
||||
@@ -253,11 +294,4 @@ async def check_community_versions_batch(
|
||||
"versions": versions,
|
||||
}
|
||||
|
||||
return [_one(s) for s in songs]
|
||||
|
||||
|
||||
def _reset_index_for_tests() -> None:
|
||||
"""Clear the module-level cache (used by tests to isolate index state)."""
|
||||
global _index, _index_expiry
|
||||
_index = None
|
||||
_index_expiry = 0.0
|
||||
return await asyncio.gather(*[_one(s) for s in songs])
|
||||
@@ -1,54 +0,0 @@
|
||||
"""KaraokeNerds brand code -> human display name.
|
||||
|
||||
Our own KaraokeNerds catalog (BigQuery `karaokenerds_community` + the GCS export)
|
||||
stores only the brand *code* (e.g. "NOMAD", "OBSK"). The old live scrape also
|
||||
surfaced the human name ("Nomad Karaoke", "ObsKure Karaoke") which the UI shows.
|
||||
KaraokeNerds exposes no authorized brand-name data source, so this static map
|
||||
(kept in sync with kjbox's version_priority registry, plus the highest-frequency
|
||||
community brands) reproduces those names. Unknown codes fall back to the code —
|
||||
the same graceful degradation the UI already applies.
|
||||
"""
|
||||
|
||||
KN_BRAND_NAMES: dict[str, str] = {
|
||||
# Community brands (mirrors kjbox version_priority.COMMUNITY_BRANDS display names)
|
||||
"CC": "CC Karaoke",
|
||||
"LC": "Lemmy Caution",
|
||||
"FBK": "Funbox Karaoke",
|
||||
"BELLY": "BellySings",
|
||||
"NOMAD": "Nomad Karaoke",
|
||||
"FAKEY": "FakeyOke",
|
||||
"PMK": "Punk Media Karaoke",
|
||||
"OBSK": "ObsKure Karaoke",
|
||||
"SDK": "SNDL Karaoke",
|
||||
"DBK": "Deep Bench Karaoke",
|
||||
# Commercial brands (mirrors version_priority.COMMERCIAL_BRANDS display names)
|
||||
"KV": "Karaoke Version",
|
||||
"SC": "Sound Choice",
|
||||
"SBI": "SBI Karaoke",
|
||||
"SF": "Sunfly",
|
||||
"CB": "Chart Buster",
|
||||
"ZM": "Zoom",
|
||||
"VS": "Vocal Star",
|
||||
"SK": "Sing King",
|
||||
"MR": "Mr. Entertainer",
|
||||
"PT": "Party Tyme",
|
||||
"EK": "Easy Karaoke",
|
||||
# Additional high-frequency community brands (harvested from KaraokeNerds).
|
||||
"IKV": "Imperfekt Karaoke",
|
||||
"ZP": "Zipper Karaoke",
|
||||
"JL311": "Rock Solid Karaoke",
|
||||
"CAR": "Caritas",
|
||||
"MKU": "Mobile Karaoke Unit",
|
||||
"VONAGAM": "Vonagam Karaoke",
|
||||
"GR": "ggnzla RECORDS",
|
||||
"HALJAM": "Hal Jam",
|
||||
"REEKIES": "Reekies Karaoke",
|
||||
"DJS": "DJ Sauly Karaoke",
|
||||
}
|
||||
|
||||
|
||||
def brand_name_for(code: str) -> str:
|
||||
"""Human display name for a KaraokeNerds brand code; the code itself if unknown."""
|
||||
if not code:
|
||||
return ""
|
||||
return KN_BRAND_NAMES.get(code.upper().strip(), code)
|
||||
@@ -30,24 +30,24 @@ class TestBatchHelper:
|
||||
async def test_batch_maps_community_results(self, monkeypatch):
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
# Seed the in-process community index (the batch helper reads it directly).
|
||||
# Brand is a CODE in the catalog; brand names resolve for display.
|
||||
rows = [
|
||||
{"Artist": "Daft Punk", "Title": "One More Time", "Brand": "KV", "Watch": ""},
|
||||
{"Artist": "Daft Punk", "Title": "One More Time", "Brand": "OBSK", "Watch": ""},
|
||||
]
|
||||
kn._reset_index_for_tests()
|
||||
monkeypatch.setattr(kn, "_load_index", lambda: kn._build_index(rows))
|
||||
async def fake_single(artist, title):
|
||||
if title == "One More Time":
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [{"community_tracks": [{"brand_name": "KV"}, {"brand_name": "KaraFun"}]}],
|
||||
"best_youtube_url": None,
|
||||
}
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
monkeypatch.setattr(kn, "check_community_versions", fake_single)
|
||||
out = await kn.check_community_versions_batch(
|
||||
[{"artist": "Daft Punk", "title": "One More Time"},
|
||||
{"artist": "Daft Punk", "title": "Aerodynamic"}]
|
||||
)
|
||||
assert out[0]["available"] is True
|
||||
assert out[0]["brands"] == ["Karaoke Version", "ObsKure Karaoke"]
|
||||
assert out[0]["brands"] == ["KV", "KaraFun"]
|
||||
assert out[1]["available"] is False
|
||||
assert out[1]["brand_count"] == 0
|
||||
kn._reset_index_for_tests()
|
||||
|
||||
|
||||
class TestAvailabilityRoute:
|
||||
|
||||
@@ -1,169 +1,263 @@
|
||||
"""
|
||||
Tests for the karaokenerds service.
|
||||
Tests for the karaokenerds service — HTML parsing, community detection, YouTube URL cleanup.
|
||||
|
||||
The service reads our OWN daily-refreshed copy of the KaraokeNerds community
|
||||
catalog (a gzipped-JSON export in GCS, populated by the authorized `kn-data-sync`
|
||||
job) into an in-process index — it never scrapes or live-queries karaokenerds.com.
|
||||
Ported from kjbox/kj-controller/tests/unit/test_karaoke_nerds.py.
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import karaokenerds_service as svc
|
||||
from backend.services.karaokenerds_service import (
|
||||
_build_index,
|
||||
_normalize_youtube_url,
|
||||
parse_results,
|
||||
_clean_youtube_url,
|
||||
_parse_single_track,
|
||||
check_community_versions,
|
||||
check_community_versions_batch,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
|
||||
# Rows mirror the community export shape: Artist, Title, Brand (a CODE), Watch.
|
||||
ROWS = [
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/aaaaaaaaaaa"},
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "OBSK",
|
||||
"Watch": "https://youtu.be/bbbbbbbbbbb"},
|
||||
# Exact duplicate (brand + url) — must collapse.
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/aaaaaaaaaaa"},
|
||||
{"Artist": "ABBA", "Title": "Dancing Queen", "Brand": "SDK",
|
||||
"Watch": "https://youtu.be/ddddddddddd"},
|
||||
# Accents + ampersand exercise the normalized match key.
|
||||
{"Artist": "Beyoncé", "Title": "Crazy in Love", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/ccccccccccc"},
|
||||
{"Artist": "Hall & Oates", "Title": "Rich Girl", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/rrrrrrrrrrr"},
|
||||
# Unknown brand code -> name falls back to the code.
|
||||
{"Artist": "Some Band", "Title": "Obscure", "Brand": "ZZTOP7",
|
||||
"Watch": "https://youtu.be/eeeeeeeeeee"},
|
||||
# Missing artist/title rows are skipped.
|
||||
{"Artist": "", "Title": "No Artist", "Brand": "X", "Watch": "https://youtu.be/fffffffffff"},
|
||||
]
|
||||
# --- YouTube URL cleanup ---
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_index(monkeypatch):
|
||||
"""Isolate the module cache and back `_get_index` with the sample catalog."""
|
||||
svc._reset_index_for_tests()
|
||||
monkeypatch.setattr(svc, "_load_index", lambda: _build_index(ROWS))
|
||||
yield
|
||||
svc._reset_index_for_tests()
|
||||
def test_clean_youtube_url_strips_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest123&index=1"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123&index=1"
|
||||
|
||||
|
||||
# --- YouTube URL normalization ---
|
||||
def test_clean_youtube_url_no_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,expected", [
|
||||
("https://youtu.be/dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PLx", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/embed/dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("", None),
|
||||
("not a url", "not a url"), # unparseable -> returned as-is, never fabricated
|
||||
])
|
||||
def test_normalize_youtube_url(raw, expected):
|
||||
assert _normalize_youtube_url(raw) == expected
|
||||
def test_clean_youtube_url_list_at_end():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
|
||||
|
||||
# --- Index building ---
|
||||
# --- Single track parsing ---
|
||||
|
||||
|
||||
def test_build_index_groups_and_dedupes():
|
||||
index = _build_index(ROWS)
|
||||
dreams = index[svc._match_key("Fleetwood Mac", "Dreams")]
|
||||
# Two distinct brands; the exact-duplicate row is collapsed.
|
||||
assert len(dreams["community_tracks"]) == 2
|
||||
codes = {t["brand_code"] for t in dreams["community_tracks"]}
|
||||
names = {t["brand_name"] for t in dreams["community_tracks"]}
|
||||
assert codes == {"NOMAD", "OBSK"}
|
||||
assert names == {"Nomad Karaoke", "ObsKure Karaoke"}
|
||||
assert all(t["is_community"] is True for t in dreams["community_tracks"])
|
||||
# youtu.be URLs are canonicalized to watch?v=.
|
||||
assert all(t["youtube_url"].startswith("https://www.youtube.com/watch?v=")
|
||||
for t in dreams["community_tracks"])
|
||||
TRACK_HTML_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=mrZRURcb1cM&list=PLtest" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=xyz789" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_YOUTUBE = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">Some Brand</a>
|
||||
<div class="ml-auto">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">
|
||||
<span class="badge badge-primary badge-pill">AB</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
|
||||
def test_build_index_unknown_brand_name_falls_back_to_code():
|
||||
index = _build_index(ROWS)
|
||||
song = index[svc._match_key("Some Band", "Obscure")]
|
||||
tr = song["community_tracks"][0]
|
||||
assert tr["brand_code"] == "ZZTOP7"
|
||||
assert tr["brand_name"] == "ZZTOP7"
|
||||
def test_parse_single_track_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Karaoke Version"
|
||||
assert track["brand_code"] == "KV"
|
||||
assert track["is_community"] is True
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
# List param should be stripped
|
||||
assert "&list=" not in track["youtube_url"]
|
||||
|
||||
|
||||
def test_build_index_skips_rows_without_artist_or_title():
|
||||
index = _build_index(ROWS)
|
||||
assert svc._match_key("", "No Artist") not in index
|
||||
def test_parse_single_track_no_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Sunfly"
|
||||
assert track["brand_code"] == "SF"
|
||||
assert track["is_community"] is False
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
|
||||
|
||||
# --- check_community_versions ---
|
||||
def test_parse_single_track_no_youtube_returns_none():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_YOUTUBE, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is None
|
||||
|
||||
|
||||
# --- Full results parsing ---
|
||||
|
||||
|
||||
FULL_RESULTS_HTML = """
|
||||
<table>
|
||||
<tbody>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/Dreams/Fleetwood-Mac/">Dreams</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">2 Brands >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=community1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=noncommunity1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/The-Chain/Fleetwood-Mac/">The Chain</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">1 Brand >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">Karafun</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=chain1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">
|
||||
<span class="badge badge-primary badge-pill">KFN</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
"""
|
||||
|
||||
|
||||
def test_parse_results_full():
|
||||
songs = parse_results(FULL_RESULTS_HTML)
|
||||
assert len(songs) == 2
|
||||
|
||||
# First song: Dreams
|
||||
assert songs[0]["title"] == "Dreams"
|
||||
assert songs[0]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[0]["tracks"]) == 2
|
||||
|
||||
# First track is community
|
||||
assert songs[0]["tracks"][0]["is_community"] is True
|
||||
assert songs[0]["tracks"][0]["brand_code"] == "KV"
|
||||
|
||||
# Second track is not community
|
||||
assert songs[0]["tracks"][1]["is_community"] is False
|
||||
assert songs[0]["tracks"][1]["brand_code"] == "SF"
|
||||
|
||||
# Second song: The Chain
|
||||
assert songs[1]["title"] == "The Chain"
|
||||
assert songs[1]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[1]["tracks"]) == 1
|
||||
assert songs[1]["tracks"][0]["is_community"] is False
|
||||
|
||||
|
||||
def test_parse_results_empty_html():
|
||||
assert parse_results("") == []
|
||||
assert parse_results("<html></html>") == []
|
||||
assert parse_results("<table></table>") == []
|
||||
|
||||
|
||||
def test_parse_results_no_table():
|
||||
assert parse_results("<div>No results</div>") == []
|
||||
|
||||
|
||||
# --- Batch availability: per-version data with YouTube URLs (Bulk Mode) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_returns_community_with_best_url():
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is True
|
||||
assert result["best_youtube_url"] == "https://www.youtube.com/watch?v=aaaaaaaaaaa"
|
||||
assert len(result["songs"]) == 1
|
||||
assert result["songs"][0]["title"] == "Dreams"
|
||||
assert result["songs"][0]["artist"] == "Fleetwood Mac"
|
||||
async def test_batch_returns_versions_with_urls_deduped_by_brand(monkeypatch):
|
||||
"""Each result carries `versions: [{brand, url}]` (community only), deduped by
|
||||
brand keeping the first URL, alongside the existing brands/brand_count."""
|
||||
|
||||
async def fake_check(artist, title):
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [
|
||||
{
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"community_tracks": [
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=aaa", "is_community": True},
|
||||
{"brand_name": "Nomad Karaoke", "brand_code": "NK",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=bbb", "is_community": True},
|
||||
# Duplicate brand — should be collapsed, keeping the first URL.
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=ccc", "is_community": True},
|
||||
],
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=aaa",
|
||||
}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_is_case_and_whitespace_insensitive():
|
||||
result = await check_community_versions(" fleetwood MAC ", "dreams")
|
||||
assert result["has_community"] is True
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service.check_community_versions", fake_check
|
||||
)
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": "ABBA", "title": "Dancing Queen"}]
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_folds_accents():
|
||||
result = await check_community_versions("Beyonce", "Crazy in Love")
|
||||
assert result["has_community"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_treats_ampersand_as_and():
|
||||
# "&" folds to "and", so "Hall and Oates" matches "Hall & Oates".
|
||||
result = await check_community_versions("Hall and Oates", "Rich Girl")
|
||||
assert result["has_community"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_match_returns_false():
|
||||
result = await check_community_versions("Nonexistent Artist", "No Such Song")
|
||||
assert result == {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blank_input_returns_false_without_lookup():
|
||||
assert (await check_community_versions("", "Dreams"))["has_community"] is False
|
||||
assert (await check_community_versions("ABBA", ""))["has_community"] is False
|
||||
|
||||
|
||||
# --- Batch (Bulk Mode) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_returns_versions_deduped_by_brand():
|
||||
results = await check_community_versions_batch([
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
{"artist": "Nope", "title": "Missing"},
|
||||
])
|
||||
assert len(results) == 2
|
||||
|
||||
dreams = results[0]
|
||||
assert dreams["available"] is True
|
||||
assert dreams["brands"] == ["Nomad Karaoke", "ObsKure Karaoke"]
|
||||
assert dreams["brand_count"] == 2
|
||||
assert dreams["versions"] == [
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=aaaaaaaaaaa"},
|
||||
{"brand": "ObsKure Karaoke", "url": "https://www.youtube.com/watch?v=bbbbbbbbbbb"},
|
||||
assert len(results) == 1
|
||||
r = results[0]
|
||||
assert r["available"] is True
|
||||
assert r["versions"] == [
|
||||
{"brand": "SNDL Karaoke", "url": "https://www.youtube.com/watch?v=aaa"},
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=bbb"},
|
||||
]
|
||||
|
||||
assert results[1]["available"] is False
|
||||
assert results[1]["versions"] == []
|
||||
# Back-compat retained.
|
||||
assert r["brands"] == ["SNDL Karaoke", "Nomad Karaoke"]
|
||||
assert r["brand_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -173,63 +267,110 @@ async def test_batch_empty_song_has_empty_versions():
|
||||
assert results[0]["versions"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_preserves_input_order():
|
||||
order = [
|
||||
{"artist": "ABBA", "title": "Dancing Queen"},
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
{"artist": "Beyonce", "title": "Crazy in Love"},
|
||||
]
|
||||
results = await check_community_versions_batch(order)
|
||||
assert [r["title"] for r in results] == ["Dancing Queen", "Dreams", "Crazy in Love"]
|
||||
assert all(r["available"] for r in results)
|
||||
# --- check_community_versions: overlong-query fallback (KaraokeNerds term cap) ---
|
||||
|
||||
|
||||
# --- Loading + resilience ---
|
||||
def _community_song(title, artist, brand="Nomad Karaoke", url="https://youtu.be/x"):
|
||||
return {
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": [
|
||||
{"brand_name": brand, "brand_code": "NK", "youtube_url": url, "is_community": True}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_community_cache():
|
||||
"""check_community_versions caches in-process; isolate each test."""
|
||||
from backend.services import karaokenerds_service as svc
|
||||
svc._cache.clear()
|
||||
yield
|
||||
svc._cache.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_index_parses_gzipped_items(monkeypatch):
|
||||
"""`_load_index` decompresses the GCS gzip and reads the `Items` array."""
|
||||
payload = gzip.compress(json.dumps({"Items": ROWS}).encode())
|
||||
async def test_overlong_query_falls_back_to_title_only(monkeypatch):
|
||||
"""An overlong "artist title" query that returns nothing retries title-only
|
||||
and matches by artist (the ABBA 'I Do, I Do, I Do, I Do, I Do' bug)."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
|
||||
class _Blob:
|
||||
def download_as_bytes(self):
|
||||
return payload
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
if query == f"ABBA {title}":
|
||||
return [] # combined query is too long -> KaraokeNerds returns nothing
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
return []
|
||||
|
||||
class _Bucket:
|
||||
def blob(self, _name):
|
||||
return _Blob()
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
class _Client:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
def bucket(self, _name):
|
||||
return _Bucket()
|
||||
|
||||
monkeypatch.setattr(svc.storage, "Client", _Client)
|
||||
# Restore the real loader (the autouse fixture stubbed it) so it runs against
|
||||
# the mocked GCS client above.
|
||||
monkeypatch.setattr(svc, "_load_index", _real_load_index)
|
||||
svc._reset_index_for_tests()
|
||||
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is True
|
||||
assert result["songs"][0]["artist"] == "ABBA"
|
||||
assert calls == [f"ABBA {title}", title] # combined first, then title-only fallback
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_failure_is_fail_open(monkeypatch):
|
||||
"""If the export can't be loaded, every song reads as no-community (fail-open)."""
|
||||
def _boom():
|
||||
raise RuntimeError("GCS unavailable")
|
||||
async def test_fallback_filters_out_wrong_artist(monkeypatch):
|
||||
"""Title-only fallback is broader, so same-titled songs by other artists
|
||||
must be discarded — no false positive."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
|
||||
async def fake_search(query):
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "Some Other Band")]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
svc._reset_index_for_tests()
|
||||
monkeypatch.setattr(svc, "_load_index", _boom)
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is False
|
||||
assert result["songs"] == []
|
||||
|
||||
|
||||
# `_real_load_index` is the unpatched module function, captured at import time so
|
||||
# the gzip-parsing test can call it after the autouse fixture stubs `_load_index`.
|
||||
_real_load_index = svc._load_index
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_empty_query_does_not_fall_back(monkeypatch):
|
||||
"""A short query that legitimately returns nothing must NOT trigger a second
|
||||
request (avoids doubling load for songs with no community version)."""
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", "Dancing Queen")
|
||||
|
||||
assert result["has_community"] is False
|
||||
assert calls == ["ABBA Dancing Queen"] # no fallback request
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nonempty_combined_result_skips_fallback(monkeypatch):
|
||||
"""If the combined query returns results, never fall back even when long."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
assert result["has_community"] is True
|
||||
assert calls == [f"ABBA {title}"] # only the combined query ran
|
||||
@@ -2,132 +2,12 @@
|
||||
|
||||
import json
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import boto3
|
||||
from boto3.s3.transfer import TransferConfig
|
||||
from botocore.exceptions import ClientError
|
||||
from google.cloud import storage, secretmanager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Upload order matters: the function has a hard request timeout, and the multi-GB
|
||||
# ``gcs/job-files/`` prefix (regenerable video finals) can consume the whole budget.
|
||||
# We upload the small, irreplaceable prefixes first (in a barrier phase) so a
|
||||
# mid-run timeout can only ever cost the large regenerable finals, never code
|
||||
# history or secrets (DR incident 2026-09: secrets + git repos went stale for days
|
||||
# while GCS job-files stayed fresh).
|
||||
_SMALL_FIRST_PREFIXES = ("secrets/", "git-repos/", "gcs/kn-data/", "firestore/")
|
||||
_LARGE_LAST_PREFIXES = ("gcs/job-files/",)
|
||||
|
||||
# Transfers stream GCS->S3 *through this function process*, so a sequential loop is
|
||||
# capped at a single stream's throughput. Fan out across threads (boto3 low-level
|
||||
# clients are thread-safe) so a night's delta transfers in minutes, not the whole
|
||||
# 1800s budget. Per-file multipart concurrency is capped so peak memory stays well
|
||||
# under the function's 4Gi: workers * max_concurrency * chunksize.
|
||||
_MAX_UPLOAD_WORKERS = 8
|
||||
_TRANSFER_CONFIG = TransferConfig(
|
||||
multipart_threshold=16 * 1024 * 1024,
|
||||
multipart_chunksize=16 * 1024 * 1024,
|
||||
max_concurrency=4,
|
||||
)
|
||||
|
||||
|
||||
def _upload_priority(name: str) -> int:
|
||||
"""Sort key for staging blobs: lower uploads first. Small/irreplaceable
|
||||
prefixes first, unknown prefixes next, large regenerable finals last."""
|
||||
for i, prefix in enumerate(_SMALL_FIRST_PREFIXES):
|
||||
if name.startswith(prefix):
|
||||
return i
|
||||
if any(name.startswith(prefix) for prefix in _LARGE_LAST_PREFIXES):
|
||||
return len(_SMALL_FIRST_PREFIXES) + 1
|
||||
return len(_SMALL_FIRST_PREFIXES)
|
||||
|
||||
|
||||
def _is_large_last(name: str) -> bool:
|
||||
return any(name.startswith(prefix) for prefix in _LARGE_LAST_PREFIXES)
|
||||
|
||||
|
||||
def _content_key(blob):
|
||||
"""A content identity for a blob (prefers crc32c, falls back to md5), or
|
||||
``None`` if the object exposes no checksum."""
|
||||
return blob.crc32c or blob.md5_hash
|
||||
|
||||
|
||||
def _dedupe_final_duplicates(blobs: list) -> tuple[list, int]:
|
||||
"""Drop byte-identical duplicate finals before upload.
|
||||
|
||||
The render pipeline writes every final under both a machine name
|
||||
(``lossless_4k_mp4.mp4``) and a human-friendly name
|
||||
(``Artist - Title (Final Karaoke Lossless 4k).mp4``). Both live in the same
|
||||
``.../finals/`` directory and are byte-identical, so the backup was storing
|
||||
and transferring the largest, most-regenerable data twice.
|
||||
|
||||
Within each ``finals/`` directory, keep one blob per distinct content
|
||||
checksum (the first by name, deterministically) and delete the duplicate
|
||||
twins from staging. Scoped to a single directory + matched on checksum, so a
|
||||
coincidental cross-job size collision can never cause a false drop. Returns
|
||||
the surviving blobs and the number of duplicates removed.
|
||||
"""
|
||||
kept = []
|
||||
seen_by_dir: dict = {}
|
||||
dup_count = 0
|
||||
# Sort so the survivor (first-by-name) is chosen deterministically.
|
||||
for blob in sorted(blobs, key=lambda b: b.name):
|
||||
if "/finals/" not in blob.name:
|
||||
kept.append(blob)
|
||||
continue
|
||||
content = _content_key(blob)
|
||||
if content is None:
|
||||
kept.append(blob)
|
||||
continue
|
||||
directory = blob.name.rsplit("/", 1)[0]
|
||||
seen = seen_by_dir.setdefault(directory, set())
|
||||
if content in seen:
|
||||
blob.delete()
|
||||
dup_count += 1
|
||||
continue
|
||||
seen.add(content)
|
||||
kept.append(blob)
|
||||
return kept, dup_count
|
||||
|
||||
|
||||
def _s3_object_matches(s3_client, s3_bucket: str, key: str, size) -> bool:
|
||||
"""True if S3 already holds ``key`` with the same byte size. Lets the nightly
|
||||
skip anything already backed up — making it genuinely incremental and
|
||||
self-healing (a file left in staging by a prior timeout/error is not
|
||||
re-transferred once it lands in S3)."""
|
||||
if size is None:
|
||||
return False
|
||||
try:
|
||||
head = s3_client.head_object(Bucket=s3_bucket, Key=key)
|
||||
except ClientError as e:
|
||||
if e.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
|
||||
return False
|
||||
raise
|
||||
return head.get("ContentLength") == size
|
||||
|
||||
|
||||
def _transfer_blob(blob, s3_client, s3_bucket: str) -> str:
|
||||
"""Idempotently move one staging blob to S3, deleting it from staging on
|
||||
success. Returns 'uploaded', 'skipped_exists', or 'error'."""
|
||||
try:
|
||||
if _s3_object_matches(s3_client, s3_bucket, blob.name, blob.size):
|
||||
blob.delete()
|
||||
return "skipped_exists"
|
||||
with blob.open("rb") as gcs_file:
|
||||
s3_client.upload_fileobj(
|
||||
Fileobj=gcs_file,
|
||||
Bucket=s3_bucket,
|
||||
Key=blob.name,
|
||||
Config=_TRANSFER_CONFIG,
|
||||
)
|
||||
blob.delete()
|
||||
return "uploaded"
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to upload {blob.name}: {e}")
|
||||
return "error"
|
||||
|
||||
|
||||
def get_aws_credentials(project: str) -> dict:
|
||||
"""Retrieve AWS credentials from GCP Secret Manager."""
|
||||
@@ -143,27 +23,16 @@ def upload_staging_to_s3(
|
||||
project: str = "nomadkaraoke",
|
||||
exclude_prefixes: list | None = None,
|
||||
) -> str:
|
||||
"""Upload staging-bucket objects to S3, incrementally and in parallel.
|
||||
"""Upload all objects in staging bucket to S3 using streaming.
|
||||
|
||||
Skips marker files (``.*``) and any object whose name starts with one of
|
||||
``exclude_prefixes`` (used to hold the nightly Firestore export back from S3
|
||||
on non-weekly days — it stays in GCS staging as a daily local restore point
|
||||
and is uploaded only on the weekly run). Excluded objects are left in staging
|
||||
(not deleted), so they remain a local backup until the GCS lifecycle policy
|
||||
or the next weekly upload removes them.
|
||||
Walks the staging bucket and uploads each object to the corresponding
|
||||
S3 key path. Skips marker files (.*) and any object whose name starts with
|
||||
one of ``exclude_prefixes`` (used to hold the nightly Firestore export back
|
||||
from S3 on non-weekly days — it stays in GCS staging as a daily local
|
||||
restore point and is uploaded only on the weekly run).
|
||||
|
||||
Efficiency:
|
||||
* **Deduped** — byte-identical duplicate finals are dropped so the largest
|
||||
data is stored/transferred once (see ``_dedupe_final_duplicates``).
|
||||
* **Incremental** — objects already in S3 (same key + size) are skipped, so
|
||||
only genuinely new/changed bytes cross the wire and a prior partial run
|
||||
self-heals (see ``_s3_object_matches``).
|
||||
* **Parallel** — transfers fan out across a thread pool instead of a single
|
||||
serialized stream.
|
||||
|
||||
Ordering guarantee: small/irreplaceable prefixes upload to completion (a
|
||||
barrier) before the large ``gcs/job-files/`` finals begin, so a mid-run
|
||||
timeout can only cost the replaceable finals.
|
||||
Excluded objects are left in staging (not deleted), so they remain a local
|
||||
backup until the GCS lifecycle policy or the next weekly upload removes them.
|
||||
"""
|
||||
exclude_prefixes = exclude_prefixes or []
|
||||
aws_creds = get_aws_credentials(project)
|
||||
@@ -177,41 +46,32 @@ def upload_staging_to_s3(
|
||||
gcs_client = storage.Client()
|
||||
bucket = gcs_client.bucket(staging_bucket)
|
||||
|
||||
candidates = [
|
||||
blob
|
||||
for blob in bucket.list_blobs()
|
||||
if not (blob.name.startswith(".") or "/.last_sync" in blob.name)
|
||||
and not any(blob.name.startswith(p) for p in exclude_prefixes)
|
||||
]
|
||||
uploaded = 0
|
||||
errors = 0
|
||||
|
||||
candidates, dup_count = _dedupe_final_duplicates(candidates)
|
||||
for blob in bucket.list_blobs():
|
||||
if blob.name.startswith(".") or "/.last_sync" in blob.name:
|
||||
continue
|
||||
|
||||
# Two phases: small/irreplaceable prefixes first (barrier), then large finals,
|
||||
# so a timeout can only ever cost the regenerable finals. Each phase runs in
|
||||
# parallel.
|
||||
critical = [b for b in candidates if not _is_large_last(b.name)]
|
||||
bulk = [b for b in candidates if _is_large_last(b.name)]
|
||||
if any(blob.name.startswith(p) for p in exclude_prefixes):
|
||||
continue
|
||||
|
||||
counts = {"uploaded": 0, "skipped_exists": 0, "error": 0}
|
||||
try:
|
||||
with blob.open("rb") as gcs_file:
|
||||
s3_client.upload_fileobj(
|
||||
Fileobj=gcs_file,
|
||||
Bucket=s3_bucket,
|
||||
Key=blob.name,
|
||||
)
|
||||
uploaded += 1
|
||||
blob.delete()
|
||||
|
||||
def run_phase(phase_blobs):
|
||||
if not phase_blobs:
|
||||
return
|
||||
with ThreadPoolExecutor(max_workers=_MAX_UPLOAD_WORKERS) as pool:
|
||||
for result in pool.map(
|
||||
lambda b: _transfer_blob(b, s3_client, s3_bucket), phase_blobs
|
||||
):
|
||||
counts[result] += 1
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to upload {blob.name}: {e}")
|
||||
errors += 1
|
||||
|
||||
run_phase(critical)
|
||||
run_phase(bulk)
|
||||
|
||||
summary = (
|
||||
f"Uploaded {counts['uploaded']} files to s3://{s3_bucket} "
|
||||
f"(skipped {counts['skipped_exists']} already present, "
|
||||
f"{dup_count} duplicate finals)"
|
||||
)
|
||||
if counts["error"]:
|
||||
summary += f" ({counts['error']} errors)"
|
||||
summary = f"Uploaded {uploaded} files to s3://{s3_bucket}"
|
||||
if errors:
|
||||
summary += f" ({errors} errors)"
|
||||
logger.info(summary)
|
||||
return summary
|
||||
@@ -1,31 +1,15 @@
|
||||
"""Tests for s3_upload: exclude/dedupe/idempotency/ordering behavior."""
|
||||
"""Tests for s3_upload module, focused on the exclude_prefixes behavior."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
_NOT_FOUND = ClientError({"Error": {"Code": "404"}}, "HeadObject")
|
||||
|
||||
|
||||
def _blob(name, size=1234, crc32c=None):
|
||||
def _blob(name):
|
||||
b = MagicMock()
|
||||
b.name = name
|
||||
b.size = size
|
||||
b.crc32c = crc32c if crc32c is not None else f"crc-{name}"
|
||||
b.md5_hash = None
|
||||
# blob.open("rb") is used as a context manager.
|
||||
b.open.return_value.__enter__.return_value = MagicMock()
|
||||
return b
|
||||
|
||||
|
||||
def _mock_boto(mock_boto):
|
||||
"""Default: nothing exists in S3 yet (HEAD -> 404), so everything uploads."""
|
||||
client = mock_boto.return_value
|
||||
client.head_object.side_effect = _NOT_FOUND
|
||||
return client
|
||||
|
||||
|
||||
class TestUploadStagingToS3(unittest.TestCase):
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@@ -34,7 +18,6 @@ class TestUploadStagingToS3(unittest.TestCase):
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
_mock_boto(mock_boto)
|
||||
fs = _blob("firestore/2026-03-29/out.bin")
|
||||
sec = _blob("secrets/2026-03-29.bin")
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [fs, sec]
|
||||
@@ -54,7 +37,6 @@ class TestUploadStagingToS3(unittest.TestCase):
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
_mock_boto(mock_boto)
|
||||
fs = _blob("firestore/2026-03-29/out.bin")
|
||||
sec = _blob("secrets/2026-03-29.bin")
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [fs, sec]
|
||||
@@ -65,106 +47,6 @@ class TestUploadStagingToS3(unittest.TestCase):
|
||||
fs.delete.assert_called_once()
|
||||
sec.delete.assert_called_once()
|
||||
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@patch("s3_upload.get_aws_credentials")
|
||||
def test_byte_identical_final_duplicate_is_deduped(self, mock_creds, mock_storage, mock_boto):
|
||||
"""The machine-named and human-named copies of a final are byte-identical
|
||||
(same crc32c) and live in the same finals/ dir — only one should upload."""
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
_mock_boto(mock_boto)
|
||||
machine = _blob("gcs/job-files/jobs/abc/finals/lossless_4k_mp4.mp4", crc32c="AAAA")
|
||||
human = _blob(
|
||||
"gcs/job-files/jobs/abc/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
crc32c="AAAA",
|
||||
)
|
||||
# A genuinely different final in the same dir must survive.
|
||||
other = _blob("gcs/job-files/jobs/abc/finals/portrait_1080x1920.mp4", crc32c="BBBB")
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [machine, human, other]
|
||||
|
||||
upload_staging_to_s3("staging", "s3b")
|
||||
|
||||
# One of the identical twins is deleted without upload; the other + the
|
||||
# distinct final are uploaded. Two distinct contents -> two uploads.
|
||||
self.assertEqual(mock_boto.return_value.upload_fileobj.call_count, 2)
|
||||
# Every blob is removed from staging (dup via dedupe, others via upload).
|
||||
for b in (machine, human, other):
|
||||
b.delete.assert_called_once()
|
||||
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@patch("s3_upload.get_aws_credentials")
|
||||
def test_already_in_s3_is_skipped_not_reuploaded(self, mock_creds, mock_storage, mock_boto):
|
||||
"""Idempotency: an object already in S3 with the same size is skipped
|
||||
(deleted from staging) rather than re-transferred."""
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
client = mock_boto.return_value
|
||||
present = _blob("gcs/job-files/jobs/abc/finals/portrait_1080x1920.mp4", size=999)
|
||||
fresh = _blob("secrets/2026-09-15.bin", size=42)
|
||||
|
||||
def head(Bucket, Key):
|
||||
if Key == present.name:
|
||||
return {"ContentLength": 999}
|
||||
raise _NOT_FOUND
|
||||
|
||||
client.head_object.side_effect = head
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [present, fresh]
|
||||
|
||||
upload_staging_to_s3("staging", "s3b")
|
||||
|
||||
# Only the not-yet-present object is uploaded; both are cleared from staging.
|
||||
self.assertEqual(client.upload_fileobj.call_count, 1)
|
||||
self.assertEqual(client.upload_fileobj.call_args.kwargs["Key"], fresh.name)
|
||||
present.delete.assert_called_once()
|
||||
fresh.delete.assert_called_once()
|
||||
|
||||
@patch("s3_upload.ThreadPoolExecutor")
|
||||
@patch("s3_upload.boto3.client")
|
||||
@patch("s3_upload.storage.Client")
|
||||
@patch("s3_upload.get_aws_credentials")
|
||||
def test_critical_prefixes_complete_before_large_finals(
|
||||
self, mock_creds, mock_storage, mock_boto, mock_pool
|
||||
):
|
||||
"""Ordering barrier: the small/irreplaceable phase must run to completion
|
||||
before the large gcs/job-files/ phase starts."""
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
|
||||
_mock_boto(mock_boto)
|
||||
|
||||
# Record which blob names each ThreadPoolExecutor.map() phase received.
|
||||
phases = []
|
||||
|
||||
class FakePool:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
def map(self, fn, blobs):
|
||||
blobs = list(blobs)
|
||||
phases.append([b.name for b in blobs])
|
||||
return [fn(b) for b in blobs]
|
||||
|
||||
mock_pool.return_value = FakePool()
|
||||
|
||||
sec = _blob("secrets/2026-09-15.bin")
|
||||
git = _blob("git-repos/nomadkaraoke/karaoke-gen.bundle")
|
||||
final = _blob("gcs/job-files/jobs/abc/finals/lossless_4k_mp4.mp4")
|
||||
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [final, sec, git]
|
||||
|
||||
upload_staging_to_s3("staging", "s3b")
|
||||
|
||||
self.assertEqual(len(phases), 2, "expected a critical phase then a bulk phase")
|
||||
critical_phase, bulk_phase = phases
|
||||
self.assertCountEqual(critical_phase, [sec.name, git.name])
|
||||
self.assertEqual(bulk_phase, [final.name])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -130,62 +130,6 @@ def _search_divebar(query: str, limit: int = 50) -> list[dict]:
|
||||
return results
|
||||
|
||||
|
||||
def _search_kn_community(query: str, limit: int = 50) -> list[dict]:
|
||||
"""Search our OWN KaraokeNerds community catalog (never scrapes karaokenerds.com).
|
||||
|
||||
Reads `karaokenerds_community` — the free, directly-playable (web/YouTube)
|
||||
tracks populated daily by the authorized `kn-data-sync` export. Matching is
|
||||
token-AND (every whitespace token must appear in "artist title"), which mirrors
|
||||
the KaraokeNerds search box closely enough for kjbox's song-search use while
|
||||
tolerating "artist title" / "title artist" / partial queries.
|
||||
|
||||
Returns flat rows ``{artist, title, brand, watch}``; the caller groups them.
|
||||
"""
|
||||
tokens = [t for t in query.lower().split() if t][:12]
|
||||
if not tokens:
|
||||
return []
|
||||
|
||||
def _like_escape(s: str) -> str:
|
||||
# Escape LIKE metacharacters so a token containing % or _ matches
|
||||
# literally instead of acting as a wildcard.
|
||||
return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
client = bigquery.Client(project=GCP_PROJECT_ID)
|
||||
haystack = "LOWER(CONCAT(COALESCE(Artist, ''), ' ', COALESCE(Title, '')))"
|
||||
conditions = []
|
||||
params = []
|
||||
for i, tok in enumerate(tokens):
|
||||
conditions.append(f"{haystack} LIKE @tok{i} ESCAPE '\\\\'")
|
||||
params.append(bigquery.ScalarQueryParameter(f"tok{i}", "STRING", f"%{_like_escape(tok)}%"))
|
||||
params.append(bigquery.ScalarQueryParameter("limit", "INT64", limit))
|
||||
|
||||
sql = f"""
|
||||
SELECT Artist, Title, Brand, Watch
|
||||
FROM `{GCP_PROJECT_ID}.{DATASET}.karaokenerds_community`
|
||||
WHERE {" AND ".join(conditions)}
|
||||
ORDER BY Artist, Title, Brand
|
||||
LIMIT @limit
|
||||
"""
|
||||
|
||||
# The endpoint is public/unauthenticated and each request runs a BigQuery job;
|
||||
# LIMIT bounds rows, not bytes scanned. Cap bytes billed so a flood of queries
|
||||
# against this small (~tens of MB) table can't run up cost (CWE-400).
|
||||
job_config = bigquery.QueryJobConfig(
|
||||
query_parameters=params,
|
||||
maximum_bytes_billed=1_000_000_000, # 1 GB ceiling
|
||||
)
|
||||
|
||||
results = []
|
||||
for row in client.query(sql, job_config=job_config).result():
|
||||
results.append({
|
||||
"artist": row.Artist,
|
||||
"title": row.Title,
|
||||
"brand": row.Brand,
|
||||
"watch": row.Watch,
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def _lookup_kn_ids(kn_ids: list[int]) -> dict[int, list[dict]]:
|
||||
"""Look up which KN songs have Divebar versions via the cross-reference table."""
|
||||
if not kn_ids:
|
||||
@@ -567,17 +511,6 @@ def divebar_lookup(request):
|
||||
results = _search_divebar(query, limit)
|
||||
return _json_response({"status": "ok", "results": results, "count": len(results)})
|
||||
|
||||
elif action == "kn_community_search":
|
||||
raw_query = body.get("query")
|
||||
if not isinstance(raw_query, str) or not (query := raw_query.strip()):
|
||||
return _json_response({"status": "error", "message": "query required"}, 400)
|
||||
raw_limit = body.get("limit", 50)
|
||||
if isinstance(raw_limit, bool) or not isinstance(raw_limit, int):
|
||||
return _json_response({"status": "error", "message": "limit must be an integer"}, 400)
|
||||
limit = max(0, min(raw_limit, 200))
|
||||
results = _search_kn_community(query, limit)
|
||||
return _json_response({"status": "ok", "results": results, "count": len(results)})
|
||||
|
||||
elif action == "lookup":
|
||||
kn_ids = body.get("kn_ids", [])
|
||||
if not kn_ids or not isinstance(kn_ids, list):
|
||||
|
||||
@@ -236,95 +236,3 @@ class TestFullStatsPercent:
|
||||
_patch_bq(monkeypatch, _stats_row(total_files=5, gcs_synced=0, gcs_pending=0, gcs_unavailable=5))
|
||||
g = main._get_full_stats()["gcs_mirror"]
|
||||
assert g["percent"] == 0
|
||||
|
||||
|
||||
def _kn_row(artist, title, brand, watch):
|
||||
row = MagicMock()
|
||||
row.Artist, row.Title, row.Brand, row.Watch = artist, title, brand, watch
|
||||
return row
|
||||
|
||||
|
||||
class TestKnCommunitySearch:
|
||||
"""`kn_community_search` reads our own karaokenerds_community — no scraping."""
|
||||
|
||||
def _patch_query(self, monkeypatch, rows):
|
||||
"""Capture the SQL + params passed to BigQuery and yield `rows`."""
|
||||
captured = {}
|
||||
client = MagicMock()
|
||||
|
||||
def _query(sql, job_config=None):
|
||||
captured["sql"] = sql
|
||||
captured["params"] = job_config.query_parameters if job_config else []
|
||||
result = MagicMock()
|
||||
result.result.return_value = rows
|
||||
return result
|
||||
|
||||
client.query.side_effect = _query
|
||||
monkeypatch.setattr(main.bigquery, "Client", lambda project=None: client)
|
||||
return captured
|
||||
|
||||
def test_returns_flat_rows(self, monkeypatch):
|
||||
rows = [
|
||||
_kn_row("Fleetwood Mac", "Dreams", "Nomad Karaoke", "https://youtu.be/a"),
|
||||
_kn_row("Fleetwood Mac", "Dreams", "WTF Karaoke", "https://youtu.be/b"),
|
||||
]
|
||||
self._patch_query(monkeypatch, rows)
|
||||
out = main._search_kn_community("fleetwood mac dreams")
|
||||
assert out == [
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams", "brand": "Nomad Karaoke", "watch": "https://youtu.be/a"},
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams", "brand": "WTF Karaoke", "watch": "https://youtu.be/b"},
|
||||
]
|
||||
|
||||
def test_token_and_matching_builds_one_condition_per_token(self, monkeypatch):
|
||||
captured = self._patch_query(monkeypatch, [])
|
||||
main._search_kn_community("daft punk one more time")
|
||||
# 5 tokens -> 5 token LIKE conditions, ANDed together, over our own table.
|
||||
assert captured["sql"].count("LIKE @tok") == 5
|
||||
assert " AND " in captured["sql"]
|
||||
assert "karaokenerds_community" in captured["sql"]
|
||||
# LIKE wildcards in tokens are escaped via an ESCAPE clause.
|
||||
assert "ESCAPE" in captured["sql"]
|
||||
|
||||
def test_blank_query_returns_empty_without_bq(self, monkeypatch):
|
||||
# No tokens -> never touches BigQuery.
|
||||
monkeypatch.setattr(main.bigquery, "Client",
|
||||
MagicMock(side_effect=AssertionError("BQ should not be called")))
|
||||
assert main._search_kn_community(" ") == []
|
||||
|
||||
def test_dispatch_returns_results_and_count(self, monkeypatch):
|
||||
self._patch_query(monkeypatch, [_kn_row("ABBA", "SOS", "Nomad Karaoke", "https://youtu.be/s")])
|
||||
body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_community_search", "query": "abba sos"})
|
||||
)
|
||||
assert status == 200
|
||||
payload = json.loads(body)
|
||||
assert payload["status"] == "ok"
|
||||
assert payload["count"] == 1
|
||||
assert payload["results"][0]["brand"] == "Nomad Karaoke"
|
||||
|
||||
def test_dispatch_missing_query_returns_400(self, monkeypatch):
|
||||
body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_community_search"})
|
||||
)
|
||||
assert status == 400
|
||||
|
||||
def test_dispatch_null_query_returns_400_not_500(self, monkeypatch):
|
||||
# {"query": null} must not crash on .strip() -> generic 500.
|
||||
body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_community_search", "query": None})
|
||||
)
|
||||
assert status == 400
|
||||
|
||||
def test_dispatch_non_integer_limit_returns_400(self, monkeypatch):
|
||||
for bad in ("50", True, 1.5):
|
||||
_body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_community_search", "query": "abba", "limit": bad})
|
||||
)
|
||||
assert status == 400, f"limit={bad!r} should be rejected"
|
||||
|
||||
def test_dispatch_negative_limit_clamped_not_500(self, monkeypatch):
|
||||
self._patch_query(monkeypatch, [])
|
||||
_body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_community_search", "query": "abba", "limit": -5})
|
||||
)
|
||||
assert status == 200
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.225.0"
|
||||
version = "0.224.0"
|
||||
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"
|
||||
|
||||
Reference in new issue
Block a user