diff --git a/.claude/plans/song-lookup-autocomplete.plan.md b/.claude/plans/song-lookup-autocomplete.plan.md new file mode 100644 index 00000000..78155081 --- /dev/null +++ b/.claude/plans/song-lookup-autocomplete.plan.md @@ -0,0 +1,239 @@ +# Plan: Song Lookup & Autocomplete + Community Version Detection + +**Created:** 2026-03-02 +**Branch:** feat/sess-20260302-2324-song-lookup-autocomplete +**Status:** Implementation Complete + +## Overview + +Add two features to the karaoke-gen job creation flow: + +1. **Artist/title autocomplete** using karaoke-decide's MusicBrainz + Spotify catalog data, so users get properly-styled artist/title text (e.g. "Fleetwood Mac" instead of "fleetwood mac") +2. **Community karaoke version detection** that warns users when a high-quality community karaoke version already exists on YouTube (via karaokenerds data), saving them credits and time + +Both features are **optional and non-blocking** — users can still type whatever they want and proceed even if a community version exists. + +## Requirements + +- [ ] Artist field autocomplete across all 3 job creation tabs (Search, Upload, URL) +- [ ] Title field autocomplete (optionally filtered by selected artist) across all 3 tabs +- [ ] Autocomplete uses canonical MusicBrainz/Spotify text styling +- [ ] Autocomplete is optional — users can ignore suggestions and type freely +- [ ] Community version check triggers when both artist and title are filled +- [ ] If community karaoke version exists, show a dismissible banner with YouTube link(s) +- [ ] Community check does not block job submission — just informs the user +- [ ] Graceful degradation if karaoke-decide API or karaokenerds.com is down + +## Architecture Decisions + +### How to access karaoke-decide catalog data + +**Decision: Proxy through karaoke-gen backend** + +Both services share the same GCP project (`nomadkaraoke`), but the frontend at `gen.nomadkaraoke.com` can't directly call `decide.nomadkaraoke.com/api/` due to CORS (different origins). Options considered: + +| Option | Pros | Cons | +|--------|------|------| +| **Proxy via karaoke-gen backend** | No CORS issues, no changes to karaoke-decide, frontend already calls api.nomadkaraoke.com | Added latency (extra hop), karaoke-decide dependency | +| Direct frontend calls + CORS | Simpler, no proxy code | Requires karaoke-decide CORS changes, cross-project coupling | +| Query BigQuery directly from karaoke-gen | No dependency on karaoke-decide service | Duplicates query logic, BigQuery setup needed, higher latency | + +The proxy approach is cleanest: karaoke-gen frontend → karaoke-gen backend → karaoke-decide API. Response caching in the proxy minimizes latency impact. + +### How to detect community karaoke versions + +**Decision: Scrape karaokenerds.com from karaoke-gen backend** (same approach as kjbox) + +The `karaokenerds_raw` BigQuery table has the catalog but NOT community status. Community status is determined by an `` badge in karaokenerds.com's HTML, only available via web scraping. The kjbox codebase has proven, well-tested scraping logic we can port directly. + +Search URL: `https://karaokenerds.com/Search?query={artist}+{title}&webFilter=OnlyWeb` + +Returns: songs with tracks, each track having `brand_name`, `brand_code`, `youtube_url`, `is_community`. + +### Autocomplete UI component + +**Decision: Use existing shadcn Command (cmdk) + Popover components** + +The frontend already has `command.tsx` and `popover.tsx` from shadcn/ui. The standard combobox pattern (Popover + Command) provides: +- Keyboard navigation (arrow keys, enter to select) +- Debounced search-as-you-type +- Clean dropdown with loading states +- Works inline within forms (not modal) + +## Technical Approach + +### Data flow + +``` +User types in artist field + → debounced (300ms) API call to GET /api/catalog/artists?q=fle + → karaoke-gen backend proxies to decide.nomadkaraoke.com/api/catalog/artists?q=fle + → returns [{ name: "Fleetwood Mac", mbid: "...", popularity: 85 }, ...] + → user selects "Fleetwood Mac" → field populated with canonical name + +User types in title field + → debounced (300ms) API call to GET /api/catalog/tracks?q=dreams&artist=Fleetwood+Mac + → returns [{ track_name: "Dreams", artist_name: "Fleetwood Mac", popularity: 82 }, ...] + → user selects "Dreams" → field populated with canonical title + +Both fields filled → community check fires + → POST /api/catalog/community-check { artist: "Fleetwood Mac", title: "Dreams" } + → backend scrapes karaokenerds.com for "Fleetwood Mac Dreams" with webFilter=OnlyWeb + → if community tracks found with YouTube URLs, return them + → frontend shows banner: "A community karaoke version already exists! [Watch on YouTube →]" +``` + +### Caching strategy + +| Endpoint | Cache TTL | Scope | +|----------|-----------|-------| +| Artist search proxy | 5 min | In-memory (backend) | +| Track search proxy | 5 min | In-memory (backend) | +| Community check | 1 hour | In-memory (backend) | + +### karaoke-decide API endpoints used + +These are all **public, no auth required**: + +- `GET /api/catalog/artists?q={query}&limit=10` — MBID-first artist search + - Returns: `[{ mbid, name, disambiguation, artist_type, tags, spotify_id, popularity, genres }]` +- `GET /api/catalog/tracks?q={query}&limit=10` — Track search (Spotify data) + - Returns: `[{ track_id, track_name, artist_name, artist_id, popularity, duration_ms, explicit }]` + +## Implementation Steps + +### Phase 1: Backend — Catalog proxy + community check endpoints + +1. [ ] **Add catalog proxy service** — `backend/services/catalog_proxy_service.py` + - HTTP client (httpx async) calling karaoke-decide API + - In-memory TTL cache for responses (5 min) + - Configurable karaoke-decide base URL + - Graceful error handling (return empty results on failure) + +2. [ ] **Port karaokenerds scraping logic** — `backend/services/karaokenerds_service.py` + - Port `search()`, `parse_results()`, `_parse_tracks()`, `_parse_single_track()`, `_clean_youtube_url()` from `kjbox/kj-controller/karaoke_nerds.py` + - Add async support (httpx instead of requests) + - In-memory TTL cache (1 hour) + - Return only community tracks with YouTube URLs + +3. [ ] **Add catalog routes** — `backend/api/routes/catalog.py` + - `GET /api/catalog/artists?q=&limit=10` — proxy to karaoke-decide + - `GET /api/catalog/tracks?q=&artist=&limit=10` — proxy to karaoke-decide + - `POST /api/catalog/community-check` — scrape karaokenerds.com + - All endpoints require auth (same as job creation) + - Pydantic request/response models + +4. [ ] **Register routes in main.py** — add `catalog.router` to app + +5. [ ] **Add config** — `backend/config.py` + - `karaoke_decide_api_url` setting (default: `https://decide.nomadkaraoke.com`) + +6. [ ] **Add `beautifulsoup4` + `httpx` dependencies** to `pyproject.toml` (if not already present) + +### Phase 2: Frontend — Autocomplete component + +7. [ ] **Create `AutocompleteInput` component** — `frontend/components/ui/autocomplete-input.tsx` + - Wraps an Input field with a Popover + Command dropdown + - Props: `value`, `onChange`, `onSelect`, `fetchSuggestions(query) => Promise`, `placeholder`, `disabled`, `renderItem` + - Debounced search (300ms) triggered on input change + - Shows loading spinner while fetching + - Shows "No results" when search returns empty + - Keyboard navigation (up/down arrows, enter to select, escape to close) + - Clicking outside closes dropdown + - When user selects a suggestion, calls `onSelect(suggestion)` and populates input + - When user types without selecting, uses their raw text (autocomplete is optional) + +8. [ ] **Add catalog API functions** — `frontend/lib/api.ts` + - `searchArtists(query: string, limit?: number)` → `GET /api/catalog/artists` + - `searchTracks(query: string, artist?: string, limit?: number)` → `GET /api/catalog/tracks` + - `checkCommunityVersions(artist: string, title: string)` → `POST /api/catalog/community-check` + +### Phase 3: Frontend — Integrate autocomplete into job creation + +9. [ ] **Replace artist Input fields with AutocompleteInput** in `JobSubmission.tsx` + - All 3 tabs: `searchArtist`, `uploadArtist`, `youtubeArtist` + - Fetch suggestions from `api.searchArtists(query)` + - On select: populate artist field with canonical name + - Show artist name + optional disambiguation in dropdown items + +10. [ ] **Replace title Input fields with AutocompleteInput** in `JobSubmission.tsx` + - All 3 tabs: `searchTitle`, `uploadTitle`, `youtubeTitle` + - Fetch suggestions from `api.searchTracks(query, selectedArtist)` + - On select: populate title field with canonical name + - Show track name + artist name + duration in dropdown items + +### Phase 4: Frontend — Community version detection + +11. [ ] **Create `CommunityVersionBanner` component** — `frontend/components/job/CommunityVersionBanner.tsx` + - Shows when community karaoke version(s) found + - Displays: "A karaoke version of this song already exists!" + - Lists community tracks with brand name and YouTube link + - "Watch on YouTube" button for top community version + - Dismissible (X button or "Continue anyway" link) + - Styled with green border (matching kjbox community track styling) + +12. [ ] **Add community check logic to `JobSubmission.tsx`** (Search tab only) + - Debounced check (500ms) when both artist AND title fields have values + - Only triggers when values change (not on every keystroke) + - Shows `CommunityVersionBanner` between the form fields and the submit button + - Does NOT block form submission + - Clears when artist or title changes + +### Phase 5: Testing + +13. [ ] **Backend unit tests** — `backend/tests/unit/test_catalog_routes.py` + - Test proxy endpoints with mocked karaoke-decide responses + - Test community check with mocked karaokenerds HTML + - Test error handling (karaoke-decide down, karaokenerds down) + - Test caching behavior + +14. [ ] **Backend unit tests** — `backend/tests/unit/test_karaokenerds_service.py` + - Port relevant tests from `kjbox/kj-controller/tests/unit/test_karaoke_nerds.py` + - Test HTML parsing, community detection, YouTube URL cleanup + +15. [ ] **Frontend component tests** — `frontend/components/ui/__tests__/autocomplete-input.test.tsx` + - Test suggestion fetching and display + - Test keyboard navigation + - Test selection behavior + - Test free-text input (no selection) + +16. [ ] **E2E tests** — `frontend/e2e/job-creation-autocomplete.spec.ts` + - Test autocomplete appears on typing + - Test selecting from autocomplete populates field + - Test community banner appears for known songs + - Test form submission works with and without autocomplete selection + +## Files to Create/Modify + +| File | Action | Description | +|------|--------|-------------| +| `backend/services/catalog_proxy_service.py` | Create | HTTP client for karaoke-decide API with caching | +| `backend/services/karaokenerds_service.py` | Create | Karaokenerds.com scraper (ported from kjbox) | +| `backend/api/routes/catalog.py` | Create | Proxy endpoints for artist/track search + community check | +| `backend/main.py` | Modify | Register catalog router | +| `backend/config.py` | Modify | Add karaoke_decide_api_url setting | +| `pyproject.toml` | Modify | Add beautifulsoup4 dependency (if missing) | +| `frontend/components/ui/autocomplete-input.tsx` | Create | Reusable autocomplete input component | +| `frontend/components/job/CommunityVersionBanner.tsx` | Create | Community version warning banner | +| `frontend/components/job/JobSubmission.tsx` | Modify | Replace Input with AutocompleteInput, add community check | +| `frontend/lib/api.ts` | Modify | Add catalog API functions | +| `backend/tests/unit/test_catalog_routes.py` | Create | Backend route tests | +| `backend/tests/unit/test_karaokenerds_service.py` | Create | Scraper unit tests | +| `frontend/components/ui/__tests__/autocomplete-input.test.tsx` | Create | Component tests | +| `frontend/e2e/job-creation-autocomplete.spec.ts` | Create | E2E tests | + +## Decisions (Resolved) + +- **Track search scope**: All Spotify tracks (256M) — better coverage for new/obscure songs +- **Community check scope**: Search tab only (Upload/URL users already have their audio) +- **Rate limiting**: 20 requests/min per user on catalog proxy endpoints (prevents abuse of karaokenerds scraping). All endpoints require auth. +- **"Display As" fields**: No autocomplete — they're for deliberate overrides like soundtrack names +- **CORS**: Proxy approach (no changes needed to karaoke-decide) + +## Rollback Plan + +- Feature is entirely additive — no existing functionality is modified +- Autocomplete fields fall back to plain text Input if API calls fail +- Community check is non-blocking — if it fails, form works normally +- All new endpoints are behind the existing auth middleware +- Can disable by reverting the frontend changes (backend proxy is harmless if unused) diff --git a/backend/api/routes/catalog.py b/backend/api/routes/catalog.py new file mode 100644 index 00000000..044e11b3 --- /dev/null +++ b/backend/api/routes/catalog.py @@ -0,0 +1,156 @@ +""" +Catalog API routes for song/artist lookup and community version detection. + +Provides autocomplete data from karaoke-decide's MusicBrainz + Spotify catalog, +and checks karaokenerds.com for existing community karaoke versions. +""" + +import logging +import time +from typing import Optional + +from fastapi import APIRouter, Depends, HTTPException, Query, Request +from pydantic import BaseModel, Field + +from backend.api.dependencies import require_auth +from backend.services.auth_service import AuthResult + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/catalog", tags=["catalog"]) + +# Simple per-user rate limiting: 20 requests/minute +# { user_email: [timestamp, timestamp, ...] } +_rate_limit_windows: dict[str, list[float]] = {} +RATE_LIMIT_MAX_REQUESTS = 20 +RATE_LIMIT_WINDOW_SECONDS = 60 + + +def _check_rate_limit(user_email: str) -> None: + """Check per-user rate limit. Raises 429 if exceeded.""" + now = time.monotonic() + window_start = now - RATE_LIMIT_WINDOW_SECONDS + + # Get or create window for this user + if user_email not in _rate_limit_windows: + _rate_limit_windows[user_email] = [] + + # Remove expired entries + timestamps = _rate_limit_windows[user_email] + _rate_limit_windows[user_email] = [t for t in timestamps if t > window_start] + + if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS: + raise HTTPException( + status_code=429, + detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.", + ) + + _rate_limit_windows[user_email].append(now) + + +# --- Response Models --- + + +class ArtistResult(BaseModel): + """Artist search result from MusicBrainz/Spotify catalog.""" + name: str + mbid: Optional[str] = None + disambiguation: Optional[str] = None + artist_type: Optional[str] = None + spotify_id: Optional[str] = None + popularity: Optional[int] = None + genres: Optional[list[str]] = None + tags: Optional[list[str]] = None + + +class TrackResult(BaseModel): + """Track search result from Spotify catalog.""" + track_name: str + artist_name: str + track_id: Optional[str] = None + artist_id: Optional[str] = None + popularity: Optional[int] = None + duration_ms: Optional[int] = None + explicit: Optional[bool] = None + + +class CommunityTrack(BaseModel): + """A community-approved karaoke track from karaokenerds.""" + brand_name: str + brand_code: str + youtube_url: str + is_community: bool = True + + +class CommunityCheckSong(BaseModel): + """A song with community karaoke tracks.""" + title: str + artist: str + community_tracks: list[CommunityTrack] + + +class CommunityCheckRequest(BaseModel): + """Request body for community version check.""" + artist: str = Field(..., min_length=1) + title: str = Field(..., min_length=1) + + +class CommunityCheckResponse(BaseModel): + """Response for community version check.""" + has_community: bool + songs: list[CommunityCheckSong] + best_youtube_url: Optional[str] = None + + +# --- Routes --- + + +@router.get("/artists", response_model=list[ArtistResult]) +async def search_artists( + q: str = Query(..., min_length=2, description="Artist name search query"), + limit: int = Query(10, ge=1, le=50, description="Maximum results"), + auth_result: AuthResult = Depends(require_auth), +): + """ + Search for artists by name. Returns canonical MusicBrainz/Spotify artist data + for autocomplete in job creation forms. + """ + _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown") + + from backend.services.catalog_proxy_service import search_artists + results = await search_artists(q, limit) + return results + + +@router.get("/tracks", response_model=list[TrackResult]) +async def search_tracks( + q: str = Query(..., min_length=2, description="Track name search query"), + artist: Optional[str] = Query(None, description="Filter by artist name"), + limit: int = Query(10, ge=1, le=50, description="Maximum results"), + auth_result: AuthResult = Depends(require_auth), +): + """ + Search for tracks by name, optionally filtered by artist. + Returns canonical Spotify track data for autocomplete in job creation forms. + """ + _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown") + + from backend.services.catalog_proxy_service import search_tracks + results = await search_tracks(q, artist, limit) + return results + + +@router.post("/community-check", response_model=CommunityCheckResponse) +async def check_community_versions( + body: CommunityCheckRequest, + auth_result: AuthResult = Depends(require_auth), +): + """ + Check if a song already has community-approved karaoke versions on YouTube + via karaokenerds.com. Non-blocking — just informs the user. + """ + _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown") + + from backend.services.karaokenerds_service import check_community_versions + result = await check_community_versions(body.artist, body.title) + return result diff --git a/backend/config.py b/backend/config.py index 7e7366a2..88ceed88 100644 --- a/backend/config.py +++ b/backend/config.py @@ -83,6 +83,9 @@ class Settings(BaseSettings): # Requires use_gce_encoding to be enabled and the GCE worker to support /encode-preview endpoint. use_gce_preview_encoding: bool = os.getenv("USE_GCE_PREVIEW_ENCODING", "false").lower() in ("true", "1", "yes") + # Karaoke-Decide catalog API (for song/artist autocomplete) + karaoke_decide_api_url: str = os.getenv("KARAOKE_DECIDE_API_URL", "https://decide.nomadkaraoke.com") + # Storage paths temp_dir: str = os.getenv("TEMP_DIR", "/tmp/karaoke-gen") diff --git a/backend/main.py b/backend/main.py index 49325932..9435ef39 100644 --- a/backend/main.py +++ b/backend/main.py @@ -7,7 +7,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from backend.config import settings -from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push +from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id from backend.services.structured_logging import setup_structured_logging from backend.services.spacy_preloader import preload_spacy_model @@ -161,6 +161,7 @@ app.include_router(users.router, prefix="/api") # User auth, credits, and Strip app.include_router(admin.router, prefix="/api") # Admin dashboard and management app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management app.include_router(push.router, prefix="/api") # Push notification subscription management +app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it) diff --git a/backend/services/catalog_proxy_service.py b/backend/services/catalog_proxy_service.py new file mode 100644 index 00000000..944f1524 --- /dev/null +++ b/backend/services/catalog_proxy_service.py @@ -0,0 +1,105 @@ +""" +Proxy service for karaoke-decide catalog API. + +Forwards artist and track search requests to the karaoke-decide backend, +providing autocomplete data from MusicBrainz + Spotify catalogs. +""" + +import logging +import time +from typing import Any + +import httpx + +from backend.config import settings + +logger = logging.getLogger(__name__) + +# In-memory TTL cache: { cache_key: (expiry_timestamp, data) } +_cache: dict[str, tuple[float, Any]] = {} +CACHE_TTL_SECONDS = 300 # 5 minutes + +KARAOKE_DECIDE_BASE_URL = "https://decide.nomadkaraoke.com" +REQUEST_TIMEOUT = 10 # seconds + + +def _get_base_url() -> str: + """Get the karaoke-decide API base URL from config or default.""" + return getattr(settings, "karaoke_decide_api_url", None) or KARAOKE_DECIDE_BASE_URL + + +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 _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) + + +async def search_artists(query: str, limit: int = 10) -> list[dict]: + """ + Search for artists via karaoke-decide catalog API. + + Returns list of artist dicts with canonical MusicBrainz names. + Falls back to empty list on any error. + """ + cache_key = f"artists:{query.lower()}:{limit}" + cached = _cache_get(cache_key) + if cached is not None: + return cached + + base_url = _get_base_url() + url = f"{base_url}/api/catalog/artists" + params = {"q": query, "limit": limit} + + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: + resp = await client.get(url, params=params) + resp.raise_for_status() + data = resp.json() + # karaoke-decide wraps results: {"artists": [...], "total": N} + results = data.get("artists", data) if isinstance(data, dict) else data + _cache_set(cache_key, results) + return results + except Exception as e: + logger.warning(f"Failed to search artists from karaoke-decide: {e}") + return [] + + +async def search_tracks(query: str, artist: str | None = None, limit: int = 10) -> list[dict]: + """ + Search for tracks via karaoke-decide catalog API. + + Returns list of track dicts with canonical Spotify/MusicBrainz names. + Falls back to empty list on any error. + """ + cache_key = f"tracks:{query.lower()}:{(artist or '').lower()}:{limit}" + cached = _cache_get(cache_key) + if cached is not None: + return cached + + base_url = _get_base_url() + url = f"{base_url}/api/catalog/tracks" + params: dict[str, Any] = {"q": query, "limit": limit} + if artist: + params["artist"] = artist + + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: + resp = await client.get(url, params=params) + resp.raise_for_status() + data = resp.json() + # karaoke-decide wraps results: {"tracks": [...], "total": N} + results = data.get("tracks", data) if isinstance(data, dict) else data + _cache_set(cache_key, results) + return results + except Exception as e: + logger.warning(f"Failed to search tracks from karaoke-decide: {e}") + return [] diff --git a/backend/services/karaokenerds_service.py b/backend/services/karaokenerds_service.py new file mode 100644 index 00000000..739d135c --- /dev/null +++ b/backend/services/karaokenerds_service.py @@ -0,0 +1,203 @@ +""" +KaraokeNerds community version detection service. + +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 logging +import re +import time +from typing import Any +from urllib.parse import urlencode + +import httpx +from bs4 import BeautifulSoup + +logger = logging.getLogger(__name__) + +SEARCH_URL = "https://karaokenerds.com/Search" +REQUEST_TIMEOUT = 8 +USER_AGENT = "NomadKaraokeGen/1.0" + +# In-memory TTL cache: { cache_key: (expiry_timestamp, data) } +_cache: dict[str, tuple[float, Any]] = {} +CACHE_TTL_SECONDS = 3600 # 1 hour + + +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 _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 _clean_youtube_url(url: str) -> str: + """Strip playlist params from YouTube URLs, keep just the video URL.""" + return re.sub(r"&list=[^&]*", "", url) + + +def _parse_single_track(li) -> dict | None: + """Parse a single track
  • element from karaokenerds search results.""" + # Brand name: first 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) + + # 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 { + "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 check_community_versions(artist: str, title: str) -> dict: + """ + Check if a song has community-approved karaoke versions on karaokenerds. + + 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) + """ + query = f"{artist} {title}" + cache_key = f"community:{query.lower().strip()}" + cached = _cache_get(cache_key) + if cached is not None: + return cached + + 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}") + result = {"has_community": False, "songs": [], "best_youtube_url": None} + _cache_set(cache_key, result) + return result + + songs = parse_results(resp.text) + + # Filter to only songs that have community tracks with YouTube URLs + community_songs = [] + best_youtube_url = 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"] + + result = { + "has_community": len(community_songs) > 0, + "songs": community_songs, + "best_youtube_url": best_youtube_url, + } + _cache_set(cache_key, result) + return result diff --git a/backend/tests/test_catalog_routes.py b/backend/tests/test_catalog_routes.py new file mode 100644 index 00000000..d0dcd9dc --- /dev/null +++ b/backend/tests/test_catalog_routes.py @@ -0,0 +1,194 @@ +""" +Tests for catalog API routes — proxy endpoints and community check. +""" + +import pytest +from unittest.mock import AsyncMock, patch, MagicMock +from fastapi.testclient import TestClient + +from backend.main import app + + +@pytest.fixture +def client(): + """Test client with mocked auth.""" + return TestClient(app) + + +@pytest.fixture +def auth_headers(): + """Headers for authenticated requests.""" + return {"Authorization": "Bearer test-admin-token"} + + +@pytest.fixture(autouse=True) +def clear_rate_limits(): + """Clear rate limit state between tests.""" + from backend.api.routes.catalog import _rate_limit_windows + _rate_limit_windows.clear() + yield + _rate_limit_windows.clear() + + +# --- Artist search --- + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock) +def test_search_artists_returns_results(mock_search, mock_auth, client, auth_headers): + mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test") + mock_search.return_value = [ + {"name": "Fleetwood Mac", "mbid": "abc-123", "popularity": 85}, + {"name": "Fleet Foxes", "mbid": "def-456", "popularity": 72}, + ] + + response = client.get("/api/catalog/artists?q=flee", headers=auth_headers) + assert response.status_code == 200 + data = response.json() + assert len(data) == 2 + assert data[0]["name"] == "Fleetwood Mac" + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock) +def test_search_artists_empty_results(mock_search, mock_auth, client, auth_headers): + mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test") + mock_search.return_value = [] + + response = client.get("/api/catalog/artists?q=zzzzz", headers=auth_headers) + assert response.status_code == 200 + assert response.json() == [] + + +def test_search_artists_requires_min_query_length(client, auth_headers): + response = client.get("/api/catalog/artists?q=a", headers=auth_headers) + assert response.status_code == 422 # Validation error + + +# --- Track search --- + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.catalog_proxy_service.search_tracks", new_callable=AsyncMock) +def test_search_tracks_returns_results(mock_search, mock_auth, client, auth_headers): + mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test") + mock_search.return_value = [ + {"track_name": "Dreams", "artist_name": "Fleetwood Mac", "popularity": 82}, + ] + + response = client.get("/api/catalog/tracks?q=dreams", headers=auth_headers) + assert response.status_code == 200 + data = response.json() + assert len(data) == 1 + assert data[0]["track_name"] == "Dreams" + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.catalog_proxy_service.search_tracks", new_callable=AsyncMock) +def test_search_tracks_with_artist_filter(mock_search, mock_auth, client, auth_headers): + mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test") + mock_search.return_value = [] + + response = client.get( + "/api/catalog/tracks?q=dreams&artist=Fleetwood+Mac", + headers=auth_headers, + ) + assert response.status_code == 200 + mock_search.assert_called_once_with("dreams", "Fleetwood Mac", 10) + + +# --- Community check --- + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.karaokenerds_service.check_community_versions", new_callable=AsyncMock) +def test_community_check_found(mock_check, mock_auth, client, auth_headers): + mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test") + mock_check.return_value = { + "has_community": True, + "songs": [ + { + "title": "Dreams", + "artist": "Fleetwood Mac", + "community_tracks": [ + { + "brand_name": "Karaoke Version", + "brand_code": "KV", + "youtube_url": "https://www.youtube.com/watch?v=abc", + "is_community": True, + } + ], + } + ], + "best_youtube_url": "https://www.youtube.com/watch?v=abc", + } + + response = client.post( + "/api/catalog/community-check", + json={"artist": "Fleetwood Mac", "title": "Dreams"}, + headers=auth_headers, + ) + assert response.status_code == 200 + data = response.json() + assert data["has_community"] is True + assert len(data["songs"]) == 1 + assert data["best_youtube_url"] == "https://www.youtube.com/watch?v=abc" + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.karaokenerds_service.check_community_versions", new_callable=AsyncMock) +def test_community_check_not_found(mock_check, mock_auth, client, auth_headers): + mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test") + mock_check.return_value = { + "has_community": False, + "songs": [], + "best_youtube_url": None, + } + + response = client.post( + "/api/catalog/community-check", + json={"artist": "Unknown Artist", "title": "Unknown Song"}, + headers=auth_headers, + ) + assert response.status_code == 200 + data = response.json() + assert data["has_community"] is False + + +def test_community_check_validation_error(client, auth_headers): + response = client.post( + "/api/catalog/community-check", + json={"artist": "", "title": "Dreams"}, + headers=auth_headers, + ) + assert response.status_code == 422 + + +# --- Rate limiting --- + + +@patch("backend.api.routes.catalog.require_auth") +@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock) +def test_rate_limit_enforced(mock_search, mock_auth, client, auth_headers): + """Rate limit allows up to 20 requests per minute, then returns 429.""" + # Use a unique email so other tests' requests don't interfere + unique_email = "ratelimit-unique-test@test.com" + mock_auth.return_value = MagicMock(user_email=unique_email, token_id="test") + mock_search.return_value = [] + + # Clear any existing rate limit state for this user + from backend.api.routes.catalog import _rate_limit_windows + _rate_limit_windows.pop(unique_email, None) + + # First 20 requests should succeed + for i in range(20): + resp = client.get("/api/catalog/artists?q=test", headers=auth_headers) + assert resp.status_code == 200, f"Request {i+1}/20 failed with {resp.status_code}" + + # 21st request should be rate limited + resp = client.get("/api/catalog/artists?q=test", headers=auth_headers) + assert resp.status_code == 429 + assert "Rate limit exceeded" in resp.json()["detail"] + + # Clean up + _rate_limit_windows.pop(unique_email, None) diff --git a/backend/tests/test_karaokenerds_service.py b/backend/tests/test_karaokenerds_service.py new file mode 100644 index 00000000..4ceebb30 --- /dev/null +++ b/backend/tests/test_karaokenerds_service.py @@ -0,0 +1,209 @@ +""" +Tests for the karaokenerds service — HTML parsing, community detection, YouTube URL cleanup. + +Ported from kjbox/kj-controller/tests/unit/test_karaoke_nerds.py. +""" + +import pytest +from backend.services.karaokenerds_service import ( + parse_results, + _clean_youtube_url, + _parse_single_track, +) +from bs4 import BeautifulSoup + + +# --- YouTube URL cleanup --- + + +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" + + +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" + + +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" + + +# --- Single track parsing --- + + +TRACK_HTML_COMMUNITY = """ +
  • + Karaoke Version + +
  • +""" + +TRACK_HTML_NO_COMMUNITY = """ +
  • + Sunfly + +
  • +""" + +TRACK_HTML_NO_YOUTUBE = """ +
  • + Some Brand + +
  • +""" + + +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_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"] + + +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 = """ + + + + + + + + + + + + + + + + + + + +
    DreamsFleetwood Mac2 Brands >>
    + +
    The ChainFleetwood Mac1 Brand >>
    + +
    +""" + + +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("") == [] + assert parse_results("
    ") == [] + + +def test_parse_results_no_table(): + assert parse_results("
    No results
    ") == [] diff --git a/frontend/components/job/CommunityVersionBanner.tsx b/frontend/components/job/CommunityVersionBanner.tsx new file mode 100644 index 00000000..bc7099cb --- /dev/null +++ b/frontend/components/job/CommunityVersionBanner.tsx @@ -0,0 +1,90 @@ +"use client" + +import { X, ExternalLink } from "lucide-react" +import type { CommunityCheckResponse } from "@/lib/api" + +interface CommunityVersionBannerProps { + data: CommunityCheckResponse + onDismiss: () => void +} + +export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBannerProps) { + if (!data.has_community || data.songs.length === 0) return null + + // Collect all community tracks across songs, take top 3 + const allTracks = data.songs.flatMap((song) => + song.community_tracks.map((track) => ({ + ...track, + songArtist: song.artist, + songTitle: song.title, + })) + ) + const displayTracks = allTracks.slice(0, 3) + + return ( +
    + + +
    +

    + A karaoke version of this song already exists! +

    +

    + Check if an existing version works for you before using a credit. +

    + +
    + {displayTracks.map((track, i) => ( + + + + {track.brand_name} + {track.brand_code && ( + + Community + + )} + + + Watch on YouTube + + + ))} +
    + + {allTracks.length > 3 && ( +

    + +{allTracks.length - 3} more version{allTracks.length - 3 > 1 ? "s" : ""} +

    + )} +
    +
    + ) +} diff --git a/frontend/components/job/JobSubmission.tsx b/frontend/components/job/JobSubmission.tsx index 46b8e774..57ee1827 100644 --- a/frontend/components/job/JobSubmission.tsx +++ b/frontend/components/job/JobSubmission.tsx @@ -1,11 +1,14 @@ "use client" -import { useState, useEffect, useMemo } from "react" +import { useState, useEffect, useMemo, useCallback, useRef } from "react" import { api, ApiError } from "@/lib/api" +import type { CatalogArtistResult, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api" import { useAuth } from "@/lib/auth" import { useTenant } from "@/lib/tenant" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" +import { AutocompleteInput, type AutocompleteSuggestion } from "@/components/ui/autocomplete-input" +import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner" import { Label } from "@/components/ui/label" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Upload, Youtube, Music, Loader2, ChevronDown, ChevronRight, AlertTriangle } from "lucide-react" @@ -67,9 +70,84 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) { const [isPrivate, setIsPrivate] = useState(false) const [showBuyCreditsDialog, setShowBuyCreditsDialog] = useState(false) + // Community version check (Search tab only) + const [communityData, setCommunityData] = useState(null) + const [communityDismissed, setCommunityDismissed] = useState(false) + const communityCheckRef = useRef | null>(null) + // Credit enforcement const noCredits = !isAdmin && user?.credits === 0 + // --- Autocomplete helpers --- + + const fetchArtistSuggestions = useCallback(async (query: string): Promise => { + try { + const results = await api.searchCatalogArtists(query) + return results.map((artist: CatalogArtistResult) => ({ + key: artist.mbid || artist.spotify_id || artist.name, + label: artist.name, + description: artist.disambiguation || undefined, + meta: artist.popularity != null ? `${artist.popularity}` : undefined, + data: artist, + })) + } catch { + return [] + } + }, []) + + const fetchTrackSuggestions = useCallback( + (artistFilter?: string) => + async (query: string): Promise => { + try { + const results = await api.searchCatalogTracks(query, artistFilter || undefined) + return results.map((track: CatalogTrackResult) => ({ + key: track.track_id || `${track.artist_name}-${track.track_name}`, + label: track.track_name, + description: track.artist_name, + meta: track.duration_ms + ? `${Math.floor(track.duration_ms / 60000)}:${String(Math.floor((track.duration_ms % 60000) / 1000)).padStart(2, "0")}` + : undefined, + data: track, + })) + } catch { + return [] + } + }, + [] + ) + + // Community check: fires when both searchArtist and searchTitle have values (Search tab only) + useEffect(() => { + // Reset when inputs change + setCommunityData(null) + setCommunityDismissed(false) + + if (communityCheckRef.current) { + clearTimeout(communityCheckRef.current) + } + + const artist = searchArtist.trim() + const title = searchTitle.trim() + if (!artist || !title || artist.length < 2 || title.length < 2) { + return + } + + communityCheckRef.current = setTimeout(async () => { + try { + const result = await api.checkCommunityVersions(artist, title) + setCommunityData(result) + } catch { + // Silently fail - community check is non-critical + } + }, 500) + + return () => { + if (communityCheckRef.current) { + clearTimeout(communityCheckRef.current) + } + } + }, [searchArtist, searchTitle]) + async function handleUploadSubmit(e: React.FormEvent) { e.preventDefault() setError("") @@ -293,29 +371,31 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
    - setUploadArtist(e.target.value)} + onChange={setUploadArtist} + fetchSuggestions={fetchArtistSuggestions} disabled={isSubmitting} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} />
    - setUploadTitle(e.target.value)} + onChange={setUploadTitle} + fetchSuggestions={fetchTrackSuggestions(uploadArtist)} disabled={isSubmitting} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} />

    - Note: Format these exactly as you want them on the title card and video filename. + Tip: Start typing and select from suggestions for correct formatting, or type freely.

    {/* Private (no YouTube upload) mode */} @@ -390,29 +470,31 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
    - setYoutubeArtist(e.target.value)} + onChange={setYoutubeArtist} + fetchSuggestions={fetchArtistSuggestions} disabled={isSubmitting} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} />
    - setYoutubeTitle(e.target.value)} + onChange={setYoutubeTitle} + fetchSuggestions={fetchTrackSuggestions(youtubeArtist)} disabled={isSubmitting} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} />

    - Note: Format these exactly as you want them on the title card and video filename. + Tip: Start typing and select from suggestions for correct formatting, or type freely.

    {/* Private (no YouTube upload) mode */} @@ -473,24 +555,26 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
    - setSearchArtist(e.target.value)} + onChange={setSearchArtist} + fetchSuggestions={fetchArtistSuggestions} disabled={isSubmitting} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} />
    - setSearchTitle(e.target.value)} + onChange={setSearchTitle} + fetchSuggestions={fetchTrackSuggestions(searchArtist)} disabled={isSubmitting} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} /> @@ -498,9 +582,17 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {

    - Note: Format these exactly as you want them on the title card and video filename. + Tip: Start typing and select from suggestions for correct formatting, or type freely.

    + {/* Community version check banner */} + {communityData?.has_community && !communityDismissed && ( + setCommunityDismissed(true)} + /> + )} + {/* Display As toggle (optional) */}
    - onTitleChange(e.target.value)} + onChange={onTitleChange} + onSelect={(s) => { + onTitleChange(s.label) + // Overwrite artist with the canonical name from the selected track + if (s.data?.artist_name) { + onArtistChange(s.data.artist_name) + } + }} + fetchSuggestions={fetchTrackSuggestions} disabled={disabled} style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }} />
    + {/* Community version banner */} + {communityData?.has_community && !communityDismissed && ( + setCommunityDismissed(true)} + /> + )} + {/* Tip callout */}
    void + /** Called when a suggestion is selected */ + onSelect?: (suggestion: AutocompleteSuggestion) => void + /** Async function to fetch suggestions for a query */ + fetchSuggestions: (query: string) => Promise + /** Minimum characters before fetching suggestions */ + minChars?: number + /** Debounce delay in ms */ + debounceMs?: number + /** Input placeholder */ + placeholder?: string + /** Disable the input */ + disabled?: boolean + /** HTML id for the input */ + id?: string + /** data-testid for testing */ + "data-testid"?: string + /** Inline style for the input element */ + style?: React.CSSProperties + /** Additional className for the input */ + className?: string +} + +export function AutocompleteInput({ + value, + onChange, + onSelect, + fetchSuggestions, + minChars = 2, + debounceMs = 300, + placeholder, + disabled, + id, + "data-testid": dataTestId, + style, + className, +}: AutocompleteInputProps) { + const [open, setOpen] = useState(false) + const [suggestions, setSuggestions] = useState([]) + const [isLoading, setIsLoading] = useState(false) + const inputRef = useRef(null) + const debounceRef = useRef | null>(null) + // Track whether the user just selected a suggestion to avoid re-fetching + const justSelectedRef = useRef(false) + + const doFetch = useCallback( + async (query: string) => { + if (query.length < minChars) { + setSuggestions([]) + setOpen(false) + return + } + + setIsLoading(true) + try { + const results = await fetchSuggestions(query) + setSuggestions(results) + setOpen(results.length > 0) + } catch { + setSuggestions([]) + setOpen(false) + } finally { + setIsLoading(false) + } + }, + [fetchSuggestions, minChars] + ) + + // Debounced fetch on value change + useEffect(() => { + if (justSelectedRef.current) { + justSelectedRef.current = false + return + } + + if (debounceRef.current) { + clearTimeout(debounceRef.current) + } + + if (value.length < minChars) { + setSuggestions([]) + setOpen(false) + return + } + + debounceRef.current = setTimeout(() => { + doFetch(value) + }, debounceMs) + + return () => { + if (debounceRef.current) { + clearTimeout(debounceRef.current) + } + } + }, [value, doFetch, debounceMs, minChars]) + + function handleSelect(suggestion: AutocompleteSuggestion) { + justSelectedRef.current = true + onChange(suggestion.label) + onSelect?.(suggestion) + setOpen(false) + setSuggestions([]) + // Re-focus input after selection + inputRef.current?.focus() + } + + function handleInputChange(e: React.ChangeEvent) { + onChange(e.target.value) + } + + function handleKeyDown(e: React.KeyboardEvent) { + // Let cmdk handle arrow keys and enter when popover is open + if (open && (e.key === "ArrowDown" || e.key === "ArrowUp")) { + // Don't prevent - let the event bubble to Command + return + } + if (e.key === "Escape") { + setOpen(false) + } + } + + return ( + + +
    + { + // Re-open if we have suggestions + if (suggestions.length > 0 && value.length >= minChars) { + setOpen(true) + } + }} + placeholder={placeholder} + disabled={disabled} + style={style} + className={cn( + "file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", + "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]", + className + )} + autoComplete="off" + /> + {isLoading && ( + + )} +
    +
    + { + // Prevent popover from stealing focus from input + e.preventDefault() + }} + > + + + + No results found + + + {suggestions.map((suggestion) => ( + handleSelect(suggestion)} + className="cursor-pointer" + > +
    +
    +
    + {suggestion.label} +
    + {suggestion.description && ( +
    + {suggestion.description} +
    + )} +
    + {suggestion.meta && ( + + {suggestion.meta} + + )} +
    +
    + ))} +
    +
    +
    +
    +
    + ) +} diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index d7f5a58e..0e586ea2 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -288,6 +288,48 @@ async function handleResponse(response: Response): Promise { return response.json(); } +// --- Catalog types (song/artist autocomplete + community check) --- + +export interface CatalogArtistResult { + name: string; + mbid?: string; + disambiguation?: string; + artist_type?: string; + spotify_id?: string; + popularity?: number; + genres?: string[]; + tags?: string[]; +} + +export interface CatalogTrackResult { + track_name: string; + artist_name: string; + track_id?: string; + artist_id?: string; + popularity?: number; + duration_ms?: number; + explicit?: boolean; +} + +export interface CommunityTrack { + brand_name: string; + brand_code: string; + youtube_url: string; + is_community: boolean; +} + +export interface CommunityCheckSong { + title: string; + artist: string; + community_tracks: CommunityTrack[]; +} + +export interface CommunityCheckResponse { + has_community: boolean; + songs: CommunityCheckSong[]; + best_youtube_url: string | null; +} + export const api = { /** * List all jobs @@ -1145,6 +1187,37 @@ export const api = { }); return handleResponse(response); }, + + // --- Catalog (song/artist autocomplete + community check) --- + + async searchCatalogArtists(query: string, limit: number = 10): Promise { + const params = new URLSearchParams({ q: query, limit: String(limit) }); + const response = await fetch(`${API_BASE_URL}/api/catalog/artists?${params}`, { + headers: getAuthHeaders() + }); + return handleResponse(response); + }, + + async searchCatalogTracks(query: string, artist?: string, limit: number = 10): Promise { + const params = new URLSearchParams({ q: query, limit: String(limit) }); + if (artist) params.set('artist', artist); + const response = await fetch(`${API_BASE_URL}/api/catalog/tracks?${params}`, { + headers: getAuthHeaders() + }); + return handleResponse(response); + }, + + async checkCommunityVersions(artist: string, title: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/catalog/community-check`, { + method: 'POST', + headers: { + ...getAuthHeaders(), + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ artist, title }), + }); + return handleResponse(response); + }, }; // Types for credits/payment diff --git a/frontend/next.config.mjs b/frontend/next.config.mjs index 27c2e6d5..1e558ccc 100644 --- a/frontend/next.config.mjs +++ b/frontend/next.config.mjs @@ -30,6 +30,11 @@ const nextConfig = { images: { unoptimized: true, }, + // Set turbopack root to the frontend directory so it can resolve packages + // from worktrees (where the path differs from the main clone) + turbopack: { + root: __dirname, + }, // GitHub Pages serves from subdomain, so no basePath needed // gen.nomadkaraoke.com -> nomadkaraoke.github.io/karaoke-gen diff --git a/pyproject.toml b/pyproject.toml index 78bb5eae..c3b6c129 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "karaoke-gen" -version = "0.122.6" +version = "0.123.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 "] license = "MIT"