mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 18:08:07 +09:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c6b471e59 |
No files matched your search
+24
-57
@@ -516,10 +516,7 @@ jobs:
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Build package
|
||||
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
|
||||
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
|
||||
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
|
||||
run: poetry build --format wheel
|
||||
run: poetry build
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
@@ -834,12 +831,7 @@ jobs:
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Build package
|
||||
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
|
||||
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
|
||||
# dead weight and pushed the project over PyPI's 10 GB storage cap.
|
||||
# pip always installs from the wheel; nothing builds karaoke-gen from
|
||||
# source (the GCE encoding worker pulls the wheel from GCS).
|
||||
run: poetry build --format wheel
|
||||
run: poetry build
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -933,6 +925,7 @@ jobs:
|
||||
prerelease: false
|
||||
files: |
|
||||
dist/*.whl
|
||||
dist/*.tar.gz
|
||||
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (Cloudflare Pages)"
|
||||
@@ -1406,47 +1399,29 @@ jobs:
|
||||
run: |
|
||||
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
|
||||
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
# Probe the worker's active_jobs. Echoes a non-negative integer on a
|
||||
# successful /health response, or "unknown" if /health can't be
|
||||
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
|
||||
# encoder running a 4K render pins all 32 cores and can miss the 5s
|
||||
# health window, and treating that as idle previously let us stop the
|
||||
# VM mid-render — orphaning the job and surfacing as "lost contact
|
||||
# with worker ... not found" (incident 2026-06-15).
|
||||
probe_active_jobs() {
|
||||
local body n
|
||||
body=$(curl -sf --connect-timeout 3 --max-time 5 \
|
||||
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
|
||||
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
|
||||
case "$n" in
|
||||
''|*[!0-9]*) echo "unknown" ;;
|
||||
*) echo "$n" ;;
|
||||
esac
|
||||
}
|
||||
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
|
||||
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
|
||||
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
|
||||
# waiting — we only stop on a definitive 0 (or after the timeout, so
|
||||
# a wedged worker can't block the deploy forever). 20 min comfortably
|
||||
# covers a full 4K render; the old primary only drains in-flight work
|
||||
# since new renders already route to the just-swapped new primary.
|
||||
DRAIN_TIMEOUT=1200
|
||||
ELAPSED=0
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "Initial active_jobs: $ACTIVE_JOBS"
|
||||
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
done
|
||||
|
||||
if [ "$ACTIVE_JOBS" = "0" ]; then
|
||||
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
|
||||
else
|
||||
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
|
||||
if [ "$ACTIVE_JOBS" -gt 0 ]; then
|
||||
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
|
||||
DRAIN_TIMEOUT=600
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
if [ "$ACTIVE_JOBS" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
@@ -1683,7 +1658,7 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-fable-5,AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
@@ -1701,14 +1676,6 @@ jobs:
|
||||
--quiet
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
|
||||
# ("Invalid secret path ... in annotation") because this job's existing
|
||||
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
|
||||
# re-validates and rejects. Proactive auto-correct env/secret
|
||||
# (AUTO_CORRECT_PROACTIVE_ENABLED + ANTHROPIC_API_KEY) must be wired by a
|
||||
# method that handles the alias format (see proactive-autocorrect plan
|
||||
# doc); until then the proactive flag stays unset and the worker's
|
||||
# _run_proactive_auto_correct() returns early (no-op).
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
|
||||
@@ -54,14 +54,8 @@ jobs:
|
||||
|
||||
BUCKET = os.environ["BUCKET"]
|
||||
# (label, prefix, max_age_hours)
|
||||
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
|
||||
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
|
||||
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
|
||||
# sees the S3 (off-site) copy, so their limits must allow a full week
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
|
||||
# files and secrets DO upload to S3 nightly, so they stay at 36h.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 192),
|
||||
("Firestore", "firestore/", 36),
|
||||
("GCS job files", "gcs/job-files/", 36),
|
||||
("Encrypted secrets", "secrets/", 36),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192),
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
name: E2E Daily Test (Tenant Portals)
|
||||
|
||||
# Full production E2E per white-label tenant: submit a job with the tenant's own
|
||||
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
|
||||
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
|
||||
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
|
||||
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
|
||||
# top-of-hour scheduler herd.
|
||||
- cron: '7 0 * * *'
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # for Workload Identity Federation
|
||||
|
||||
jobs:
|
||||
e2e-tenant:
|
||||
name: "Tenant E2E: ${{ matrix.tenant }}"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
|
||||
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
|
||||
max-parallel: 1
|
||||
matrix:
|
||||
tenant: [vocalstar, singa]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install google-cloud-storage google-cloud-secret-manager
|
||||
|
||||
- name: Run tenant E2E
|
||||
id: run_test
|
||||
env:
|
||||
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
run: |
|
||||
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
|
||||
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
|
||||
path: e2e-output.log
|
||||
retention-days: 14
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
|
||||
run: |
|
||||
if [ -n "$DISCORD_WEBHOOK" ]; then
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
|
||||
"$DISCORD_WEBHOOK" || true
|
||||
fi
|
||||
|
||||
- name: Fail the job if the test failed
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
run: exit 1
|
||||
|
||||
notify-email:
|
||||
name: "Email summary"
|
||||
runs-on: ubuntu-latest
|
||||
needs: e2e-tenant
|
||||
if: ${{ always() && github.event_name == 'schedule' }}
|
||||
steps:
|
||||
- name: Send email notification
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.postmarkapp.com
|
||||
server_port: 587
|
||||
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
Tenant E2E Daily Test (Vocal Star + Singa)
|
||||
Result: ${{ needs.e2e-tenant.result }}
|
||||
Run: #${{ github.run_number }}
|
||||
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -1,436 +0,0 @@
|
||||
"""Bulk Mode API routes.
|
||||
|
||||
Lets a user submit up to 100 karaoke jobs at once, by text (artist/title rows)
|
||||
or by album (MusicBrainz release lookup). Album tracklists and text rows are
|
||||
enriched with KaraokeNerds community-version availability so the user can skip
|
||||
tracks that already exist.
|
||||
|
||||
Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
|
||||
(added in later phases).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
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="/bulk", tags=["bulk"])
|
||||
|
||||
MAX_BULK_SONGS = 100
|
||||
|
||||
|
||||
# --- Models -----------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkArtist(BaseModel):
|
||||
mbid: Optional[str] = None
|
||||
name: str
|
||||
disambiguation: str = ""
|
||||
type: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
|
||||
|
||||
class BulkAlbum(BaseModel):
|
||||
release_group_mbid: str
|
||||
title: str
|
||||
primary_type: Optional[str] = None
|
||||
secondary_types: list[str] = []
|
||||
first_release_date: str = ""
|
||||
is_studio: bool = True
|
||||
|
||||
|
||||
class BulkEdition(BaseModel):
|
||||
release_mbid: str
|
||||
title: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
date: str = ""
|
||||
country: Optional[str] = None
|
||||
track_count: int = 0
|
||||
|
||||
|
||||
class BulkTrack(BaseModel):
|
||||
position: Optional[int] = None
|
||||
title: str
|
||||
recording_mbid: Optional[str] = None
|
||||
length_ms: Optional[int] = None
|
||||
is_extra: bool = False
|
||||
extra_reason: str = ""
|
||||
# Availability (filled from KaraokeNerds); available=True => already exists
|
||||
available: bool = False
|
||||
brands: list[str] = []
|
||||
|
||||
|
||||
class BulkTracklistResponse(BaseModel):
|
||||
release_mbid: Optional[str] = None
|
||||
canonical_release_mbid: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
date: str = ""
|
||||
tracks: list[BulkTrack] = []
|
||||
editions: list[BulkEdition] = []
|
||||
|
||||
|
||||
class AvailabilityItem(BaseModel):
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class AvailabilityRequest(BaseModel):
|
||||
tracks: list[AvailabilityItem]
|
||||
|
||||
|
||||
class AvailabilityResult(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
available: bool
|
||||
brands: list[str] = []
|
||||
brand_count: int = 0
|
||||
|
||||
|
||||
class AvailabilityResponse(BaseModel):
|
||||
results: list[AvailabilityResult]
|
||||
|
||||
|
||||
# --- Album lookup routes ----------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/album/artists", response_model=list[BulkArtist])
|
||||
async def album_artists(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Artist name search"),
|
||||
limit: int = Query(8, ge=1, le=25),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Search MusicBrainz for artists (album-mode step 1)."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
|
||||
try:
|
||||
results = await get_musicbrainz_service().search_artists(q, limit=limit)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz artist search failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Artist lookup is temporarily unavailable")
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/album/albums", response_model=list[BulkAlbum])
|
||||
async def album_albums(
|
||||
request: Request,
|
||||
artist_mbid: str = Query(..., min_length=1),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""List an artist's albums (release-groups) for the album picker."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
|
||||
try:
|
||||
return await get_musicbrainz_service().get_albums(artist_mbid)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz album list failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Album lookup is temporarily unavailable")
|
||||
|
||||
|
||||
@router.get("/album/tracklist", response_model=BulkTracklistResponse)
|
||||
async def album_tracklist(
|
||||
request: Request,
|
||||
artist: str = Query(..., min_length=1, description="Artist name for availability checks"),
|
||||
release_group_mbid: Optional[str] = Query(None),
|
||||
release_mbid: Optional[str] = Query(None, description="Specific edition to load"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Resolve an album's canonical tracklist (or a specific edition) and enrich
|
||||
each track with KaraokeNerds community-version availability."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
from backend.services.karaokenerds_service import check_community_versions_batch
|
||||
|
||||
if not release_group_mbid and not release_mbid:
|
||||
raise HTTPException(status_code=422, detail="release_group_mbid or release_mbid required")
|
||||
|
||||
mb = get_musicbrainz_service()
|
||||
try:
|
||||
if release_mbid:
|
||||
tracklist = await mb.get_release_tracklist(release_mbid)
|
||||
tracklist.setdefault("editions", [])
|
||||
tracklist.setdefault("canonical_release_mbid", release_mbid)
|
||||
else:
|
||||
tracklist = await mb.get_album_tracklist(release_group_mbid)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz tracklist failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Tracklist lookup is temporarily unavailable")
|
||||
|
||||
tracks = tracklist.get("tracks", [])
|
||||
# Availability enrichment — never fatal.
|
||||
try:
|
||||
avail = await check_community_versions_batch(
|
||||
[{"artist": artist, "title": t["title"]} for t in tracks]
|
||||
)
|
||||
for t, a in zip(tracks, avail):
|
||||
t["available"] = a["available"]
|
||||
t["brands"] = a["brands"]
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Availability enrichment failed (non-fatal): %s", e)
|
||||
|
||||
return BulkTracklistResponse(
|
||||
release_mbid=tracklist.get("release_mbid"),
|
||||
canonical_release_mbid=tracklist.get("canonical_release_mbid"),
|
||||
title=tracklist.get("title"),
|
||||
date=tracklist.get("date", ""),
|
||||
tracks=[BulkTrack(**t) for t in tracks],
|
||||
editions=[BulkEdition(**e) for e in tracklist.get("editions", [])],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/availability", response_model=AvailabilityResponse)
|
||||
async def bulk_availability(
|
||||
request: Request,
|
||||
body: AvailabilityRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Batch KaraokeNerds availability check for text-mode rows."""
|
||||
from backend.services.karaokenerds_service import check_community_versions_batch
|
||||
|
||||
if len(body.tracks) > MAX_BULK_SONGS:
|
||||
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} tracks per request")
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": t.artist, "title": t.title} for t in body.tracks]
|
||||
)
|
||||
return AvailabilityResponse(results=[AvailabilityResult(**r) for r in results])
|
||||
|
||||
|
||||
# --- Submission -------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkSong(BaseModel):
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
display_artist: Optional[str] = None
|
||||
display_title: Optional[str] = None
|
||||
|
||||
|
||||
class BulkSettings(BaseModel):
|
||||
auto_select_if_lossless: bool = True
|
||||
is_private: bool = False
|
||||
skip_audio_edit: bool = True
|
||||
skip_customization: bool = True
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
songs: list[BulkSong]
|
||||
settings: BulkSettings = Field(default_factory=BulkSettings)
|
||||
|
||||
|
||||
class BulkSubmitResponse(BaseModel):
|
||||
batch_id: str
|
||||
job_ids: list[str]
|
||||
total: int
|
||||
|
||||
|
||||
@router.post("/submit", response_model=BulkSubmitResponse)
|
||||
async def bulk_submit(
|
||||
request: Request,
|
||||
body: BulkSubmitRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Create one job per song, gate on credits upfront, and dispatch the batch
|
||||
search worker. Jobs start parked (auto_download=False) and the worker either
|
||||
auto-selects a confident lossless match or leaves them awaiting selection."""
|
||||
from backend.config import get_settings
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.models.job import JobCreate
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
n = len(body.songs)
|
||||
if n == 0:
|
||||
raise HTTPException(status_code=422, detail="At least one song is required")
|
||||
if n > MAX_BULK_SONGS:
|
||||
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} songs per batch")
|
||||
|
||||
user_email = auth_result.user_email
|
||||
is_admin = bool(auth_result.is_admin)
|
||||
|
||||
# Upfront credit gate (1 credit/song minimum). Admins bypass.
|
||||
if not is_admin and user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
available = get_user_service().check_credits(user_email)
|
||||
if available < n:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"error": "insufficient_credits",
|
||||
"message": "You don't have enough credits for this batch.",
|
||||
"credits_available": available,
|
||||
"credits_required": n,
|
||||
},
|
||||
)
|
||||
|
||||
settings = get_settings()
|
||||
theme_service = get_theme_service()
|
||||
theme_id = theme_service.get_default_theme_id()
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
|
||||
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
bulk_settings = body.settings.model_dump()
|
||||
job_manager = JobManager()
|
||||
job_ids: list[str] = []
|
||||
|
||||
for song in body.songs:
|
||||
display_artist = (song.display_artist or song.artist).strip()
|
||||
display_title = (song.display_title or song.title).strip()
|
||||
request_metadata = {
|
||||
"created_from": "bulk",
|
||||
"batch_id": batch_id,
|
||||
"user_email": user_email,
|
||||
}
|
||||
job_create = JobCreate(
|
||||
artist=display_artist,
|
||||
title=display_title,
|
||||
theme_id=theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
user_email=user_email,
|
||||
audio_search_artist=song.artist.strip(),
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
discord_webhook_url=settings.default_discord_webhook_url,
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
request_metadata=request_metadata,
|
||||
)
|
||||
try:
|
||||
job = job_manager.create_job(job_create, is_admin=is_admin)
|
||||
except InsufficientCreditsError:
|
||||
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
|
||||
# already-created jobs are valid and will proceed.
|
||||
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
|
||||
break
|
||||
|
||||
job_manager.update_job(
|
||||
job.job_id,
|
||||
{
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
},
|
||||
)
|
||||
job_ids.append(job.job_id)
|
||||
|
||||
if not job_ids:
|
||||
raise HTTPException(status_code=402, detail="No jobs could be created")
|
||||
|
||||
# Dispatch the batch search worker. Retry once on transient failure. If it
|
||||
# still fails the jobs exist (and are charged) but won't process, so surface
|
||||
# an explicit error with the batch_id — and tell the user NOT to resubmit
|
||||
# (that would create+charge a second batch); the batch can be re-dispatched.
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
logger.critical(
|
||||
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
|
||||
batch_id, len(job_ids),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={
|
||||
"error": "dispatch_failed",
|
||||
"message": "Your batch was created but processing couldn't start. "
|
||||
"Please don't resubmit — contact support with this batch ID and we'll start it.",
|
||||
"batch_id": batch_id,
|
||||
"job_ids": job_ids,
|
||||
},
|
||||
)
|
||||
logger.info("[batch:%s] created %d jobs, dispatched bulk-search worker", batch_id, len(job_ids))
|
||||
|
||||
return BulkSubmitResponse(batch_id=batch_id, job_ids=job_ids, total=len(job_ids))
|
||||
|
||||
|
||||
# --- Progress ---------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkJobStatus(BaseModel):
|
||||
job_id: str
|
||||
artist: str
|
||||
title: str
|
||||
status: str
|
||||
auto_selected: bool = False
|
||||
|
||||
|
||||
class BulkBatchResponse(BaseModel):
|
||||
batch_id: str
|
||||
total: int
|
||||
counts: dict
|
||||
jobs: list[BulkJobStatus]
|
||||
|
||||
|
||||
# Status -> progress bucket for the batch summary.
|
||||
_AWAITING = "awaiting_audio_selection"
|
||||
_TERMINAL_OK = "complete"
|
||||
_TERMINAL_FAIL = "failed"
|
||||
_SEARCHING = {"pending", "searching_audio"}
|
||||
|
||||
|
||||
def _bucket(status: str, pending_search: bool) -> str:
|
||||
if pending_search or status in _SEARCHING:
|
||||
return "searching"
|
||||
if status == _AWAITING:
|
||||
return "awaiting_selection"
|
||||
if status == _TERMINAL_OK:
|
||||
return "complete"
|
||||
if status == _TERMINAL_FAIL:
|
||||
return "failed"
|
||||
return "processing"
|
||||
|
||||
|
||||
@router.get("/{batch_id}", response_model=BulkBatchResponse)
|
||||
async def bulk_batch(
|
||||
request: Request,
|
||||
batch_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Progress summary for a batch: counts by bucket + per-job status."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job_manager = JobManager()
|
||||
jobs = job_manager.list_jobs_by_batch_id(batch_id)
|
||||
|
||||
if not bool(auth_result.is_admin):
|
||||
email = (auth_result.user_email or "").lower()
|
||||
jobs = [j for j in jobs if (j.user_email or "").lower() == email]
|
||||
|
||||
if not jobs:
|
||||
raise HTTPException(status_code=404, detail="Batch not found")
|
||||
|
||||
counts = {"searching": 0, "awaiting_selection": 0, "processing": 0, "complete": 0, "failed": 0}
|
||||
job_statuses: list[BulkJobStatus] = []
|
||||
for j in jobs:
|
||||
status = j.status.value if hasattr(j.status, "value") else str(j.status)
|
||||
sd = j.state_data or {}
|
||||
bucket = _bucket(status, bool(sd.get("bulk_pending_search")))
|
||||
counts[bucket] += 1
|
||||
job_statuses.append(
|
||||
BulkJobStatus(
|
||||
job_id=j.job_id,
|
||||
artist=j.audio_search_artist or j.artist or "",
|
||||
title=j.audio_search_title or j.title or "",
|
||||
status=status,
|
||||
auto_selected=bool(sd.get("bulk_auto_selected")),
|
||||
)
|
||||
)
|
||||
|
||||
return BulkBatchResponse(
|
||||
batch_id=batch_id, total=len(jobs), counts=counts, jobs=job_statuses
|
||||
)
|
||||
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Literal, Optional
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -103,38 +103,6 @@ class CommunityCheckResponse(BaseModel):
|
||||
best_youtube_url: Optional[str] = None
|
||||
|
||||
|
||||
class MatchJudgeRequest(BaseModel):
|
||||
"""Request body for the artist/title match judge."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
# The audio search's confidence tier (1=strong..3=weak), so the judge can
|
||||
# tell whether weak results hint at a typo. Optional.
|
||||
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
|
||||
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
|
||||
# parallel with the audio search; "full" = complete pipeline once the tier is
|
||||
# known. Defaults to "full" so a single legacy call still works.
|
||||
stage: Literal["fast", "full"] = "full"
|
||||
|
||||
|
||||
class MatchJudgeAlternative(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
class MatchJudgeResponse(BaseModel):
|
||||
"""Verdict on a typed artist/title — formatting + match acceptance."""
|
||||
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[MatchJudgeAlternative] = []
|
||||
engine: str # "deterministic" | "catalog" | "ai"
|
||||
reason: str = ""
|
||||
# Set by a "fast" pass that couldn't decide — the client should follow up with
|
||||
# a "full" call once the audio tier is known.
|
||||
needs_ai: bool = False
|
||||
|
||||
|
||||
# --- Routes ---
|
||||
|
||||
|
||||
@@ -193,31 +161,3 @@ async def check_community_versions(
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/match-judge", response_model=MatchJudgeResponse)
|
||||
async def match_judge(
|
||||
request: Request,
|
||||
body: MatchJudgeRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Judge a typed artist/title: decide official formatting + whether it matches a
|
||||
real song. Deterministic + catalog layers run first; a light AI model fires
|
||||
only when those aren't confident. Never blocks the submission flow — failures
|
||||
degrade to a "none" verdict.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.match_judge.service import judge_match
|
||||
verdict = await judge_match(
|
||||
body.artist, body.title,
|
||||
audio_tier=body.audio_confidence_tier,
|
||||
stage=body.stage,
|
||||
)
|
||||
logger.info(
|
||||
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
|
||||
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
|
||||
)
|
||||
return verdict.to_dict()
|
||||
@@ -57,19 +57,6 @@ def _is_youtube_url(url: str) -> bool:
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _select_mixed_audio_files(files):
|
||||
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
|
||||
|
||||
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
|
||||
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
|
||||
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
|
||||
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
|
||||
the instrumental — so transcription would run on the backing track instead of the
|
||||
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
|
||||
"""
|
||||
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
@@ -80,20 +67,12 @@ def _apply_tenant_overrides(
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
|
||||
distribution settings, so tenant outputs never inherit the global consumer defaults
|
||||
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
|
||||
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
|
||||
tenant job would land in the shared consumer Dropbox folder and upload to the global
|
||||
Google Drive, regardless of the tenant's own config.
|
||||
|
||||
For tenant jobs:
|
||||
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
|
||||
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
|
||||
otherwise disables that channel entirely (no global-default leak)
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload (tenants never publish to YouTube)
|
||||
- Disables YouTube upload
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
@@ -102,12 +81,14 @@ def _apply_tenant_overrides(
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
features = tenant_config.features
|
||||
|
||||
# Authoritative distribution routing (overrides any global defaults in `dist`).
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
@@ -1401,14 +1382,12 @@ async def mark_uploads_complete(
|
||||
|
||||
# List files with this prefix to find the actual uploaded file
|
||||
files = storage_service.list_files(prefix)
|
||||
if file_type == 'audio':
|
||||
files = _select_mixed_audio_files(files)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
|
||||
)
|
||||
|
||||
|
||||
# Use the first (and should be only) file found
|
||||
gcs_path = files[0]
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.workers.audio_worker import process_audio_separation
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
from backend.workers.lyrics_worker import process_lyrics_transcription
|
||||
from backend.workers.screens_worker import generate_screens
|
||||
from backend.workers.video_worker import generate_video
|
||||
@@ -228,48 +227,6 @@ async def trigger_lyrics_worker(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/auto-correct", response_model=WorkerResponse)
|
||||
async def trigger_auto_correct_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Proactively pre-generate + cache AI auto-correct suggestions for a job.
|
||||
|
||||
Called by the lyrics worker once transcription + references are ready, so
|
||||
the suggestions are cached before the reviewer opens the lyrics UI. Runs
|
||||
HERE (the API service) because the service has the working Anthropic key /
|
||||
compare-models config; the lyrics job does not.
|
||||
|
||||
Best-effort and runs synchronously within the request (the caller awaits
|
||||
with its own timeout): the work never fails the karaoke job, and the
|
||||
response just reports what happened. Gated by AUTO_CORRECT_PROACTIVE_ENABLED.
|
||||
"""
|
||||
job_id = request.job_id
|
||||
|
||||
# Extract trace context from incoming request (propagated via the trigger).
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_TRIGGER worker=auto-correct")
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("worker", "auto-correct")
|
||||
|
||||
# process_proactive_auto_correct already swallows its own errors; the extra
|
||||
# guard keeps the endpoint itself best-effort no matter what.
|
||||
try:
|
||||
result = await process_proactive_auto_correct(job_id)
|
||||
add_span_event("auto_correct_proactive", {"result": result.get("status", "unknown")})
|
||||
return WorkerResponse(
|
||||
status=result.get("status", "unknown"),
|
||||
job_id=job_id,
|
||||
message=f"Proactive auto-correct: {result.get('status', 'unknown')}",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fail the caller
|
||||
logger.warning(f"[job:{job_id}] auto-correct endpoint error (non-fatal): {e}")
|
||||
add_span_event("auto_correct_proactive", {"result": "error"})
|
||||
return WorkerResponse(status="error", job_id=job_id, message=f"error: {e}")
|
||||
|
||||
|
||||
@router.post("/workers/screens", response_model=WorkerResponse)
|
||||
async def trigger_screens_worker(
|
||||
request: WorkerRequest,
|
||||
|
||||
@@ -576,8 +576,6 @@ _SUMMARY_STATE_DATA_KEYS = {
|
||||
'pending_additional_credits',
|
||||
'duration_actual_seconds',
|
||||
'duration_confirm_reason',
|
||||
'batch_id',
|
||||
'bulk_auto_selected',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
|
||||
@@ -1477,13 +1475,6 @@ async def complete_review(
|
||||
try:
|
||||
# Store instrumental selection if provided (combined review flow)
|
||||
instrumental_selection = body.instrumental_selection if body else None
|
||||
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
|
||||
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
|
||||
# render uses the provided instrumental instead of a separated stem that was never
|
||||
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
|
||||
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
instrumental_selection = 'custom'
|
||||
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
|
||||
if instrumental_selection:
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
|
||||
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
|
||||
@@ -2443,21 +2434,11 @@ async def create_job_from_search(
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
|
||||
|
||||
# Determine display values.
|
||||
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
|
||||
# body.title carry whatever is currently in the wizard's artist/title fields,
|
||||
# which reflect a "Use official formatting" correction the user may have applied
|
||||
# after searching. The displayed job name must honour that correction, so prefer
|
||||
# the request body over the stored query. An explicit display override wins above all.
|
||||
# Determine display values
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
# body.artist/body.title are required but unvalidated for whitespace, so strip
|
||||
# them and fall back to the stored query if blank (display_* is pre-stripped to
|
||||
# None by its validator). This keeps a stray " " from becoming the job name.
|
||||
body_artist = (body.artist or "").strip()
|
||||
body_title = (body.title or "").strip()
|
||||
effective_display_artist = body.display_artist or body_artist or session_artist
|
||||
effective_display_title = body.display_title or body_title or session_title
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id') or ""
|
||||
|
||||
|
||||
@@ -105,7 +105,6 @@ class AutoCorrectResponse(_PydBaseModel):
|
||||
elapsed_seconds: float
|
||||
settings_applied: dict
|
||||
warnings: list[str]
|
||||
cached: bool = False
|
||||
|
||||
|
||||
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
|
||||
@@ -748,7 +747,6 @@ async def auto_correct_suggestions(
|
||||
elapsed_seconds=result.elapsed_seconds,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
warnings=result.warnings,
|
||||
cached=result.cached,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -95,27 +95,6 @@ class Settings(BaseSettings):
|
||||
# Models used by the multi-model "compare" mode (semicolon-separated —
|
||||
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
|
||||
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
|
||||
# Proactively generate (and cache) auto-correct suggestions in the lyrics
|
||||
# worker once transcription + references are ready, so the review UI has
|
||||
# them instantly. Best-effort: failures never block or fail the job. Only
|
||||
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
|
||||
# (the lyrics-transcription-job, via ci.yml). Default off.
|
||||
auto_correct_proactive_enabled: bool = os.getenv(
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Match judge — artist/title formatting + match-acceptance for the job
|
||||
# submission flow. Deterministic + catalog layers always run; the light AI
|
||||
# layer (Vertex Gemini Flash) fires only when those aren't confident.
|
||||
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
|
||||
"true", "1", "yes",
|
||||
)
|
||||
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
|
||||
# Bounds the AI call so a hung model never strands the submission UI. Kept
|
||||
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
|
||||
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
|
||||
# call still runs off the critical path and degrades to "none" on timeout.
|
||||
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
|
||||
|
||||
# Cloud Tasks (for scalable worker coordination)
|
||||
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
|
||||
|
||||
+1
-2
@@ -10,7 +10,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, catalog, encoding_worker, client_errors, bulk
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors
|
||||
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
|
||||
@@ -187,7 +187,6 @@ app.include_router(admin.router, prefix="/api") # Admin dashboard and managemen
|
||||
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(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Operational and maintenance scripts for the karaoke-gen backend."""
|
||||
@@ -1,199 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill original input audio into past jobs' Dropbox folders.
|
||||
|
||||
Restores files like ``<artist> - <title> (flacfetch).flac`` / ``(uploaded).mp3`` to
|
||||
the organised Dropbox track folders for completed jobs that predate the pipeline fix
|
||||
(the distributed pipeline stopped copying the source audio into the output folder).
|
||||
|
||||
Dry-run by default; pass ``--live`` to actually upload. NOTE: this cannot backfill the
|
||||
screen ``.mov`` files — those require re-encoding the job.
|
||||
|
||||
Usage:
|
||||
python -m backend.scripts.backfill_original_audio # dry-run, since 2026-03-01
|
||||
python -m backend.scripts.backfill_original_audio --live # actually upload
|
||||
python -m backend.scripts.backfill_original_audio --since 2026-02-01 --limit 50 -v
|
||||
"""
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.original_audio import (
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("backfill_original_audio")
|
||||
|
||||
# The regression window: screen/audio files stopped reaching Dropbox once the
|
||||
# distributed pipeline took over (last known-good folder ~Feb; PR #647/#650 Mar 31).
|
||||
DEFAULT_SINCE = "2026-03-01"
|
||||
|
||||
|
||||
def plan_job_backfill(job, *, storage, dropbox):
|
||||
"""Decide what to do for one job (existence checks only — no uploads).
|
||||
|
||||
Returns ``(action, detail)`` where action is one of:
|
||||
- ``"skip-no-dropbox"`` — job was never uploaded to Dropbox
|
||||
- ``"skip-no-audio-record"`` — no original-audio reference on the job
|
||||
- ``"skip-audio-missing-gcs"`` — original audio no longer in GCS (detail=gcs_path)
|
||||
- ``"skip-folder-missing"`` — the track's Dropbox folder doesn't exist (detail=folder)
|
||||
- ``"skip-already-present"`` — file already in the Dropbox folder (detail=remote_path)
|
||||
- ``"upload"`` — detail={gcs_path, remote_path, filename}
|
||||
"""
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
state = getattr(job, "state_data", None) or {}
|
||||
brand_code = state.get("brand_code")
|
||||
# Use the EFFECTIVE dropbox path — private (NOMADNP) tracks upload to the
|
||||
# NonPublished path, not the job's stored (public) dropbox_path. This mirrors
|
||||
# what the orchestrator does at distribution time.
|
||||
dropbox_path = get_effective_distribution_for_job(job).dropbox_path
|
||||
if not brand_code or not dropbox_path:
|
||||
return ("skip-no-dropbox", None)
|
||||
|
||||
gcs_path = original_audio_gcs_path(job)
|
||||
if not gcs_path:
|
||||
return ("skip-no-audio-record", None)
|
||||
if not storage.file_exists(gcs_path):
|
||||
return ("skip-audio-missing-gcs", gcs_path)
|
||||
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
filename = original_audio_output_filename(job, base_name)
|
||||
folder = f"{dropbox_path.rstrip('/')}/{brand_code} - {base_name}"
|
||||
remote_path = f"{folder}/{filename}"
|
||||
|
||||
# Only backfill into a track folder that already exists — never create a new
|
||||
# folder (guards against drifted brand/artist/title naming producing an orphan).
|
||||
if not dropbox.file_exists(folder):
|
||||
return ("skip-folder-missing", folder)
|
||||
|
||||
if dropbox.file_exists(remote_path):
|
||||
return ("skip-already-present", remote_path)
|
||||
|
||||
return ("upload", {"gcs_path": gcs_path, "remote_path": remote_path, "filename": filename})
|
||||
|
||||
|
||||
def _execute_upload(detail, *, storage, dropbox):
|
||||
"""Download the original audio from GCS and upload it to the Dropbox folder."""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
local = os.path.join(td, detail["filename"])
|
||||
storage.download_file(detail["gcs_path"], local)
|
||||
dropbox.upload_file(local, detail["remote_path"])
|
||||
|
||||
|
||||
def run_backfill(*, since, until=None, limit, environment, live):
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
jm = JobManager()
|
||||
storage = StorageService()
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
logger.error("Dropbox not configured; aborting.")
|
||||
return
|
||||
|
||||
# NOTE: created_at is stored as an ISO string in Firestore, so server-side
|
||||
# created_after/created_before datetime filters match nothing. We fetch the most
|
||||
# recent completed jobs (ordered by created_at desc) and filter dates in Python.
|
||||
# `limit` therefore bounds how far back we look — set it high enough to cover the
|
||||
# window since `since`.
|
||||
jobs = jm.list_jobs(status=JobStatus.COMPLETE, limit=limit)
|
||||
|
||||
def _created(j):
|
||||
c = getattr(j, "created_at", None)
|
||||
if c is None:
|
||||
return None
|
||||
return c.replace(tzinfo=None) if getattr(c, "tzinfo", None) else c
|
||||
|
||||
since_naive = since.replace(tzinfo=None)
|
||||
until_naive = until.replace(tzinfo=None) if until else None
|
||||
|
||||
def _in_window(j):
|
||||
c = _created(j)
|
||||
if c is None:
|
||||
return False
|
||||
if c < since_naive:
|
||||
return False
|
||||
if until_naive and c >= until_naive:
|
||||
return False
|
||||
return True
|
||||
|
||||
jobs = [j for j in jobs if _in_window(j)]
|
||||
|
||||
if environment:
|
||||
def _env(j):
|
||||
rm = getattr(j, "request_metadata", None)
|
||||
if rm is None:
|
||||
return None
|
||||
return rm.get("environment") if isinstance(rm, dict) else getattr(rm, "environment", None)
|
||||
jobs = [j for j in jobs if _env(j) == environment]
|
||||
|
||||
logger.info(
|
||||
"Considering %d completed jobs since %s (env=%s, fetch limit=%d)",
|
||||
len(jobs), since.date(), environment or "all", limit,
|
||||
)
|
||||
|
||||
tally = {}
|
||||
for job in jobs:
|
||||
try:
|
||||
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
|
||||
except Exception as e:
|
||||
# A transient GCS/Dropbox error while planning shouldn't abort the whole run.
|
||||
logger.error(" planning failed for %s: %s", getattr(job, "job_id", "?"), e)
|
||||
tally["error"] = tally.get("error", 0) + 1
|
||||
continue
|
||||
tally[action] = tally.get(action, 0) + 1
|
||||
if action == "upload":
|
||||
verb = "uploading" if live else "[DRY-RUN] would upload"
|
||||
logger.info("%s: %s -> %s", verb, job.job_id, detail["remote_path"])
|
||||
if live:
|
||||
try:
|
||||
_execute_upload(detail, storage=storage, dropbox=dropbox)
|
||||
except Exception as e:
|
||||
logger.error(" upload failed for %s: %s", job.job_id, e)
|
||||
tally["upload"] -= 1
|
||||
tally["error"] = tally.get("error", 0) + 1
|
||||
else:
|
||||
logger.debug("%s: %s (%s)", action, job.job_id, detail)
|
||||
|
||||
logger.info("=== Backfill summary (%s) ===", "LIVE" if live else "DRY-RUN")
|
||||
for k in sorted(tally):
|
||||
logger.info(" %-24s %d", k, tally[k])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--since", default=DEFAULT_SINCE, help="Only jobs created on/after YYYY-MM-DD")
|
||||
parser.add_argument("--until", default=None, help="Only jobs created before YYYY-MM-DD")
|
||||
parser.add_argument("--limit", type=int, default=5000,
|
||||
help="Max completed jobs to fetch (most-recent first). Bounds how far "
|
||||
"back the date window can reach.")
|
||||
parser.add_argument("--env", default=None, dest="environment",
|
||||
help="Filter to a request environment (e.g. production). Default: all "
|
||||
"(test jobs are skipped anyway — no brand code / Dropbox folder).")
|
||||
parser.add_argument("--live", action="store_true", help="Actually upload (default: dry-run)")
|
||||
parser.add_argument("-v", "--verbose", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(message)s",
|
||||
)
|
||||
|
||||
since = datetime.strptime(args.since, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
until = (
|
||||
datetime.strptime(args.until, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
if args.until else None
|
||||
)
|
||||
run_backfill(since=since, until=until, limit=args.limit, environment=args.environment, live=args.live)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -18,8 +18,7 @@ downloads since Cloud Run doesn't support BitTorrent peer connections.
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import List, Optional
|
||||
|
||||
import nest_asyncio
|
||||
|
||||
@@ -48,151 +47,6 @@ AudioSearchError = AudioFetcherError
|
||||
AudioDownloadResult = AudioFetchResult
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bulk Mode: tier-1 auto-selection.
|
||||
#
|
||||
# This is a faithful port of the frontend confidence-tier logic in
|
||||
# frontend/lib/audio-search-utils.ts (categorizeResult / getBestResult /
|
||||
# checkFilenameMismatch / getSearchConfidence). It operates on the dicts
|
||||
# produced by AudioSearchResult.to_dict() (keys: is_lossless, quality_data,
|
||||
# seeders, provider, release_type, target_file, title, index).
|
||||
#
|
||||
# MAINTENANCE SEAM: if the frontend tier rule changes, update both. The
|
||||
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_BEST_RESULT_PRIORITY = [
|
||||
"BEST CHOICE",
|
||||
"STUDIO ALBUMS",
|
||||
"HI-RES 24-BIT",
|
||||
"SINGLES",
|
||||
"COMPILATIONS",
|
||||
"SPOTIFY",
|
||||
"YOUTUBE",
|
||||
"OTHER",
|
||||
]
|
||||
|
||||
|
||||
def _categorize_result(result: Dict[str, Any]) -> str:
|
||||
"""Port of categorizeResult() from audio-search-utils.ts."""
|
||||
is_lossless = result.get("is_lossless") is True
|
||||
quality_data = result.get("quality_data") or {}
|
||||
is_24bit = quality_data.get("bit_depth") == 24
|
||||
seeders = result.get("seeders") or 0
|
||||
provider = (result.get("provider") or "").lower()
|
||||
release_type = (result.get("release_type") or "").lower()
|
||||
media = (quality_data.get("media") or "").lower()
|
||||
|
||||
if provider == "spotify":
|
||||
return "SPOTIFY"
|
||||
if provider == "youtube" or not is_lossless:
|
||||
return "YOUTUBE"
|
||||
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
|
||||
if is_lossless and media == "vinyl":
|
||||
return "VINYL RIPS"
|
||||
if is_lossless and seeders >= 50:
|
||||
return "BEST CHOICE"
|
||||
if is_lossless and is_24bit:
|
||||
return "HI-RES 24-BIT"
|
||||
if is_lossless and (
|
||||
release_type == "live album" or release_type == "bootleg" or "live" in release_type
|
||||
):
|
||||
return "LIVE VERSIONS"
|
||||
if is_lossless and release_type in ("compilation", "soundtrack", "anthology"):
|
||||
return "COMPILATIONS"
|
||||
if is_lossless and release_type in ("single", "ep"):
|
||||
return "SINGLES"
|
||||
if is_lossless and (release_type == "album" or not release_type):
|
||||
return "STUDIO ALBUMS"
|
||||
return "OTHER"
|
||||
|
||||
|
||||
def _get_best_result(results: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""Port of getBestResult() — highest-priority category, skipping vinyl."""
|
||||
if not results:
|
||||
return None
|
||||
best: Optional[Dict[str, Any]] = None
|
||||
best_priority = float("inf")
|
||||
for result in results:
|
||||
category = _categorize_result(result)
|
||||
if category == "VINYL RIPS":
|
||||
continue
|
||||
try:
|
||||
priority = _BEST_RESULT_PRIORITY.index(category)
|
||||
except ValueError:
|
||||
priority = float("inf")
|
||||
if priority < best_priority:
|
||||
best = result
|
||||
best_priority = priority
|
||||
elif priority == best_priority and best is not None:
|
||||
if (result.get("seeders") or 0) > (best.get("seeders") or 0):
|
||||
best = result
|
||||
return best if best is not None else results[0]
|
||||
|
||||
|
||||
def _check_filename_mismatch(search_title: str, result: Dict[str, Any]) -> bool:
|
||||
"""Port of checkFilenameMismatch() — True if the file is clearly another track."""
|
||||
if len(search_title) < 3:
|
||||
return False
|
||||
|
||||
target_file = result.get("target_file")
|
||||
if target_file:
|
||||
raw_filename = target_file.split("/")[-1] or target_file
|
||||
without_ext = re.sub(r"\.[^.]+$", "", raw_filename)
|
||||
filename = re.sub(r"^\d{1,3}\s*[-.\s]\s*", "", without_ext)
|
||||
elif result.get("title"):
|
||||
filename = result["title"]
|
||||
else:
|
||||
return False
|
||||
|
||||
def normalize(s: str) -> str:
|
||||
s = s.lower()
|
||||
s = re.sub(r"[_\-.]+", " ", s)
|
||||
s = re.sub(r"[^a-z0-9\s]", "", s)
|
||||
s = re.sub(r"\s+", " ", s)
|
||||
return s.strip()
|
||||
|
||||
norm_title = normalize(search_title)
|
||||
norm_file = normalize(filename)
|
||||
if not norm_file or not norm_title:
|
||||
return False
|
||||
|
||||
# Stricter than the frontend's substring check (intentional — for the bulk
|
||||
# AUTO-select path we'd rather park an uncertain match than auto-pick the
|
||||
# wrong track). A match requires every title word to appear as a whole word
|
||||
# in the filename, so "One" no longer matches "Someone".
|
||||
title_tokens = [t for t in norm_title.split() if t]
|
||||
file_tokens = set(norm_file.split())
|
||||
if not title_tokens:
|
||||
return False
|
||||
matches = all(tok in file_tokens for tok in title_tokens)
|
||||
return not matches
|
||||
|
||||
|
||||
def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -> Optional[int]:
|
||||
"""Return the index to auto-select, or None if no confident lossless pick.
|
||||
|
||||
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
|
||||
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
|
||||
must match ``search_title`` (the song the user searched for). Otherwise we
|
||||
defer to human selection.
|
||||
"""
|
||||
if not results:
|
||||
return None
|
||||
# Require a usable title before auto-selecting: a blank/too-short title can't
|
||||
# be verified against the filename, so defer to human selection.
|
||||
if len((search_title or "").strip()) < 3:
|
||||
return None
|
||||
best = _get_best_result(results)
|
||||
if best is None:
|
||||
return None
|
||||
if _categorize_result(best) != "BEST CHOICE":
|
||||
return None
|
||||
if _check_filename_mismatch(search_title, best):
|
||||
return None
|
||||
return best.get("index")
|
||||
|
||||
|
||||
class AudioSearchService:
|
||||
"""
|
||||
Service for searching and downloading audio files.
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
"""Token pricing for auto-correct model calls.
|
||||
|
||||
Used to turn the per-call token usage we capture from each provider into an
|
||||
estimated USD cost, for both the production usage logs and the offline
|
||||
measurement script (``scripts/measure_autocorrect_cost.py``).
|
||||
|
||||
Prices are USD per 1,000,000 tokens.
|
||||
|
||||
- **Anthropic** prices are authoritative (published Claude API pricing).
|
||||
``output`` is the billed output rate, which already includes adaptive
|
||||
*thinking* tokens — they are billed as output and are not separable from
|
||||
the final answer in the Anthropic usage object.
|
||||
- **Gemini** prices are a best-known ESTIMATE for the Vertex preview tier and
|
||||
are clearly marked below. Verify against current Vertex pricing before
|
||||
relying on the dollar figure. Gemini thinking tokens ARE separable
|
||||
(``thoughts_token_count``) and are billed at the output rate, so we fold
|
||||
them into the output total.
|
||||
|
||||
The raw token counts are always logged alongside the dollar figure, so the
|
||||
cost here is a derived convenience — if a rate is stale, recompute from the
|
||||
logged tokens rather than trusting the historical USD value.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
class TokenUsage(TypedDict):
|
||||
"""Normalized, provider-agnostic usage for one model call.
|
||||
|
||||
``output_tokens`` is the total billed output (final answer + thinking).
|
||||
``thinking_tokens`` is informational only (None when the provider does
|
||||
not report it separately) — it is already counted inside ``output_tokens``.
|
||||
"""
|
||||
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
cache_read_tokens: int
|
||||
thinking_tokens: Optional[int]
|
||||
|
||||
|
||||
class _Rate(TypedDict):
|
||||
input: float
|
||||
output: float
|
||||
cache_read: float
|
||||
|
||||
|
||||
# USD per 1,000,000 tokens.
|
||||
MODEL_PRICING: dict[str, _Rate] = {
|
||||
# --- Anthropic (authoritative) ---
|
||||
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
|
||||
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
|
||||
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
|
||||
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
|
||||
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
|
||||
# tier; confirm against current Google pricing before trusting USD) ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
}
|
||||
|
||||
|
||||
def get_rate(model: str) -> Optional[_Rate]:
|
||||
"""Return the rate card for ``model``, or None if we have no pricing.
|
||||
|
||||
Falls back to a prefix match on the model family (e.g. a dated
|
||||
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
|
||||
so a minor model-id change doesn't silently drop cost tracking.
|
||||
"""
|
||||
if model in MODEL_PRICING:
|
||||
return MODEL_PRICING[model]
|
||||
for known, rate in MODEL_PRICING.items():
|
||||
if model.startswith(known):
|
||||
return rate
|
||||
return None
|
||||
|
||||
|
||||
def estimate_cost_usd(model: str, usage: Optional[TokenUsage]) -> Optional[float]:
|
||||
"""Estimate the USD cost of one model call from its token usage.
|
||||
|
||||
Returns None when usage is unavailable or the model has no known pricing,
|
||||
so callers can distinguish "free/zero" from "unknown".
|
||||
"""
|
||||
if not usage:
|
||||
return None
|
||||
rate = get_rate(model)
|
||||
if rate is None:
|
||||
return None
|
||||
input_tokens = usage.get("input_tokens") or 0
|
||||
output_tokens = usage.get("output_tokens") or 0
|
||||
cache_read = usage.get("cache_read_tokens") or 0
|
||||
return (
|
||||
input_tokens * rate["input"]
|
||||
+ output_tokens * rate["output"]
|
||||
+ cache_read * rate["cache_read"]
|
||||
) / 1_000_000.0
|
||||
@@ -1,19 +1,17 @@
|
||||
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
|
||||
from backend.services.auto_correct.prompts import (
|
||||
RESPONSE_SCHEMA,
|
||||
build_system_prompt,
|
||||
@@ -68,8 +66,6 @@ class AutoCorrectResult:
|
||||
elapsed_seconds: float
|
||||
settings_applied: AutoCorrectSettings
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
# True when served from the per-job GCS cache (no LLM call was made).
|
||||
cached: bool = False
|
||||
|
||||
|
||||
class AutoCorrectService:
|
||||
@@ -114,35 +110,13 @@ class AutoCorrectService:
|
||||
)
|
||||
|
||||
models = self._models_for(settings)
|
||||
|
||||
# Re-running on byte-identical input (lyrics, references, settings,
|
||||
# models) returns the previous result instead of paying for another
|
||||
# LLM call. Word ids are part of the key, so cached suggestions
|
||||
# always reference words that still exist.
|
||||
cache_path = self._cache_path(
|
||||
job_id, models, settings, flat, reference_lyrics, artist, title
|
||||
)
|
||||
cached = self._cache_get(cache_path)
|
||||
if cached is not None:
|
||||
logger.info(
|
||||
"auto-correct cache hit job=%s suggestions=%d", job_id,
|
||||
len(cached.suggestions),
|
||||
)
|
||||
return cached
|
||||
|
||||
t0 = time.time()
|
||||
per_model: dict[str, list[Suggestion]] = {}
|
||||
# Token usage per successful model call (None when the provider's
|
||||
# usage object couldn't be read). Drives the cost log below.
|
||||
per_model_usage: dict[str, Optional[TokenUsage]] = {}
|
||||
warnings: list[str] = []
|
||||
if len(models) == 1:
|
||||
raw, usage = self._call_model(
|
||||
models[0], system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
raw = self._call_model(models[0], system_prompt, user_prompt, job_id=job_id)
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
per_model[models[0]] = suggestions
|
||||
per_model_usage[models[0]] = usage
|
||||
warnings.extend(vw)
|
||||
else:
|
||||
import concurrent.futures as cf
|
||||
@@ -156,7 +130,7 @@ class AutoCorrectService:
|
||||
}
|
||||
for fut, m in futures.items():
|
||||
try:
|
||||
raw, usage = fut.result()
|
||||
raw = fut.result()
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
except AutoCorrectServiceError as exc:
|
||||
# One model failing (call OR malformed output) must not
|
||||
@@ -164,7 +138,6 @@ class AutoCorrectService:
|
||||
warnings.append(f"model {m} failed: {exc}")
|
||||
continue
|
||||
per_model[m] = suggestions
|
||||
per_model_usage[m] = usage
|
||||
warnings.extend(f"[{m}] {w}" for w in vw)
|
||||
if not per_model:
|
||||
raise AutoCorrectServiceError(
|
||||
@@ -178,131 +151,13 @@ class AutoCorrectService:
|
||||
"auto-correct job=%s models=%s words=%d suggestions=%d dropped_warnings=%d elapsed=%.1fs",
|
||||
job_id, model_label, len(flat), len(merged), len(warnings), elapsed,
|
||||
)
|
||||
self._log_usage(job_id, per_model_usage)
|
||||
result = AutoCorrectResult(
|
||||
return AutoCorrectResult(
|
||||
suggestions=merged,
|
||||
model=model_label,
|
||||
elapsed_seconds=round(elapsed, 1),
|
||||
settings_applied=settings,
|
||||
warnings=warnings,
|
||||
)
|
||||
self._cache_put(cache_path, result)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _log_usage(
|
||||
job_id: str, per_model_usage: dict[str, Optional[TokenUsage]]
|
||||
) -> None:
|
||||
"""Emit greppable per-model and total cost lines for one suggest() call.
|
||||
|
||||
Token counts are ground truth; the USD figures are derived from
|
||||
``pricing.MODEL_PRICING`` and use ESTIMATED Gemini rates (see that
|
||||
module). Query in Cloud Logging via ``auto-correct usage`` /
|
||||
``auto-correct cost``. Observability only — never raises.
|
||||
"""
|
||||
total_cost = 0.0
|
||||
any_cost = False
|
||||
for model, usage in per_model_usage.items():
|
||||
cost = estimate_cost_usd(model, usage)
|
||||
if cost is not None:
|
||||
total_cost += cost
|
||||
any_cost = True
|
||||
if usage is None:
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s tokens=unavailable",
|
||||
job_id, model,
|
||||
)
|
||||
continue
|
||||
thinking = usage.get("thinking_tokens")
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s input_tokens=%d "
|
||||
"output_tokens=%d thinking_tokens=%s cache_read_tokens=%d "
|
||||
"est_cost_usd=%s",
|
||||
job_id,
|
||||
model,
|
||||
usage.get("input_tokens", 0),
|
||||
usage.get("output_tokens", 0),
|
||||
"na" if thinking is None else thinking,
|
||||
usage.get("cache_read_tokens", 0),
|
||||
"unknown" if cost is None else f"{cost:.4f}",
|
||||
)
|
||||
logger.info(
|
||||
"auto-correct cost job=%s models=%s total_est_cost_usd=%s",
|
||||
job_id,
|
||||
", ".join(per_model_usage.keys()),
|
||||
f"{total_cost:.4f}" if any_cost else "unknown",
|
||||
)
|
||||
|
||||
# ---- suggestion cache (GCS, best-effort) ----
|
||||
|
||||
def _get_storage(self):
|
||||
if not hasattr(self, "_storage"):
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._storage = StorageService()
|
||||
return self._storage
|
||||
|
||||
@staticmethod
|
||||
def _cache_path(
|
||||
job_id: str,
|
||||
models: list[str],
|
||||
settings: AutoCorrectSettings,
|
||||
flat: list[tuple[str, str, str]],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> str:
|
||||
payload = {
|
||||
"v": 1,
|
||||
"models": models,
|
||||
"settings": settings.to_dict(),
|
||||
"words": [[word_id, text] for word_id, text, _seg in flat],
|
||||
"references": {
|
||||
source: [seg.get("text", "") for seg in (ref.get("segments") or [])]
|
||||
for source, ref in sorted((reference_lyrics or {}).items())
|
||||
},
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
|
||||
).hexdigest()[:24]
|
||||
return f"jobs/{job_id}/lyrics/auto_correct_cache/{digest}.json"
|
||||
|
||||
def _cache_get(self, path: str) -> Optional[AutoCorrectResult]:
|
||||
"""Best-effort: any storage/shape problem is a cache miss, never an error."""
|
||||
try:
|
||||
storage = self._get_storage()
|
||||
if not storage.bucket.blob(path).exists():
|
||||
return None
|
||||
data = storage.download_json(path)
|
||||
return AutoCorrectResult(
|
||||
suggestions=[Suggestion(**s) for s in data["suggestions"]],
|
||||
model=data["model"],
|
||||
elapsed_seconds=0.0,
|
||||
settings_applied=AutoCorrectSettings(**data["settings_applied"]),
|
||||
warnings=list(data.get("warnings") or []),
|
||||
cached=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache read failed for %s", path, exc_info=True)
|
||||
return None
|
||||
|
||||
def _cache_put(self, path: str, result: AutoCorrectResult) -> None:
|
||||
"""Best-effort: a failed cache write never fails the request."""
|
||||
try:
|
||||
self._get_storage().upload_json(
|
||||
path,
|
||||
{
|
||||
"suggestions": [asdict(s) for s in result.suggestions],
|
||||
"model": result.model,
|
||||
"settings_applied": result.settings_applied.to_dict(),
|
||||
"warnings": result.warnings,
|
||||
"elapsed_seconds": result.elapsed_seconds,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache write failed for %s", path, exc_info=True)
|
||||
|
||||
def _models_for(self, settings: AutoCorrectSettings) -> list[str]:
|
||||
if settings.compare_models:
|
||||
@@ -387,59 +242,14 @@ class AutoCorrectService:
|
||||
|
||||
def _call_model(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
|
||||
) -> Any:
|
||||
if model.startswith("claude"):
|
||||
return self._call_anthropic(model, system_prompt, user_prompt, job_id=job_id)
|
||||
return self._call_gemini(model, system_prompt, user_prompt, job_id=job_id)
|
||||
|
||||
@staticmethod
|
||||
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from an Anthropic response.
|
||||
|
||||
``output_tokens`` already includes adaptive thinking tokens (billed as
|
||||
output); they are not separable here, so thinking_tokens is None.
|
||||
Returns None on any shape problem — usage must never break the call.
|
||||
"""
|
||||
try:
|
||||
u = response.usage
|
||||
return TokenUsage(
|
||||
input_tokens=int(getattr(u, "input_tokens", 0) or 0),
|
||||
output_tokens=int(getattr(u, "output_tokens", 0) or 0),
|
||||
cache_read_tokens=int(getattr(u, "cache_read_input_tokens", 0) or 0),
|
||||
thinking_tokens=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Anthropic usage", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _gemini_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from a Gemini (Vertex) response.
|
||||
|
||||
Gemini reports thinking separately (``thoughts_token_count``); it is
|
||||
billed at the output rate, so it's folded into output_tokens and also
|
||||
reported separately for visibility. Returns None on any shape problem.
|
||||
"""
|
||||
try:
|
||||
u = response.usage_metadata
|
||||
prompt = int(getattr(u, "prompt_token_count", 0) or 0)
|
||||
candidates = int(getattr(u, "candidates_token_count", 0) or 0)
|
||||
thoughts = int(getattr(u, "thoughts_token_count", 0) or 0)
|
||||
cached = int(getattr(u, "cached_content_token_count", 0) or 0)
|
||||
return TokenUsage(
|
||||
input_tokens=prompt,
|
||||
output_tokens=candidates + thoughts,
|
||||
cache_read_tokens=cached,
|
||||
thinking_tokens=thoughts,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Gemini usage", exc_info=True)
|
||||
return None
|
||||
|
||||
def _call_anthropic(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
) -> Any:
|
||||
import os
|
||||
|
||||
import anthropic
|
||||
@@ -482,10 +292,9 @@ class AutoCorrectService:
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._anthropic_usage(response)
|
||||
try:
|
||||
text = next(b.text for b in response.content if b.type == "text")
|
||||
return json.loads(text), usage
|
||||
return json.loads(text)
|
||||
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
@@ -496,7 +305,7 @@ class AutoCorrectService:
|
||||
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
) -> Any:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
@@ -524,9 +333,8 @@ class AutoCorrectService:
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._gemini_usage(response)
|
||||
try:
|
||||
return json.loads(response.text), usage
|
||||
return json.loads(response.text)
|
||||
except (json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
|
||||
@@ -151,37 +151,6 @@ class DropboxService:
|
||||
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
|
||||
return next_code
|
||||
|
||||
def file_exists(self, remote_path: str) -> bool:
|
||||
"""
|
||||
Check whether a file exists at the given Dropbox path.
|
||||
|
||||
Args:
|
||||
remote_path: Dropbox path (must start with /)
|
||||
|
||||
Returns:
|
||||
True if a file exists at the path, False otherwise.
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
if not remote_path.startswith("/"):
|
||||
remote_path = f"/{remote_path}"
|
||||
|
||||
try:
|
||||
self.client.files_get_metadata(remote_path)
|
||||
return True
|
||||
except ApiError as e:
|
||||
# Only a genuine "not found" means the file is absent. Re-raise other
|
||||
# API errors (auth, network, rate limit) so callers don't mistake a
|
||||
# transient failure for "missing" (e.g. the backfill uploading a dup).
|
||||
err = e.error
|
||||
if (
|
||||
hasattr(err, "is_path")
|
||||
and err.is_path()
|
||||
and err.get_path().is_not_found()
|
||||
):
|
||||
return False
|
||||
raise
|
||||
|
||||
def upload_file(self, local_path: str, remote_path: str) -> None:
|
||||
"""
|
||||
Upload a single file to Dropbox.
|
||||
|
||||
@@ -65,12 +65,6 @@ class EncodingOutput:
|
||||
lossless_mkv_path: Optional[str] = None # MKV with FLAC (for YouTube)
|
||||
lossy_720p_mp4_path: Optional[str] = None # 720p web version
|
||||
|
||||
# Standalone 5-second screen videos generated from the title/end images.
|
||||
# Kept so they land in the Dropbox folder (regression after #647/#650 moved
|
||||
# screen generation to the encoder). Not used downstream.
|
||||
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
|
||||
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
|
||||
|
||||
# All output files as a dict for convenience
|
||||
output_files: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@@ -391,10 +385,6 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
elif filename_lower.endswith("(title).mov"):
|
||||
output_files["title_mov"] = path
|
||||
elif filename_lower.endswith("(end).mov"):
|
||||
output_files["end_mov"] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
@@ -406,8 +396,6 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
lossless_mkv_path=output_files.get("mkv_4k"),
|
||||
lossy_720p_mp4_path=output_files.get("mp4_720p"),
|
||||
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
|
||||
title_mov_path=output_files.get("title_mov"),
|
||||
end_mov_path=output_files.get("end_mov"),
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name
|
||||
|
||||
@@ -350,7 +350,6 @@ class EncodingService:
|
||||
timeout: float = 30.0,
|
||||
job_id: str = "unknown",
|
||||
path: Optional[str] = None,
|
||||
allow_failover: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Make an HTTP request with retry logic for transient failures.
|
||||
@@ -372,13 +371,6 @@ class EncodingService:
|
||||
fallback VM in another zone) and invalidate the URL cache; the
|
||||
next retry then targets the freshly-routed URL instead of the
|
||||
original primary which is dead.
|
||||
allow_failover: When True (default), a connection error fires the
|
||||
fallback-VM warmup and lets retries re-resolve the URL. Set False
|
||||
for requests pinned to a specific worker (in-flight status polls):
|
||||
a pinned poll must never re-route to active_url nor spin up a
|
||||
fallback VM, because a different/fresh VM cannot have the job — it
|
||||
would only return "not found" and orphan a render that is actually
|
||||
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
|
||||
|
||||
Returns:
|
||||
Dict with keys:
|
||||
@@ -400,7 +392,7 @@ class EncodingService:
|
||||
# active_override change made by the warmup actually takes effect.
|
||||
# Without this, all 8 retry attempts hammer the original (dead)
|
||||
# URL even though the warmup successfully routed to a fallback VM.
|
||||
if allow_failover and path and warmup_ran and self._worker_manager is not None:
|
||||
if path and warmup_ran and self._worker_manager is not None:
|
||||
resolved = f"{self._get_worker_url()}{path}"
|
||||
if resolved != url:
|
||||
logger.info(
|
||||
@@ -432,7 +424,7 @@ class EncodingService:
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if allow_failover and attempt == 0:
|
||||
if attempt == 0:
|
||||
try:
|
||||
await self._warmup_encoding_worker_fallback(job_id)
|
||||
warmup_ran = True
|
||||
@@ -538,23 +530,12 @@ class EncodingService:
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def get_job_status(
|
||||
self, job_id: str, worker_url: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the status of an encoding job.
|
||||
|
||||
Args:
|
||||
job_id: Job identifier
|
||||
worker_url: When set, pin the request to this worker base URL instead
|
||||
of resolving the current active_url. In-flight polls must stay on
|
||||
the worker that accepted the job: a blue-green deploy can swap the
|
||||
active_url primary pointer mid-render, and an unpinned poll would
|
||||
migrate to the new primary — which never received the job and 404s
|
||||
"not found", orphaning a render that is succeeding on the original
|
||||
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
|
||||
disables failover (allow_failover=False) so it never re-routes nor
|
||||
starts a fallback VM.
|
||||
|
||||
Returns:
|
||||
Job status including: status, progress, error, output_files
|
||||
@@ -565,10 +546,7 @@ class EncodingService:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = f"/status/{job_id}"
|
||||
if worker_url:
|
||||
url = f"{worker_url}{path}"
|
||||
else:
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
@@ -577,10 +555,7 @@ class EncodingService:
|
||||
headers=headers,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
# When pinned, never re-resolve or fail over — the job lives on this
|
||||
# exact worker; do not pass `path` (which drives re-resolution).
|
||||
path=None if worker_url else path,
|
||||
allow_failover=not worker_url,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -598,7 +573,6 @@ class EncodingService:
|
||||
poll_interval: float = 10.0,
|
||||
timeout: float = 3600.0,
|
||||
progress_callback=None,
|
||||
worker_url: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Poll for encoding job completion with tolerance for transient failures.
|
||||
@@ -613,11 +587,6 @@ class EncodingService:
|
||||
poll_interval: Seconds between status checks
|
||||
timeout: Maximum time to wait (default 1 hour)
|
||||
progress_callback: Optional callback(progress: int) for progress updates
|
||||
worker_url: Worker base URL the job was submitted to. When set, every
|
||||
poll is pinned to this worker (see get_job_status) so a mid-render
|
||||
blue-green primary swap can't migrate the poll to a worker that
|
||||
never received the job. When None, polls resolve active_url (legacy
|
||||
behaviour, e.g. direct callers/tests).
|
||||
|
||||
Returns:
|
||||
Final job status with output files
|
||||
@@ -638,7 +607,7 @@ class EncodingService:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
|
||||
try:
|
||||
status = await self.get_job_status(job_id, worker_url=worker_url)
|
||||
status = await self.get_job_status(job_id)
|
||||
# Reset failure counter on successful poll
|
||||
consecutive_failures = 0
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
|
||||
@@ -739,14 +708,11 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actually doing CPU work for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
|
||||
async def submit_preview_encoding_job(
|
||||
@@ -871,15 +837,11 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion with shorter timeout
|
||||
return await self.wait_for_completion(
|
||||
job_id=job_id,
|
||||
poll_interval=poll_interval,
|
||||
timeout=timeout,
|
||||
worker_url=pinned_url,
|
||||
)
|
||||
|
||||
async def submit_render_video_job(
|
||||
@@ -999,18 +961,11 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
|
||||
|
||||
# Pin status polls to the worker the job actually landed on. Resolving
|
||||
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
|
||||
# the URL cache) while being BEFORE any later blue-green deploy swap —
|
||||
# so the poll follows the job, not the floating active_url primary
|
||||
# pointer (incident 2026-06-16, job d3af33ae).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actively rendering for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
|
||||
@@ -177,23 +177,7 @@ class FirestoreService:
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs: {e}")
|
||||
raise
|
||||
|
||||
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
|
||||
"""List all jobs belonging to a Bulk Mode batch (state_data.batch_id == batch_id).
|
||||
|
||||
Single-field equality, so no composite index is required.
|
||||
"""
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(self.collection)
|
||||
.where(filter=FieldFilter('state_data.batch_id', '==', batch_id))
|
||||
.limit(limit)
|
||||
)
|
||||
return [Job(**doc.to_dict()) for doc in query.stream()]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs for batch {batch_id}: {e}")
|
||||
raise
|
||||
|
||||
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
@@ -210,8 +194,6 @@ class FirestoreService:
|
||||
'state_data.pending_additional_credits',
|
||||
'state_data.duration_actual_seconds',
|
||||
'state_data.duration_confirm_reason',
|
||||
'state_data.batch_id',
|
||||
'state_data.bulk_auto_selected',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
'processing_metadata',
|
||||
]
|
||||
|
||||
@@ -827,20 +827,6 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
|
||||
jobs[job_id]["progress"] = 90
|
||||
|
||||
# Include the standalone 5-second screen videos in the uploaded outputs so they
|
||||
# land in the Dropbox folder. They are generated above (or passed in) purely as
|
||||
# concat inputs and used to live only in screens/; copy them into outputs/ with
|
||||
# the canonical names. Regression fix: screen MOVs disappeared from Dropbox after
|
||||
# #647/#650 moved screen generation to this encoder.
|
||||
for screen_video, suffix in ((title_video, "Title"), (end_video, "End")):
|
||||
if screen_video and Path(screen_video).is_file():
|
||||
dest = output_dir / f"{base_name} ({suffix}).mov"
|
||||
try:
|
||||
shutil.copy2(screen_video, dest)
|
||||
logger.info(f"Staged screen video for upload: {dest.name}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to stage {suffix} MOV into outputs: {e}")
|
||||
|
||||
# Collect output files
|
||||
output_files = [str(f) for f in output_dir.glob("*") if f.is_file()]
|
||||
jobs[job_id]["output_files"] = output_files
|
||||
|
||||
@@ -189,10 +189,6 @@ class JobManager:
|
||||
def update_job(self, job_id: str, updates: Dict[str, Any]) -> None:
|
||||
"""Update job with arbitrary fields."""
|
||||
self.firestore.update_job(job_id, updates)
|
||||
|
||||
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
|
||||
"""List all jobs in a Bulk Mode batch (state_data.batch_id == batch_id)."""
|
||||
return self.firestore.list_jobs_by_batch_id(batch_id, limit=limit)
|
||||
|
||||
def list_jobs(
|
||||
self,
|
||||
|
||||
@@ -5,7 +5,6 @@ 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 logging
|
||||
import re
|
||||
import time
|
||||
@@ -202,40 +201,3 @@ async def check_community_versions(artist: str, title: str) -> dict:
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
|
||||
async def check_community_versions_batch(
|
||||
songs: list[dict], concurrency: int = 5
|
||||
) -> list[dict]:
|
||||
"""Check community-version availability for many songs (Bulk Mode).
|
||||
|
||||
``songs`` is a list of ``{"artist": str, "title": str}``. Returns a list in the
|
||||
same order, each ``{"artist", "title", "available": bool, "brands": [str],
|
||||
"brand_count": int}``. 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.
|
||||
"""
|
||||
sem = asyncio.Semaphore(max(1, concurrency))
|
||||
|
||||
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}
|
||||
async with sem:
|
||||
res = await check_community_versions(artist, title)
|
||||
brands: list[str] = []
|
||||
for matched in res.get("songs", []):
|
||||
for track in matched.get("community_tracks", []):
|
||||
name = track.get("brand_name")
|
||||
if name and name not in brands:
|
||||
brands.append(name)
|
||||
return {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"available": bool(res.get("has_community")),
|
||||
"brands": brands,
|
||||
"brand_count": len(brands),
|
||||
}
|
||||
|
||||
return await asyncio.gather(*[_one(s) for s in songs])
|
||||
@@ -1,8 +0,0 @@
|
||||
"""Artist/title match-judge: deterministic + catalog + light-AI formatting and
|
||||
match-acceptance decisions for the job-submission flow.
|
||||
|
||||
See docs/archive/2026-06-15-artist-title-matching-rework-plan.md.
|
||||
"""
|
||||
from backend.services.match_judge.verdict import MatchVerdict
|
||||
|
||||
__all__ = ["MatchVerdict"]
|
||||
@@ -1,174 +0,0 @@
|
||||
"""The light-AI layer of the match judge.
|
||||
|
||||
Invoked only when the deterministic+catalog classifier can't decide. Uses a
|
||||
small Vertex Gemini model to judge whether the typed artist/title is a real
|
||||
song, what its canonical formatting is, and whether any change is cosmetic,
|
||||
content-level, or ambiguous. The model call is injectable for testing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_CONTENT,
|
||||
KIND_COSMETIC,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_VALID_KINDS = {KIND_COSMETIC, KIND_CONTENT, KIND_AMBIGUOUS}
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You normalise song metadata for a karaoke service. Given what a user typed "
|
||||
"for an artist and title (plus optional catalog candidates), decide whether it "
|
||||
"refers to a real, released song and how its artist/title should be formatted.\n"
|
||||
"Return JSON with: kind, confident, canonical_artist, canonical_title, "
|
||||
"alternatives, reason.\n"
|
||||
"kind:\n"
|
||||
" 'cosmetic' – same song, only formatting/casing/punctuation/diacritics differ.\n"
|
||||
" 'content' – the user made a typo or used a wrong/variant title; the correct "
|
||||
"song text differs in actual characters.\n"
|
||||
" 'ambiguous' – more than one plausible song matches; list them in alternatives.\n"
|
||||
" 'none' – already correct, or you cannot confidently suggest anything.\n"
|
||||
"confident: true only when you are sure. Never invent songs. Prefer the user's "
|
||||
"input when unsure (kind='none'). canonical_artist/canonical_title must use "
|
||||
"official formatting. alternatives is a list of {artist,title}."
|
||||
)
|
||||
|
||||
# OpenAPI-style schema handed to the Vertex genai client at runtime.
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
|
||||
"confident": {"type": "boolean"},
|
||||
"canonical_artist": {"type": "string"},
|
||||
"canonical_title": {"type": "string"},
|
||||
"alternatives": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"reason": {"type": "string"},
|
||||
},
|
||||
"required": ["kind", "confident"],
|
||||
}
|
||||
|
||||
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return "gemini-3.5-flash"
|
||||
|
||||
|
||||
def build_prompts(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> tuple[str, str]:
|
||||
lines = [f'User typed: artist="{artist}" title="{title}"']
|
||||
if audio_tier is not None:
|
||||
lines.append(
|
||||
f"Audio-search confidence tier: {audio_tier} "
|
||||
"(1 = strong match found, 3 = weak/no results — a weak tier hints the "
|
||||
"title may be misspelled)."
|
||||
)
|
||||
if candidates:
|
||||
lines.append("Catalog candidates (canonical formatting):")
|
||||
for c in candidates:
|
||||
lines.append(f'- {c.get("artist_name", "")} — {c.get("track_name", "")}')
|
||||
else:
|
||||
lines.append("No catalog candidates were found.")
|
||||
return _SYSTEM_PROMPT, "\n".join(lines)
|
||||
|
||||
|
||||
def _verdict_from_response(
|
||||
data: object, *, fallback_artist: str, fallback_title: str
|
||||
) -> MatchVerdict:
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
kind = data.get("kind")
|
||||
if kind not in _VALID_KINDS:
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, fallback_artist, fallback_title,
|
||||
engine="ai", reason="no suggestion",
|
||||
)
|
||||
canonical_artist = (data.get("canonical_artist") or "").strip() or fallback_artist
|
||||
canonical_title = (data.get("canonical_title") or "").strip() or fallback_title
|
||||
alternatives = []
|
||||
for alt in data.get("alternatives") or []:
|
||||
if isinstance(alt, dict) and alt.get("artist") and alt.get("title"):
|
||||
alternatives.append(
|
||||
{"artist": str(alt["artist"]), "title": str(alt["title"])}
|
||||
)
|
||||
return MatchVerdict(
|
||||
kind=kind,
|
||||
confident=bool(data.get("confident", False)),
|
||||
canonical_artist=canonical_artist,
|
||||
canonical_title=canonical_title,
|
||||
alternatives=alternatives,
|
||||
engine="ai",
|
||||
reason=str(data.get("reason") or ""),
|
||||
)
|
||||
|
||||
|
||||
async def ai_judge_match(
|
||||
artist: str,
|
||||
title: str,
|
||||
candidates: list[dict],
|
||||
audio_tier: Optional[int],
|
||||
*,
|
||||
model: Optional[str] = None,
|
||||
generate: Optional[Generate] = None,
|
||||
) -> MatchVerdict:
|
||||
model = model or _model()
|
||||
gen = generate or _default_generate
|
||||
system_prompt, user_prompt = build_prompts(artist, title, candidates, audio_tier)
|
||||
data = await gen(model, system_prompt, user_prompt)
|
||||
return _verdict_from_response(
|
||||
data, fallback_artist=artist, fallback_title=title
|
||||
)
|
||||
|
||||
|
||||
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
import copy
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -1,82 +0,0 @@
|
||||
"""Deterministic + catalog match classification (no AI, no network).
|
||||
|
||||
`classify_catalog_match` returns a confident :class:`MatchVerdict` when the
|
||||
typed artist/title clearly correspond to a catalog candidate (a cosmetic
|
||||
formatting fix, or nothing to change). When it cannot confidently decide, it
|
||||
returns ``None`` — the caller should then escalate to the AI judge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Optional
|
||||
|
||||
from karaoke_gen.utils import normalize_text
|
||||
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_COSMETIC,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
|
||||
_WS = re.compile(r"\s+")
|
||||
|
||||
|
||||
def _fold_accents(text: str) -> str:
|
||||
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
|
||||
decomposed = unicodedata.normalize("NFKD", text)
|
||||
return "".join(c for c in decomposed if not unicodedata.combining(c))
|
||||
|
||||
|
||||
def normalize_for_match(text: str) -> str:
|
||||
"""Aggressive key used only for equality comparison (never displayed).
|
||||
|
||||
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
|
||||
"""
|
||||
s = normalize_text(text or "")
|
||||
s = s.replace("&", " and ")
|
||||
s = _fold_accents(s)
|
||||
s = s.casefold()
|
||||
s = _NON_ALNUM.sub(" ", s)
|
||||
s = _WS.sub(" ", s).strip()
|
||||
return s
|
||||
|
||||
|
||||
def classify_catalog_match(
|
||||
artist: str, title: str, candidates: list[dict]
|
||||
) -> Optional[MatchVerdict]:
|
||||
"""Return a confident verdict from catalog candidates, or None to escalate.
|
||||
|
||||
candidates: dicts with ``artist_name`` and ``track_name`` (Spotify/MB canonical).
|
||||
"""
|
||||
key_artist = normalize_for_match(artist)
|
||||
key_title = normalize_for_match(title)
|
||||
|
||||
for cand in candidates:
|
||||
cand_artist = cand.get("artist_name") or ""
|
||||
cand_title = cand.get("track_name") or ""
|
||||
if (
|
||||
normalize_for_match(cand_artist) == key_artist
|
||||
and normalize_for_match(cand_title) == key_title
|
||||
):
|
||||
# Same song. Cosmetic fix unless the user already typed it exactly.
|
||||
if cand_artist == artist and cand_title == title:
|
||||
return MatchVerdict(
|
||||
kind=KIND_NONE,
|
||||
confident=True,
|
||||
canonical_artist=artist,
|
||||
canonical_title=title,
|
||||
engine="catalog",
|
||||
reason="already canonical",
|
||||
)
|
||||
return MatchVerdict(
|
||||
kind=KIND_COSMETIC,
|
||||
confident=True,
|
||||
canonical_artist=cand_artist,
|
||||
canonical_title=cand_title,
|
||||
engine="catalog",
|
||||
reason="formatting differs from catalog",
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -1,128 +0,0 @@
|
||||
"""Match-judge orchestration.
|
||||
|
||||
Composes the deterministic+catalog classifier with the AI judge. The AI judge
|
||||
runs ONLY when the classifier can't confidently decide, and never blocks or
|
||||
errors the caller — any failure degrades to "no suggestion".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Literal, Optional
|
||||
|
||||
from backend.services.match_judge.classifier import classify_catalog_match
|
||||
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CATALOG_CANDIDATE_LIMIT = 8
|
||||
|
||||
Stage = Literal["fast", "full"]
|
||||
|
||||
# Audio tiers at or above this are "weak" (poor / no results). A weak tier hints
|
||||
# the typed title may be a typo, so even a confident catalog match is verified
|
||||
# with the AI judge (it can be a junk/misspelled Spotify entry).
|
||||
WEAK_TIER = 3
|
||||
|
||||
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
|
||||
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
|
||||
|
||||
|
||||
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
return await search_tracks(query, artist, limit)
|
||||
|
||||
|
||||
async def _default_ai_judge(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> MatchVerdict:
|
||||
from backend.services.match_judge.ai import ai_judge_match
|
||||
return await ai_judge_match(artist, title, candidates, audio_tier)
|
||||
|
||||
|
||||
def _default_enabled() -> bool:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return bool(getattr(settings, "match_judge_enabled", True))
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return True
|
||||
|
||||
|
||||
async def judge_match(
|
||||
artist: str,
|
||||
title: str,
|
||||
audio_tier: Optional[int] = None,
|
||||
*,
|
||||
stage: Stage = "full",
|
||||
search_tracks: Optional[SearchTracks] = None,
|
||||
ai_judge: Optional[AiJudge] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
) -> MatchVerdict:
|
||||
"""Return a :class:`MatchVerdict` for the typed artist/title.
|
||||
|
||||
audio_tier: the audio search's confidence tier (1=best..3=poor), used by the
|
||||
AI judge to decide whether weak results suggest a typo. May be None.
|
||||
|
||||
stage:
|
||||
"fast" — catalog-only pass (no AI, tier ignored). Runs in parallel with the
|
||||
audio search so the common cosmetic tidy is ready before results render.
|
||||
Returns the catalog verdict if confident, else a ``needs_ai=True`` marker
|
||||
telling the caller to make a "full" call once the tier is known.
|
||||
"full" — the complete pipeline: catalog, then the AI judge when catalog isn't
|
||||
confident OR (item 4) when a confident catalog match coincides with a weak
|
||||
audio tier (the match may be a junk/typo'd entry — let AI override).
|
||||
"""
|
||||
search = search_tracks or _default_search_tracks
|
||||
ai = ai_judge or _default_ai_judge
|
||||
if enabled is None:
|
||||
enabled = _default_enabled()
|
||||
|
||||
try:
|
||||
candidates = await search(title, artist, CATALOG_CANDIDATE_LIMIT)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"match-judge catalog search failed; continuing without candidates",
|
||||
exc_info=True,
|
||||
)
|
||||
candidates = []
|
||||
|
||||
catalog_verdict = classify_catalog_match(artist, title, candidates)
|
||||
|
||||
# Fast pass: catalog only. Never touches the AI layer.
|
||||
if stage == "fast":
|
||||
if catalog_verdict is not None:
|
||||
return catalog_verdict
|
||||
return MatchVerdict(
|
||||
KIND_NONE, False, artist, title,
|
||||
engine="catalog", reason="needs ai", needs_ai=True,
|
||||
)
|
||||
|
||||
# Full pass.
|
||||
if catalog_verdict is not None:
|
||||
weak = audio_tier is not None and audio_tier >= WEAK_TIER
|
||||
if not (enabled and weak):
|
||||
return catalog_verdict
|
||||
# Item 4: weak audio results make the typo hypothesis plausible even though
|
||||
# the catalog "matched" — verify with AI and let a confident verdict override.
|
||||
try:
|
||||
ai_verdict = await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"match-judge AI verification failed; keeping catalog verdict"
|
||||
)
|
||||
return catalog_verdict
|
||||
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
|
||||
return ai_verdict
|
||||
return catalog_verdict
|
||||
|
||||
if not enabled:
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="deterministic", reason="ai disabled"
|
||||
)
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
logger.exception("match-judge AI call failed; returning no-suggestion")
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
|
||||
)
|
||||
@@ -1,47 +0,0 @@
|
||||
"""The verdict returned by the match judge."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
|
||||
# kind values:
|
||||
# "cosmetic" – same song, formatting-only fix → apply invisibly
|
||||
# "content" – actual characters change (typo/different title) → surface + maybe re-search
|
||||
# "ambiguous" – more than one plausible song → ask the user first
|
||||
# "none" – nothing to change (already correct, or no confident suggestion)
|
||||
KIND_COSMETIC = "cosmetic"
|
||||
KIND_CONTENT = "content"
|
||||
KIND_AMBIGUOUS = "ambiguous"
|
||||
KIND_NONE = "none"
|
||||
|
||||
|
||||
Kind = Literal["cosmetic", "content", "ambiguous", "none"]
|
||||
Engine = Literal["deterministic", "catalog", "ai"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchVerdict:
|
||||
kind: Kind
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[dict] = field(default_factory=list) # [{"artist","title"}]
|
||||
engine: Engine = "deterministic"
|
||||
reason: str = ""
|
||||
# True only from a "fast" (catalog-only) pass that couldn't confidently decide:
|
||||
# the caller should escalate to a "full" pass (with the audio tier) for an AI
|
||||
# verdict. Always False on a full-pass verdict.
|
||||
needs_ai: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"kind": self.kind,
|
||||
"confident": self.confident,
|
||||
"canonical_artist": self.canonical_artist,
|
||||
"canonical_title": self.canonical_title,
|
||||
"alternatives": self.alternatives,
|
||||
"engine": self.engine,
|
||||
"reason": self.reason,
|
||||
"needs_ai": self.needs_ai,
|
||||
}
|
||||
@@ -1,286 +0,0 @@
|
||||
"""MusicBrainz lookup service for Bulk Mode album/release lookup.
|
||||
|
||||
Provides artist search, album (release-group) listing, canonical-release
|
||||
selection, and tracklist retrieval with "extra track" detection (live /
|
||||
remix / bonus / demo / acoustic / instrumental).
|
||||
|
||||
MusicBrainz asks for a descriptive User-Agent and ~1 request/second. We add a
|
||||
small process-wide throttle and a short in-memory TTL cache because album
|
||||
lookups are interactive and low-volume.
|
||||
|
||||
API shapes (captured from the live API, 2026-06):
|
||||
- GET /ws/2/artist?query=&fmt=json -> {artists: [{id,name,disambiguation,type,score,country}]}
|
||||
- GET /ws/2/release-group?artist=&type=album&fmt=json
|
||||
-> {release-groups: [{id,title,primary-type,secondary-types:[str],first-release-date}]}
|
||||
- GET /ws/2/release?release-group=&inc=media&fmt=json
|
||||
-> {releases: [{id,title,status,date,country,packaging,disambiguation,media:[{track-count}]}]}
|
||||
- GET /ws/2/release/{id}?inc=recordings&fmt=json
|
||||
-> {id,title,status,date,country,media:[{format,track-count,
|
||||
tracks:[{position,title,length,recording:{id,title,disambiguation,length}}]}]}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import Counter
|
||||
from typing import Any, Dict, List, Optional
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MB_BASE = "https://musicbrainz.org/ws/2"
|
||||
USER_AGENT = "NomadKaraoke/1.0 (contact@nomadkaraoke.com)"
|
||||
_MIN_INTERVAL_S = 1.0 # MusicBrainz politeness: ~1 req/s
|
||||
_CACHE_TTL_S = 600 # 10 min — album metadata is effectively static
|
||||
_REQUEST_TIMEOUT_S = 15.0
|
||||
_MAX_RETRIES = 3 # MusicBrainz 503s / transient transport errors are common from cloud egress
|
||||
_RETRY_BACKOFF_S = 0.5
|
||||
|
||||
# Country preference for canonical-release tie-breaks (worldwide / Europe / US / UK).
|
||||
_PREFERRED_COUNTRIES = ["XW", "XE", "US", "GB"]
|
||||
|
||||
# "Extra" track qualifier keywords. Matched only inside (), [], or after " - "
|
||||
# so we don't misfire on legitimate titles that happen to contain a word.
|
||||
_EXTRA_KEYWORDS = [
|
||||
"live",
|
||||
"remix",
|
||||
"remixed",
|
||||
"bonus",
|
||||
"demo",
|
||||
"acoustic",
|
||||
"instrumental",
|
||||
"rehearsal",
|
||||
"alternate",
|
||||
"alternative",
|
||||
"radio edit",
|
||||
"single edit",
|
||||
"extended",
|
||||
"re-recorded",
|
||||
"rerecorded",
|
||||
"session",
|
||||
"outtake",
|
||||
]
|
||||
_EXTRA_KEYWORDS_RE = "|".join(re.escape(k) for k in _EXTRA_KEYWORDS)
|
||||
# A qualifier segment: (...keyword...), [...keyword...], or " - ...keyword..."
|
||||
_QUALIFIER_RE = re.compile(
|
||||
r"(?:[\(\[][^\)\]]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b[^\)\]]*[\)\]])"
|
||||
r"|(?:\s[-–]\s[^\(\[]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def classify_extra(title: str, disambiguation: str = "") -> tuple[bool, str]:
|
||||
"""Return (is_extra, reason). Conservative: only flags clear qualifiers."""
|
||||
disamb = (disambiguation or "").strip().lower()
|
||||
if disamb:
|
||||
for kw in _EXTRA_KEYWORDS:
|
||||
if re.search(r"\b" + re.escape(kw) + r"\b", disamb):
|
||||
return True, disamb
|
||||
m = _QUALIFIER_RE.search(title or "")
|
||||
if m:
|
||||
return True, m.group(0).strip(" -–()[]")
|
||||
return False, ""
|
||||
|
||||
|
||||
class MusicBrainzService:
|
||||
"""Thin async client around the MusicBrainz web service."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_request_at = 0.0
|
||||
self._throttle_lock = asyncio.Lock()
|
||||
self._cache: Dict[str, tuple[float, Any]] = {}
|
||||
|
||||
# -- HTTP plumbing -----------------------------------------------------
|
||||
|
||||
async def _throttle(self) -> None:
|
||||
# Non-blocking: yields to the event loop instead of stalling it.
|
||||
async with self._throttle_lock:
|
||||
now = time.monotonic()
|
||||
wait = self._last_request_at + _MIN_INTERVAL_S - now
|
||||
if wait > 0:
|
||||
await asyncio.sleep(wait)
|
||||
self._last_request_at = time.monotonic()
|
||||
|
||||
async def _get(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
cache_key = path + "?" + urlencode(sorted(params.items()))
|
||||
cached = self._cache.get(cache_key)
|
||||
if cached and (time.monotonic() - cached[0]) < _CACHE_TTL_S:
|
||||
return cached[1]
|
||||
params = {**params, "fmt": "json"}
|
||||
last_exc: Optional[Exception] = None
|
||||
for attempt in range(_MAX_RETRIES):
|
||||
await self._throttle()
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT_S) as client:
|
||||
resp = await client.get(
|
||||
f"{MB_BASE}/{path}", params=params, headers={"User-Agent": USER_AGENT}
|
||||
)
|
||||
# MusicBrainz returns 503 when rate-limited/throttled — retry those.
|
||||
if resp.status_code == 503 and attempt < _MAX_RETRIES - 1:
|
||||
last_exc = httpx.HTTPStatusError(
|
||||
"503 from MusicBrainz", request=resp.request, response=resp
|
||||
)
|
||||
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
|
||||
continue
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
self._cache[cache_key] = (time.monotonic(), data)
|
||||
return data
|
||||
except (httpx.TransportError, httpx.TimeoutException) as e:
|
||||
# Connection/timeout errors — retry with backoff.
|
||||
last_exc = e
|
||||
logger.warning("MusicBrainz %s attempt %d/%d failed: %r", path, attempt + 1, _MAX_RETRIES, e)
|
||||
if attempt < _MAX_RETRIES - 1:
|
||||
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
|
||||
# Exhausted retries.
|
||||
raise last_exc if last_exc else RuntimeError(f"MusicBrainz request failed: {path}")
|
||||
|
||||
# -- Public API --------------------------------------------------------
|
||||
|
||||
async def search_artists(self, name: str, limit: int = 8) -> List[Dict[str, Any]]:
|
||||
"""Search artists by name."""
|
||||
if not name or not name.strip():
|
||||
return []
|
||||
data = await self._get("artist", {"query": name.strip(), "limit": limit})
|
||||
out = []
|
||||
for a in data.get("artists", []):
|
||||
out.append(
|
||||
{
|
||||
"mbid": a.get("id"),
|
||||
"name": a.get("name"),
|
||||
"disambiguation": a.get("disambiguation") or "",
|
||||
"type": a.get("type"),
|
||||
"country": a.get("country"),
|
||||
"score": a.get("score"),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
async def get_albums(self, artist_mbid: str, limit: int = 100) -> List[Dict[str, Any]]:
|
||||
"""List an artist's albums (release-groups), studio albums first, then by date."""
|
||||
data = await self._get(
|
||||
"release-group",
|
||||
{"artist": artist_mbid, "type": "album|ep", "limit": limit},
|
||||
)
|
||||
groups = []
|
||||
for rg in data.get("release-groups", []):
|
||||
secondary = rg.get("secondary-types") or []
|
||||
groups.append(
|
||||
{
|
||||
"release_group_mbid": rg.get("id"),
|
||||
"title": rg.get("title"),
|
||||
"primary_type": rg.get("primary-type"),
|
||||
"secondary_types": secondary,
|
||||
"first_release_date": rg.get("first-release-date") or "",
|
||||
"is_studio": len(secondary) == 0,
|
||||
}
|
||||
)
|
||||
# Studio albums first, then earliest release date.
|
||||
groups.sort(key=lambda g: (not g["is_studio"], g["first_release_date"] or "9999"))
|
||||
return groups
|
||||
|
||||
@staticmethod
|
||||
def _total_tracks(release: Dict[str, Any]) -> int:
|
||||
return sum((m.get("track-count") or 0) for m in (release.get("media") or []))
|
||||
|
||||
async def _list_editions(self, release_group_mbid: str) -> List[Dict[str, Any]]:
|
||||
data = await self._get(
|
||||
"release",
|
||||
{"release-group": release_group_mbid, "inc": "media", "limit": 100},
|
||||
)
|
||||
editions = []
|
||||
for r in data.get("releases", []):
|
||||
editions.append(
|
||||
{
|
||||
"release_mbid": r.get("id"),
|
||||
"title": r.get("title"),
|
||||
"status": r.get("status"),
|
||||
"date": r.get("date") or "",
|
||||
"country": r.get("country"),
|
||||
"packaging": r.get("packaging"),
|
||||
"disambiguation": r.get("disambiguation") or "",
|
||||
"track_count": self._total_tracks(r),
|
||||
}
|
||||
)
|
||||
return editions
|
||||
|
||||
@staticmethod
|
||||
def pick_canonical_edition(editions: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""Pick the standard edition: official, modal track count, earliest, preferred country.
|
||||
|
||||
Choosing the most common track count avoids deluxe/remaster editions that
|
||||
tack bonus tracks on the end.
|
||||
"""
|
||||
if not editions:
|
||||
return None
|
||||
official = [e for e in editions if e.get("status") == "Official"] or editions
|
||||
with_tracks = [e for e in official if e.get("track_count", 0) > 0] or official
|
||||
counts = Counter(e["track_count"] for e in with_tracks if e.get("track_count", 0) > 0)
|
||||
if counts:
|
||||
standard = counts.most_common(1)[0][0]
|
||||
candidates = [e for e in with_tracks if e["track_count"] == standard]
|
||||
else:
|
||||
candidates = with_tracks
|
||||
|
||||
def country_rank(e: Dict[str, Any]) -> int:
|
||||
c = e.get("country")
|
||||
return _PREFERRED_COUNTRIES.index(c) if c in _PREFERRED_COUNTRIES else len(_PREFERRED_COUNTRIES)
|
||||
|
||||
candidates.sort(key=lambda e: (e.get("date") or "9999", country_rank(e)))
|
||||
return candidates[0]
|
||||
|
||||
async def get_release_tracklist(self, release_mbid: str) -> Dict[str, Any]:
|
||||
"""Fetch a release's tracklist with per-track extra detection."""
|
||||
data = await self._get(f"release/{release_mbid}", {"inc": "recordings"})
|
||||
tracks: List[Dict[str, Any]] = []
|
||||
for medium in data.get("media") or []:
|
||||
for t in medium.get("tracks") or []:
|
||||
rec = t.get("recording") or {}
|
||||
title = t.get("title") or rec.get("title") or ""
|
||||
disamb = rec.get("disambiguation") or ""
|
||||
is_extra, reason = classify_extra(title, disamb)
|
||||
length_ms = t.get("length") or rec.get("length")
|
||||
tracks.append(
|
||||
{
|
||||
"position": t.get("position"),
|
||||
"title": title,
|
||||
"recording_mbid": rec.get("id"),
|
||||
"disambiguation": disamb,
|
||||
"length_ms": length_ms,
|
||||
"is_extra": is_extra,
|
||||
"extra_reason": reason,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"release_mbid": data.get("id"),
|
||||
"title": data.get("title"),
|
||||
"date": data.get("date") or "",
|
||||
"country": data.get("country"),
|
||||
"tracks": tracks,
|
||||
}
|
||||
|
||||
async def get_album_tracklist(self, release_group_mbid: str) -> Dict[str, Any]:
|
||||
"""Resolve the canonical edition of an album and return its tracklist + editions."""
|
||||
editions = await self._list_editions(release_group_mbid)
|
||||
canonical = self.pick_canonical_edition(editions)
|
||||
if not canonical:
|
||||
return {"release_mbid": None, "title": None, "tracks": [], "editions": editions}
|
||||
tracklist = await self.get_release_tracklist(canonical["release_mbid"])
|
||||
tracklist["editions"] = editions
|
||||
tracklist["canonical_release_mbid"] = canonical["release_mbid"]
|
||||
return tracklist
|
||||
|
||||
|
||||
_service: Optional[MusicBrainzService] = None
|
||||
|
||||
|
||||
def get_musicbrainz_service() -> MusicBrainzService:
|
||||
global _service
|
||||
if _service is None:
|
||||
_service = MusicBrainzService()
|
||||
return _service
|
||||
@@ -1,73 +0,0 @@
|
||||
"""Helpers for locating and naming a job's original input audio.
|
||||
|
||||
The original downloaded/uploaded audio (the source used for separation,
|
||||
transcription and the With Vocals video) is stored in GCS but is no longer
|
||||
copied into the final output folder by the distributed pipeline. These helpers
|
||||
let the orchestrator (and the backfill script) restore it to the Dropbox track
|
||||
folder with the historical source-tagged name, e.g.::
|
||||
|
||||
<artist> - <title> (flacfetch).flac
|
||||
<artist> - <title> (uploaded).mp3
|
||||
<artist> - <title> (YouTube).webm
|
||||
|
||||
The naming mirrors the legacy monolith convention.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
# Map a job's audio_source_type to the historical filename suffix.
|
||||
_SOURCE_TAGS = {
|
||||
"file_upload": "uploaded",
|
||||
"youtube_url": "YouTube",
|
||||
"audio_search": "flacfetch",
|
||||
}
|
||||
|
||||
|
||||
def original_audio_source_tag(job) -> str:
|
||||
"""Return the parenthesised source suffix for a job's original audio.
|
||||
|
||||
Falls back gracefully for older jobs that predate ``audio_source_type``.
|
||||
"""
|
||||
tag = _SOURCE_TAGS.get(getattr(job, "audio_source_type", None))
|
||||
if tag:
|
||||
return tag
|
||||
# Fallbacks for legacy jobs without an explicit source type.
|
||||
if getattr(job, "url", None):
|
||||
return "YouTube"
|
||||
if getattr(job, "filename", None) or getattr(job, "input_media_gcs_path", None):
|
||||
return "uploaded"
|
||||
return "input"
|
||||
|
||||
|
||||
def original_audio_gcs_path(job) -> Optional[str]:
|
||||
"""Return the GCS blob path of the original input audio, or None.
|
||||
|
||||
Prefers ``input_media_gcs_path`` (uploads are persisted under jobs/ and URL
|
||||
jobs record their downloaded file here), then falls back to
|
||||
``file_urls['input']`` which may be a plain string or a nested
|
||||
``{'audio': ...}`` dict depending on the code path that wrote it.
|
||||
"""
|
||||
path = getattr(job, "input_media_gcs_path", None)
|
||||
if path:
|
||||
return path
|
||||
file_urls = getattr(job, "file_urls", None) or {}
|
||||
inp = file_urls.get("input")
|
||||
if isinstance(inp, dict):
|
||||
return inp.get("audio")
|
||||
if isinstance(inp, str):
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def original_audio_output_filename(job, base_name: str) -> Optional[str]:
|
||||
"""Return the output filename for the original audio, or None if absent.
|
||||
|
||||
e.g. ``"<artist> - <title> (flacfetch).flac"``. The extension is preserved
|
||||
from the GCS path.
|
||||
"""
|
||||
gcs_path = original_audio_gcs_path(job)
|
||||
if not gcs_path:
|
||||
return None
|
||||
ext = os.path.splitext(gcs_path)[1]
|
||||
return f"{base_name} ({original_audio_source_tag(job)}){ext}"
|
||||
@@ -59,17 +59,6 @@ class StorageService:
|
||||
logger.error(f"Error downloading file {source_path}: {e}")
|
||||
raise
|
||||
|
||||
def copy_blob(self, source_path: str, destination_path: str) -> str:
|
||||
"""Server-side copy of a blob within the bucket (no download/upload)."""
|
||||
try:
|
||||
src = self.bucket.blob(source_path)
|
||||
self.bucket.copy_blob(src, self.bucket, destination_path)
|
||||
logger.info(f"Copied gs://{settings.gcs_bucket_name}/{source_path} -> {destination_path}")
|
||||
return destination_path
|
||||
except Exception as e:
|
||||
logger.error(f"Error copying blob {source_path} -> {destination_path}: {e}")
|
||||
raise
|
||||
|
||||
def generate_signed_url(self, blob_path: str, expiration_minutes: int = 60) -> str:
|
||||
"""Generate a signed URL for downloading a file.
|
||||
|
||||
|
||||
@@ -379,47 +379,6 @@ class WorkerService:
|
||||
worker_module="audio_download_worker",
|
||||
)
|
||||
|
||||
async def trigger_bulk_search_worker(self, batch_id: str) -> bool:
|
||||
"""Trigger the Bulk Mode search worker for a whole batch as a Cloud Run Job.
|
||||
|
||||
The worker processes every job stamped with ``batch_id``: it runs each
|
||||
audio search, auto-selects confident lossless matches, and parks the rest
|
||||
in AWAITING_AUDIO_SELECTION. Uses a Cloud Run Job (not BackgroundTasks) so
|
||||
the batch survives API instance scale-down and the user can close the tab.
|
||||
"""
|
||||
try:
|
||||
from google.cloud import run_v2
|
||||
|
||||
project = self.settings.google_cloud_project
|
||||
if not project:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger bulk search job")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/bulk-search-job"
|
||||
client = run_v2.JobsClient()
|
||||
request = run_v2.RunJobRequest(
|
||||
name=job_name,
|
||||
overrides=run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[
|
||||
run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=[
|
||||
"python", "-m", "backend.workers.bulk_search_worker",
|
||||
"--batch-id", batch_id,
|
||||
],
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
operation = client.run_job(request=request)
|
||||
logger.info(f"[batch:{batch_id}] Started Cloud Run Job bulk-search-job: {operation.metadata}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[batch:{batch_id}] Failed to trigger bulk-search-job: {e}", exc_info=True
|
||||
)
|
||||
return False
|
||||
|
||||
async def trigger_audio_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger audio separation worker.
|
||||
@@ -451,34 +410,6 @@ class WorkerService:
|
||||
async def trigger_screens_worker(self, job_id: str) -> bool:
|
||||
"""Trigger screen generation worker."""
|
||||
return await self.trigger_worker("screens", job_id)
|
||||
|
||||
async def trigger_auto_correct(self, job_id: str, timeout_seconds: int = 200) -> bool:
|
||||
"""Trigger proactive auto-correct generation on the API service.
|
||||
|
||||
Direct, awaited HTTP call (NOT Cloud Tasks): the endpoint runs the work
|
||||
synchronously, so awaiting it keeps both the caller (lyrics job) and the
|
||||
service instance alive until the cache is written. Best-effort — returns
|
||||
False on any failure and never raises, so it can't affect the job.
|
||||
"""
|
||||
if not self._base_url:
|
||||
logger.info(f"[job:{job_id}] auto-correct trigger skipped: no service base URL")
|
||||
return False
|
||||
url = f"{self._base_url}/api/internal/workers/auto-correct"
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self._admin_token:
|
||||
headers["X-Admin-Token"] = self._admin_token
|
||||
# Propagate trace context so the service-side span links to this job.
|
||||
headers = inject_trace_context(headers)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds) as client:
|
||||
resp = await client.post(url, json={"job_id": job_id}, headers=headers)
|
||||
logger.info(
|
||||
f"[job:{job_id}] auto-correct trigger -> HTTP {resp.status_code}"
|
||||
)
|
||||
return resp.status_code < 400
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fatal
|
||||
logger.warning(f"[job:{job_id}] auto-correct trigger failed (non-fatal): {e}")
|
||||
return False
|
||||
|
||||
def _warmup_encoding_worker(self, job_id: str) -> None:
|
||||
"""Fire-and-forget warmup of the encoding worker VM.
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
"""Tests for the per-job auto-correct suggestion cache."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectResult,
|
||||
AutoCorrectService,
|
||||
Suggestion,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
SEGMENTS = [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"words": [
|
||||
{"id": "w0", "text": "straight"},
|
||||
{"id": "w1", "text": "glory"},
|
||||
],
|
||||
},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "straight chlorine"}]}}
|
||||
RAW = {
|
||||
"suggestions": [
|
||||
{
|
||||
"op": "replace",
|
||||
"start_idx": 1,
|
||||
"end_idx": 1,
|
||||
"new_text": "chlorine",
|
||||
"reason": "r",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.9,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
FLAT = [("w0", "straight", "seg-1"), ("w1", "glory", "seg-1")]
|
||||
|
||||
|
||||
def _suggest(service, **overrides):
|
||||
kwargs = dict(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
kwargs.update(overrides)
|
||||
return service.suggest(**kwargs)
|
||||
|
||||
|
||||
def test_cache_hit_skips_model_call() -> None:
|
||||
service = AutoCorrectService()
|
||||
cached_result = AutoCorrectResult(
|
||||
suggestions=[
|
||||
Suggestion(
|
||||
id="cached-1",
|
||||
op="replace",
|
||||
word_ids=["w1"],
|
||||
segment_ids=["seg-1"],
|
||||
original_text="glory",
|
||||
new_text="chlorine",
|
||||
reason="r",
|
||||
category="mishearing",
|
||||
confidence=0.9,
|
||||
)
|
||||
],
|
||||
model="claude-fable-5",
|
||||
elapsed_seconds=0.0,
|
||||
settings_applied=AutoCorrectSettings(),
|
||||
cached=True,
|
||||
)
|
||||
with patch.object(service, "_cache_get", return_value=cached_result), \
|
||||
patch.object(service, "_call_model") as call, \
|
||||
patch.object(service, "_cache_put") as put:
|
||||
result = _suggest(service)
|
||||
call.assert_not_called()
|
||||
put.assert_not_called()
|
||||
assert result.cached is True
|
||||
assert result.suggestions[0].id == "cached-1"
|
||||
|
||||
|
||||
def test_cache_miss_calls_model_and_writes_cache() -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_call_model", return_value=(RAW, None)) as call, \
|
||||
patch.object(service, "_cache_put") as put:
|
||||
result = _suggest(service)
|
||||
call.assert_called_once()
|
||||
put.assert_called_once()
|
||||
assert result.cached is False
|
||||
assert put.call_args.args[1] is result
|
||||
|
||||
|
||||
def test_cache_key_stable_for_identical_input() -> None:
|
||||
s = AutoCorrectSettings()
|
||||
k1 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
|
||||
k2 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
|
||||
assert k1 == k2
|
||||
assert k1.startswith("jobs/j/lyrics/auto_correct_cache/")
|
||||
|
||||
|
||||
def test_cache_key_changes_with_input() -> None:
|
||||
s = AutoCorrectSettings()
|
||||
base = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
|
||||
edited_words = [("w0", "straight", "seg-1"), ("w1", "chlorine", "seg-1")]
|
||||
assert AutoCorrectService._cache_path("j", ["m"], s, edited_words, REFS, "A", "T") != base
|
||||
assert AutoCorrectService._cache_path("j", ["m", "m2"], s, FLAT, REFS, "A", "T") != base
|
||||
other_settings = AutoCorrectSettings(min_confidence=0.8)
|
||||
assert AutoCorrectService._cache_path("j", ["m"], other_settings, FLAT, REFS, "A", "T") != base
|
||||
other_refs = {"genius": {"segments": [{"text": "different text"}]}}
|
||||
assert AutoCorrectService._cache_path("j", ["m"], s, FLAT, other_refs, "A", "T") != base
|
||||
|
||||
|
||||
def test_cache_get_round_trips_via_storage_payload() -> None:
|
||||
"""_cache_put's payload must be readable by _cache_get."""
|
||||
service = AutoCorrectService()
|
||||
stored = {}
|
||||
|
||||
class FakeBlob:
|
||||
def exists(self):
|
||||
return bool(stored)
|
||||
|
||||
class FakeStorage:
|
||||
class bucket: # noqa: N801 - mimic attribute access
|
||||
@staticmethod
|
||||
def blob(path):
|
||||
return FakeBlob()
|
||||
|
||||
@staticmethod
|
||||
def upload_json(path, data):
|
||||
stored[path] = data
|
||||
|
||||
@staticmethod
|
||||
def download_json(path):
|
||||
return stored[path]
|
||||
|
||||
with patch.object(service, "_get_storage", return_value=FakeStorage()):
|
||||
original = AutoCorrectResult(
|
||||
suggestions=[
|
||||
Suggestion(
|
||||
id="s1",
|
||||
op="replace",
|
||||
word_ids=["w1"],
|
||||
segment_ids=["seg-1"],
|
||||
original_text="glory",
|
||||
new_text="chlorine",
|
||||
reason="r",
|
||||
category="mishearing",
|
||||
confidence=0.9,
|
||||
models=["m1", "m2"],
|
||||
consensus=2,
|
||||
total_models=2,
|
||||
conflict_group=None,
|
||||
)
|
||||
],
|
||||
model="m1, m2",
|
||||
elapsed_seconds=5.0,
|
||||
settings_applied=AutoCorrectSettings(compare_models=True),
|
||||
warnings=["w"],
|
||||
)
|
||||
service._cache_put("p", original)
|
||||
restored = service._cache_get("p")
|
||||
|
||||
assert restored is not None
|
||||
assert restored.cached is True
|
||||
assert restored.model == "m1, m2"
|
||||
assert restored.warnings == ["w"]
|
||||
assert restored.settings_applied == AutoCorrectSettings(compare_models=True)
|
||||
s = restored.suggestions[0]
|
||||
assert s.consensus == 2 and s.models == ["m1", "m2"]
|
||||
|
||||
|
||||
def test_corrupt_cache_entry_is_a_miss() -> None:
|
||||
service = AutoCorrectService()
|
||||
|
||||
class FakeBlob:
|
||||
def exists(self):
|
||||
return True
|
||||
|
||||
class FakeStorage:
|
||||
class bucket: # noqa: N801
|
||||
@staticmethod
|
||||
def blob(path):
|
||||
return FakeBlob()
|
||||
|
||||
@staticmethod
|
||||
def download_json(path):
|
||||
return {"suggestions": [{"bogus": True}], "model": "m"}
|
||||
|
||||
with patch.object(service, "_get_storage", return_value=FakeStorage()):
|
||||
assert service._cache_get("p") is None
|
||||
|
||||
|
||||
def test_storage_failure_never_breaks_request() -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
|
||||
patch.object(service, "_call_model", return_value=(RAW, None)):
|
||||
result = _suggest(service)
|
||||
assert result.cached is False
|
||||
assert len(result.suggestions) == 1
|
||||
@@ -49,16 +49,13 @@ def _run_compare(responses_by_model, compare_models_env="model-a;model-b",
|
||||
resp = responses_by_model[model]
|
||||
if isinstance(resp, Exception):
|
||||
raise resp
|
||||
# _call_model now returns (parsed_json, token_usage).
|
||||
return resp, None
|
||||
return resp
|
||||
|
||||
with patch.object(
|
||||
service.settings, "auto_correct_compare_models", compare_models_env
|
||||
), patch.object(
|
||||
service.settings, "auto_correct_model", single_model
|
||||
), patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
), patch.object(service, "_call_model", side_effect=fake_call):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
"""Tests for auto-correct token pricing and usage extraction/logging."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.auto_correct.pricing import (
|
||||
MODEL_PRICING,
|
||||
estimate_cost_usd,
|
||||
get_rate,
|
||||
)
|
||||
from backend.services.auto_correct.service import AutoCorrectService
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
# ---- pricing ----
|
||||
|
||||
def test_estimate_cost_fable_known_rates() -> None:
|
||||
# 5000 in @ $10/M + 4000 out @ $50/M = 0.05 + 0.20 = 0.25
|
||||
usage = {
|
||||
"input_tokens": 5000,
|
||||
"output_tokens": 4000,
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
cost = estimate_cost_usd("claude-fable-5", usage)
|
||||
assert cost == round(0.05 + 0.20, 10)
|
||||
|
||||
|
||||
def test_estimate_cost_includes_cache_read() -> None:
|
||||
usage = {
|
||||
"input_tokens": 1_000_000,
|
||||
"output_tokens": 0,
|
||||
"cache_read_tokens": 1_000_000,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
# 1M input @ $10 + 1M cache_read @ $1 = 11.0
|
||||
assert estimate_cost_usd("claude-fable-5", usage) == 11.0
|
||||
|
||||
|
||||
def test_estimate_cost_none_usage_returns_none() -> None:
|
||||
assert estimate_cost_usd("claude-fable-5", None) is None
|
||||
|
||||
|
||||
def test_estimate_cost_unknown_model_returns_none() -> None:
|
||||
usage = {
|
||||
"input_tokens": 1000,
|
||||
"output_tokens": 1000,
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
assert estimate_cost_usd("some-unknown-model-9", usage) is None
|
||||
|
||||
|
||||
def test_get_rate_prefix_match_for_dated_snapshot() -> None:
|
||||
# A dated snapshot id still resolves to its family rate card.
|
||||
assert get_rate("claude-fable-5-20260601") == MODEL_PRICING["claude-fable-5"]
|
||||
|
||||
|
||||
# ---- usage extraction ----
|
||||
|
||||
def test_anthropic_usage_extraction() -> None:
|
||||
response = SimpleNamespace(
|
||||
usage=SimpleNamespace(
|
||||
input_tokens=4321,
|
||||
output_tokens=3210,
|
||||
cache_read_input_tokens=100,
|
||||
)
|
||||
)
|
||||
usage = AutoCorrectService._anthropic_usage(response)
|
||||
assert usage == {
|
||||
"input_tokens": 4321,
|
||||
"output_tokens": 3210, # already includes thinking
|
||||
"cache_read_tokens": 100,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
|
||||
|
||||
def test_gemini_usage_folds_thoughts_into_output() -> None:
|
||||
response = SimpleNamespace(
|
||||
usage_metadata=SimpleNamespace(
|
||||
prompt_token_count=4000,
|
||||
candidates_token_count=500,
|
||||
thoughts_token_count=2500,
|
||||
cached_content_token_count=0,
|
||||
)
|
||||
)
|
||||
usage = AutoCorrectService._gemini_usage(response)
|
||||
assert usage == {
|
||||
"input_tokens": 4000,
|
||||
"output_tokens": 3000, # 500 visible + 2500 thinking
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": 2500,
|
||||
}
|
||||
|
||||
|
||||
def test_usage_extraction_never_raises_on_bad_shape() -> None:
|
||||
# Missing usage attribute entirely -> None, not an exception.
|
||||
assert AutoCorrectService._anthropic_usage(SimpleNamespace()) is None
|
||||
assert AutoCorrectService._gemini_usage(SimpleNamespace()) is None
|
||||
|
||||
|
||||
# ---- logging ----
|
||||
|
||||
SEGMENTS = [
|
||||
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "chlorine"}]}}
|
||||
|
||||
|
||||
def _raw():
|
||||
return {
|
||||
"suggestions": [
|
||||
{
|
||||
"op": "replace",
|
||||
"start_idx": 0,
|
||||
"end_idx": 0,
|
||||
"new_text": "chlorine",
|
||||
"reason": "r",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.9,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_suggest_logs_per_model_and_total_cost(caplog) -> None:
|
||||
service = AutoCorrectService()
|
||||
usage = {
|
||||
"input_tokens": 5000,
|
||||
"output_tokens": 4000,
|
||||
"cache_read_tokens": 0,
|
||||
"thinking_tokens": None,
|
||||
}
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", return_value=(_raw(), usage)), \
|
||||
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
|
||||
with caplog.at_level("INFO"):
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
text = caplog.text
|
||||
assert "auto-correct usage job=job-1 model=claude-fable-5" in text
|
||||
assert "input_tokens=5000" in text
|
||||
assert "output_tokens=4000" in text
|
||||
assert "est_cost_usd=0.2500" in text
|
||||
assert "auto-correct cost job=job-1" in text
|
||||
assert "total_est_cost_usd=0.2500" in text
|
||||
|
||||
|
||||
def test_suggest_logs_unavailable_usage_without_crashing(caplog) -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", return_value=(_raw(), None)), \
|
||||
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
|
||||
with caplog.at_level("INFO"):
|
||||
service.suggest(
|
||||
job_id="job-2",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert "auto-correct usage job=job-2 model=claude-fable-5 tokens=unavailable" in caplog.text
|
||||
assert "total_est_cost_usd=unknown" in caplog.text
|
||||
@@ -35,9 +35,7 @@ REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
|
||||
|
||||
def _suggest(raw_response, settings=None):
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_call_model", return_value=(raw_response, None)), \
|
||||
patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"):
|
||||
with patch.object(service, "_call_model", return_value=raw_response):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
@@ -217,8 +215,8 @@ def test_non_dict_suggestion_entries_dropped() -> None:
|
||||
|
||||
def test_call_model_dispatches_claude_to_anthropic() -> None:
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service, "_call_anthropic", return_value=({"suggestions": []}, None)) as anth, \
|
||||
patch.object(service, "_call_gemini", return_value=({"suggestions": []}, None)) as gem:
|
||||
with patch.object(service, "_call_anthropic", return_value={"suggestions": []}) as anth, \
|
||||
patch.object(service, "_call_gemini", return_value={"suggestions": []}) as gem:
|
||||
service._call_model("claude-fable-5", "s", "u", job_id="j")
|
||||
anth.assert_called_once()
|
||||
gem.assert_not_called()
|
||||
@@ -262,8 +260,8 @@ def test_anthropic_schema_strips_genai_pollution(monkeypatch) -> None:
|
||||
|
||||
monkeypatch.setattr(anthropic_sdk, "Anthropic", FakeClient)
|
||||
service = AutoCorrectService()
|
||||
raw, _usage = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
|
||||
assert raw == {"suggestions": []}
|
||||
result = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
|
||||
assert result == {"suggestions": []}
|
||||
schema = captured["output_config"]["format"]["schema"]
|
||||
assert "property_ordering" not in schema
|
||||
assert "property_ordering" not in schema["properties"]["suggestions"]["items"]
|
||||
|
||||
Whitespace-only changes.
@@ -1,103 +0,0 @@
|
||||
"""Tests for the AI judge: prompt construction + response→verdict mapping.
|
||||
|
||||
The model call (`generate`) is injected, so these tests are offline and
|
||||
deterministic. The real `generate` wraps the Vertex genai client.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from backend.services.match_judge.ai import ai_judge_match, build_prompts
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_CONTENT,
|
||||
KIND_NONE,
|
||||
)
|
||||
|
||||
|
||||
def _gen(response: dict):
|
||||
async def generate(model, system_prompt, user_prompt):
|
||||
return response
|
||||
return generate
|
||||
|
||||
|
||||
class TestBuildPrompts:
|
||||
def test_prompt_includes_input_candidates_and_tier(self):
|
||||
system, user = build_prompts(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
[{"artist_name": "Queen", "track_name": "Bohemian Rhapsody"}],
|
||||
audio_tier=3,
|
||||
)
|
||||
assert "bohemian rapsody" in user
|
||||
assert "Bohemian Rhapsody" in user # candidate shown
|
||||
# The poor-results signal must reach the model so it can favour a typo fix.
|
||||
assert "3" in user
|
||||
|
||||
|
||||
class TestResponseMapping:
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_content_correction(self):
|
||||
verdict = await ai_judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
[],
|
||||
3,
|
||||
generate=_gen(
|
||||
{
|
||||
"kind": "content",
|
||||
"confident": True,
|
||||
"canonical_artist": "Queen",
|
||||
"canonical_title": "Bohemian Rhapsody",
|
||||
"alternatives": [],
|
||||
"reason": "typo",
|
||||
}
|
||||
),
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.confident is True
|
||||
assert verdict.canonical_title == "Bohemian Rhapsody"
|
||||
assert verdict.engine == "ai"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ambiguous_carries_alternatives(self):
|
||||
verdict = await ai_judge_match(
|
||||
"",
|
||||
"bruises",
|
||||
[],
|
||||
3,
|
||||
generate=_gen(
|
||||
{
|
||||
"kind": "ambiguous",
|
||||
"confident": False,
|
||||
"canonical_artist": "Lewis Capaldi",
|
||||
"canonical_title": "Bruises",
|
||||
"alternatives": [{"artist": "Fox Stevenson", "title": "Bruises"}],
|
||||
"reason": "multiple artists",
|
||||
}
|
||||
),
|
||||
)
|
||||
assert verdict.kind == KIND_AMBIGUOUS
|
||||
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_kind_is_treated_as_none(self):
|
||||
verdict = await ai_judge_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
[],
|
||||
1,
|
||||
generate=_gen({"kind": "garbage", "confident": True}),
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.canonical_artist == "queen" # falls back to user input
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_canonical_falls_back_to_input(self):
|
||||
verdict = await ai_judge_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
[],
|
||||
1,
|
||||
generate=_gen({"kind": "content", "confident": True}),
|
||||
)
|
||||
assert verdict.canonical_artist == "queen"
|
||||
assert verdict.canonical_title == "bohemian rhapsody"
|
||||
@@ -1,66 +0,0 @@
|
||||
"""Tests for the deterministic + catalog match classifier.
|
||||
|
||||
The classifier decides, WITHOUT any AI/network call, whether a typed
|
||||
artist/title cosmetically matches a catalog candidate (so we can silently
|
||||
tidy formatting) or whether the decision must be escalated to the AI judge.
|
||||
"""
|
||||
from backend.services.match_judge.classifier import (
|
||||
normalize_for_match,
|
||||
classify_catalog_match,
|
||||
)
|
||||
|
||||
|
||||
def _cand(artist: str, title: str) -> dict:
|
||||
return {"artist_name": artist, "track_name": title}
|
||||
|
||||
|
||||
class TestNormalizeForMatch:
|
||||
def test_casing_and_whitespace_collapse_to_same_key(self):
|
||||
assert normalize_for_match("Paramore") == normalize_for_match(" paramore ")
|
||||
|
||||
def test_punctuation_is_ignored(self):
|
||||
assert normalize_for_match("Big Man, Little Dignity") == normalize_for_match(
|
||||
"big man little dignity"
|
||||
)
|
||||
|
||||
def test_ampersand_and_and_are_equivalent(self):
|
||||
assert normalize_for_match("Jay-Z & Beyonce") == normalize_for_match(
|
||||
"Jay Z and Beyonce"
|
||||
)
|
||||
|
||||
|
||||
class TestClassifyCatalogMatch:
|
||||
def test_casing_only_difference_is_cosmetic(self):
|
||||
verdict = classify_catalog_match(
|
||||
"paramore",
|
||||
"big man, little dignity",
|
||||
[_cand("Paramore", "Big Man, Little Dignity")],
|
||||
)
|
||||
assert verdict is not None
|
||||
assert verdict.kind == "cosmetic"
|
||||
assert verdict.confident is True
|
||||
assert verdict.canonical_artist == "Paramore"
|
||||
assert verdict.canonical_title == "Big Man, Little Dignity"
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
def test_exact_match_needs_no_change(self):
|
||||
verdict = classify_catalog_match(
|
||||
"Paramore",
|
||||
"Big Man, Little Dignity",
|
||||
[_cand("Paramore", "Big Man, Little Dignity")],
|
||||
)
|
||||
assert verdict is not None
|
||||
assert verdict.kind == "none"
|
||||
assert verdict.confident is True
|
||||
|
||||
def test_no_catalog_match_escalates_to_ai(self):
|
||||
# Returns None => the service should call the AI judge.
|
||||
verdict = classify_catalog_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
[_cand("Paramore", "Big Man, Little Dignity")],
|
||||
)
|
||||
assert verdict is None
|
||||
|
||||
def test_empty_candidates_escalates_to_ai(self):
|
||||
assert classify_catalog_match("queen", "bohemian rhapsody", []) is None
|
||||
@@ -1,272 +0,0 @@
|
||||
"""Orchestration tests for the match-judge service.
|
||||
|
||||
The service composes the deterministic+catalog classifier with the AI judge:
|
||||
the AI judge is invoked ONLY when the classifier can't confidently decide.
|
||||
Catalog search and the AI judge are injected so these tests touch no network.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from backend.services.match_judge.service import judge_match
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_COSMETIC,
|
||||
KIND_CONTENT,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
|
||||
def _candidates(*pairs):
|
||||
async def _search(query, artist, limit):
|
||||
return [{"artist_name": a, "track_name": t} for a, t in pairs]
|
||||
return _search
|
||||
|
||||
|
||||
def _ai_never(*_a, **_k):
|
||||
raise AssertionError("AI judge must not be called")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_cosmetic_match_skips_ai():
|
||||
calls = {"ai": 0}
|
||||
|
||||
async def ai(*_a, **_k):
|
||||
calls["ai"] += 1
|
||||
raise AssertionError("should not run")
|
||||
|
||||
verdict = await judge_match(
|
||||
"paramore",
|
||||
"big man, little dignity",
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
assert calls["ai"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_catalog_match_calls_ai():
|
||||
seen = {}
|
||||
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
seen["candidates"] = candidates
|
||||
seen["tier"] = audio_tier
|
||||
return MatchVerdict(
|
||||
kind=KIND_CONTENT,
|
||||
confident=True,
|
||||
canonical_artist="Queen",
|
||||
canonical_title="Bohemian Rhapsody",
|
||||
engine="ai",
|
||||
reason="typo fix",
|
||||
)
|
||||
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.engine == "ai"
|
||||
assert seen["tier"] == 3
|
||||
assert seen["candidates"] == [{"artist_name": "Queen", "track_name": "Radio Ga Ga"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_flag_skips_ai_and_returns_none():
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=False,
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.confident is True
|
||||
assert verdict.canonical_artist == "queen" # leaves user input untouched
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_failure_falls_back_to_none():
|
||||
async def ai(*_a, **_k):
|
||||
raise RuntimeError("model exploded")
|
||||
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.canonical_title == "bohemian rapsody"
|
||||
|
||||
|
||||
# --- Fast stage (catalog-only parallel pass) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fast_stage_returns_catalog_verdict_without_ai():
|
||||
verdict = await judge_match(
|
||||
"paramore",
|
||||
"big man, little dignity",
|
||||
stage="fast",
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
assert verdict.needs_ai is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fast_stage_undecided_signals_needs_ai_without_calling_ai():
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rapsody",
|
||||
stage="fast",
|
||||
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_NONE
|
||||
assert verdict.needs_ai is True
|
||||
assert verdict.confident is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fast_stage_never_calls_ai_even_when_undecided():
|
||||
# _ai_never raises if called; reaching here proves the fast pass skipped AI.
|
||||
verdict = await judge_match(
|
||||
"queen", "bohemian rapsody", stage="fast",
|
||||
search_tracks=_candidates(), ai_judge=_ai_never, enabled=True,
|
||||
)
|
||||
assert verdict.needs_ai is True
|
||||
|
||||
|
||||
# --- Item 4: verify a confident catalog match with AI when the audio tier is weak ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_catalog_match_is_verified_and_overridden_by_ai():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(
|
||||
KIND_CONTENT, True, "Queen", "Bohemian Rhapsody",
|
||||
engine="ai", reason="typo",
|
||||
)
|
||||
|
||||
# Catalog "matched" the user's exact typo (junk entry) → would normally be
|
||||
# 'none'/already-canonical. Weak tier (3) makes us verify with AI, which overrides.
|
||||
verdict = await judge_match(
|
||||
"Queen", "Bohemian Rapsody",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_CONTENT
|
||||
assert verdict.canonical_title == "Bohemian Rhapsody"
|
||||
assert verdict.engine == "ai"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strong_tier_catalog_match_still_skips_ai():
|
||||
verdict = await judge_match(
|
||||
"Queen", "Bohemian Rapsody",
|
||||
audio_tier=1,
|
||||
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=True,
|
||||
)
|
||||
# Strong audio results → trust the catalog match, no AI.
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_keeps_catalog_verdict_when_ai_unconfident():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(KIND_NONE, False, artist, title, engine="ai")
|
||||
|
||||
verdict = await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
# AI wasn't confident about a change → keep the cosmetic catalog tidy.
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_keeps_catalog_verdict_when_ai_fails():
|
||||
async def ai(*_a, **_k):
|
||||
raise RuntimeError("model exploded")
|
||||
|
||||
verdict = await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_does_not_verify_when_ai_disabled():
|
||||
verdict = await judge_match(
|
||||
"paramore", "big man, little dignity",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
|
||||
ai_judge=_ai_never,
|
||||
enabled=False,
|
||||
)
|
||||
assert verdict.kind == KIND_COSMETIC
|
||||
assert verdict.engine == "catalog"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weak_tier_ai_can_escalate_to_ambiguous():
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
return MatchVerdict(
|
||||
KIND_AMBIGUOUS, True, "Lewis Capaldi", "Bruises",
|
||||
alternatives=[{"artist": "Fox Stevenson", "title": "Bruises"}],
|
||||
engine="ai",
|
||||
)
|
||||
|
||||
verdict = await judge_match(
|
||||
"capaldi", "bruises",
|
||||
audio_tier=3,
|
||||
search_tracks=_candidates(("Lewis Capaldi", "Bruises")),
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.kind == KIND_AMBIGUOUS
|
||||
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_search_failure_still_lets_ai_run():
|
||||
async def failing_search(query, artist, limit):
|
||||
raise RuntimeError("catalog down")
|
||||
|
||||
async def ai(artist, title, candidates, audio_tier):
|
||||
assert candidates == [] # gracefully degraded to no candidates
|
||||
return MatchVerdict(KIND_NONE, True, artist, title, engine="ai")
|
||||
|
||||
verdict = await judge_match(
|
||||
"queen",
|
||||
"bohemian rhapsody",
|
||||
search_tracks=failing_search,
|
||||
ai_judge=ai,
|
||||
enabled=True,
|
||||
)
|
||||
assert verdict.engine == "ai"
|
||||
@@ -124,11 +124,6 @@ class TestProcessAudioDownload:
|
||||
'input_media_gcs_path': "uploads/test-job-123/audio/song.mp3",
|
||||
'filename': "song.mp3",
|
||||
})
|
||||
# Original audio recorded in file_urls so it shows in the admin files
|
||||
# manifest (and can be staged into the Dropbox folder) for URL/search jobs.
|
||||
mock_jm.update_file_url.assert_any_call(
|
||||
"test-job-123", 'input', 'audio', "uploads/test-job-123/audio/song.mp3"
|
||||
)
|
||||
mock_jm.transition_to_state.assert_called_once()
|
||||
mock_ws.trigger_audio_worker.assert_awaited_once_with("test-job-123")
|
||||
mock_ws.trigger_lyrics_worker.assert_awaited_once_with("test-job-123")
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
"""
|
||||
Regression tests for AudioShake leading-padding handling.
|
||||
|
||||
Some user-provided audio (e.g. the Vocal Star bulk-batch MP3s) begins with a block of
|
||||
null bytes before the first ID3/MPEG frame. ffmpeg tolerates it, but AudioShake rejects
|
||||
the asset with "Error fetching or processing asset" (400 on /tasks). The AudioUploadOptimizer
|
||||
must detect this and losslessly remux before upload — while leaving clean files and
|
||||
container formats (.mp4/.mov, which legitimately start with null box-size bytes) untouched.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioUploadOptimizer
|
||||
|
||||
|
||||
def _write(tmp_path, name, head: bytes):
|
||||
p = os.path.join(tmp_path, name)
|
||||
with open(p, "wb") as f:
|
||||
f.write(head + b"\x00" * 2048)
|
||||
return p
|
||||
|
||||
|
||||
def test_has_leading_padding_detects_null_start(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
|
||||
assert opt._has_leading_padding(padded) is True
|
||||
|
||||
|
||||
def test_has_leading_padding_false_for_id3(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
|
||||
assert opt._has_leading_padding(clean) is False
|
||||
|
||||
|
||||
def test_has_leading_padding_false_for_frame_sync(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
clean = _write(str(tmp_path), "sync.mp3", b"\xff\xfb\xc0\x04")
|
||||
assert opt._has_leading_padding(clean) is False
|
||||
|
||||
|
||||
def test_padded_mp3_is_remuxed(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
|
||||
with patch.object(opt, "_remux_clean", return_value=("/tmp/clean.mp3", "/tmp/clean.mp3")) as remux:
|
||||
result = opt.prepare_for_upload(padded)
|
||||
remux.assert_called_once()
|
||||
assert result == ("/tmp/clean.mp3", "/tmp/clean.mp3")
|
||||
|
||||
|
||||
def test_clean_mp3_uploaded_directly(tmp_path):
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
|
||||
with patch.object(opt, "_remux_clean") as remux:
|
||||
result = opt.prepare_for_upload(clean)
|
||||
remux.assert_not_called()
|
||||
assert result == (clean, None)
|
||||
|
||||
|
||||
def test_container_format_not_remuxed_despite_null_start(tmp_path):
|
||||
""".mp4/.mov begin with a null box-size prefix — must NOT be treated as padding."""
|
||||
opt = AudioUploadOptimizer(MagicMock())
|
||||
mp4 = _write(str(tmp_path), "video.mp4", b"\x00\x00\x00\x20ftyp")
|
||||
with patch.object(opt, "_remux_clean") as remux:
|
||||
result = opt.prepare_for_upload(mp4)
|
||||
remux.assert_not_called()
|
||||
assert result == (mp4, None)
|
||||
@@ -1,93 +0,0 @@
|
||||
"""Tests for the original-audio backfill planner (backend/scripts/backfill_original_audio.py)."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from backend.scripts.backfill_original_audio import plan_job_backfill
|
||||
|
||||
|
||||
def _job(**kwargs):
|
||||
base = dict(
|
||||
job_id="job-1",
|
||||
artist="Eddie Money",
|
||||
title="I'll Get By",
|
||||
audio_source_type="audio_search",
|
||||
url=None,
|
||||
filename=None,
|
||||
input_media_gcs_path="jobs/job-1/input/track.flac",
|
||||
file_urls={},
|
||||
dropbox_path="/Karaoke/Tracks-Organized",
|
||||
state_data={"brand_code": "NOMAD-1184"},
|
||||
)
|
||||
base.update(kwargs)
|
||||
return SimpleNamespace(**base)
|
||||
|
||||
|
||||
def _services(gcs_exists=True, folder_exists=True, file_present=False):
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = gcs_exists
|
||||
dropbox = MagicMock()
|
||||
# plan_job_backfill calls dropbox.file_exists for the folder first, then the file.
|
||||
calls = {"n": 0}
|
||||
|
||||
def _fe(_path):
|
||||
calls["n"] += 1
|
||||
return folder_exists if calls["n"] == 1 else file_present
|
||||
|
||||
dropbox.file_exists.side_effect = _fe
|
||||
return storage, dropbox
|
||||
|
||||
|
||||
class TestPlanJobBackfill:
|
||||
def test_upload_when_audio_present_and_not_yet_uploaded(self):
|
||||
storage, dropbox = _services(gcs_exists=True, folder_exists=True, file_present=False)
|
||||
action, detail = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
|
||||
assert action == "upload"
|
||||
assert detail["gcs_path"] == "jobs/job-1/input/track.flac"
|
||||
assert detail["remote_path"] == (
|
||||
"/Karaoke/Tracks-Organized/NOMAD-1184 - Eddie Money - I'll Get By/"
|
||||
"Eddie Money - I'll Get By (flacfetch).flac"
|
||||
)
|
||||
assert detail["filename"] == "Eddie Money - I'll Get By (flacfetch).flac"
|
||||
|
||||
def test_skip_when_no_brand_code(self):
|
||||
storage, dropbox = _services()
|
||||
action, _ = plan_job_backfill(_job(state_data={}), storage=storage, dropbox=dropbox)
|
||||
assert action == "skip-no-dropbox"
|
||||
|
||||
def test_skip_when_no_dropbox_path(self):
|
||||
storage, dropbox = _services()
|
||||
action, _ = plan_job_backfill(_job(dropbox_path=None), storage=storage, dropbox=dropbox)
|
||||
assert action == "skip-no-dropbox"
|
||||
|
||||
def test_skip_when_no_audio_record(self):
|
||||
storage, dropbox = _services()
|
||||
job = _job(input_media_gcs_path=None, file_urls={})
|
||||
action, _ = plan_job_backfill(job, storage=storage, dropbox=dropbox)
|
||||
assert action == "skip-no-audio-record"
|
||||
|
||||
def test_skip_when_audio_missing_from_gcs(self):
|
||||
storage, dropbox = _services(gcs_exists=False)
|
||||
action, detail = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
|
||||
assert action == "skip-audio-missing-gcs"
|
||||
assert detail == "jobs/job-1/input/track.flac"
|
||||
|
||||
def test_skip_when_already_present_in_dropbox(self):
|
||||
storage, dropbox = _services(gcs_exists=True, folder_exists=True, file_present=True)
|
||||
action, _ = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
|
||||
assert action == "skip-already-present"
|
||||
|
||||
def test_skip_when_track_folder_missing(self):
|
||||
storage, dropbox = _services(gcs_exists=True, folder_exists=False)
|
||||
action, detail = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
|
||||
assert action == "skip-folder-missing"
|
||||
assert detail.endswith("NOMAD-1184 - Eddie Money - I'll Get By")
|
||||
|
||||
def test_sanitizes_artist_title_for_paths(self):
|
||||
storage, dropbox = _services(gcs_exists=True, folder_exists=True, file_present=False)
|
||||
job = _job(artist="AC/DC", title="T:N/T")
|
||||
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
|
||||
assert action == "upload"
|
||||
# No raw slashes/colons leak into the Dropbox path beyond real separators
|
||||
tail = detail["remote_path"].split("/NOMAD-1184 - ", 1)[1]
|
||||
assert ":" not in tail
|
||||
@@ -1,114 +0,0 @@
|
||||
"""Tests for Bulk Mode album lookup + availability routes and the batch helper."""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_auth, AuthResult, UserType
|
||||
|
||||
|
||||
def _auth():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.STRIPE,
|
||||
remaining_uses=999,
|
||||
message="ok",
|
||||
user_email="t@example.com",
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestBatchHelper:
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_maps_community_results(self, monkeypatch):
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
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"] == ["KV", "KaraFun"]
|
||||
assert out[1]["available"] is False
|
||||
assert out[1]["brand_count"] == 0
|
||||
|
||||
|
||||
class TestAvailabilityRoute:
|
||||
def test_availability_endpoint(self, client, monkeypatch):
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
async def fake_batch(songs, concurrency=5):
|
||||
return [{"artist": s["artist"], "title": s["title"], "available": True,
|
||||
"brands": ["KV"], "brand_count": 1} for s in songs]
|
||||
|
||||
monkeypatch.setattr(kn, "check_community_versions_batch", fake_batch)
|
||||
resp = client.post("/api/bulk/availability", json={"tracks": [{"artist": "A", "title": "B"}]})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["results"][0]["available"] is True
|
||||
|
||||
def test_availability_rejects_over_limit(self, client):
|
||||
tracks = [{"artist": f"A{i}", "title": f"T{i}"} for i in range(101)]
|
||||
resp = client.post("/api/bulk/availability", json={"tracks": tracks})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
class TestAlbumTracklistRoute:
|
||||
def test_tracklist_merges_availability(self, client, monkeypatch):
|
||||
from backend.services import musicbrainz_service as mbs
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
class FakeMB:
|
||||
async def get_album_tracklist(self, rg):
|
||||
return {
|
||||
"release_mbid": "rel1",
|
||||
"canonical_release_mbid": "rel1",
|
||||
"title": "Discovery",
|
||||
"date": "2001",
|
||||
"tracks": [
|
||||
{"position": 1, "title": "One More Time", "recording_mbid": "r1",
|
||||
"length_ms": 320840, "is_extra": False, "extra_reason": ""},
|
||||
{"position": 2, "title": "Aerodynamic (Live)", "recording_mbid": "r2",
|
||||
"length_ms": 210000, "is_extra": True, "extra_reason": "live"},
|
||||
],
|
||||
"editions": [{"release_mbid": "rel1", "title": "Discovery", "status": "Official",
|
||||
"date": "2001", "country": "XE", "track_count": 2}],
|
||||
}
|
||||
|
||||
async def fake_batch(songs, concurrency=5):
|
||||
return [{"artist": s["artist"], "title": s["title"],
|
||||
"available": s["title"] == "One More Time",
|
||||
"brands": ["KV"] if s["title"] == "One More Time" else [],
|
||||
"brand_count": 1 if s["title"] == "One More Time" else 0} for s in songs]
|
||||
|
||||
monkeypatch.setattr(mbs, "get_musicbrainz_service", lambda: FakeMB())
|
||||
monkeypatch.setattr(kn, "check_community_versions_batch", fake_batch)
|
||||
|
||||
resp = client.get("/api/bulk/album/tracklist", params={"artist": "Daft Punk", "release_group_mbid": "rg1"})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["canonical_release_mbid"] == "rel1"
|
||||
assert data["tracks"][0]["available"] is True
|
||||
assert data["tracks"][0]["brands"] == ["KV"]
|
||||
assert data["tracks"][1]["is_extra"] is True
|
||||
assert data["tracks"][1]["available"] is False
|
||||
|
||||
def test_tracklist_requires_an_id(self, client):
|
||||
resp = client.get("/api/bulk/album/tracklist", params={"artist": "X"})
|
||||
assert resp.status_code == 422
|
||||
@@ -1,108 +0,0 @@
|
||||
"""Tests for Bulk Mode backend foundations.
|
||||
|
||||
Covers:
|
||||
- batch_id summary projection regression (Task 1.1)
|
||||
- pick_auto_selection tier-1 helper (Task 1.2), mirroring the frontend
|
||||
tier rule in frontend/lib/audio-search-utils.ts (getSearchConfidence tier 1).
|
||||
"""
|
||||
|
||||
|
||||
class TestBatchIdProjection:
|
||||
"""Regression: batch_id must be projected so the dashboard can group/filter."""
|
||||
|
||||
def test_batch_id_in_summary_field_paths(self):
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
assert 'state_data.batch_id' in FirestoreService.SUMMARY_FIELD_PATHS
|
||||
|
||||
def test_batch_id_in_summary_state_data_keys(self):
|
||||
from backend.api.routes.jobs import _SUMMARY_STATE_DATA_KEYS
|
||||
assert 'batch_id' in _SUMMARY_STATE_DATA_KEYS
|
||||
|
||||
|
||||
def _lossless_best(index=0, seeders=80, title="Bohemian Rhapsody", target_file=None):
|
||||
"""A confident lossless result -> BEST CHOICE category."""
|
||||
return {
|
||||
"index": index,
|
||||
"title": title,
|
||||
"provider": "RED",
|
||||
"is_lossless": True,
|
||||
"seeders": seeders,
|
||||
"release_type": "album",
|
||||
"target_file": target_file,
|
||||
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
|
||||
}
|
||||
|
||||
|
||||
def _lossy(index=0, title="Bohemian Rhapsody"):
|
||||
return {
|
||||
"index": index,
|
||||
"title": title,
|
||||
"provider": "YouTube",
|
||||
"is_lossless": False,
|
||||
"seeders": None,
|
||||
"release_type": "",
|
||||
"target_file": None,
|
||||
"quality_data": {"format": "OPUS", "bitrate": 160},
|
||||
}
|
||||
|
||||
|
||||
def _vinyl_lossless(index=0, seeders=120, title="Bohemian Rhapsody"):
|
||||
return {
|
||||
"index": index,
|
||||
"title": title,
|
||||
"provider": "RED",
|
||||
"is_lossless": True,
|
||||
"seeders": seeders,
|
||||
"release_type": "album",
|
||||
"target_file": None,
|
||||
"quality_data": {"format": "FLAC", "bit_depth": 24, "media": "vinyl"},
|
||||
}
|
||||
|
||||
|
||||
class TestPickAutoSelection:
|
||||
"""pick_auto_selection returns an index ONLY for a confident lossless (tier-1) pick."""
|
||||
|
||||
def test_confident_lossless_returns_its_index(self):
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
results = [_lossy(0), _lossless_best(1, seeders=80)]
|
||||
assert pick_auto_selection(results, "Bohemian Rhapsody") == 1
|
||||
|
||||
def test_only_lossy_returns_none(self):
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([_lossy(0), _lossy(1)], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_lossless_but_low_seeders_returns_none(self):
|
||||
# seeders < 50 -> STUDIO ALBUMS, not BEST CHOICE -> tier 2, no auto-pick
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([_lossless_best(0, seeders=10)], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_filename_mismatch_returns_none(self):
|
||||
# best is lossless+well-seeded but the file is clearly a different track
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
r = _lossless_best(0, seeders=80, title="Bohemian Rhapsody",
|
||||
target_file="03 - Love of My Life.flac")
|
||||
assert pick_auto_selection([r], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_only_vinyl_lossless_returns_none(self):
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([_vinyl_lossless(0)], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_empty_returns_none(self):
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_picks_highest_seeders_among_best_choice(self):
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
results = [_lossless_best(0, seeders=60), _lossless_best(1, seeders=200)]
|
||||
assert pick_auto_selection(results, "Bohemian Rhapsody") == 1
|
||||
|
||||
def test_short_title_is_not_auto_selected(self):
|
||||
# Too-short titles can't be verified against the filename -> defer to human.
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([_lossless_best(0, seeders=80, title="Go")], "Go") is None
|
||||
|
||||
def test_partial_word_filename_is_a_mismatch(self):
|
||||
# Title "One" must NOT match a file for "Someone" (whole-word matching).
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
r = _lossless_best(0, seeders=80, title="Someone", target_file="04 - Someone.flac")
|
||||
assert pick_auto_selection([r], "One") is None
|
||||
@@ -1,84 +0,0 @@
|
||||
"""Tests for GET /api/bulk/{batch_id} progress summary."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_auth, AuthResult, UserType
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
|
||||
def _auth(is_admin=False, email="t@example.com"):
|
||||
def _dep():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN if is_admin else UserType.STRIPE,
|
||||
remaining_uses=999, message="ok", user_email=email, is_admin=is_admin,
|
||||
)
|
||||
return _dep
|
||||
|
||||
|
||||
def _job(job_id, status, email="t@example.com", pending=False, auto=False, artist="A", title="T"):
|
||||
j = MagicMock()
|
||||
j.job_id = job_id
|
||||
j.status = status
|
||||
j.user_email = email
|
||||
j.artist = artist
|
||||
j.title = title
|
||||
j.audio_search_artist = artist
|
||||
j.audio_search_title = title
|
||||
j.state_data = {"batch_id": "b1", "bulk_pending_search": pending, "bulk_auto_selected": auto}
|
||||
return j
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
c = TestClient(app)
|
||||
yield c
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_progress_buckets(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
jm = MagicMock()
|
||||
jm.list_jobs_by_batch_id.return_value = [
|
||||
_job("j1", JobStatus.AWAITING_AUDIO_SELECTION),
|
||||
_job("j2", JobStatus.DOWNLOADING_AUDIO, auto=True),
|
||||
_job("j3", JobStatus.COMPLETE, auto=True),
|
||||
_job("j4", JobStatus.SEARCHING_AUDIO, pending=True),
|
||||
]
|
||||
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
|
||||
|
||||
resp = client.get("/api/bulk/b1")
|
||||
assert resp.status_code == 200, resp.text
|
||||
data = resp.json()
|
||||
assert data["total"] == 4
|
||||
assert data["counts"]["awaiting_selection"] == 1
|
||||
assert data["counts"]["processing"] == 1
|
||||
assert data["counts"]["complete"] == 1
|
||||
assert data["counts"]["searching"] == 1
|
||||
j2 = next(j for j in data["jobs"] if j["job_id"] == "j2")
|
||||
assert j2["auto_selected"] is True
|
||||
|
||||
|
||||
def test_other_users_batch_is_404(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth(email="me@example.com")
|
||||
jm = MagicMock()
|
||||
jm.list_jobs_by_batch_id.return_value = [_job("j1", JobStatus.COMPLETE, email="someone@else.com")]
|
||||
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
|
||||
|
||||
resp = client.get("/api/bulk/b1")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_admin_sees_any_batch(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth(is_admin=True, email="admin@example.com")
|
||||
jm = MagicMock()
|
||||
jm.list_jobs_by_batch_id.return_value = [_job("j1", JobStatus.COMPLETE, email="someone@else.com")]
|
||||
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
|
||||
|
||||
resp = client.get("/api/bulk/b1")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["total"] == 1
|
||||
@@ -1,178 +0,0 @@
|
||||
"""Tests for the Bulk Mode search worker: auto-select vs park branching."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
import backend.workers.bulk_search_worker as worker
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.audio_search_service import NoResultsError
|
||||
|
||||
|
||||
class FakeResult:
|
||||
def __init__(self, d):
|
||||
self._d = d
|
||||
|
||||
def to_dict(self):
|
||||
return self._d
|
||||
|
||||
|
||||
def _lossless_best(index=0, seeders=80, duration=240):
|
||||
return {
|
||||
"index": index, "title": "One More Time", "artist": "Daft Punk",
|
||||
"provider": "RED", "is_lossless": True, "seeders": seeders,
|
||||
"release_type": "album", "target_file": "01 - One More Time.flac",
|
||||
"duration": duration, "source_id": "abc",
|
||||
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
|
||||
}
|
||||
|
||||
|
||||
def _lossy(index=0):
|
||||
return {
|
||||
"index": index, "title": "One More Time", "artist": "Daft Punk",
|
||||
"provider": "YouTube", "is_lossless": False, "seeders": None,
|
||||
"release_type": "", "duration": 240, "quality_data": {"format": "OPUS"},
|
||||
}
|
||||
|
||||
|
||||
def _make_job(job_id="job1", auto=True, state_extra=None):
|
||||
job = MagicMock()
|
||||
job.job_id = job_id
|
||||
job.artist = "Daft Punk"
|
||||
job.title = "One More Time"
|
||||
job.audio_search_artist = "Daft Punk"
|
||||
job.audio_search_title = "One More Time"
|
||||
job.theme_id = None # skip theme prep
|
||||
job.user_email = "t@example.com"
|
||||
job.state_data = {"batch_id": "b1", "bulk_settings": {"auto_select_if_lossless": auto},
|
||||
"bulk_pending_search": True, "credits_charged": 1}
|
||||
if state_extra:
|
||||
job.state_data.update(state_extra)
|
||||
return job
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patched(monkeypatch):
|
||||
jm = MagicMock()
|
||||
transitions = []
|
||||
jm.transition_to_state.side_effect = lambda **kw: transitions.append(kw["new_status"]) or True
|
||||
ass = MagicMock()
|
||||
ass.last_remote_search_id = "remote-1"
|
||||
# default no theme prep import path needed (theme_id None)
|
||||
monkeypatch.setattr(worker, "get_worker_service", lambda: _async_worker_service())
|
||||
return jm, ass, transitions
|
||||
|
||||
|
||||
def _async_worker_service():
|
||||
ws = MagicMock()
|
||||
async def _dl(job_id):
|
||||
return True
|
||||
ws.trigger_audio_download_worker = _dl
|
||||
return ws
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_selects_confident_lossless(monkeypatch, patched):
|
||||
jm, ass, transitions = patched
|
||||
job = _make_job(auto=True)
|
||||
jm.get_job.return_value = job
|
||||
|
||||
async def _search(artist, title):
|
||||
return [FakeResult(_lossy(0)), FakeResult(_lossless_best(1))]
|
||||
ass.search_async = _search
|
||||
|
||||
# No duration delta owed (240s -> 1 credit, already charged 1)
|
||||
monkeypatch.setattr(worker, "_validate_and_prepare_selection_imported", None, raising=False)
|
||||
monkeypatch.setattr("backend.api.routes.audio_search._validate_and_prepare_selection",
|
||||
lambda job_id, idx: {"ok": True})
|
||||
|
||||
await worker.process_job("job1", jm, ass)
|
||||
|
||||
# Auto path: should NOT end in AWAITING_AUDIO_SELECTION; SEARCHING_AUDIO only
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION not in transitions
|
||||
# bulk_auto_selected True recorded
|
||||
final = jm.update_job.call_args[0][1]
|
||||
assert final["state_data.bulk_auto_selected"] is True
|
||||
assert final["state_data.bulk_pending_search"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parks_when_only_lossy(monkeypatch, patched):
|
||||
jm, ass, transitions = patched
|
||||
jm.get_job.return_value = _make_job(auto=True)
|
||||
|
||||
async def _search(artist, title):
|
||||
return [FakeResult(_lossy(0))]
|
||||
ass.search_async = _search
|
||||
|
||||
await worker.process_job("job1", jm, ass)
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
|
||||
final = jm.update_job.call_args[0][1]
|
||||
assert final["state_data.bulk_pending_search"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parks_when_auto_disabled_even_if_lossless(monkeypatch, patched):
|
||||
jm, ass, transitions = patched
|
||||
jm.get_job.return_value = _make_job(auto=False)
|
||||
|
||||
async def _search(artist, title):
|
||||
return [FakeResult(_lossless_best(0))]
|
||||
ass.search_async = _search
|
||||
|
||||
await worker.process_job("job1", jm, ass)
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_results_parks(monkeypatch, patched):
|
||||
jm, ass, transitions = patched
|
||||
jm.get_job.return_value = _make_job(auto=True)
|
||||
|
||||
async def _search(artist, title):
|
||||
raise NoResultsError("nope")
|
||||
ass.search_async = _search
|
||||
|
||||
await worker.process_job("job1", jm, ass)
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_select_charges_duration_delta(monkeypatch, patched):
|
||||
jm, ass, transitions = patched
|
||||
# 1300s -> ceil(1300/600)=3 credits; already charged 1 -> owed 2
|
||||
job = _make_job(auto=True)
|
||||
jm.get_job.return_value = job
|
||||
|
||||
async def _search(artist, title):
|
||||
return [FakeResult(_lossless_best(0, duration=1300))]
|
||||
ass.search_async = _search
|
||||
|
||||
us = MagicMock()
|
||||
us.deduct_credits.return_value = (True, 0, "ok")
|
||||
monkeypatch.setattr(worker, "get_user_service", lambda: us)
|
||||
monkeypatch.setattr("backend.api.routes.audio_search._validate_and_prepare_selection",
|
||||
lambda job_id, idx: {"ok": True})
|
||||
|
||||
await worker.process_job("job1", jm, ass)
|
||||
|
||||
us.deduct_credits.assert_called_once()
|
||||
_, kwargs = us.deduct_credits.call_args
|
||||
assert kwargs["amount"] == 2 # the delta
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_select_parks_when_delta_unaffordable(monkeypatch, patched):
|
||||
jm, ass, transitions = patched
|
||||
jm.get_job.return_value = _make_job(auto=True)
|
||||
|
||||
async def _search(artist, title):
|
||||
return [FakeResult(_lossless_best(0, duration=1300))]
|
||||
ass.search_async = _search
|
||||
|
||||
us = MagicMock()
|
||||
us.deduct_credits.return_value = (False, 0, "insufficient")
|
||||
monkeypatch.setattr(worker, "get_user_service", lambda: us)
|
||||
|
||||
await worker.process_job("job1", jm, ass)
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
|
||||
@@ -1,150 +0,0 @@
|
||||
"""Tests for POST /api/bulk/submit — upfront credit gate + batch job creation."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_auth, AuthResult, UserType
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
|
||||
|
||||
def _auth(is_admin=False, email="t@example.com"):
|
||||
def _dep():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN if is_admin else UserType.STRIPE,
|
||||
remaining_uses=999,
|
||||
message="ok",
|
||||
user_email=email,
|
||||
is_admin=is_admin,
|
||||
)
|
||||
return _dep
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_deps(monkeypatch):
|
||||
"""Patch the heavy collaborators used by bulk_submit."""
|
||||
import backend.api.routes.bulk as bulk
|
||||
|
||||
# Theme + settings + cdg/txt
|
||||
theme = MagicMock()
|
||||
theme.get_default_theme_id.return_value = "nomad"
|
||||
monkeypatch.setattr("backend.services.theme_service.get_theme_service", lambda: theme)
|
||||
monkeypatch.setattr("backend.services.job_defaults_service.resolve_cdg_txt_defaults", lambda *a, **k: (False, False))
|
||||
settings = MagicMock(
|
||||
default_brand_prefix="NOMAD", default_enable_youtube_upload=False,
|
||||
default_youtube_description="", default_discord_webhook_url=None,
|
||||
default_dropbox_path=None, default_gdrive_folder_id=None,
|
||||
)
|
||||
monkeypatch.setattr("backend.config.get_settings", lambda: settings)
|
||||
|
||||
# Worker trigger
|
||||
worker = MagicMock()
|
||||
async def _trigger(batch_id):
|
||||
return True
|
||||
worker.trigger_bulk_search_worker = _trigger
|
||||
monkeypatch.setattr("backend.services.worker_service.get_worker_service", lambda: worker)
|
||||
|
||||
yield
|
||||
|
||||
|
||||
def _patch_user_service(monkeypatch, credits):
|
||||
us = MagicMock()
|
||||
us.check_credits.return_value = credits
|
||||
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: us)
|
||||
return us
|
||||
|
||||
|
||||
def _patch_job_manager(monkeypatch, fail_after=None):
|
||||
"""JobManager whose create_job returns sequential ids, optionally failing after N."""
|
||||
created = {"count": 0}
|
||||
jm = MagicMock()
|
||||
|
||||
def _create_job(job_create, is_admin=False):
|
||||
if fail_after is not None and created["count"] >= fail_after:
|
||||
raise InsufficientCreditsError(message="out", credits_available=0, credits_required=1)
|
||||
created["count"] += 1
|
||||
job = MagicMock()
|
||||
job.job_id = f"job{created['count']}"
|
||||
return job
|
||||
|
||||
jm.create_job.side_effect = _create_job
|
||||
jm.update_job.return_value = None
|
||||
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
|
||||
return jm
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
c = TestClient(app)
|
||||
yield c
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_happy_path_creates_jobs_and_dispatches(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
_patch_user_service(monkeypatch, credits=10)
|
||||
jm = _patch_job_manager(monkeypatch)
|
||||
|
||||
resp = client.post("/api/bulk/submit", json={
|
||||
"songs": [{"artist": "Daft Punk", "title": "One More Time"},
|
||||
{"artist": "Daft Punk", "title": "Aerodynamic"}],
|
||||
"settings": {"auto_select_if_lossless": True, "is_private": False},
|
||||
})
|
||||
assert resp.status_code == 200, resp.text
|
||||
data = resp.json()
|
||||
assert data["total"] == 2
|
||||
assert len(data["job_ids"]) == 2
|
||||
assert jm.create_job.call_count == 2
|
||||
# batch_id + bulk settings stamped via update_job
|
||||
assert jm.update_job.call_count == 2
|
||||
_, kwargs_call = jm.update_job.call_args
|
||||
stamped = jm.update_job.call_args[0][1]
|
||||
assert "state_data.batch_id" in stamped
|
||||
assert stamped["state_data.bulk_pending_search"] is True
|
||||
|
||||
|
||||
def test_insufficient_credits_creates_nothing(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
_patch_user_service(monkeypatch, credits=1)
|
||||
jm = _patch_job_manager(monkeypatch)
|
||||
|
||||
resp = client.post("/api/bulk/submit", json={
|
||||
"songs": [{"artist": "A", "title": "B"}, {"artist": "C", "title": "D"}],
|
||||
})
|
||||
assert resp.status_code == 402
|
||||
assert jm.create_job.call_count == 0
|
||||
|
||||
|
||||
def test_admin_bypasses_credit_gate(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth(is_admin=True)
|
||||
us = _patch_user_service(monkeypatch, credits=0)
|
||||
jm = _patch_job_manager(monkeypatch)
|
||||
|
||||
resp = client.post("/api/bulk/submit", json={"songs": [{"artist": "A", "title": "B"}]})
|
||||
assert resp.status_code == 200
|
||||
us.check_credits.assert_not_called()
|
||||
assert jm.create_job.call_count == 1
|
||||
|
||||
|
||||
def test_rejects_over_100(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
_patch_user_service(monkeypatch, credits=1000)
|
||||
_patch_job_manager(monkeypatch)
|
||||
songs = [{"artist": f"A{i}", "title": f"T{i}"} for i in range(101)]
|
||||
resp = client.post("/api/bulk/submit", json={"songs": songs})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_partial_failure_returns_created_jobs(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
_patch_user_service(monkeypatch, credits=3) # gate passes for 3
|
||||
jm = _patch_job_manager(monkeypatch, fail_after=2) # but only 2 succeed
|
||||
|
||||
resp = client.post("/api/bulk/submit", json={
|
||||
"songs": [{"artist": "A", "title": "1"}, {"artist": "A", "title": "2"}, {"artist": "A", "title": "3"}],
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["total"] == 2
|
||||
@@ -471,63 +471,3 @@ class TestCreateSharedLink:
|
||||
|
||||
assert url == "https://dropbox.com/s/existing/file.mp4"
|
||||
|
||||
|
||||
|
||||
class TestFileExists:
|
||||
"""Test DropboxService.file_exists (used by the original-audio backfill)."""
|
||||
|
||||
def test_returns_true_when_metadata_found(self):
|
||||
from backend.services.dropbox_service import DropboxService
|
||||
|
||||
service = DropboxService()
|
||||
mock_client = MagicMock()
|
||||
service._client = mock_client
|
||||
|
||||
assert service.file_exists("/Karaoke/NOMAD-1 - A - B/A - B (flacfetch).flac") is True
|
||||
mock_client.files_get_metadata.assert_called_once_with(
|
||||
"/Karaoke/NOMAD-1 - A - B/A - B (flacfetch).flac"
|
||||
)
|
||||
|
||||
def test_returns_false_on_not_found(self):
|
||||
from dropbox.exceptions import ApiError
|
||||
from backend.services.dropbox_service import DropboxService
|
||||
|
||||
service = DropboxService()
|
||||
mock_client = MagicMock()
|
||||
# Genuine "not found": is_path() -> get_path().is_not_found() == True
|
||||
not_found_err = MagicMock()
|
||||
not_found_err.is_path.return_value = True
|
||||
not_found_err.get_path.return_value.is_not_found.return_value = True
|
||||
mock_client.files_get_metadata.side_effect = ApiError(
|
||||
request_id="r", error=not_found_err, user_message_text=None, user_message_locale=None
|
||||
)
|
||||
service._client = mock_client
|
||||
|
||||
assert service.file_exists("/missing.flac") is False
|
||||
|
||||
def test_reraises_non_not_found_api_error(self):
|
||||
"""Auth/network/rate-limit errors must NOT be masked as 'file missing'."""
|
||||
from dropbox.exceptions import ApiError
|
||||
from backend.services.dropbox_service import DropboxService
|
||||
|
||||
service = DropboxService()
|
||||
mock_client = MagicMock()
|
||||
other_err = MagicMock()
|
||||
other_err.is_path.return_value = False
|
||||
mock_client.files_get_metadata.side_effect = ApiError(
|
||||
request_id="r", error=other_err, user_message_text=None, user_message_locale=None
|
||||
)
|
||||
service._client = mock_client
|
||||
|
||||
with pytest.raises(ApiError):
|
||||
service.file_exists("/some.flac")
|
||||
|
||||
def test_prepends_leading_slash(self):
|
||||
from backend.services.dropbox_service import DropboxService
|
||||
|
||||
service = DropboxService()
|
||||
mock_client = MagicMock()
|
||||
service._client = mock_client
|
||||
|
||||
service.file_exists("Karaoke/x.flac")
|
||||
mock_client.files_get_metadata.assert_called_once_with("/Karaoke/x.flac")
|
||||
@@ -394,48 +394,6 @@ class TestGCEEncodingBackend:
|
||||
assert output.lossless_mkv_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv"
|
||||
assert output.lossy_720p_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4"
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_maps_screen_movs_from_list(self, mock_get_service):
|
||||
"""Test GCE encoding maps the standalone (Title).mov / (End).mov from output_files list.
|
||||
|
||||
The GCE worker now copies the 5-second screen videos into its outputs/ dir so they
|
||||
upload to GCS finals. The mapper must recognise them and populate
|
||||
title_mov_path / end_mov_path so the orchestrator downloads them into output_dir
|
||||
(and thus into the Dropbox folder). Regression for: screen MOVs lost from Dropbox
|
||||
after #647/#650 moved screen generation to the encoder.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Title).mov",
|
||||
"jobs/test/finals/Artist - Title (End).mov",
|
||||
]
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.png",
|
||||
karaoke_video_path="/input/karaoke.mkv",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is True
|
||||
assert output.title_mov_path == "jobs/test/finals/Artist - Title (Title).mov"
|
||||
assert output.end_mov_path == "jobs/test/finals/Artist - Title (End).mov"
|
||||
|
||||
|
||||
class TestGetEncodingBackend:
|
||||
"""Test encoding backend factory function."""
|
||||
|
||||
@@ -601,7 +601,7 @@ class TestWaitForCompletionPollTolerance:
|
||||
"""Tolerates up to MAX_CONSECUTIVE_POLL_FAILURES-1 consecutive failures."""
|
||||
call_count = 0
|
||||
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
async def mock_get_status(job_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count <= 2:
|
||||
@@ -623,7 +623,7 @@ class TestWaitForCompletionPollTolerance:
|
||||
@pytest.mark.asyncio
|
||||
async def test_fails_after_max_consecutive_poll_failures(self, encoding_service):
|
||||
"""Fails after MAX_CONSECUTIVE_POLL_FAILURES consecutive failures."""
|
||||
async def always_fail(job_id, worker_url=None):
|
||||
async def always_fail(job_id):
|
||||
raise aiohttp.ClientConnectorError(
|
||||
connection_key=MagicMock(), os_error=OSError("Connection refused")
|
||||
)
|
||||
@@ -640,7 +640,7 @@ class TestWaitForCompletionPollTolerance:
|
||||
"""A successful poll resets the consecutive failure counter."""
|
||||
call_count = 0
|
||||
|
||||
async def intermittent_failures(job_id, worker_url=None):
|
||||
async def intermittent_failures(job_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
# Fail for 2, succeed (running), fail for 2 more, succeed (complete)
|
||||
@@ -752,128 +752,3 @@ class TestFormatException:
|
||||
e = aiohttp.ClientConnectorError(MagicMock(), OSError())
|
||||
# Type name should always appear
|
||||
assert "ClientConnectorError" in _format_exception(e)
|
||||
|
||||
|
||||
class TestWorkerUrlPinning:
|
||||
"""Status polls must stay pinned to the worker that ACCEPTED the job.
|
||||
|
||||
Regression for incident 2026-06-16 (job d3af33ae): a blue-green deploy
|
||||
swapped the primary pointer mid-render, and because status polls re-resolved
|
||||
`active_url` on every call, they migrated from the worker actually encoding
|
||||
the job (old primary) to the freshly-swapped new primary — which 404'd
|
||||
"Encoding job ... not found" and failed the render after 5 polls, even though
|
||||
the original worker finished the encode fine.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_job_status_targets_pinned_url(self, encoding_service):
|
||||
"""A pinned poll hits the given worker_url, not active_url, and disables
|
||||
failover (a pinned poll must never re-resolve or spin up a fallback VM —
|
||||
a fresh VM cannot have the in-flight job)."""
|
||||
# active_url would resolve to worker-b, but the job lives on worker-a.
|
||||
captured = {}
|
||||
|
||||
async def fake_request(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": 200, "json": {"status": "running", "progress": 40}, "text": None}
|
||||
|
||||
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
|
||||
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
|
||||
result = await encoding_service.get_job_status("d3af33ae", worker_url="http://worker-a:8080")
|
||||
|
||||
assert result["status"] == "running"
|
||||
assert captured["url"] == "http://worker-a:8080/status/d3af33ae"
|
||||
assert captured["allow_failover"] is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_job_status_without_pin_uses_active_url(self, encoding_service):
|
||||
"""Regression: unpinned polls still resolve the current active_url."""
|
||||
captured = {}
|
||||
|
||||
async def fake_request(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": 200, "json": {"status": "running"}, "text": None}
|
||||
|
||||
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
|
||||
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
|
||||
await encoding_service.get_job_status("d3af33ae")
|
||||
|
||||
assert captured["url"] == "http://worker-b:8080/status/d3af33ae"
|
||||
# Unpinned keeps the existing failover/re-resolution behaviour.
|
||||
assert captured.get("allow_failover", True) is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_for_completion_threads_pinned_url_into_polls(self, encoding_service):
|
||||
"""wait_for_completion forwards its worker_url to every status poll."""
|
||||
seen_urls = []
|
||||
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
seen_urls.append(worker_url)
|
||||
return {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
result = await encoding_service.wait_for_completion(
|
||||
"d3af33ae", worker_url="http://worker-a:8080"
|
||||
)
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert seen_urls == ["http://worker-a:8080"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_with_retry_no_failover_when_disabled(self, encoding_service):
|
||||
"""With allow_failover=False, a connection error must NOT trigger the
|
||||
fallback-VM warmup nor URL re-resolution — it just retries the same URL
|
||||
and surfaces the failure to the caller's own poll-tolerance loop."""
|
||||
encoding_service.set_worker_manager(MagicMock())
|
||||
warmup = AsyncMock()
|
||||
|
||||
with patch.object(encoding_service, "_warmup_encoding_worker_fallback", warmup), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("aiohttp.ClientSession") as mock_session:
|
||||
mock_session.side_effect = aiohttp.ClientConnectorError(
|
||||
MagicMock(), OSError("Connection refused")
|
||||
)
|
||||
with pytest.raises(aiohttp.ClientConnectorError):
|
||||
await encoding_service._request_with_retry(
|
||||
method="GET",
|
||||
url="http://worker-a:8080/status/j1",
|
||||
headers={},
|
||||
job_id="j1",
|
||||
path=None,
|
||||
allow_failover=False,
|
||||
)
|
||||
|
||||
warmup.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_video_keeps_polling_submission_worker_after_swap(self, encoding_service):
|
||||
"""End-to-end: when active_url has swapped to a worker that 404s, the
|
||||
render keeps polling the worker the job was submitted to and completes.
|
||||
|
||||
This FAILS before the fix (the poll follows active_url to worker-b and
|
||||
gets "not found"), and PASSES after (the poll is pinned to worker-a)."""
|
||||
encoding_service.set_worker_manager(MagicMock())
|
||||
|
||||
async def fake_submit(job_id, render_config):
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
async def fake_get_status(job_id, worker_url=None):
|
||||
# worker-a owns the job; the post-swap active worker (worker-b, or an
|
||||
# unpinned None) has never seen it.
|
||||
if worker_url == "http://worker-a:8080":
|
||||
return {"status": "complete", "output_files": ["4k.mp4"]}
|
||||
raise RuntimeError(f"Encoding job {job_id} not found")
|
||||
|
||||
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-a:8080"), \
|
||||
patch.object(encoding_service, "submit_render_video_job", side_effect=fake_submit), \
|
||||
patch.object(encoding_service, "get_job_status", side_effect=fake_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
result = await encoding_service.render_video_on_gce("d3af33ae", {"foo": "bar"})
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert result["output_files"] == ["4k.mp4"]
|
||||
@@ -508,50 +508,3 @@ class TestWheelVersionSorting:
|
||||
wheels = ["/tmp/karaoke_gen-current.whl"]
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
assert latest is None
|
||||
|
||||
|
||||
class TestScreenVideoStaging:
|
||||
"""Test that the standalone screen MOVs are copied into outputs/ for upload.
|
||||
|
||||
Mirrors the copy logic in run_encoding (kept self-contained, like the other
|
||||
tests in this file). Regression: (Title).mov / (End).mov disappeared from the
|
||||
Dropbox folder after #647/#650 moved screen generation into this encoder.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def stage_screen_videos(title_video, end_video, output_dir: Path, base_name: str):
|
||||
"""Replicates run_encoding's screen-video staging step."""
|
||||
import shutil
|
||||
for screen_video, suffix in ((title_video, "Title"), (end_video, "End")):
|
||||
if screen_video and Path(screen_video).is_file():
|
||||
dest = output_dir / f"{base_name} ({suffix}).mov"
|
||||
shutil.copy2(screen_video, dest)
|
||||
|
||||
def test_copies_title_and_end_with_canonical_names(self, tmp_path):
|
||||
screens = tmp_path / "screens"
|
||||
screens.mkdir()
|
||||
title = screens / "title.mov"
|
||||
end = screens / "end.mov"
|
||||
title.write_bytes(b"title-mov-bytes")
|
||||
end.write_bytes(b"end-mov-bytes")
|
||||
outputs = tmp_path / "outputs"
|
||||
outputs.mkdir()
|
||||
|
||||
self.stage_screen_videos(title, end, outputs, "Artist - Title")
|
||||
|
||||
assert (outputs / "Artist - Title (Title).mov").read_bytes() == b"title-mov-bytes"
|
||||
assert (outputs / "Artist - Title (End).mov").read_bytes() == b"end-mov-bytes"
|
||||
|
||||
def test_skips_missing_end_video(self, tmp_path):
|
||||
screens = tmp_path / "screens"
|
||||
screens.mkdir()
|
||||
title = screens / "title.mov"
|
||||
title.write_bytes(b"title-mov-bytes")
|
||||
outputs = tmp_path / "outputs"
|
||||
outputs.mkdir()
|
||||
|
||||
# end_video is None (no end screen) — must not raise
|
||||
self.stage_screen_videos(title, None, outputs, "Artist - Title")
|
||||
|
||||
assert (outputs / "Artist - Title (Title).mov").is_file()
|
||||
assert not (outputs / "Artist - Title (End).mov").exists()
|
||||
@@ -1,120 +0,0 @@
|
||||
"""Tests for POST /api/catalog/match-judge."""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.services.match_judge.verdict import MatchVerdict, KIND_COSMETIC, KIND_NONE
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
return {"Authorization": "Bearer test-admin-token"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_rate_limits():
|
||||
from backend.api.routes.catalog import _rate_limit_windows
|
||||
_rate_limit_windows.clear()
|
||||
yield
|
||||
_rate_limit_windows.clear()
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_returns_verdict(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict(
|
||||
kind=KIND_COSMETIC,
|
||||
confident=True,
|
||||
canonical_artist="Paramore",
|
||||
canonical_title="Big Man, Little Dignity",
|
||||
engine="catalog",
|
||||
reason="casing",
|
||||
)
|
||||
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "paramore", "title": "big man, little dignity"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["kind"] == "cosmetic"
|
||||
assert data["confident"] is True
|
||||
assert data["canonical_artist"] == "Paramore"
|
||||
assert data["canonical_title"] == "Big Man, Little Dignity"
|
||||
assert data["engine"] == "catalog"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_passes_audio_tier(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
|
||||
|
||||
client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b", "audio_confidence_tier": 3},
|
||||
headers=auth_headers,
|
||||
)
|
||||
# judge_match(artist, title, audio_tier=...) — tier forwarded
|
||||
_, kwargs = mock_judge.call_args
|
||||
assert kwargs.get("audio_tier") == 3 or mock_judge.call_args.args[2] == 3
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_defaults_to_full_stage(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
|
||||
|
||||
client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
_, kwargs = mock_judge.call_args
|
||||
assert kwargs.get("stage") == "full"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
|
||||
def test_match_judge_forwards_fast_stage(mock_judge, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
|
||||
mock_judge.return_value = MatchVerdict(
|
||||
KIND_NONE, False, "q", "b", engine="catalog", reason="needs ai", needs_ai=True
|
||||
)
|
||||
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b", "stage": "fast"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["needs_ai"] is True
|
||||
_, kwargs = mock_judge.call_args
|
||||
assert kwargs.get("stage") == "fast"
|
||||
|
||||
|
||||
def test_match_judge_rejects_unknown_stage(client, auth_headers):
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "q", "title": "b", "stage": "turbo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_match_judge_validation_error(client, auth_headers):
|
||||
resp = client.post(
|
||||
"/api/catalog/match-judge",
|
||||
json={"artist": "", "title": "Dreams"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
@@ -1,188 +0,0 @@
|
||||
"""Tests for the MusicBrainz lookup service (Bulk Mode album lookup).
|
||||
|
||||
HTTP is mocked; fixtures mirror real API shapes captured 2026-06.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.musicbrainz_service import (
|
||||
MusicBrainzService,
|
||||
classify_extra,
|
||||
)
|
||||
|
||||
|
||||
class TestClassifyExtra:
|
||||
def test_plain_studio_track_is_not_extra(self):
|
||||
assert classify_extra("One More Time") == (False, "")
|
||||
|
||||
def test_live_in_parens_is_extra(self):
|
||||
is_extra, reason = classify_extra("Bohemian Rhapsody (Live at Wembley)")
|
||||
assert is_extra is True
|
||||
assert "live" in reason.lower()
|
||||
|
||||
def test_remix_after_dash_is_extra(self):
|
||||
is_extra, _ = classify_extra("Get Lucky - Daft Punk Remix")
|
||||
assert is_extra is True
|
||||
|
||||
def test_bonus_disambiguation_is_extra(self):
|
||||
is_extra, _ = classify_extra("Some Song", disambiguation="bonus track")
|
||||
assert is_extra is True
|
||||
|
||||
def test_word_in_normal_title_not_flagged(self):
|
||||
# "Alive" contains "live" but not as a standalone qualifier keyword
|
||||
assert classify_extra("Alive") == (False, "")
|
||||
# "Living on a Prayer" should not be flagged
|
||||
assert classify_extra("Living on a Prayer") == (False, "")
|
||||
|
||||
|
||||
class TestPickCanonical:
|
||||
def test_prefers_modal_track_count_then_earliest(self):
|
||||
editions = [
|
||||
{"release_mbid": "deluxe", "status": "Official", "date": "2011", "country": "US", "track_count": 20},
|
||||
{"release_mbid": "std-2001", "status": "Official", "date": "2001-03-12", "country": "XE", "track_count": 14},
|
||||
{"release_mbid": "std-2005", "status": "Official", "date": "2005", "country": "US", "track_count": 14},
|
||||
{"release_mbid": "promo", "status": "Promotion", "date": "2000", "country": "US", "track_count": 14},
|
||||
]
|
||||
chosen = MusicBrainzService.pick_canonical_edition(editions)
|
||||
# modal count is 14 (std-2001, std-2005, promo-but-not-official filtered);
|
||||
# earliest official among 14-track -> std-2001
|
||||
assert chosen["release_mbid"] == "std-2001"
|
||||
|
||||
def test_empty_returns_none(self):
|
||||
assert MusicBrainzService.pick_canonical_edition([]) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestServiceCalls:
|
||||
async def _svc_with(self, monkeypatch, responses):
|
||||
"""Return a service whose _get returns canned responses keyed by path prefix."""
|
||||
svc = MusicBrainzService()
|
||||
|
||||
async def fake_get(path, params):
|
||||
for key, val in responses.items():
|
||||
if path.startswith(key):
|
||||
return val
|
||||
raise AssertionError(f"unexpected path {path}")
|
||||
|
||||
monkeypatch.setattr(svc, "_get", fake_get)
|
||||
return svc
|
||||
|
||||
async def test_search_artists_parses(self, monkeypatch):
|
||||
svc = await self._svc_with(
|
||||
monkeypatch,
|
||||
{
|
||||
"artist": {
|
||||
"artists": [
|
||||
{"id": "abc", "name": "Daft Punk", "disambiguation": "", "type": "Group", "country": "FR", "score": 100}
|
||||
]
|
||||
}
|
||||
},
|
||||
)
|
||||
out = await svc.search_artists("Daft Punk")
|
||||
assert out[0]["mbid"] == "abc"
|
||||
assert out[0]["name"] == "Daft Punk"
|
||||
|
||||
async def test_album_tracklist_resolves_canonical_and_flags_extras(self, monkeypatch):
|
||||
editions = {
|
||||
"release": {
|
||||
"releases": [
|
||||
{"id": "rel-std", "title": "Discovery", "status": "Official", "date": "2001-03-12", "country": "XE", "media": [{"track-count": 3}]},
|
||||
{"id": "rel-deluxe", "title": "Discovery (Deluxe)", "status": "Official", "date": "2021", "country": "US", "media": [{"track-count": 5}]},
|
||||
]
|
||||
}
|
||||
}
|
||||
tracklist = {
|
||||
"release/rel-std": {
|
||||
"id": "rel-std",
|
||||
"title": "Discovery",
|
||||
"date": "2001-03-12",
|
||||
"country": "XE",
|
||||
"media": [
|
||||
{
|
||||
"format": "CD",
|
||||
"track-count": 3,
|
||||
"tracks": [
|
||||
{"position": 1, "title": "One More Time", "length": 320840, "recording": {"id": "r1", "title": "One More Time", "disambiguation": "", "length": 320840}},
|
||||
{"position": 2, "title": "Aerodynamic", "length": 207533, "recording": {"id": "r2", "title": "Aerodynamic", "disambiguation": "", "length": 207533}},
|
||||
{"position": 3, "title": "Aerodynamic (Live)", "length": 210000, "recording": {"id": "r3", "title": "Aerodynamic", "disambiguation": "live", "length": 210000}},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
# _list_editions calls _get("release", {release-group...}); tracklist calls _get("release/<id>", ...)
|
||||
# Order matters: "release/rel-std" must match before "release".
|
||||
svc = MusicBrainzService()
|
||||
|
||||
async def fake_get(path, params):
|
||||
if path.startswith("release/"):
|
||||
return tracklist[path]
|
||||
if path == "release":
|
||||
return editions["release"]
|
||||
raise AssertionError(path)
|
||||
|
||||
monkeypatch.setattr(svc, "_get", fake_get)
|
||||
|
||||
result = await svc.get_album_tracklist("rg-discovery")
|
||||
assert result["canonical_release_mbid"] == "rel-std" # modal 3-track studio edition
|
||||
assert len(result["tracks"]) == 3
|
||||
assert result["tracks"][0]["is_extra"] is False
|
||||
assert result["tracks"][2]["is_extra"] is True # the (Live) track
|
||||
assert len(result["editions"]) == 2
|
||||
|
||||
|
||||
import httpx as _httpx
|
||||
|
||||
|
||||
class _FakeResp:
|
||||
def __init__(self, status, json_data=None):
|
||||
self.status_code = status
|
||||
self._json = json_data
|
||||
self.request = _httpx.Request("GET", "https://musicbrainz.org/ws/2/artist")
|
||||
|
||||
def raise_for_status(self):
|
||||
if self.status_code >= 400:
|
||||
raise _httpx.HTTPStatusError(
|
||||
f"{self.status_code}", request=self.request, response=self
|
||||
)
|
||||
|
||||
def json(self):
|
||||
return self._json
|
||||
|
||||
|
||||
def _patch_http(monkeypatch, mbs, svc, responses):
|
||||
"""Make AsyncClient.get return queued _FakeResp objects; disable throttle/backoff."""
|
||||
async def _noop():
|
||||
return None
|
||||
monkeypatch.setattr(svc, "_throttle", _noop)
|
||||
monkeypatch.setattr(mbs, "_RETRY_BACKOFF_S", 0)
|
||||
calls = {"n": 0}
|
||||
|
||||
async def fake_get(self, url, **kwargs):
|
||||
r = responses[min(calls["n"], len(responses) - 1)]
|
||||
calls["n"] += 1
|
||||
return r
|
||||
|
||||
monkeypatch.setattr(_httpx.AsyncClient, "get", fake_get)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestRetry:
|
||||
async def test_retries_503_then_succeeds(self, monkeypatch):
|
||||
from backend.services import musicbrainz_service as mbs
|
||||
svc = mbs.MusicBrainzService()
|
||||
calls = _patch_http(monkeypatch, mbs, svc, [
|
||||
_FakeResp(503),
|
||||
_FakeResp(200, {"artists": [{"id": "x", "name": "Queen"}]}),
|
||||
])
|
||||
out = await svc.search_artists("Queen")
|
||||
assert out[0]["mbid"] == "x"
|
||||
assert calls["n"] == 2 # one 503 retry, then success
|
||||
|
||||
async def test_exhausts_retries_raises(self, monkeypatch):
|
||||
from backend.services import musicbrainz_service as mbs
|
||||
svc = mbs.MusicBrainzService()
|
||||
_patch_http(monkeypatch, mbs, svc, [_FakeResp(503)])
|
||||
with pytest.raises(_httpx.HTTPStatusError):
|
||||
await svc.search_artists("Queen")
|
||||
@@ -1,78 +0,0 @@
|
||||
"""Tests for original-audio naming/location helpers (backend/services/original_audio.py).
|
||||
|
||||
These back the regression fix that restores the original input audio
|
||||
(e.g. '<artist> - <title> (flacfetch).flac') to the Dropbox track folder.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.original_audio import (
|
||||
original_audio_source_tag,
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
)
|
||||
|
||||
|
||||
def _job(**kwargs):
|
||||
base = dict(
|
||||
audio_source_type=None,
|
||||
url=None,
|
||||
filename=None,
|
||||
input_media_gcs_path=None,
|
||||
file_urls={},
|
||||
)
|
||||
base.update(kwargs)
|
||||
return SimpleNamespace(**base)
|
||||
|
||||
|
||||
class TestSourceTag:
|
||||
def test_file_upload_maps_to_uploaded(self):
|
||||
assert original_audio_source_tag(_job(audio_source_type="file_upload")) == "uploaded"
|
||||
|
||||
def test_youtube_url_maps_to_youtube(self):
|
||||
assert original_audio_source_tag(_job(audio_source_type="youtube_url")) == "YouTube"
|
||||
|
||||
def test_audio_search_maps_to_flacfetch(self):
|
||||
assert original_audio_source_tag(_job(audio_source_type="audio_search")) == "flacfetch"
|
||||
|
||||
def test_legacy_url_job_without_source_type(self):
|
||||
assert original_audio_source_tag(_job(url="https://youtu.be/x")) == "YouTube"
|
||||
|
||||
def test_legacy_upload_without_source_type(self):
|
||||
assert original_audio_source_tag(_job(filename="song.mp3")) == "uploaded"
|
||||
|
||||
def test_unknown_falls_back_to_input(self):
|
||||
assert original_audio_source_tag(_job()) == "input"
|
||||
|
||||
|
||||
class TestGcsPath:
|
||||
def test_prefers_input_media_gcs_path(self):
|
||||
job = _job(input_media_gcs_path="jobs/j1/input/song.mp3",
|
||||
file_urls={"input": "jobs/j1/other.flac"})
|
||||
assert original_audio_gcs_path(job) == "jobs/j1/input/song.mp3"
|
||||
|
||||
def test_file_urls_input_as_string(self):
|
||||
job = _job(file_urls={"input": "jobs/j1/input.flac"})
|
||||
assert original_audio_gcs_path(job) == "jobs/j1/input.flac"
|
||||
|
||||
def test_file_urls_input_as_dict(self):
|
||||
job = _job(file_urls={"input": {"audio": "jobs/j1/input/song.flac"}})
|
||||
assert original_audio_gcs_path(job) == "jobs/j1/input/song.flac"
|
||||
|
||||
def test_none_when_no_source(self):
|
||||
assert original_audio_gcs_path(_job()) is None
|
||||
|
||||
|
||||
class TestOutputFilename:
|
||||
def test_flacfetch_flac(self):
|
||||
job = _job(audio_source_type="audio_search",
|
||||
input_media_gcs_path="jobs/j1/input/track.flac")
|
||||
assert original_audio_output_filename(job, "Artist - Title") == "Artist - Title (flacfetch).flac"
|
||||
|
||||
def test_uploaded_mp3(self):
|
||||
job = _job(audio_source_type="file_upload",
|
||||
input_media_gcs_path="jobs/j1/input/My Song.mp3")
|
||||
assert original_audio_output_filename(job, "Artist - Title") == "Artist - Title (uploaded).mp3"
|
||||
|
||||
def test_none_when_no_audio(self):
|
||||
assert original_audio_output_filename(_job(), "Artist - Title") is None
|
||||
@@ -1,124 +0,0 @@
|
||||
"""Tests for proactive auto-correct: the service-side worker + the lyrics-worker trigger.
|
||||
|
||||
The work runs on the API service (process_proactive_auto_correct); the lyrics
|
||||
worker only fires an HTTP trigger. Both must be best-effort: gated by a flag,
|
||||
never raise, never block, and use the multi-model default settings that line up
|
||||
with the review UI's request.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
from backend.workers.lyrics_worker import _trigger_proactive_auto_correct
|
||||
|
||||
|
||||
CORRECTIONS = {
|
||||
"corrected_segments": [
|
||||
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
|
||||
],
|
||||
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
|
||||
}
|
||||
|
||||
|
||||
def _settings(enabled: bool):
|
||||
return SimpleNamespace(auto_correct_proactive_enabled=enabled)
|
||||
|
||||
|
||||
def _patch(enabled=True, corrections=CORRECTIONS, exists=True, service=None, job=None):
|
||||
"""Patch the dependencies process_proactive_auto_correct imports lazily."""
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = exists
|
||||
storage.download_json.return_value = corrections
|
||||
jm = MagicMock()
|
||||
jm.return_value.get_job.return_value = job or SimpleNamespace(artist="A", title="T")
|
||||
return (
|
||||
patch("backend.config.get_settings", return_value=_settings(enabled)),
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage),
|
||||
patch("backend.services.job_manager.JobManager", jm),
|
||||
patch("backend.services.auto_correct.get_auto_correct_service",
|
||||
return_value=service or MagicMock()),
|
||||
storage,
|
||||
)
|
||||
|
||||
|
||||
# ---- service-side worker ----
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_flag_short_circuits() -> None:
|
||||
p_set, p_st, p_jm, p_svc, storage = _patch(enabled=False)
|
||||
with p_set, p_st, p_jm, p_svc:
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result == {"status": "disabled"}
|
||||
storage.file_exists.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_no_references() -> None:
|
||||
corr = {"corrected_segments": [{"id": "s", "words": []}], "reference_lyrics": {}}
|
||||
p_set, p_st, p_jm, p_svc, storage = _patch(corrections=corr)
|
||||
svc = MagicMock()
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result["status"] == "skipped"
|
||||
svc.suggest.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_no_corrections_file() -> None:
|
||||
p_set, p_st, p_jm, p_svc, storage = _patch(exists=False)
|
||||
with p_set, p_st, p_jm, p_svc:
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result["status"] == "skipped"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_happy_path_runs_multi_model_and_caches() -> None:
|
||||
svc = MagicMock()
|
||||
svc.suggest.return_value = SimpleNamespace(
|
||||
suggestions=[1, 2], model="claude-fable-5, gemini-3.1-pro-preview",
|
||||
elapsed_seconds=12.3,
|
||||
)
|
||||
p_set, p_st, p_jm, _p_svc, storage = _patch(service=svc)
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-1")
|
||||
assert result == {"status": "generated", "suggestions": 2}
|
||||
kwargs = svc.suggest.call_args.kwargs
|
||||
assert kwargs["job_id"] == "job-1"
|
||||
assert kwargs["settings"].compare_models is True
|
||||
assert kwargs["artist"] == "A"
|
||||
assert kwargs["segments"] == CORRECTIONS["corrected_segments"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_swallows_service_errors() -> None:
|
||||
svc = MagicMock()
|
||||
svc.suggest.side_effect = RuntimeError("anthropic down / out of credits")
|
||||
p_set, p_st, p_jm, _p_svc, storage = _patch(service=svc)
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-1") # must not raise
|
||||
assert result["status"] == "error"
|
||||
|
||||
|
||||
# ---- lyrics-worker trigger ----
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lyrics_worker_fires_trigger() -> None:
|
||||
ws = MagicMock()
|
||||
ws.trigger_auto_correct = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.WorkerService", return_value=ws):
|
||||
await _trigger_proactive_auto_correct("job-1", MagicMock())
|
||||
ws.trigger_auto_correct.assert_awaited_once_with("job-1")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lyrics_worker_trigger_swallows_errors() -> None:
|
||||
ws = MagicMock()
|
||||
ws.trigger_auto_correct = AsyncMock(side_effect=RuntimeError("network down"))
|
||||
job_log = MagicMock()
|
||||
with patch("backend.services.worker_service.WorkerService", return_value=ws):
|
||||
await _trigger_proactive_auto_correct("job-1", job_log) # must not raise
|
||||
job_log.warning.assert_called()
|
||||
@@ -365,44 +365,6 @@ class TestCompleteReviewZeroSegmentValidation:
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_existing_instrumental_defaults_selection_to_custom(self, _patched_client):
|
||||
"""Jobs that supplied their own instrumental (tenant/existing_instrumental flow)
|
||||
have no instrumental-selection UI step, so complete-review must default the
|
||||
selection to 'custom' — otherwise the render defaults to 'clean' (a separated
|
||||
stem that was never produced) and fails the prerequisite check."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
|
||||
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"job-zero-seg", "instrumental_selection", "custom"
|
||||
)
|
||||
|
||||
def test_existing_instrumental_does_not_override_explicit_selection(self, _patched_client):
|
||||
"""An explicit instrumental_selection in the request still wins over the default."""
|
||||
client, mock_jm = _patched_client
|
||||
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
|
||||
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/job-zero-seg/complete-review",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
json={"instrumental_selection": "clean"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"job-zero-seg", "instrumental_selection", "clean"
|
||||
)
|
||||
|
||||
|
||||
class TestPreviewStyleLoading:
|
||||
"""Tests for the unified style loader used in preview video generation.
|
||||
|
||||
@@ -545,57 +545,6 @@ class TestCreateJobFromSearch:
|
||||
assert job_create.artist == "Abba (Display)"
|
||||
assert job_create.title == "Waterloo (Karaoke)"
|
||||
|
||||
def test_corrected_artist_title_wins_over_session_query(self, create_from_search_client, auth_headers):
|
||||
"""Regression: when the user clicks "Use official formatting", the corrected
|
||||
artist/title sent in the request body must win over the original (raw) search
|
||||
query stored in the session. Previously the job was named with the raw query,
|
||||
so the official formatting selection was silently ignored."""
|
||||
# Session was created from the raw lowercase query the user typed...
|
||||
raw_session = _make_search_session(user_email="test@example.com")
|
||||
raw_session["artist"] = "hard-fi"
|
||||
raw_session["title"] = "hard to beat"
|
||||
create_from_search_client._mock_firestore.get_search_session.return_value = raw_session
|
||||
create_from_search_client._mock_firestore.consume_search_session.return_value = raw_session
|
||||
|
||||
# ...then the user picked the official formatting, so the frontend sends the
|
||||
# corrected artist/title (no separate display override).
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "Hard-Fi",
|
||||
"title": "Hard to Beat",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0]
|
||||
assert job_create.artist == "Hard-Fi"
|
||||
assert job_create.title == "Hard to Beat"
|
||||
# The original query is still preserved for audio-search matching metadata.
|
||||
assert job_create.audio_search_artist == "hard-fi"
|
||||
assert job_create.audio_search_title == "hard to beat"
|
||||
|
||||
def test_blank_body_artist_title_falls_back_to_session_query(self, create_from_search_client, auth_headers):
|
||||
"""Whitespace-only artist/title in the body must not become the job name —
|
||||
fall back to the stored search query instead."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": " ",
|
||||
"title": "\t",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0]
|
||||
# Session stores "ABBA" / "Waterloo" (see _make_search_session).
|
||||
assert job_create.artist == "ABBA"
|
||||
assert job_create.title == "Waterloo"
|
||||
|
||||
def test_session_consumed_atomically(self, create_from_search_client, auth_headers):
|
||||
"""Session is consumed (atomically read+deleted) via consume_search_session."""
|
||||
create_from_search_client.post(
|
||||
|
||||
@@ -38,36 +38,9 @@ class TestStorageServiceInit:
|
||||
assert service.bucket == mock_bucket
|
||||
|
||||
|
||||
class TestStorageServiceCopy:
|
||||
"""Test server-side copy (used to stage the tenant instrumental for the GCE encoder)."""
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_copy_blob(self, mock_settings, mock_client_class):
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_src_blob = Mock()
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_src_blob
|
||||
mock_client = Mock()
|
||||
mock_client.bucket.return_value = mock_bucket
|
||||
mock_client_class.return_value = mock_client
|
||||
|
||||
service = StorageService()
|
||||
result = service.copy_blob(
|
||||
"uploads/job123/audio/existing_instrumental.mp3",
|
||||
"jobs/job123/existing_instrumental.mp3",
|
||||
)
|
||||
|
||||
mock_bucket.blob.assert_called_once_with("uploads/job123/audio/existing_instrumental.mp3")
|
||||
mock_bucket.copy_blob.assert_called_once_with(
|
||||
mock_src_blob, mock_bucket, "jobs/job123/existing_instrumental.mp3"
|
||||
)
|
||||
assert result == "jobs/job123/existing_instrumental.mp3"
|
||||
|
||||
|
||||
class TestStorageServiceUpload:
|
||||
"""Test upload operations."""
|
||||
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_upload_file(self, mock_settings, mock_client_class):
|
||||
|
||||
@@ -56,43 +56,6 @@ def _make_job_mock(**kwargs):
|
||||
return job
|
||||
|
||||
|
||||
class TestSelectMixedAudioFiles:
|
||||
"""Regression tests for _select_mixed_audio_files() in file_upload.py.
|
||||
|
||||
The existing-instrumental file shares the uploads/{job}/audio/ directory with the
|
||||
mixed audio, so the 'audio/' prefix matches both. Before the fix, files[0] resolved to
|
||||
'existing_instrumental.mp3' (it sorts first) and transcription ran on the instrumental.
|
||||
"""
|
||||
|
||||
def _fn(self):
|
||||
from backend.api.routes.file_upload import _select_mixed_audio_files
|
||||
return _select_mixed_audio_files
|
||||
|
||||
def test_excludes_existing_instrumental(self):
|
||||
fn = self._fn()
|
||||
# Listing is sorted alphabetically by GCS, so the instrumental comes first.
|
||||
files = [
|
||||
"uploads/job123/audio/existing_instrumental.mp3",
|
||||
"uploads/job123/audio/mixed.mp3",
|
||||
]
|
||||
result = fn(files)
|
||||
assert result == ["uploads/job123/audio/mixed.mp3"]
|
||||
assert result[0] == "uploads/job123/audio/mixed.mp3"
|
||||
|
||||
def test_plain_audio_only_unchanged(self):
|
||||
fn = self._fn()
|
||||
files = ["uploads/job123/audio/My Song.flac"]
|
||||
assert fn(files) == files
|
||||
|
||||
def test_real_filenames_with_instrumental(self):
|
||||
fn = self._fn()
|
||||
files = [
|
||||
"uploads/job123/audio/existing_instrumental.mp3",
|
||||
"uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3",
|
||||
]
|
||||
assert fn(files) == ["uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3"]
|
||||
|
||||
|
||||
class TestApplyTenantOverrides:
|
||||
"""Tests for _apply_tenant_overrides() in file_upload.py."""
|
||||
|
||||
@@ -162,70 +125,24 @@ class TestApplyTenantOverrides:
|
||||
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert yt_upload is False
|
||||
|
||||
def test_tenant_config_overrides_global_defaults(self):
|
||||
"""Tenant config is authoritative: it overrides any global/consumer default
|
||||
distribution settings already seeded into `dist`.
|
||||
|
||||
Regression guard: prod sets DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID /
|
||||
DEFAULT_BRAND_PREFIX globally, which get_effective_distribution_settings seeds
|
||||
into `dist`. If tenant overrides only filled in *unset* fields, every tenant job
|
||||
would leak into the shared consumer Dropbox folder and global Google Drive.
|
||||
"""
|
||||
def test_request_values_take_precedence(self):
|
||||
"""Explicit request-level values are not overridden by tenant defaults."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
# `dist` arrives pre-seeded with the GLOBAL consumer defaults.
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized", # global default
|
||||
gdrive_folder_id="global-consumer-folder", # global default
|
||||
dropbox_path="/Custom/Path",
|
||||
gdrive_folder_id="custom-folder",
|
||||
discord_webhook_url=None,
|
||||
brand_prefix="NOMAD", # global default
|
||||
brand_prefix="CUSTOM",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
# Tenant config wins on every distribution field.
|
||||
assert new_dist.brand_prefix == "VSTAR"
|
||||
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
|
||||
|
||||
def test_gdrive_disabled_clears_global_default(self):
|
||||
"""When the tenant disables gdrive_upload, the global default GDrive folder is
|
||||
cleared so the tenant job never publishes to Google Drive (the B2B requirement)."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
# Tenant has a gdrive folder configured but the feature is OFF — the disabled
|
||||
# flag must win, clearing both the configured folder and any global default.
|
||||
tenant_config = _make_tenant_config()
|
||||
tenant_config.features.gdrive_upload = False
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None,
|
||||
gdrive_folder_id="global-consumer-folder", # would otherwise leak
|
||||
discord_webhook_url=None,
|
||||
brand_prefix=None,
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.gdrive_folder_id is None
|
||||
assert yt_upload is False
|
||||
|
||||
def test_dropbox_disabled_clears_path(self):
|
||||
"""When the tenant disables dropbox_upload, the Dropbox path is cleared."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
tenant_config.features.dropbox_upload = False
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized",
|
||||
gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.dropbox_path is None
|
||||
assert new_dist.brand_prefix == "CUSTOM"
|
||||
assert new_dist.dropbox_path == "/Custom/Path"
|
||||
assert new_dist.gdrive_folder_id == "custom-folder"
|
||||
|
||||
def test_no_tenant_config_passthrough(self):
|
||||
"""When no tenant config, all values pass through unchanged."""
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
"""Test that _upload_results registers the standalone screen MOVs in file_urls.
|
||||
|
||||
This makes (Title).mov / (End).mov appear in the admin files manifest and verifiable
|
||||
by the daily E2E. Regression: the screen MOVs were absent from Dropbox track folders.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers.video_worker import _upload_results
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_results_registers_screen_movs():
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Create local files the orchestrator would have downloaded into output_dir
|
||||
title_mov = os.path.join(temp_dir, "Artist - Title (Title).mov")
|
||||
end_mov = os.path.join(temp_dir, "Artist - Title (End).mov")
|
||||
lossless = os.path.join(temp_dir, "Artist - Title (Final Karaoke Lossless 4k).mp4")
|
||||
for p in (title_mov, end_mov, lossless):
|
||||
with open(p, "wb") as f:
|
||||
f.write(b"x")
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
job_manager = MagicMock()
|
||||
storage = MagicMock()
|
||||
storage.upload_file.side_effect = lambda local, gcs: f"gs://bucket/{gcs}"
|
||||
|
||||
result = {
|
||||
"final_video": lossless,
|
||||
"title_mov": title_mov,
|
||||
"end_mov": end_mov,
|
||||
}
|
||||
|
||||
await _upload_results("job-1", job_manager, storage, temp_dir, result)
|
||||
|
||||
# The screen MOVs are uploaded under finals/ and recorded in file_urls
|
||||
registered = {
|
||||
(c.args[1], c.args[2]) for c in job_manager.update_file_url.call_args_list
|
||||
}
|
||||
assert ("finals", "title_mov") in registered
|
||||
assert ("finals", "end_mov") in registered
|
||||
|
||||
uploaded_gcs = {c.args[1] for c in storage.upload_file.call_args_list}
|
||||
assert "jobs/job-1/finals/title_mov.mov" in uploaded_gcs
|
||||
assert "jobs/job-1/finals/end_mov.mov" in uploaded_gcs
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_results_skips_missing_screen_movs():
|
||||
"""Jobs without screen MOVs (legacy/None) must not error or register them."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lossless = os.path.join(temp_dir, "Artist - Title (Final Karaoke Lossless 4k).mp4")
|
||||
with open(lossless, "wb") as f:
|
||||
f.write(b"x")
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
job_manager = MagicMock()
|
||||
storage = MagicMock()
|
||||
storage.upload_file.side_effect = lambda local, gcs: f"gs://bucket/{gcs}"
|
||||
|
||||
result = {"final_video": lossless, "title_mov": None} # end_mov absent entirely
|
||||
|
||||
await _upload_results("job-1", job_manager, storage, temp_dir, result)
|
||||
|
||||
registered = {
|
||||
(c.args[1], c.args[2]) for c in job_manager.update_file_url.call_args_list
|
||||
}
|
||||
assert ("finals", "title_mov") not in registered
|
||||
assert ("finals", "end_mov") not in registered
|
||||
@@ -1058,52 +1058,6 @@ class TestVideoWorkerOrchestratorEncoding:
|
||||
with pytest.raises(RuntimeError, match="stale"):
|
||||
await orchestrator._download_gce_encoded_files(output)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_gce_includes_screen_movs(self):
|
||||
"""Screen MOVs returned by the encoder are downloaded into output_dir.
|
||||
|
||||
Regression: the standalone (Title).mov / (End).mov stopped reaching the
|
||||
Dropbox folder after #647/#650. They must be pulled back like other finals.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path=os.path.join(temp_dir, "title.png"),
|
||||
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
|
||||
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
|
||||
output_dir=temp_dir,
|
||||
)
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.download_file = MagicMock()
|
||||
|
||||
orchestrator = VideoWorkerOrchestrator(config, storage=mock_storage)
|
||||
|
||||
from backend.services.encoding_interface import EncodingOutput
|
||||
output = EncodingOutput(
|
||||
success=True,
|
||||
lossless_4k_mp4_path="jobs/test-job/finals/Test Artist - Test Title (Final Karaoke Lossless 4k).mp4",
|
||||
title_mov_path="jobs/test-job/finals/Test Artist - Test Title (Title).mov",
|
||||
end_mov_path="jobs/test-job/finals/Test Artist - Test Title (End).mov",
|
||||
encoding_time_seconds=0.0,
|
||||
encoding_backend="gce",
|
||||
)
|
||||
|
||||
await orchestrator._download_gce_encoded_files(output)
|
||||
|
||||
downloaded = {os.path.basename(c.args[0]) for c in mock_storage.download_file.call_args_list}
|
||||
assert "Test Artist - Test Title (Title).mov" in downloaded
|
||||
assert "Test Artist - Test Title (End).mov" in downloaded
|
||||
# Result points the screen MOVs at their local copies in output_dir
|
||||
assert orchestrator.result.title_mov == os.path.join(
|
||||
temp_dir, "Test Artist - Test Title (Title).mov"
|
||||
)
|
||||
assert orchestrator.result.end_mov == os.path.join(
|
||||
temp_dir, "Test Artist - Test Title (End).mov"
|
||||
)
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorOrganization:
|
||||
"""Test organization stage."""
|
||||
@@ -1451,36 +1405,6 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
|
||||
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental User).mp3"
|
||||
|
||||
def test_create_config_includes_original_audio(self):
|
||||
"""Config carries the original input audio so it can be staged into the
|
||||
Dropbox folder. Regression: source audio stopped reaching organised outputs.
|
||||
"""
|
||||
job = MagicMock()
|
||||
job.job_id = "test-123"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
job.state_data = {"instrumental_selection": "clean"}
|
||||
job.enable_cdg = False
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = False
|
||||
job.is_private = False
|
||||
job.brand_prefix = "NOMAD"
|
||||
job.discord_webhook_url = None
|
||||
job.youtube_description_template = None
|
||||
job.dropbox_path = "/Karaoke"
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
|
||||
# flacfetch (audio_search) download
|
||||
job.audio_source_type = "audio_search"
|
||||
job.input_media_gcs_path = "jobs/test-123/input/track.flac"
|
||||
|
||||
config = create_orchestrator_config_from_job(job=job, temp_dir="/tmp/test")
|
||||
|
||||
assert config.original_audio_gcs_path == "jobs/test-123/input/track.flac"
|
||||
assert config.original_audio_filename == "Test Artist - Test Title (flacfetch).flac"
|
||||
|
||||
def test_create_config_passes_instrumental_selection(self):
|
||||
"""Test that instrumental_selection is passed through to OrchestratorConfig.
|
||||
|
||||
@@ -1979,73 +1903,3 @@ class TestLrcHasLyricsContent:
|
||||
lrc_file.write_text("[ti:Song Title]\n[ar:Artist Name]\n[re:MidiCo]\n")
|
||||
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
|
||||
assert orchestrator._lrc_has_lyrics_content() is False
|
||||
|
||||
|
||||
class TestStageOriginalAudio:
|
||||
"""Original input audio is staged into output_dir before folder uploads.
|
||||
|
||||
Regression: the source audio ((flacfetch).flac / (uploaded).mp3) stopped
|
||||
appearing in the Dropbox track folder after the move to the distributed
|
||||
pipeline. It must be fetched from GCS into output_dir before upload.
|
||||
"""
|
||||
|
||||
def _make(self, temp_dir, **overrides):
|
||||
cfg = dict(
|
||||
job_id="job-1",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path=os.path.join(temp_dir, "title.png"),
|
||||
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
|
||||
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
|
||||
output_dir=temp_dir,
|
||||
)
|
||||
cfg.update(overrides)
|
||||
config = OrchestratorConfig(**cfg)
|
||||
storage = MagicMock()
|
||||
return VideoWorkerOrchestrator(config, storage=storage), storage
|
||||
|
||||
def test_downloads_original_audio_into_output_dir(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orch, storage = self._make(
|
||||
temp_dir,
|
||||
original_audio_gcs_path="jobs/job-1/input/track.flac",
|
||||
original_audio_filename="Test Artist - Test Title (flacfetch).flac",
|
||||
)
|
||||
orch._stage_original_audio_for_upload()
|
||||
|
||||
storage.download_file.assert_called_once()
|
||||
args = storage.download_file.call_args.args
|
||||
assert args[0] == "jobs/job-1/input/track.flac"
|
||||
assert args[1] == os.path.join(temp_dir, "Test Artist - Test Title (flacfetch).flac")
|
||||
|
||||
def test_noop_when_no_original_audio_configured(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orch, storage = self._make(temp_dir)
|
||||
orch._stage_original_audio_for_upload()
|
||||
storage.download_file.assert_not_called()
|
||||
|
||||
def test_skips_when_already_present(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
fname = "Test Artist - Test Title (uploaded).mp3"
|
||||
# File already in output_dir (e.g. legacy/local run)
|
||||
with open(os.path.join(temp_dir, fname), "wb") as f:
|
||||
f.write(b"existing")
|
||||
orch, storage = self._make(
|
||||
temp_dir,
|
||||
original_audio_gcs_path="jobs/job-1/input/song.mp3",
|
||||
original_audio_filename=fname,
|
||||
)
|
||||
orch._stage_original_audio_for_upload()
|
||||
storage.download_file.assert_not_called()
|
||||
|
||||
def test_download_failure_is_non_fatal(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orch, storage = self._make(
|
||||
temp_dir,
|
||||
original_audio_gcs_path="jobs/job-1/input/track.flac",
|
||||
original_audio_filename="Test Artist - Test Title (flacfetch).flac",
|
||||
)
|
||||
storage.download_file.side_effect = Exception("gcs boom")
|
||||
# Must not raise
|
||||
orch._stage_original_audio_for_upload()
|
||||
assert any("Original audio" in w for w in orch.result.distribution_warnings)
|
||||
@@ -232,10 +232,6 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': filename,
|
||||
})
|
||||
# Record the original input audio in file_urls too (the upload path does this
|
||||
# in audio_worker), so it appears in the admin files manifest consistently
|
||||
# across all source types and can be staged into the output folder.
|
||||
job_manager.update_file_url(job_id, 'input', 'audio', audio_gcs_path)
|
||||
|
||||
# Download succeeded — clear any stale retry-pending marker and
|
||||
# previous error so the UI stops showing a resolved failure.
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
"""Proactive auto-correct generation, run on the API service.
|
||||
|
||||
The lyrics worker (a Cloud Run Job) triggers this via the internal endpoint
|
||||
once transcription + references are ready. It runs HERE — on the API service —
|
||||
rather than in the lyrics job, because the service already has a working
|
||||
ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS configuration (the lyrics job's
|
||||
secrets use Cloud Run secret aliases that `gcloud run jobs update
|
||||
--update-secrets` can't extend; see docs/archive/2026-06-11-proactive-autocorrect-plan.md).
|
||||
|
||||
Pre-generates + caches the multi-model suggestion run so the review UI's
|
||||
on-load request is an instant cache hit. Best-effort: it must never raise — a
|
||||
failure just means the UI does the call on demand instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def process_proactive_auto_correct(job_id: str) -> dict:
|
||||
"""Generate + cache auto-correct suggestions for a job. Never raises.
|
||||
|
||||
Returns a small status dict for the endpoint to echo. Gated by
|
||||
settings.auto_correct_proactive_enabled; reads the corrections.json the
|
||||
lyrics worker just wrote (the same data the review UI loads on first open)
|
||||
and runs the multi-model path with default settings so the cache key lines
|
||||
up with the UI request.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.auto_correct_proactive_enabled:
|
||||
return {"status": "disabled"}
|
||||
|
||||
try:
|
||||
from backend.services.auto_correct import get_auto_correct_service
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
storage = StorageService()
|
||||
corrections_path = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
if not storage.file_exists(corrections_path):
|
||||
logger.info("[job:%s] proactive auto-correct skipped: no corrections.json", job_id)
|
||||
return {"status": "skipped", "reason": "no_corrections"}
|
||||
data = storage.download_json(corrections_path)
|
||||
segments = data.get("corrected_segments") or data.get("segments") or []
|
||||
reference_lyrics = data.get("reference_lyrics") or {}
|
||||
if not segments or not reference_lyrics:
|
||||
# No references → nothing to compare against. The reviewer can paste
|
||||
# references in the UI and trigger auto-correct manually later.
|
||||
logger.info(
|
||||
"[job:%s] proactive auto-correct skipped: %d segments, %d ref sources",
|
||||
job_id, len(segments), len(reference_lyrics),
|
||||
)
|
||||
return {"status": "skipped", "reason": "no_references"}
|
||||
|
||||
job = JobManager().get_job(job_id)
|
||||
service = get_auto_correct_service()
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=getattr(job, "artist", None) if job else None,
|
||||
title=getattr(job, "title", None) if job else None,
|
||||
# Must match what the review UI sends (default settings,
|
||||
# multi-model) or the cache key won't line up.
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
),
|
||||
timeout=180,
|
||||
)
|
||||
logger.info(
|
||||
"[job:%s] proactive auto-correct done: %d suggestions cached (models=%s, %.1fs)",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
return {"status": "generated", "suggestions": len(result.suggestions)}
|
||||
except Exception as e: # noqa: BLE001 — proactive is best-effort, never fatal
|
||||
logger.warning("[job:%s] proactive auto-correct failed (non-fatal): %s", job_id, e, exc_info=True)
|
||||
return {"status": "error", "message": str(e)}
|
||||
@@ -1,260 +0,0 @@
|
||||
"""Bulk Mode search worker.
|
||||
|
||||
Processes every job in a batch (state_data.batch_id == batch_id): runs the audio
|
||||
search, auto-selects a confident lossless ("tier 1") match when the batch enabled
|
||||
it, and otherwise parks the job in AWAITING_AUDIO_SELECTION for the review queue.
|
||||
|
||||
Runs as a Cloud Run Job (one execution per batch) so it survives API instance
|
||||
scale-down and the user can close the tab. Mirrors the single-job search flow in
|
||||
backend/api/routes/audio_search.py:search_audio.
|
||||
|
||||
Usage:
|
||||
python -m backend.workers.bulk_search_worker --batch-id <batch_id>
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.audio_search_service import (
|
||||
AudioSearchError,
|
||||
AudioSearchService,
|
||||
NoResultsError,
|
||||
pick_auto_selection,
|
||||
)
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# How many per-song searches to run concurrently within a batch.
|
||||
SEARCH_CONCURRENCY = 4
|
||||
|
||||
|
||||
def _prepare_theme(job, job_manager: JobManager) -> None:
|
||||
"""Best-effort: copy the job's theme style into its folder (mirrors search_audio)."""
|
||||
theme_id = getattr(job, "theme_id", None)
|
||||
if not theme_id:
|
||||
return
|
||||
try:
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
|
||||
color_overrides = getattr(job, "color_overrides", None) or {}
|
||||
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job.job_id, theme_id, color_overrides
|
||||
)
|
||||
updates = {
|
||||
"style_params_gcs_path": style_params_path,
|
||||
"style_assets": theme_style_assets,
|
||||
}
|
||||
if youtube_desc:
|
||||
updates["youtube_description_template"] = youtube_desc
|
||||
job_manager.update_job(job.job_id, updates)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("[bulk] theme prep failed for job %s: %s", job.job_id, e)
|
||||
|
||||
|
||||
async def _auto_select(job, selection_index: int, selected: dict,
|
||||
job_manager: JobManager) -> bool:
|
||||
"""Charge the duration delta and start the download for an auto-selected job.
|
||||
|
||||
Returns True if the job was successfully auto-selected and the download
|
||||
triggered; False if it should instead be parked for human selection (e.g.
|
||||
track too long, or insufficient credits for the duration delta).
|
||||
|
||||
NOTE (money path): this replicates the duration-delta charge from
|
||||
audio_search.select_audio_source using the SAME primitives and state keys
|
||||
(credits_charged / select_charge_applied) rather than refactoring the proven
|
||||
route. Keep the two in sync; covered by test_bulk_search_worker.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
sd = job.state_data or {}
|
||||
duration = selected.get("duration")
|
||||
|
||||
# Track too long → defer to human (they may pick a different source).
|
||||
if duration is not None and is_blocked(duration):
|
||||
logger.info("[bulk] job %s auto-pick is over 60min; parking for selection", job_id)
|
||||
return False
|
||||
|
||||
if not sd.get("select_charge_applied"):
|
||||
credits_charged = int(sd.get("credits_charged", 1))
|
||||
target_total = duration_to_credits(duration) if duration is not None else credits_charged
|
||||
owed = max(0, target_total - credits_charged)
|
||||
bypass = bool(sd.get("payment_bypassed", False))
|
||||
if owed > 0 and not bypass:
|
||||
user_email = job.user_email
|
||||
if not user_email:
|
||||
return False
|
||||
# Crash-safety: if a previous attempt already marked the charge as
|
||||
# pending, the deduction may have gone through — do NOT deduct again
|
||||
# (bias toward under-charge over double-charge on worker retry).
|
||||
if sd.get("bulk_charge_pending"):
|
||||
logger.warning(
|
||||
"[bulk] job %s had a pending charge from a prior attempt; "
|
||||
"skipping re-deduction to avoid double-charge", job_id
|
||||
)
|
||||
else:
|
||||
job_manager.update_job(job_id, {"state_data.bulk_charge_pending": owed})
|
||||
ok, _, _ = get_user_service().deduct_credits(
|
||||
user_email, job_id, amount=owed, reason="job_creation",
|
||||
count_as_job_creation=False,
|
||||
)
|
||||
if not ok:
|
||||
job_manager.update_job(job_id, {"state_data.bulk_charge_pending": None})
|
||||
logger.info("[bulk] job %s lacks credits for duration delta; parking", job_id)
|
||||
return False
|
||||
update = {
|
||||
"state_data.credits_charged": target_total,
|
||||
"state_data.select_charge_applied": True,
|
||||
"state_data.bulk_charge_pending": None,
|
||||
}
|
||||
if duration is not None:
|
||||
update["state_data.duration_estimate_seconds"] = duration
|
||||
update["state_data.duration_estimate_source"] = "search_metadata"
|
||||
job_manager.update_job(job_id, update)
|
||||
|
||||
# Reuse the proven route helper to validate + transition to DOWNLOADING_AUDIO.
|
||||
from backend.api.routes.audio_search import _validate_and_prepare_selection
|
||||
|
||||
try:
|
||||
_validate_and_prepare_selection(job_id, selection_index)
|
||||
except Exception as e: # noqa: BLE001 (route helper raises HTTPException)
|
||||
logger.warning("[bulk] job %s validate/prepare failed: %s", job_id, e)
|
||||
return False
|
||||
|
||||
return await get_worker_service().trigger_audio_download_worker(job_id)
|
||||
|
||||
|
||||
async def process_job(job_id: str, job_manager: JobManager, audio_search_service) -> None:
|
||||
"""Search one batch job and either auto-select or park it."""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.warning("[bulk] job %s not found", job_id)
|
||||
return
|
||||
|
||||
artist = job.audio_search_artist or job.artist
|
||||
title = job.audio_search_title or job.title
|
||||
sd = job.state_data or {}
|
||||
bulk_settings = sd.get("bulk_settings", {}) or {}
|
||||
auto_enabled = bulk_settings.get("auto_select_if_lossless", True)
|
||||
|
||||
_prepare_theme(job, job_manager)
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.SEARCHING_AUDIO,
|
||||
progress=5,
|
||||
message=f"Searching for: {artist} - {title}",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
try:
|
||||
results = await audio_search_service.search_async(artist, title)
|
||||
except (NoResultsError, AudioSearchError) as e:
|
||||
logger.warning("[bulk] search failed for job %s (%s); parking", job_id, e)
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message="No automatic audio sources found. Please choose a source.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
return
|
||||
|
||||
results_dicts = [r.to_dict() for r in results]
|
||||
store = {"state_data.audio_search_results": results_dicts}
|
||||
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
|
||||
if remote_id:
|
||||
store["state_data.remote_search_id"] = remote_id
|
||||
job_manager.update_job(job_id, store)
|
||||
|
||||
selection_index = pick_auto_selection(results_dicts, title) if auto_enabled else None
|
||||
|
||||
if selection_index is None:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=f"Found {len(results_dicts)} sources. Please choose one.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
return
|
||||
|
||||
auto_ok = await _auto_select(job, selection_index, results_dicts[selection_index], job_manager)
|
||||
if not auto_ok:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=f"Found {len(results_dicts)} sources. Please choose one.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(
|
||||
job_id,
|
||||
{"state_data.bulk_pending_search": False, "state_data.bulk_auto_selected": bool(auto_ok)},
|
||||
)
|
||||
|
||||
|
||||
async def process_batch(batch_id: str) -> int:
|
||||
"""Process all pending-search jobs in a batch. Returns the count processed."""
|
||||
job_manager = JobManager()
|
||||
|
||||
jobs = job_manager.list_jobs_by_batch_id(batch_id)
|
||||
pending = [j for j in jobs if (j.state_data or {}).get("bulk_pending_search")]
|
||||
logger.info("[batch:%s] processing %d/%d jobs needing search", batch_id, len(pending), len(jobs))
|
||||
|
||||
sem = asyncio.Semaphore(SEARCH_CONCURRENCY)
|
||||
|
||||
async def _guarded(job_id: str) -> None:
|
||||
async with sem:
|
||||
# Fresh service per task: last_remote_search_id is instance state and
|
||||
# would be cross-contaminated if shared across concurrent searches.
|
||||
audio_search_service = AudioSearchService()
|
||||
try:
|
||||
await process_job(job_id, job_manager, audio_search_service)
|
||||
except Exception as e: # noqa: BLE001 (one job must not kill the batch)
|
||||
logger.error("[batch:%s] job %s crashed: %s", batch_id, job_id, e, exc_info=True)
|
||||
try:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message="Search error. Please choose a source.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
await asyncio.gather(*[_guarded(j.job_id) for j in pending])
|
||||
return len(pending)
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser(description="Bulk Mode search worker")
|
||||
parser.add_argument("--batch-id", required=True, help="Batch ID to process")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
logger.info("Starting bulk search worker for batch %s", args.batch_id)
|
||||
try:
|
||||
count = asyncio.run(process_batch(args.batch_id))
|
||||
logger.info("Bulk search worker finished batch %s (%d jobs)", args.batch_id, count)
|
||||
sys.exit(0)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error("Bulk search worker crashed: %s", e, exc_info=True)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -170,26 +170,6 @@ def create_lyrics_processor(
|
||||
)
|
||||
|
||||
|
||||
async def _trigger_proactive_auto_correct(job_id, job_log) -> None:
|
||||
"""Trigger proactive auto-correct generation on the API service.
|
||||
|
||||
The actual multi-model LLM call + caching runs on the API service (which
|
||||
has the working Anthropic key / compare-models config) — see
|
||||
backend/workers/auto_correct_worker.py. Here we just fire the HTTP trigger
|
||||
and await it. Best-effort and fully isolated: it must NEVER raise, fail the
|
||||
job, or block the pipeline — downstream stages are already triggered before
|
||||
this runs, and the service gates the work behind AUTO_CORRECT_PROACTIVE_ENABLED.
|
||||
"""
|
||||
try:
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
ok = await WorkerService().trigger_auto_correct(job_id)
|
||||
job_log.info("Proactive auto-correct trigger %s", "ok" if ok else "skipped/failed")
|
||||
except Exception as e: # noqa: BLE001 — never let auto-correct affect the job
|
||||
job_log.warning(f"Proactive auto-correct trigger failed (non-fatal): {e}")
|
||||
logger.warning(f"[job:{job_id}] Proactive auto-correct trigger failed (non-fatal): {e}")
|
||||
|
||||
|
||||
async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
"""
|
||||
Process lyrics transcription and correction for a job using karaoke_gen.LyricsProcessor.
|
||||
@@ -536,15 +516,7 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
# This will check if audio is also complete and transition to next stage if so
|
||||
job_log.info("Lyrics worker complete, checking if audio is also done...")
|
||||
job_manager.mark_lyrics_complete(job_id)
|
||||
|
||||
# Proactively pre-generate + cache AI auto-correct suggestions so
|
||||
# they're ready when the reviewer opens the lyrics UI. The work
|
||||
# runs on the API service (it has the Anthropic key); we just fire
|
||||
# the trigger here. Done AFTER mark_lyrics_complete (downstream is
|
||||
# already triggered, so this never blocks it) and fully isolated —
|
||||
# it can never fail or delay the job beyond its own timeout.
|
||||
await _trigger_proactive_auto_correct(job_id, job_log)
|
||||
|
||||
|
||||
duration = time.time() - start_time
|
||||
# Store worker-level timing
|
||||
job_manager.update_processing_metadata(job_id, "timing.lyrics_worker_seconds", round(duration, 1))
|
||||
|
||||
@@ -107,21 +107,6 @@ async def _encode_via_gce(
|
||||
instrumental_selection = job.state_data.get('instrumental_selection', 'clean')
|
||||
existing_instrumental = getattr(job, 'existing_instrumental_gcs_path', None)
|
||||
|
||||
# Stage the user-provided instrumental into the encoder's input prefix (jobs/{job_id}/).
|
||||
# It is uploaded under uploads/, which the GCE encoder does NOT pull via input_gcs_path;
|
||||
# copying it here makes the encoder's recursive find_file("*existing_instrumental*")
|
||||
# locate it regardless of the worker image version (older encoder images predate the
|
||||
# encoding_config "existing_instrumental" download path). Without this, tenant /
|
||||
# existing-instrumental jobs fail with "No instrumental audio found".
|
||||
if existing_instrumental:
|
||||
try:
|
||||
ext = os.path.splitext(existing_instrumental)[1].lower() or ".mp3"
|
||||
staged_path = f"jobs/{job_id}/existing_instrumental{ext}"
|
||||
storage.copy_blob(existing_instrumental, staged_path)
|
||||
job_log.info(f"Staged existing instrumental for encoder: {staged_path}")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Failed to stage existing instrumental into jobs/ prefix: {e}")
|
||||
|
||||
encoding_config = {
|
||||
"formats": ["mp4_4k_lossless", "mp4_4k_lossy", "mp4_720p"],
|
||||
"base_name": base_name,
|
||||
@@ -359,8 +344,6 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
'final_with_vocals_mp4': result.final_with_vocals_mp4,
|
||||
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
|
||||
'final_karaoke_txt_zip': result.final_karaoke_txt_zip,
|
||||
'title_mov': result.title_mov,
|
||||
'end_mov': result.end_mov,
|
||||
})
|
||||
|
||||
# Store result metadata in job BEFORE transitioning to COMPLETE
|
||||
@@ -1606,10 +1589,6 @@ async def _upload_results(
|
||||
('final_with_vocals_mp4', 'finals', 'with_vocals_mp4'),
|
||||
('final_karaoke_cdg_zip', 'packages', 'cdg_zip'),
|
||||
('final_karaoke_txt_zip', 'packages', 'txt_zip'),
|
||||
# Standalone screen videos — recorded so they appear in the admin files
|
||||
# manifest and are verifiable (regression: missing from Dropbox folders)
|
||||
('title_mov', 'finals', 'title_mov'),
|
||||
('end_mov', 'finals', 'end_mov'),
|
||||
]
|
||||
|
||||
for result_key, category, file_key in file_mappings:
|
||||
|
||||
@@ -28,10 +28,6 @@ from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.tracing import job_span, add_span_event
|
||||
from backend.services.original_audio import (
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
)
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -71,11 +67,6 @@ class OrchestratorConfig:
|
||||
dropbox_path: Optional[str] = None
|
||||
gdrive_folder_id: Optional[str] = None
|
||||
|
||||
# Original input audio to include in the uploaded folder (the archival master,
|
||||
# e.g. "<artist> - <title> (flacfetch).flac"). GCS blob path + target filename.
|
||||
original_audio_gcs_path: Optional[str] = None
|
||||
original_audio_filename: Optional[str] = None
|
||||
|
||||
# Keep existing brand code (for re-processing)
|
||||
keep_brand_code: Optional[str] = None
|
||||
|
||||
@@ -121,11 +112,6 @@ class OrchestratorResult:
|
||||
final_karaoke_cdg_zip: Optional[str] = None
|
||||
final_karaoke_txt_zip: Optional[str] = None
|
||||
|
||||
# Standalone 5-second screen videos (downloaded from GCE finals so they land in
|
||||
# the Dropbox folder). Not used downstream — kept for archival/upload only.
|
||||
title_mov: Optional[str] = None
|
||||
end_mov: Optional[str] = None
|
||||
|
||||
# Organization
|
||||
brand_code: Optional[str] = None
|
||||
|
||||
@@ -466,27 +452,6 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.countdown_padding_seconds:
|
||||
self.job_log.info(f"Countdown padding: {self.config.countdown_padding_seconds}s - instrumental will be padded")
|
||||
|
||||
# The GCE encoder downloads its inputs from input_gcs_path (jobs/{job_id}/) and resolves
|
||||
# the instrumental via find_file. For jobs that supply their own instrumental
|
||||
# (existing_instrumental flow, e.g. tenant submissions), the file lives under
|
||||
# uploads/{job_id}/audio/existing_instrumental.* — which is NOT under jobs/{job_id}/ and
|
||||
# is NOT a name the encoder's 'custom' branch looks for. The encoder's 'custom' branch
|
||||
# globs for "*custom_instrumental*.{flac,mp3}" / "*Instrumental Custom*", so copy the
|
||||
# supplied instrumental into jobs/{job_id}/custom_instrumental.<ext> (server-side, from
|
||||
# the authoritative GCS source — no dependency on local temp files). Without this,
|
||||
# existing-instrumental jobs fail at the encoder with "No instrumental audio found".
|
||||
if encoding_backend.name == "gce" and self.storage:
|
||||
try:
|
||||
srcs = self.storage.list_files(f"uploads/{self.config.job_id}/audio/existing_instrumental")
|
||||
if srcs:
|
||||
src = srcs[0]
|
||||
ext = os.path.splitext(src)[1].lower() or ".mp3"
|
||||
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
|
||||
self.storage.copy_blob(src, dest)
|
||||
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
|
||||
|
||||
# Run encoding
|
||||
with job_span("encoding", self.config.job_id) as span:
|
||||
add_span_event("encoding_started", {"backend": encoding_backend.name})
|
||||
@@ -567,9 +532,6 @@ class VideoWorkerOrchestrator:
|
||||
('lossy_4k_mp4_path', 'final_video_lossy'),
|
||||
('lossy_720p_mp4_path', 'final_video_720p'),
|
||||
('with_vocals_mp4_path', 'final_with_vocals_mp4'),
|
||||
# Standalone screen videos — pulled back so they reach the Dropbox folder
|
||||
('title_mov_path', 'title_mov'),
|
||||
('end_mov_path', 'end_mov'),
|
||||
]
|
||||
|
||||
downloaded_count = 0
|
||||
@@ -640,16 +602,6 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.info("Starting distribution stage")
|
||||
self._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
|
||||
|
||||
# Stage the original input audio into output_dir before any folder upload
|
||||
# (Dropbox/GDrive upload the whole directory). Only worth the GCS fetch when
|
||||
# such an upload will actually happen.
|
||||
will_upload_folder = (
|
||||
(self.config.dropbox_path and self.config.brand_prefix)
|
||||
or self.config.gdrive_folder_id
|
||||
)
|
||||
if will_upload_folder:
|
||||
self._stage_original_audio_for_upload()
|
||||
|
||||
# YouTube upload
|
||||
if self.config.enable_youtube_upload and self.config.youtube_credentials:
|
||||
await self._upload_to_youtube()
|
||||
@@ -786,32 +738,6 @@ class VideoWorkerOrchestrator:
|
||||
f"YouTube upload skipped (quota exceeded) and failed to queue: {e}"
|
||||
)
|
||||
|
||||
def _stage_original_audio_for_upload(self):
|
||||
"""Copy the original input audio into output_dir so uploads include it.
|
||||
|
||||
The source audio (e.g. "<artist> - <title> (flacfetch).flac" /
|
||||
"(uploaded).mp3") is the archival master used for separation/transcription.
|
||||
The distributed pipeline otherwise leaves it in GCS only, so it stopped
|
||||
appearing in the Dropbox track folder. Best-effort: never fail the pipeline.
|
||||
"""
|
||||
gcs_path = self.config.original_audio_gcs_path
|
||||
filename = self.config.original_audio_filename
|
||||
if not gcs_path or not filename:
|
||||
return
|
||||
|
||||
dest = os.path.join(self.config.output_dir, filename)
|
||||
if os.path.exists(dest):
|
||||
self.job_log.info(f"Original audio already present, skipping: {filename}")
|
||||
return
|
||||
|
||||
try:
|
||||
self.job_log.info(f"Staging original audio for upload: {filename}")
|
||||
self.storage.download_file(gcs_path, dest)
|
||||
self.job_log.info(f"Staged original audio: {dest}")
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to stage original audio ({filename}): {e}")
|
||||
self.result.distribution_warnings.append(f"Original audio not included: {e}")
|
||||
|
||||
async def _upload_to_dropbox(self):
|
||||
"""Upload files to Dropbox."""
|
||||
self.job_log.info("Uploading to Dropbox")
|
||||
@@ -1048,10 +974,6 @@ def create_orchestrator_config_from_job(
|
||||
dropbox_path=dist.dropbox_path,
|
||||
gdrive_folder_id=dist.gdrive_folder_id,
|
||||
|
||||
# Original input audio to include in the uploaded folder (archival master)
|
||||
original_audio_gcs_path=original_audio_gcs_path(job),
|
||||
original_audio_filename=original_audio_output_filename(job, base_name),
|
||||
|
||||
# Keep existing brand code
|
||||
keep_brand_code=getattr(job, 'keep_brand_code', None),
|
||||
|
||||
|
||||
+7
-109
@@ -560,29 +560,20 @@ Content-Type: application/json
|
||||
"suggest_adlib_removal": true,
|
||||
"allow_insertions": true,
|
||||
"min_confidence": 0.0,
|
||||
"compare_models": true
|
||||
"compare_models": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
AI correction suggestions for the lyrics review UI. Stateless: one whole-song
|
||||
LLM call per model (Claude models use the Anthropic API via the
|
||||
Opt-in, user-triggered AI correction suggestions for the lyrics review UI.
|
||||
Stateless: one whole-song LLM call per model (default model from
|
||||
`AUTO_CORRECT_MODEL`; Claude models use the Anthropic API via the
|
||||
`anthropic-api-key` secret, Gemini models use Vertex AI) compares the
|
||||
client's current transcription against the reference sources and returns
|
||||
word-id-keyed suggestions. Nothing is applied server-side — the reviewer
|
||||
accepts/rejects each suggestion in the UI and persistence flows through the
|
||||
existing corrections/complete paths.
|
||||
|
||||
The review UI always requests the multi-model path (`compare_models: true`)
|
||||
and auto-runs once on load, so suggestions appear without a click. To make
|
||||
that load instant, suggestions are **proactively pre-generated and cached**
|
||||
once transcription + references are ready: the lyrics worker fires an internal
|
||||
trigger (`POST /api/internal/workers/auto-correct`) that runs the same
|
||||
multi-model generation on the API service (gated by
|
||||
`AUTO_CORRECT_PROACTIVE_ENABLED`; best-effort — it never blocks or fails the
|
||||
karaoke job). Because the proactive run uses the same default settings the UI
|
||||
sends, the on-load request is normally a cache hit with no extra cost.
|
||||
|
||||
With `"compare_models": true`, every model in `AUTO_CORRECT_COMPARE_MODELS`
|
||||
(semicolon-separated) is queried in parallel; identical suggestions are
|
||||
deduplicated with a per-suggestion `consensus` count, and suggestions that
|
||||
@@ -606,28 +597,19 @@ Returns:
|
||||
"reason": "All references read 'chlorine' here",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.95,
|
||||
"models": ["claude-opus-4-8", "gemini-3.1-pro-preview"],
|
||||
"models": ["claude-fable-5", "gemini-3.1-pro-preview"],
|
||||
"consensus": 2,
|
||||
"total_models": 2,
|
||||
"conflict_group": null
|
||||
}
|
||||
],
|
||||
"model": "claude-opus-4-8, gemini-3.1-pro-preview",
|
||||
"model": "claude-fable-5, gemini-3.1-pro-preview",
|
||||
"elapsed_seconds": 27.4,
|
||||
"settings_applied": { "suggest_adlib_removal": true, "allow_insertions": true, "min_confidence": 0.0 },
|
||||
"warnings": [],
|
||||
"cached": false
|
||||
"warnings": []
|
||||
}
|
||||
```
|
||||
|
||||
Results are cached per job in GCS
|
||||
(`jobs/{job_id}/lyrics/auto_correct_cache/{hash}.json`), keyed on the exact
|
||||
input: word ids + texts, reference lyrics texts, settings, and the resolved
|
||||
model list. Re-running on unmodified lyrics returns the previous result with
|
||||
`"cached": true` and incurs no LLM cost; any edit to the lyrics, references,
|
||||
or settings produces a new key and a fresh run. Cache reads/writes are
|
||||
best-effort — storage failures degrade to a normal uncached run.
|
||||
|
||||
`op` is `replace` | `delete` | `insert_after` (for `insert_after`, `word_ids`
|
||||
holds the anchor word). Errors: `422` when no reference lyrics are available,
|
||||
`400` for invalid settings, `502` when the model call fails or returns
|
||||
@@ -831,65 +813,6 @@ Response:
|
||||
|
||||
When `has_community` is true, the frontend shows a dismissible green banner suggesting the user check existing versions before creating a new one.
|
||||
|
||||
#### Match Judge (artist/title formatting + match acceptance)
|
||||
|
||||
```http
|
||||
POST /api/catalog/match-judge
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "paramore",
|
||||
"title": "big man, little dignity",
|
||||
"audio_confidence_tier": 1,
|
||||
"stage": "full"
|
||||
}
|
||||
```
|
||||
|
||||
Decides the official formatting for a typed artist/title and whether it matches a
|
||||
real song. A deterministic normalizer + the catalog run first; a light Vertex
|
||||
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.5-flash`) is consulted
|
||||
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
|
||||
optional) lets the judge tell whether weak audio results hint at a typo. The call
|
||||
never blocks job creation — on timeout/error it returns a `none` verdict. Disable
|
||||
the AI layer with `MATCH_JUDGE_ENABLED=false` (deterministic+catalog still run).
|
||||
|
||||
`stage` (optional, `"fast"` | `"full"`, default `"full"`) supports a two-call
|
||||
pattern the frontend uses to keep the tidy off the critical path:
|
||||
|
||||
- `"fast"` — catalog-only pass (no AI, `audio_confidence_tier` ignored). The
|
||||
client fires this on mount, in parallel with the audio search. Returns a
|
||||
confident catalog verdict when it can, otherwise `needs_ai: true` (a marker
|
||||
telling the client to follow up with a `"full"` call once the tier is known).
|
||||
- `"full"` — the complete pipeline. Runs the AI judge when the catalog isn't
|
||||
confident, **and** when a confident catalog match coincides with a weak audio
|
||||
tier (`>= 3`) — a weak tier means the match may be a junk/typo'd entry, so the
|
||||
AI verifies it and can override.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"kind": "cosmetic",
|
||||
"confident": true,
|
||||
"canonical_artist": "Paramore",
|
||||
"canonical_title": "Big Man, Little Dignity",
|
||||
"alternatives": [],
|
||||
"engine": "catalog",
|
||||
"reason": "formatting differs from catalog",
|
||||
"needs_ai": false
|
||||
}
|
||||
```
|
||||
|
||||
`kind` drives the Step 2 UI: `cosmetic` → silent tidy with a two-way toggle
|
||||
("keep what I typed" ⇄ "use tidied version"); `content` (confident) → applied
|
||||
with a "Corrected … · Undo" toggle, re-searching audio only when the original
|
||||
results were weak; `ambiguous` (or unconfident `content`) → an ask-first "Did you
|
||||
mean?" prompt; `none` → no change. `needs_ai` is only ever `true` on a `"fast"`
|
||||
verdict that couldn't decide; it is always `false` on a `"full"` verdict.
|
||||
|
||||
Until the judge settles, the Step 2 audio-selection buttons are disabled with a
|
||||
subtle "Checking song details…" indicator, so a user can never advance with
|
||||
un-tidied metadata; a 12s timeout guarantees the gate releases.
|
||||
|
||||
### Audio Search
|
||||
|
||||
#### Search for Audio
|
||||
@@ -2270,31 +2193,6 @@ Referred users with an active discount window (default 30 days) automatically re
|
||||
|
||||
After a credit purchase by a referred user, earnings are recorded automatically in the Stripe webhook handler. When a referrer's pending balance reaches $20 and they have a Stripe Connect account, a payout is triggered automatically.
|
||||
|
||||
## Bulk Mode
|
||||
|
||||
Submit up to 100 karaoke jobs at once (by text rows or by album lookup). All
|
||||
routes require auth.
|
||||
|
||||
### Album lookup (MusicBrainz)
|
||||
|
||||
- `GET /api/bulk/album/artists?q=<name>` → `[{mbid,name,disambiguation,type,country}]`
|
||||
- `GET /api/bulk/album/albums?artist_mbid=<mbid>` → `[{release_group_mbid,title,primary_type,secondary_types,first_release_date,is_studio}]` (studio albums first)
|
||||
- `GET /api/bulk/album/tracklist?artist=<name>&release_group_mbid=<mbid>` (or `&release_mbid=<mbid>` for a specific edition) → `{release_mbid,canonical_release_mbid,title,date,tracks:[{position,title,recording_mbid,length_ms,is_extra,extra_reason,available,brands}],editions:[{release_mbid,title,status,date,country,track_count}]}`. Each track is enriched with KaraokeNerds community-version availability (`available`/`brands`); enrichment is best-effort and never fatal.
|
||||
|
||||
### Availability (text mode)
|
||||
|
||||
- `POST /api/bulk/availability` body `{tracks:[{artist,title}]}` (≤100) → `{results:[{artist,title,available,brands,brand_count}]}`. Backed by the existing KaraokeNerds community-version scraper (1h cache, bounded concurrency).
|
||||
|
||||
### Submit
|
||||
|
||||
- `POST /api/bulk/submit` body `{songs:[{artist,title,display_artist?,display_title?}],settings:{auto_select_if_lossless,is_private,skip_audio_edit,skip_customization}}` → `{batch_id,job_ids,total}`.
|
||||
- Credit gate: requires `credits >= len(songs)` (1/song minimum) before any job is created; admins bypass. Returns `402` with `{credits_available,credits_required}` if short (no jobs created). `422` for 0 or >100 songs.
|
||||
- Creates one parked job per song (`auto_download=False`), stamps `state_data.batch_id` + `bulk_settings`, and dispatches the `bulk-search-job` Cloud Run Job which runs each search and either auto-selects a confident lossless match or parks the job in `AWAITING_AUDIO_SELECTION`.
|
||||
|
||||
### Progress
|
||||
|
||||
- `GET /api/bulk/{batch_id}` → `{batch_id,total,counts:{searching,awaiting_selection,processing,complete,failed},jobs:[{job_id,artist,title,status,auto_selected}]}`. Ownership-scoped (admins see any); `404` for another user's batch. Parked jobs are completed via the existing `/api/audio-search/{job_id}/select` flow.
|
||||
|
||||
## Webhooks
|
||||
|
||||
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Disaster Recovery Runbook
|
||||
|
||||
**Last updated:** 2026-06-18
|
||||
**Last updated:** 2026-04-20
|
||||
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
|
||||
**Implementation plan:** `docs/archive/2026-03-29-business-continuity-plan.md`
|
||||
**External services reference:** `docs/archive/2026-03-29-external-services-config.md`
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
| Data | Backup Location | Recovery Method | RPO |
|
||||
|------|----------------|-----------------|-----|
|
||||
| Firestore | S3 `firestore/YYYY-MM-DD/` | Import to new GCP project | 7 days off-site (S3); 24h local (GCS staging) |
|
||||
| Firestore | S3 `firestore/YYYY-MM-DD/` | Import to new GCP project | 24h |
|
||||
| BigQuery (weekly) | S3 `bigquery/daily-refresh/` | Load Parquet files | 7 days |
|
||||
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
|
||||
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
|
||||
@@ -343,15 +343,6 @@ export AWS_DEFAULT_REGION=us-east-1
|
||||
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, and `bigquery/daily-refresh/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
|
||||
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
|
||||
|
||||
| Prefix | S3 upload cadence | Monitor limit |
|
||||
|--------|-------------------|---------------|
|
||||
| `gcs/job-files/`, `secrets/` | nightly | 36h |
|
||||
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
|
||||
|
||||
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
|
||||
|
||||
This monitor runs in GitHub, not GCP, so it survives a complete GCP project loss.
|
||||
|
||||
**Required GitHub secrets** (set via `gh secret set`):
|
||||
|
||||
@@ -6,26 +6,6 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## Bulk Mode (Jun 2026)
|
||||
|
||||
- **Auto-pick "tier 1" rule is duplicated** between `frontend/lib/audio-search-utils.ts`
|
||||
(`getSearchConfidence`) and `backend/services/audio_search_service.py`
|
||||
(`pick_auto_selection`). The backend port drives the `bulk_search_worker`
|
||||
auto-select decision. If you change the rule, change BOTH — the parity is guarded
|
||||
by `backend/tests/test_bulk_foundations.py`.
|
||||
- **The duration-delta charge is replicated** in `bulk_search_worker._auto_select`
|
||||
using the same primitives/state keys (`credits_charged`/`select_charge_applied`)
|
||||
as `audio_search.select_audio_source`, rather than refactoring the proven money
|
||||
path. Keep them in sync.
|
||||
- **KaraokeNerds availability** reuses the existing `karaokenerds_service`
|
||||
scraper via `check_community_versions_batch` (it has the `is_community` flag,
|
||||
matching "community-*created* version"). We deliberately did NOT add a
|
||||
karaoke-decide BigQuery endpoint — its catalog is search-based and lacks the
|
||||
community distinction.
|
||||
- **Parked bulk jobs are hidden from the main jobs list** (the dashboard filters
|
||||
out `awaiting_audio_selection`). The bulk review queue renders them itself, and
|
||||
the batch_id is persisted to `localStorage` so a returning user can finish them.
|
||||
|
||||
## AI Generation Patterns
|
||||
|
||||
### Auto-Correction Take 3: Suggestion Layer, Not Silent Application (Jun 2026)
|
||||
@@ -92,13 +72,6 @@ When a metadata key is missing, don't set it to "now" and skip the action — th
|
||||
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
|
||||
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
|
||||
|
||||
### "Is It Busy?" Guards Must Fail SAFE, Not Fail Open (Jun 2026)
|
||||
Both stop paths for the GCE encoder VMs guarded against killing a busy worker by checking `/health`'s `active_jobs` — but both defaulted to **0 (= idle)** when `/health` was unreachable or slow (CI drain: `... || echo "0"`; idle Cloud Function: `except: return 0`). A busy encoder runs a 4K ffmpeg on all 32 cores and shares uvicorn with the encode subprocess, so `/health` can miss its timeout *while the VM is hard at work*. Combined with blue/green deploy churn (every merge cycles the VMs) and the 5-min idle check, this stopped VMs **mid-render**, orphaning the in-memory job so backend polls got 404 → "lost contact with worker ... not found" (incident 2026-06-15; the burst was self-inflicted by rapid PR merges during the tenant E2E, 0 in the prior 48h). **Rule:** a guard that decides whether to destroy work must treat "couldn't confirm" as "assume busy / don't act," never as the permissive default. Retry the probe, and only act on a *confirmed* safe signal (here: a real `active_jobs == 0` from a 200 response), with a bounded timeout so a wedged worker can't block forever.
|
||||
|
||||
### In-Flight Status Polls Must Be Pinned to the Worker, Not the Floating Primary (Jun 2026)
|
||||
|
||||
The day after the drain fix above, the **same** "lost contact ... not found" error recurred (incident 2026-06-16, job d3af33ae) — but this time the VM was *never* stopped mid-render. `EncodingService.get_job_status()` re-resolved the worker URL on **every poll** via `_get_worker_url()` → `config.active_url`. A blue-green deploy swapped the Firestore `primary_vm` pointer at 04:33:46 (worker-a → worker-b); 7s later the in-flight render's polls started hitting worker-b, which had never received the job → 404 → 5 failures → render failed. Worker-a was alive and finished the encode the whole time; nobody was listening. The drain (which keeps the old VM *alive*) can't help — the job is orphaned at the **poll layer** the instant the pointer swaps, 47s before any VM stop. **Rule:** once a job is accepted by a specific worker, every subsequent poll for that job must target *that* worker until terminal — the poll follows the job, not the floating primary pointer. URL re-resolution is correct for *capacity fallback* (dead primary → start fallback → re-route a fresh submission) but wrong for an *in-flight poll* (a different/fresh VM can't have the job; re-routing only yields 404). Fix: capture the worker URL **after** submit (reflects a fallback re-route, precedes any later swap) and pass it as `worker_url=` through `wait_for_completion` → `get_job_status`, which then pins the request and sets `allow_failover=False`. v0.184.2.
|
||||
|
||||
### Cloud Run GPU: Let the Platform Scale, Not Your Code (Mar 2026)
|
||||
|
||||
**Don't use fire-and-forget + semaphore on Cloud Run.** We tried making the `/separate` endpoint return immediately (fire-and-forget background thread) with a `threading.Semaphore(1)` to serialize GPU work. Cloud Run couldn't see background threads as "busy", so it routed ALL requests to one instance where they queued behind the semaphore — causing 30-minute timeouts in production.
|
||||
|
||||
@@ -7,9 +7,6 @@
|
||||
- **Web App**: https://gen.nomadkaraoke.com
|
||||
- `/` - Landing page with pricing
|
||||
- `/app` - Main app (upload audio, review lyrics, download videos)
|
||||
- **Bulk Mode** (Jun 2026): submit up to 100 jobs at once by text or by album
|
||||
(MusicBrainz lookup + KaraokeNerds availability); auto-picks confident
|
||||
lossless audio, parks the rest in a review queue. See `docs/API.md` § Bulk Mode.
|
||||
- `/admin` - Admin dashboard (user management, job monitoring)
|
||||
- **Backend API**: https://api.nomadkaraoke.com - FastAPI on Cloud Run
|
||||
- **CLI Tools**: `karaoke-gen` (local), `karaoke-gen-remote` (cloud)
|
||||
|
||||
@@ -58,8 +58,6 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
|
||||
|
||||
**Prevention:** The video worker now runs as a **Cloud Run Job** (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`), which runs to completion and is immune to Cloud Run Service deployment rollouts. This replaces the `BackgroundTask` pattern that was vulnerable to instance termination during deployments. Additionally, CI performs a graceful drain before restarting the GCE encoding worker, the encoding client retries for ~90s, and status polling tolerates up to 5 consecutive failures.
|
||||
|
||||
Since v0.184.2, in-flight status polls are also **pinned to the worker that accepted the job** (`get_job_status(..., worker_url=)`), so a blue-green deploy that swaps the `active_url` primary pointer mid-render no longer migrates the poll to a worker that never received the job. If you still see `lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`, confirm via step 2 above that the worker the job was submitted to (not necessarily the current primary) still has the job — a `not found` from the *current* primary while the job is alive on the old primary was the pre-v0.184.2 failure mode (incident 2026-06-16, job d3af33ae).
|
||||
|
||||
---
|
||||
|
||||
## CDG/TXT packages missing from completed job
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
# Proactive AI Auto-Correction + UI De-AI-ification
|
||||
|
||||
**Date:** 2026-06-11
|
||||
**Branch:** `feat/sess-20260611-1514-autocorrect-cost-logging`
|
||||
**Context:** Measured cost ~$0.13/track (multi-model). Cheap enough to run on every job.
|
||||
|
||||
## Goal (user's words)
|
||||
|
||||
Run multi-model auto-correction automatically on every karaoke job so suggestions
|
||||
are ready to review/approve/reject by the time anyone reaches the lyrics review UI.
|
||||
Must fail gracefully — never block the karaoke job if AI APIs are flaky / out of
|
||||
credits. Remove all "AI"/"model" mentions from the review UI; button becomes just
|
||||
"Auto-correct"; drop the user-configurable model selection and always use multi-model.
|
||||
Keep the button for the case where references arrive later (user pastes reference
|
||||
lyrics during review, then clicks it).
|
||||
|
||||
## Architecture decisions (validated against the codebase)
|
||||
|
||||
1. **Where proactive runs: the `lyrics-transcription-job` Cloud Run Job**, after
|
||||
`mark_lyrics_complete()` (so downstream screens/render are already triggered and
|
||||
are NOT blocked), awaited (a fire-and-forget task would die when the job
|
||||
entrypoint returns). The job is long-lived, so an extra ~15-30s is fine and the
|
||||
process stays alive to finish the cache write.
|
||||
2. **Cache alignment = the whole point.** `AutoCorrectService` already writes a
|
||||
per-job GCS cache keyed on (models, settings, word-id+text list, ref texts,
|
||||
artist, title). If the proactive run uses the SAME inputs + settings + models the
|
||||
UI will send, the UI's on-load call is a **cache hit** (instant, no second spend).
|
||||
- Proactive settings = `AutoCorrectSettings(compare_models=True)` (all other
|
||||
fields default). Backend defaults == frontend `DEFAULT_AUTO_CORRECT_SETTINGS`
|
||||
once we flip `compare_models` to `true`. Both paths build settings server-side
|
||||
and hash the same dict.
|
||||
- `models` is derived server-side identically in both paths via `_models_for()`.
|
||||
- Proactive reads `corrections.json` (corrected_segments + reference_lyrics) — the
|
||||
exact data the review-data endpoint serves on first load (before any edits).
|
||||
3. **Env/secret wiring (REQUIRED for it to actually work).** The lyrics job currently
|
||||
has neither `ANTHROPIC_API_KEY` nor `AUTO_CORRECT_*`. It uses the SAME SA as the
|
||||
API service (`karaoke-backend@…`), which already reads `anthropic-api-key`
|
||||
(project-level secret access) — so adding the secret to the job is low-risk.
|
||||
Add via `--update-env-vars`/`--update-secrets` in the ci.yml job-update step
|
||||
(merges, doesn't wipe the existing 12 vars).
|
||||
4. **Feature flag:** `auto_correct_proactive_enabled` (config), default **false** in
|
||||
code, set `AUTO_CORRECT_PROACTIVE_ENABLED=true` on the lyrics job via ci.yml.
|
||||
5. **UI auto-run on load:** on review load, if references exist, auto-invoke
|
||||
auto-correct (cache hit → instant). Keep the button for manual re-run after the
|
||||
user pastes references. Always send `compare_models: true`.
|
||||
|
||||
## Changes
|
||||
|
||||
### Backend
|
||||
- `backend/config.py`: add `auto_correct_proactive_enabled`.
|
||||
- `backend/workers/lyrics_worker.py`: after `mark_lyrics_complete`, await a guarded
|
||||
helper `_run_proactive_auto_correct(job_id, ...)` — loads corrections.json, calls
|
||||
`suggest(..., settings=AutoCorrectSettings(compare_models=True))`, `asyncio.wait_for`
|
||||
timeout, swallow ALL exceptions (log only). Never affects job status.
|
||||
- Tests: worker test that it's gated by the flag, swallows errors, and skips when no
|
||||
references.
|
||||
|
||||
### Infra
|
||||
- `.github/workflows/ci.yml`: lyrics-transcription-job update step gains
|
||||
`--update-env-vars "AUTO_CORRECT_MODEL=claude-fable-5,AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true"`
|
||||
and `--update-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest"`.
|
||||
|
||||
### Frontend (`frontend/`, next-intl, 33 locales)
|
||||
- Always multi-model: `DEFAULT_AUTO_CORRECT_SETTINGS.compare_models = true`; remove
|
||||
the compare/model toggle from `AutoCorrectModal.tsx`.
|
||||
- Strip model attribution: remove model-name badge + consensus "X/Y models" badge in
|
||||
`AutoCorrectPanel.tsx`; reword the conflict badge to not mention models (keep the
|
||||
conflict-resolution behavior).
|
||||
- Rename button to "Auto-correct"; remove "AI"/"model" from all related strings.
|
||||
- Auto-run on review load when references exist (cache hit → instant); keep button.
|
||||
- i18n: edit `messages/en.json`, then `python frontend/scripts/translate.py
|
||||
--messages-dir frontend/messages --target all` for all 33 locales.
|
||||
- Update `e2e/production/auto-correct-suggestions.spec.ts` button selector.
|
||||
|
||||
## Failure modes (all non-blocking by design)
|
||||
- Anthropic down / no credits → claude call raises, caught; Gemini result still cached
|
||||
(multi-model degrades to whatever answered). UI on-load call same behaviour.
|
||||
- Both providers fail → proactive logs warning, job proceeds normally; UI on-load call
|
||||
returns 502 and the panel shows nothing (or the manual button can retry later).
|
||||
- Proactive task times out → `wait_for` cancels it, job proceeds.
|
||||
- No references at lyrics-complete time → proactive skipped; user pastes refs in UI →
|
||||
clicks button → on-demand call.
|
||||
@@ -1,105 +0,0 @@
|
||||
# Artist/Title Matching, Suggestions & Auto-Correction Rework (Phase 1)
|
||||
|
||||
**Date:** 2026-06-15
|
||||
**Worktree:** `karaoke-gen-submission-form-simplify`
|
||||
**Branch:** `feat/sess-20260615-0101-submission-form-simplify`
|
||||
**Status:** Design + plan — pending implementation
|
||||
|
||||
## Problem
|
||||
|
||||
On Step 2 ("Choose Audio") the wizard stacks two green "success" cards: the **"Song found in our database"** catalog panel and the **"Perfect match found"** audio card. User feedback: the first reads like "we already have this karaoke video," when its only real job is to nudge the user toward **official artist/title formatting** (a quality-bar concern for *published* tracks). It's confusing, and the underlying case-insensitive match is imperfect.
|
||||
|
||||
This phase reworks **only** the artist/title matching → suggestion → auto-correction behavior. The broader flow structure is deliberately left intact (see "Constraints from history"). The title-screen preview perf fix is tracked separately.
|
||||
|
||||
## Decisions (from 2026-06-15 brainstorm with Andrew)
|
||||
|
||||
1. **Invisible cosmetic tidy.** When formatting differs only cosmetically (casing, spacing, punctuation, diacritics, `&`/`feat.` conventions) and we're confident it's the same song, **silently apply** the official formatting. No green "database" card. Show only a faint, dismissible line: *"Tidied to **Paramore — Big Man, Little Dignity** · keep what I typed"*.
|
||||
2. **Confident content correction → auto-apply + surface + smart re-search.** When the correction changes actual characters (e.g. `Yesteray → Yesterday`) and we're confident, apply it **and** surface it with one-tap Undo: *"Corrected to **Yesterday** — you typed 'Yesteray' · Undo"*. Because characters changed, the original audio search may be poor, so **re-run the audio search** — automatically **only when the original results were weak** (tier 3 / empty); otherwise offer a quiet "Search again" link.
|
||||
3. **Ambiguous → ask first.** When the judge isn't confident which song is meant (multiple plausible candidates), show an ask-first prompt: *"Did you mean **X**? [Use this] [Keep mine]"* before changing anything.
|
||||
4. **Three-layer engine, all in v1.** Deterministic rules → catalog canonical → light AI judge. **The AI judge fires only when the deterministic + catalog layers are not confident** (cheap; happy path never invokes it).
|
||||
|
||||
## Constraints from history (do NOT regress)
|
||||
|
||||
From `docs/archive/2026-02-28-ux-*`, `2026-03-02-decouple-search-from-job-creation.md`, `2026-03-08-step2-song-suggestions.plan.md`, `2026-03-08-fuzzy-did-you-mean.plan.md`, `docs/LESSONS-LEARNED.md`, PRs #444/#451/#480/#495/#512:
|
||||
|
||||
- **No Step-1 autocomplete.** It was added (PR #451) then removed (PR #512) because users didn't understand it. Suggestions belong on Step 2, in parallel with the audio search.
|
||||
- **Cosmetic correction must NOT restart the audio search.** Already a documented decision — the existing catalog `onArtistTitleCorrection` updates artist/title without re-searching. Preserve this. (Content corrections that change characters MAY re-search — see decision 2.)
|
||||
- **Deferred job creation (search-session pattern).** No job is created until the final confirm step. Don't move creation earlier. The tidied artist/title is passed at `create-from-search` time; the audio `search_session_id` is unaffected by a metadata tidy.
|
||||
- **Preserve the fuzzy artist-tiebreaker lesson:** when title-matching returns multiple artists with the same song name, use the user's (possibly garbled) artist input as a tiebreaker. And the gating: fuzzy/"did you mean" only triggers when audio results are poor.
|
||||
- **`display_artist`/`display_title`** stay distinct from matching `artist`/`title`; they're set at creation time. The tidy applies to the **matching** artist/title (what drives search, lyrics, and published metadata).
|
||||
- **Public vs private brand rule, audio-before-customize ordering, combined review flow** — untouched by this phase.
|
||||
|
||||
## Architecture
|
||||
|
||||
Consolidate today's scattered client-side matching (case-insensitive exact match in `SongSuggestionPanel` + LCS fuzzy in `audio-search-utils.ts`) into **one backend "match judge" service**, called from Step 2 in parallel with the audio search (replacing the current `searchCatalogTracks` + client fuzzy effect). Rationale: testable, consistent canonical formatting, and the AI layer needs the backend's LLM clients/keys.
|
||||
|
||||
### Backend: `POST /api/catalog/match-judge`
|
||||
|
||||
Request: `{ artist, title, audio_confidence_tier?: 1|2|3 }`
|
||||
(The frontend passes the audio search's computed confidence tier so the judge knows whether weak results suggest a typo.)
|
||||
|
||||
Pipeline (server-side):
|
||||
1. **Deterministic normalize** (reuse/extend `karaoke_gen.utils.normalize_text`): trim, collapse whitespace, fix obvious casing (title-case with small-word handling), straighten quotes, standardize `feat.`/`ft.` → `(feat. …)` and `and`↔`&` per house style.
|
||||
2. **Catalog lookup** (existing `search_tracks` via `catalog_proxy_service`). If a candidate matches the normalized input under a strict normalized-equality test → **confident cosmetic**: return the catalog's canonical `artist_name`/`track_name`.
|
||||
3. **AI judge — only if (1)+(2) not confident.** Invoke a light model (see "Model") with the typed input, the top catalog candidates, and the audio tier. It returns a structured verdict.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"kind": "cosmetic | content | ambiguous | none",
|
||||
"confident": true,
|
||||
"canonical_artist": "Paramore",
|
||||
"canonical_title": "Big Man, Little Dignity",
|
||||
"alternatives": [{"artist": "...", "title": "..."}],
|
||||
"engine": "deterministic | catalog | ai",
|
||||
"reason": "casing only"
|
||||
}
|
||||
```
|
||||
- `kind=cosmetic` → frontend applies invisibly + faint line (no re-search).
|
||||
- `kind=content` + `confident` → frontend auto-applies + Undo line; re-search if audio tier was weak.
|
||||
- `kind=ambiguous` (or `content` not confident) → frontend shows ask-first "Did you mean?" with `alternatives`.
|
||||
- `kind=none` → no suggestion (leave user input as typed).
|
||||
|
||||
**Resilience:** AI judge runs under a short timeout (~2–3s) and is fully optional — on timeout/error/unparseable output, fall back to deterministic+catalog result (or `kind=none`). Never block the audio search; never error the request. Mirror `auto_correct`'s greppable usage/cost logging (`match-judge usage/cost job/session=…`).
|
||||
|
||||
### Model (decided)
|
||||
|
||||
Reuse `auto_correct` dispatch (`claude*` → Anthropic, else Gemini via `genai.Client(vertexai=True, project=…, location="global").models.generate_content(model=…)`).
|
||||
**Decision (Andrew, 2026-06-15):** default `MATCH_JUDGE_MODEL=gemini-3.5-flash` — the latest Vertex Gemini Flash (https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-5-flash). Passed bare to the genai Vertex client exactly like `auto_correct` passes `gemini-3.1-pro-preview`. No `ANTHROPIC_API_KEY` needed. Env-configurable, so if Vertex requires a version suffix it's a one-line env change (an invalid id surfaces as a loud error on first call). Add `gemini-3.5-flash` pricing to `pricing.py` for cost logging.
|
||||
|
||||
### Frontend (`AudioSourceStep.tsx`)
|
||||
|
||||
- Replace the parallel `searchCatalogTracks` + client fuzzy `useEffect` with a single `api.matchJudge(artist, title, tier)` call fired in parallel on mount (after the audio tier is known, or fired and reconciled when the tier resolves).
|
||||
- **Remove** the green `SongSuggestionPanel`. Add a quiet `TidyNotice` (cosmetic) and reuse/restyle `DidYouMeanBanner` for the surfaced-content (Undo) and ambiguous (ask) cases.
|
||||
- Wire cosmetic/confident-content application through the existing `onArtistTitleCorrection` (no restart). Add a `reSearch()` path (reuse `handleFuzzyAccept`'s restart logic) gated on weak prior results for content corrections.
|
||||
- Keep the `confidence.tier` gating and artist-tiebreaker semantics (now enforced server-side, but the frontend still passes the tier).
|
||||
|
||||
## Out of scope (this phase)
|
||||
|
||||
- Title-screen preview perf (separate task: smaller canvas + low-res bg + preload at step 2 + spinner).
|
||||
- Any change to step count / visibility / customize / job-creation timing.
|
||||
- Auto-selecting audio on a Tier-1 match (possible later, separately).
|
||||
|
||||
## Testing strategy
|
||||
|
||||
Per `docs/TESTING.md`:
|
||||
- **Backend unit:** deterministic normalizer rule table (casing, spacing, punctuation, feat./&, quotes); judge response parsing; confidence/kind classification; AI-failure fallback; "only call AI when not confident" gating.
|
||||
- **Backend integration:** `/api/catalog/match-judge` happy/edge paths with catalog mocked and AI mocked.
|
||||
- **Frontend unit (Jest):** TidyNotice rendering + Undo; content-correction auto-apply + smart re-search gating (weak vs ok results); ambiguous ask-first; preserve "no restart on cosmetic".
|
||||
- **E2E (Playwright) + prod E2E:** end-to-end on a real song (cosmetic case), a typo case (content + re-search), and an ambiguous case.
|
||||
|
||||
## Telemetry
|
||||
|
||||
- Log judge decisions + engine used + latency + token cost (greppable, like `auto-correct usage/cost`).
|
||||
- Count cosmetic / content / ambiguous / none and Undo clicks to measure real-world correction quality (informs whether thresholds need tuning).
|
||||
|
||||
## Open decisions
|
||||
|
||||
1. ~~Judge model default~~ — DECIDED: `gemini-3.5-flash` (Vertex), configurable via `MATCH_JUDGE_MODEL`.
|
||||
2. Confidence thresholds for cosmetic vs content vs ambiguous (start conservative; tune from telemetry).
|
||||
3. Whether to keep a tiny instant frontend normalizer for immediate display, or rely solely on the judge response (~sub-second). Lean: rely on judge for v1; add instant normalize later if the delay is noticeable.
|
||||
|
||||
## Rollout
|
||||
|
||||
- `MATCH_JUDGE_ENABLED` env flag (default on) so the AI layer can be disabled without a deploy; deterministic+catalog still function if AI is off.
|
||||
- Bump `pyproject.toml` version. Ship behind normal CI; Andrew reviews locally (localhost:3000 → prod backend) before merge/deploy.
|
||||
@@ -1,98 +0,0 @@
|
||||
# White-Label Tenant Portals: Made Working End-to-End (Jun 2026)
|
||||
|
||||
## Context
|
||||
|
||||
The two B2B white-label tenant portals (`vocalstar.nomadkaraoke.com`, `singa.nomadkaraoke.com`)
|
||||
had full data models, middleware, GCS config, themes, a simplified job form, a separate
|
||||
Cloudflare deployment, and 280+ unit tests — and were documented as "production ready."
|
||||
**But no tenant job had ever actually completed:** 0 of the 484 most recent prod jobs
|
||||
carried a `tenant_id`. The feature looked done but was broken at every stage that had
|
||||
never been exercised by a real end-to-end tenant job.
|
||||
|
||||
This session drove a real Vocal Star track (`Eddy Grant - I Don't Wanna Dance`, from their
|
||||
bulk batch) through the full pipeline in production, fixing each blocker in turn, until a
|
||||
tenant job completed: correct attribution → transcription → screens → review → render →
|
||||
Dropbox delivery, with the locked theme and **no** YouTube / Google Drive.
|
||||
|
||||
## The seven blockers (each was the next never-exercised stage)
|
||||
|
||||
1. **Tenant attribution never happened (root cause).** The frontend API client never sent
|
||||
the `X-Tenant-ID` header (`getTenantHeaders()` existed but was unwired). Tenant portals
|
||||
call the shared `api.nomadkaraoke.com`, whose Host isn't the tenant subdomain, and the
|
||||
`?tenant=` param is prod-disabled — so the backend never detected the tenant and every
|
||||
sign-in/job silently became a consumer job. Fix: attach `X-Tenant-ID` from
|
||||
`window.__TENANT_CONFIG__` in `lib/api.ts` (`getBaseHeaders`), incl. the magic-link
|
||||
request. PR #824.
|
||||
|
||||
2. **Tenant config not authoritative.** Prod sets global `DEFAULT_DROPBOX_PATH` /
|
||||
`DEFAULT_GDRIVE_FOLDER_ID` / `DEFAULT_BRAND_PREFIX`; `_apply_tenant_overrides` only
|
||||
filled unset fields, so tenant jobs leaked into the shared consumer Dropbox folder and
|
||||
uploaded to the global Google Drive. Fix: tenant config is authoritative, gated by
|
||||
feature flags (gdrive/dropbox cleared when disabled). PR #824.
|
||||
|
||||
3. **Wrong file transcribed.** existing-instrumental jobs upload mixed + instrumental into
|
||||
the same `uploads/{job}/audio/` dir; `uploads-complete` resolved the `audio` slot via
|
||||
`files[0]`, which sorts to `existing_instrumental.mp3`. Transcription ran on the
|
||||
instrumental. Fix: `_select_mixed_audio_files` excludes the instrumental. PR #825.
|
||||
|
||||
4. **AudioShake rejected the audio.** Vocal Star's MP3s begin with ~731 leading null bytes
|
||||
before the first frame; ffmpeg tolerates it, AudioShake 400s ("Error fetching or
|
||||
processing asset"). Consumer jobs never hit this (they transcribe re-encoded stems).
|
||||
Fix: detect leading null padding on `.mp3/.aac` and losslessly remux (`ffmpeg -c copy`)
|
||||
before upload. Verified against the live AudioShake API. PR #826.
|
||||
|
||||
5. **Theme incomplete.** The strict theme validator requires every field; the tenant
|
||||
themes (created Jan 2026) were missing `extra_text_text_transform` (intro + end),
|
||||
added to the schema later → "Title screen generation failed." Fix: added the field to
|
||||
the live GCS themes and the setup scripts. PR #827.
|
||||
|
||||
6. **Theme assets not downloaded.** The setup scripts wrote full `gs://bucket/themes/.../assets/X`
|
||||
URLs, but `theme_service._build_style_assets_mapping` only resolves bare basenames (the
|
||||
consumer convention) → `style_assets` empty → assets never localized → encoder failed
|
||||
with "Video background image not found". Fix: rewrote the live themes + setup scripts to
|
||||
bare basenames. PR #827.
|
||||
|
||||
7. **Render prerequisites — "No instrumental selected".** existing-instrumental jobs have
|
||||
no instrumental-selection UI step; the orchestrator defaults to `'clean'` (a stem never
|
||||
produced) and `_validate_prerequisites` rejected the job. Fix: `complete-review`
|
||||
defaults `instrumental_selection` to `'custom'` when `existing_instrumental_gcs_path`
|
||||
is set. PR #827.
|
||||
|
||||
## Tenant config (final, both tenants)
|
||||
|
||||
- Locked theme (`vocalstar` / `singa`), no theme selection.
|
||||
- `youtube_upload=false`, `gdrive_upload=false` (folder cleared), `dropbox_upload=true`.
|
||||
- Dropbox: `/MediaUnsynced/Karaoke/Tracks-VocalStar`, `/MediaUnsynced/Karaoke/Tracks-Singa`.
|
||||
- Jobs forced `is_private=true`; CDG + 4K enabled.
|
||||
|
||||
## Daily E2E
|
||||
|
||||
`scripts/e2e/tenant_e2e.py` + `.github/workflows/e2e-tenant-daily.yml` run a full job per
|
||||
tenant daily (07:37 UTC, matrix vocalstar/singa): submit → approve review → render →
|
||||
assert (completes, Dropbox link present, no YouTube, downloads available) → clean up the
|
||||
job + uploads. Auth via WIF + `E2E_ADMIN_TOKEN`; test audio in `gs://.../e2e-tests/shared/`.
|
||||
|
||||
## Outcome
|
||||
|
||||
Both tenants pass the full prod E2E (PRs #824–#830): log in → submit (artist, title, mixed,
|
||||
instrumental) → transcribe → review → render with the locked theme → encode → package →
|
||||
Dropbox delivery, with **no YouTube, no Google Drive**, and all outputs (4K / 720p /
|
||||
with-vocals MP4 + CDG + TXT) downloadable from the portal via `job.file_urls`.
|
||||
|
||||
The encoder blocker (bug #8) took three iterations: the staging had to land in the
|
||||
**orchestrator** path (`video_worker_orchestrator._run_encoding`, not the legacy
|
||||
`_encode_via_gce`) and use the filename the running encoder VM's `custom` branch globs for
|
||||
(`custom_instrumental.<ext>`, since the live VM boots the 2026-01-23 image whose `custom`
|
||||
branch predates `*existing_instrumental*` / `*Instrumental User*`). The instrumental is
|
||||
server-side-copied from `uploads/{job}/audio/existing_instrumental.*` →
|
||||
`jobs/{job}/custom_instrumental.<ext>`.
|
||||
|
||||
## Gotchas / lessons
|
||||
|
||||
- The tenant pipeline had never run end-to-end, so every stage hid a latent bug. "Has a
|
||||
real job of this shape ever completed in prod?" is a better readiness question than test
|
||||
count.
|
||||
- Theme asset paths must be **bare basenames** (consumer convention), not `gs://` URLs.
|
||||
- AudioShake needs clean audio at offset 0; user-provided files vary — remux defensively.
|
||||
- Public tenant config API redacts `dropbox_path`/`gdrive_folder_id`/`brand_prefix`; read
|
||||
the stored GCS config for the real values.
|
||||
@@ -1,106 +0,0 @@
|
||||
# Match-Judge Improvements — Implementation Plan
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Worktree:** `karaoke-gen-match-judge-improvements`
|
||||
**Branch:** `feat/sess-20260616-0053-match-judge-improvements`
|
||||
**Builds on:** match-judge v0.184.1 (PRs #836 + #838)
|
||||
**Spec:** `docs/archive/2026-06-16-match-judge-improvements-prompt.md` (decisions by Andrew — settled)
|
||||
|
||||
Four items. Decisions are already made in the prompt; this doc records the concrete
|
||||
shapes I'm committing to and the test plan. TDD throughout.
|
||||
|
||||
---
|
||||
|
||||
## Item 1 — Race fix: parallel tidy + hard gate
|
||||
|
||||
**Backend shape (decided: two-call `stage` contract).** Add `stage: "fast" | "full"`
|
||||
to the endpoint + `judge_match`. Default `"full"` (backwards-compatible).
|
||||
|
||||
- `stage="fast"` (no tier needed): run catalog search + `classify_catalog_match` ONLY.
|
||||
Never calls AI.
|
||||
- confident catalog verdict (cosmetic/none) → return it (`needs_ai=False`).
|
||||
- catalog undecided → return `MatchVerdict(none, confident=False, engine="catalog",
|
||||
reason="needs ai", needs_ai=True)`.
|
||||
- `stage="full"` (tier known): current pipeline + Item 4 (see below).
|
||||
|
||||
New field `needs_ai: bool = False` on `MatchVerdict` (+ `to_dict`, response model, TS type).
|
||||
|
||||
**Frontend two-phase coordination (AudioSourceStep):**
|
||||
1. On mount (parallel with audio search): `matchJudge(artist, title, { stage: 'fast' })`.
|
||||
Store the promise in a ref. If it resolves to a confident cosmetic verdict, apply the
|
||||
silent tidy immediately (no re-search).
|
||||
2. When the audio search resolves (tier known), one coordinating effect:
|
||||
- `await` the fast promise.
|
||||
- `needFull = fast == null || fast.needs_ai || (fastIsCatalogConfident && tier >= 3)`.
|
||||
- if `needFull` → `matchJudge(artist, title, { stage: 'full', audioConfidenceTier: tier })`,
|
||||
apply its verdict.
|
||||
- settle the gate in a `finally` (always).
|
||||
|
||||
**Hard gate.** `gateReleased` state (starts false) → true when the judge settles.
|
||||
Pick/select buttons (PickCard, ResultRow) and the fallback submit buttons are disabled
|
||||
while `!gateReleased`. A subtle "Checking song details…" line shows when
|
||||
`!gateReleased && !isSearching`. Safety timeout `JUDGE_GATE_TIMEOUT_MS = 12000` from when
|
||||
the full call fires guarantees release even on a network hang (backend AI already caps at
|
||||
12s). Gate never deadlocks: every path (disabled flag, fast/full failure, timeout) settles.
|
||||
|
||||
On a content re-search, keep the gate open (don't re-judge) — mirrors the existing
|
||||
`judgeTriggered` semantics.
|
||||
|
||||
**Acceptance:** impossible to reach Step 3 with un-tidied metadata in normal flow; a slow
|
||||
AI verdict never clobbers the selection; gate is imperceptible in cosmetic cases and bounded
|
||||
(≤12s) otherwise.
|
||||
|
||||
## Item 2 — Two-way toggle for tidy/correction (frontend only)
|
||||
|
||||
`MatchNotice` becomes a clean two-way toggle. Add `correctionActive` state (default true).
|
||||
- cosmetic applied: "Tidied to **X** · keep what I typed" → revert.
|
||||
- cosmetic reverted: "Using what you typed: **Y** · use tidied version" → reapply.
|
||||
- content applied: "Corrected to **X** — you typed “Y” · Undo" → revert.
|
||||
- content reverted: "Using what you typed: **Y** · use the correction" → reapply.
|
||||
|
||||
Toggle is metadata-only (no re-search on toggle — matches old Undo + the "no restart on
|
||||
cosmetic" rule). `appliedFrom` already holds the typed text; `verdict` holds canonical.
|
||||
|
||||
New i18n keys (translate all locales): `matchUsingTyped`, `matchUseTidied`,
|
||||
`matchUseCorrection`.
|
||||
|
||||
## Item 3 — Title-screen preview perf (frontend only)
|
||||
|
||||
`TitleCardPreview.tsx` + `KaraokeBackgroundPreview.tsx`:
|
||||
- Render canvas at **preview resolution** (960×540, dpr-aware, clamp dpr≤2) instead of
|
||||
3840×2160. Keep coordinate constants in 4K space; apply `ctx.setTransform(scale,…)` so
|
||||
drawing code is unchanged.
|
||||
- Add **low-res** bg assets: `public/title-card-bg-preview.png`,
|
||||
`public/karaoke-bg-preview.png` (downscaled from the 2.7 MB 4K originals). Previews use
|
||||
these; the 4K originals stay for any real render path.
|
||||
- **Preload** the preview bg(s) at Step 2 (export `preloadTitleCardBg()` /
|
||||
`preloadKaraokeBg()`, call from AudioSourceStep mount) so they're warm by Step 4.
|
||||
- **Spinner** "Loading title screen preview" overlay until the first draw completes
|
||||
(`ready` state).
|
||||
- Update `TitleCardPreview.test.tsx` mock (add `setTransform`/`scale`), add coverage for
|
||||
the spinner + low-res bg src.
|
||||
|
||||
## Item 4 — Catalog-match trust: verify weak matches with AI (backend)
|
||||
|
||||
In `judge_match` (stage=full): when `classify_catalog_match` returns a confident verdict
|
||||
BUT the audio tier is weak (`>= 3`), still call AI and let it override — catches a junk/
|
||||
misspelled Spotify entry matching the user's exact typo (prod: `Queen / Bohemian Rapsody`
|
||||
→ wrongly "already canonical"). AI overrides only when confident and `kind != none`;
|
||||
otherwise keep the catalog verdict. Extra ~$0.0003/call cost only on weak-result cases.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Backend unit** (`test_service.py`): fast-stage returns catalog verdict / needs_ai;
|
||||
fast never calls AI; full-stage weak-tier catalog match → AI consulted → override;
|
||||
full-stage strong-tier catalog match → no AI; AI-unconfident on weak tier → keep catalog.
|
||||
- **Backend unit** (`test_classifier.py`): unchanged (still escalates on no match).
|
||||
- **Backend route** (`test_match_judge_routes.py`): `stage` forwarded; `needs_ai` in response.
|
||||
- **Frontend** (`AudioSourceStep.test.tsx`): fast call on mount; cosmetic applies from fast;
|
||||
gate disables pick button until settled then enables; full call fired only when needed;
|
||||
two-way toggle revert↔reapply.
|
||||
- **Frontend** (`TitleCardPreview.test.tsx`): preview-res canvas, low-res bg, spinner.
|
||||
- `make test` full suite green before `/shipit`.
|
||||
|
||||
## Out of scope / preserved
|
||||
No Step-1 autocomplete; cosmetic must not restart search; deferred job creation; public
|
||||
brand rule; audio-before-customize ordering. (Constraints from the 2026-06-15 doc.)
|
||||
@@ -1,67 +0,0 @@
|
||||
# Match-Judge Improvements — New-Session Prompt Doc
|
||||
|
||||
**Created:** 2026-06-16
|
||||
**For:** a fresh session, started via `/startnomad gen match-judge improvements`
|
||||
**Builds on:** the artist/title match-judge feature shipped in gen **v0.184.1** (PRs #836 + #838).
|
||||
|
||||
## Read first (context)
|
||||
|
||||
- Feature overview + gotchas: agent memory `project_match_judge.md` (and `[[project_match_judge]]`).
|
||||
- Original design + history constraints: `docs/archive/2026-06-15-artist-title-matching-rework-plan.md`.
|
||||
- **Honor the "Constraints from history" section of that plan** — no Step-1 autocomplete; cosmetic correction must not restart the audio search; deferred job-creation/search-session pattern; public-style brand rule; audio-before-customize ordering. Don't undo these.
|
||||
|
||||
### Where the code lives
|
||||
- Backend: `backend/services/match_judge/` — `classifier.py` (deterministic + catalog), `ai.py` (Vertex `gemini-3.5-flash`), `service.py` (orchestration), `verdict.py` (`MatchVerdict`). Endpoint: `POST /api/catalog/match-judge` in `backend/api/routes/catalog.py`. Config in `backend/config.py` (`MATCH_JUDGE_ENABLED` / `MATCH_JUDGE_MODEL` / `MATCH_JUDGE_TIMEOUT_MS=12000`).
|
||||
- Frontend: `frontend/components/job/steps/AudioSourceStep.tsx` — the judge effect, `applyCorrection`/`handleSuggestionAccept`/`handleUndoCorrection`, and the `MatchNotice` component. Client: `api.matchJudge` in `frontend/lib/api.ts`. i18n keys live in `frontend/messages/en.json` under `jobFlow` (`matchTidiedTo`, `matchKeepMine`, `matchCorrectedTo`, `matchUndo`, `matchDidYouMean`) — any new/changed strings must be translated to all 33 locales (`python scripts/translate.py --messages-dir ./messages --target all`).
|
||||
|
||||
### How it currently works (the starting point)
|
||||
On Step 2, the judge effect fires **after** the audio search resolves (`isSearching === false`), passing `confidence.tier`. The verdict drives `MatchNotice`: cosmetic → silent apply + quiet "Tidied to X · keep what I typed" (no re-search); confident content → apply + "Corrected to X · Undo", re-search only if tier 3; ambiguous → ask-first "Did you mean?". `applyCorrection(newArtist, newTitle, reSearch)` writes to the parent via `onArtistTitleCorrection` (no-restart path) and, when `reSearch`, resets `searchTriggered`/results so the mount effect re-runs.
|
||||
|
||||
---
|
||||
|
||||
## Work items (with decisions already made)
|
||||
|
||||
### 1. Race: audio results can arrive before the tidy finishes
|
||||
**Problem:** the judge runs *after* the audio search, so there's a window where results are shown but the tidy hasn't applied. If the user selects audio / advances fast, the un-tidied artist/title can be what's saved (job creation is deferred to Step 4, so it's usually caught, but not guaranteed). Worse: a `content`+reSearch verdict landing while the user is mid-selection can blow away results / a pick.
|
||||
|
||||
**Decision (Andrew):** **Tidy earlier (parallel) + a hard gate.**
|
||||
- Run the **deterministic + catalog** tidy **in parallel with the audio search** (kick it off on mount; it doesn't need the tier). The **AI** layer still needs the tier, so it runs once the audio search resolves — but only when deterministic+catalog aren't confident.
|
||||
- This likely means splitting the single `match-judge` call, OR adding a query param so the backend can do a fast catalog-only pass immediately and a full pass (with tier) after. Decide the cleanest shape — could be two calls (`/match-judge` cheap-first without tier, then a second with tier only if needed) or one call kicked off as soon as possible. Keep the backend contract clean.
|
||||
- **Hard-gate selection:** disable "Use This Audio" (all audio pick buttons) with a subtle indicator (e.g. "Checking song details…") until **both** the audio search **and** the judge verdict have resolved + applied. The judge's 12s timeout must still unlock the gate (never strand the user). Because the tidy runs in parallel, the common cosmetic case adds ~no perceptible wait; only the rarer AI path holds the gate briefly.
|
||||
- Gate releases when the verdict reaches a terminal state (cosmetic applied / content applied / ambiguous prompt shown / none / timeout). For **ambiguous**, release the gate (don't block indefinitely on an unsure result) but keep the "Did you mean?" prompt visible.
|
||||
|
||||
**Acceptance:** it is impossible to reach Step 3 with un-tidied metadata in the normal flow; a slow AI verdict never clobbers a selection; the gate is imperceptible for cosmetic cases and bounded (≤12s) otherwise.
|
||||
|
||||
### 2. Make "keep what I typed" reversible (two-way toggle)
|
||||
**Decision (Andrew):** the tidy notice should let the user **see what it would revert to**, and **switch back** to the tidied version if they change their mind.
|
||||
- Show both values. e.g. tidied state: *"Tidied to **Hard-Fi — I Shall Overcome** · keep what I typed"*. After clicking, reverted state: *"Using what you typed: **hard-fi - i shall overcome** · use tidied version"*, and "use tidied version" switches back. A clean two-way toggle; current value always clear.
|
||||
- Same for the **content** correction ("Corrected to X · Undo") — Undo should be reversible back to the correction too.
|
||||
- This is just frontend `MatchNotice` + state (`appliedFrom` already tracks the pre-correction text; add the inverse). New i18n keys as needed (translate all 33 locales).
|
||||
|
||||
### 3. Title-screen preview performance (the original "point D")
|
||||
`frontend/components/job/TitleCardPreview.tsx` renders a **3840×2160 (4K) canvas** and loads a **4K** background PNG (`/title-card-bg.png`) — for what's shown as a small thumbnail. Slow, especially on mobile.
|
||||
- Render the canvas at **display resolution** (e.g. ~960×540, or `devicePixelRatio`-aware), not 4K.
|
||||
- Add a **low-res** background asset (downscale `public/title-card-bg.png`) and use it for the preview; keep the 4K for any real render path.
|
||||
- **Preload** the background once the artist/title are locked at Step 2 (the preview currently lives on Step 4), so it's warm by the time the user arrives.
|
||||
- Add a **"Loading title screen preview"** spinner while it renders.
|
||||
- Note: private mode has a second canvas (`KaraokeBackgroundPreview.tsx`) — apply the same treatment. There's a `TitleCardPreview.test.tsx`; update it.
|
||||
|
||||
### 4. Catalog-match trust (the "second point" — yes, it's a real bug)
|
||||
**Problem:** the classifier's exact catalog match can match a junk / misspelled Spotify entry (e.g. a karaoke/lyric upload titled with the user's exact typo), so it returns `none`/"already canonical" and **the AI judge never runs**. Observed in prod: `Queen / Bohemian Rapsody` → "already canonical" (wrong).
|
||||
**Decision (Andrew):** **Verify weak matches with AI.** When the audio results were weak (**tier 3**), run the AI judge **even if the catalog "matched"**, and let the AI override the catalog verdict. The extra cost (~$0.0003/call) is only incurred on weak-result cases. Implement in `service.py` (don't let `classify_catalog_match` short-circuit when tier is weak) and/or `classifier.py`. Add unit tests covering: weak tier + junk exact-match → AI consulted → corrected; strong tier + exact-match → still short-circuits (no AI).
|
||||
|
||||
---
|
||||
|
||||
## Process
|
||||
|
||||
1. `/startnomad gen match-judge improvements`, read the context docs above.
|
||||
2. Brainstorm/confirm the parallel-tidy backend shape (item 1) before coding — it's the trickiest. Consider visual mockups only if helpful; the decisions above are settled, so keep it light.
|
||||
3. TDD: backend changes get unit/integration tests; frontend changes get Jest tests (mirror the existing `AudioSourceStep.test.tsx` / `TitleCardPreview.test.tsx` patterns). Update i18n for all 33 locales when strings change.
|
||||
4. Run `make test` (full suite), then `/shipit` (CodeRabbit → version bump → PR with `@coderabbitai ignore` → merge → wait for deploy → verify prod). **Verify item 1 and item 4 live in prod** with real `/api/catalog/match-judge` calls and by clicking through Step 2 on localhost:3000 (dev server proxies to prod backend by default).
|
||||
5. After shipping, trigger the daily prod E2E workflow: `gh workflow run e2e-daily.yml --ref main`.
|
||||
|
||||
## Notes / gotchas
|
||||
- The shell/rtk wrapper mangles `&&`, `2>&1`, and reformats `gh --json -q` output — use `;`-separated commands and `rtk proxy gh …` for raw JSON.
|
||||
- `gh pr merge --delete-branch` errors locally because `main` is checked out in the main clone worktree; the remote merge still succeeds — verify with `gh pr view <n> --json state`.
|
||||
- CI dedupes test jobs on merge and goes straight to "Deploy - Backend (Cloud Run)"; the definitive deploy signal is the prod root version (`https://api.nomadkaraoke.com/`) flipping to the new value.
|
||||
- Admin token for prod API tests: `gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1`, send as `Authorization: Bearer <token>`.
|
||||
@@ -1,83 +0,0 @@
|
||||
# Render status-poll pinning — fix for deploy-swap orphaning (job d3af33ae)
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Worktree:** `karaoke-gen-encoding-job-not-found`
|
||||
**Incident error:** `Encoding job <ID> lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`
|
||||
|
||||
## What happened (job d3af33ae, 2026-06-16 UTC)
|
||||
|
||||
| Time | Event |
|
||||
|------|-------|
|
||||
| 04:29:09 | `karaoke-backend@` starts **worker-a** (`34.57.78.246`) — render warmup |
|
||||
| ~04:31:39 | Render submitted to **worker-a**; encoding begins |
|
||||
| 04:33:01 | `github-actions-deployer@` starts **worker-b** (`34.10.189.118`) — deploy begins |
|
||||
| **04:33:46.985** | Firestore `last_swap_at`: primary swapped worker-a → **worker-b** |
|
||||
| 04:33:53 → 04:34:33 | Backend status polls fail 1/5 → 5/5: "Encoding job d3af33ae not found" |
|
||||
| 04:34:33 | Render failed; deploy stops worker-a |
|
||||
| 04:46:35 | User retried → re-rendered on worker-b → **success** |
|
||||
|
||||
The 4 polls that failed at 04:33:53–04:34:23 happened **while worker-a was still running and encoding**. The 404s came from worker-b (the just-swapped primary), which never received the job.
|
||||
|
||||
## Root cause
|
||||
|
||||
`EncodingService.get_job_status()` resolves the worker URL **fresh on every poll** via
|
||||
`_get_worker_url()` → `config.active_url`. When a blue-green deploy flips `primary_vm` in
|
||||
Firestore mid-render, in-flight status polls migrate from the worker that owns the job
|
||||
(old primary) to the new primary, which 404s. A clean 404 is counted as a transient poll
|
||||
failure; 5 in a row fails the render — even though the original worker finished the encode.
|
||||
|
||||
URL re-resolution is **correct for capacity fallback** (primary VM dead → start fallback →
|
||||
re-route), but **wrong for a deploy swap** (old primary alive, still owns the job).
|
||||
|
||||
The drain logic added 2026-06-15 (`ci.yml` "Drain and stop old primary") prevents *stopping*
|
||||
a busy VM, but the job is orphaned at the **poll layer** the instant the pointer swaps —
|
||||
47s before the VM is stopped. The drain can't fix this.
|
||||
|
||||
## Fix: pin in-flight polls to the worker that accepted the job
|
||||
|
||||
Invariant: **once a job is accepted by a worker VM, all status polls for that job target
|
||||
that same VM until terminal** — the poll follows the job, not the floating primary pointer.
|
||||
|
||||
### Changes (`backend/services/encoding_service.py`)
|
||||
|
||||
1. **`_request_with_retry(..., allow_failover: bool = True)`** — gate the warmup-on-failure
|
||||
block and the post-warmup URL re-resolution on `allow_failover`. Default `True` keeps all
|
||||
existing submit callers (and capacity fallback) unchanged.
|
||||
|
||||
2. **`get_job_status(job_id, worker_url: Optional[str] = None)`** — when `worker_url` is given,
|
||||
poll `f"{worker_url}/status/{job_id}"` with `allow_failover=False` (a pinned poll must never
|
||||
re-resolve to active_url nor spin up a fallback VM — a fresh VM can't have the job). When
|
||||
omitted, behave exactly as today.
|
||||
|
||||
3. **`wait_for_completion(..., worker_url: Optional[str] = None)`** — thread `worker_url` into
|
||||
`get_job_status`. Consecutive-failure tolerance unchanged (still rides out a brief restart of
|
||||
the *pinned* worker). A pinned 404 is now the *true* "owning worker lost the job" signal.
|
||||
|
||||
4. **`encode_videos` / `render_video_on_gce` / `encode_preview_video`** — capture
|
||||
`pinned_url = self._get_worker_url()` **after** submit returns, and pass it as `worker_url=`
|
||||
to `wait_for_completion`. Capturing post-submit reflects a capacity-fallback re-route during
|
||||
submit (warmup invalidates the cache, so `_get_worker_url()` returns the fallback URL) while
|
||||
being *before* any later deploy swap.
|
||||
|
||||
### Why post-submit capture (not the submit return value)
|
||||
|
||||
A capacity-fallback during submit updates `active_override` + invalidates the URL cache, so the
|
||||
*next* `_get_worker_url()` already returns the worker the job actually landed on. This avoids
|
||||
threading the URL back through three `submit_*` return contracts.
|
||||
|
||||
## Tests (TDD — `backend/tests/test_encoding_service.py`)
|
||||
|
||||
- `get_job_status` targets the pinned URL over active_url, with `allow_failover=False`.
|
||||
- `get_job_status` without a pin still uses active_url (regression).
|
||||
- `wait_for_completion` threads `worker_url` into each poll.
|
||||
- `_request_with_retry` does **not** warm up / re-resolve when `allow_failover=False`.
|
||||
- **End-to-end:** `render_video_on_gce` keeps polling the submission worker even when
|
||||
`active_url` has swapped to a worker that 404s — would fail before the fix, passes after.
|
||||
- Update the 3 existing `wait_for_completion` tolerance mocks to accept `worker_url=None`.
|
||||
|
||||
## Scope notes / non-goals
|
||||
|
||||
- The single `get_job_status` call inside the `submit_*` 409-conflict handler stays unpinned
|
||||
(rare two-request-same-job-during-swap edge); the main poll loop is pinned via the convenience
|
||||
methods, which covers the join case.
|
||||
- No change to the CI drain logic — it remains the correct guard for *stopping* a busy VM.
|
||||
@@ -1,175 +0,0 @@
|
||||
# Plan: Restore missing files in Dropbox track output folders
|
||||
|
||||
**Date:** 2026-06-17
|
||||
**Branch:** `feat/sess-20260617-1501-dropbox-missing-files`
|
||||
**Status:** Implemented (v0.186.0) — Parts A/B/C done + a bundled CLI ffmpeg-hang fix (see end).
|
||||
|
||||
## Problem
|
||||
|
||||
Track output folders uploaded to Dropbox (e.g. `NOMAD-1184 - Eddie Money - I'll Get By`)
|
||||
are missing two file types that used to be present (last good folder ~Feb 2026):
|
||||
|
||||
1. **Screen videos** — the 5-second `.mov` clips generated from the title/end screen
|
||||
images: `<artist> - <title> (Title).mov` and `<artist> - <title> (End).mov`.
|
||||
The folder still has the `(Title).png`/`.jpg`/`(End).png` images, just not the `.mov`s.
|
||||
2. **Original input audio** — the source file used for separation/transcription/with-vocals,
|
||||
e.g. `<artist> - <title> (flacfetch).flac` or `<artist> - <title> (uploaded).mp3`.
|
||||
|
||||
## Root cause
|
||||
|
||||
The Dropbox upload (`VideoWorkerOrchestrator._upload_to_dropbox`,
|
||||
`backend/workers/video_worker_orchestrator.py`) uploads **the entire `output_dir`** wholesale
|
||||
via `dropbox.upload_folder(...)`. There is no curated file list — whatever is in `output_dir`
|
||||
gets uploaded. So both files are missing simply because they are **no longer in `output_dir`**
|
||||
by the time distribution runs. The pipeline migrated from a monolith (one working dir held
|
||||
everything) to distributed GCE workers, narrowing what lands in `output_dir`:
|
||||
|
||||
### `.mov` screen videos — broke with PRs #647/#650 (2026-03-31)
|
||||
- Old: `screens_worker` generated `(Title).mov`/`(End).mov` locally; `video_worker` pulled
|
||||
them into `output_dir`.
|
||||
- Now: to fit Cloud Run's 2 GiB cap (#640), `screens_worker` emits **PNG only**
|
||||
(`intro_video_duration=0`), and `video_worker`/orchestrator download the **PNG**.
|
||||
- The GCE encoder (`backend/services/gce_encoding/main.py`, `generate_mov_from_png`)
|
||||
**still generates** `title.mov`/`end.mov` from the PNGs — but as throwaway intermediates in
|
||||
a `screens/` temp dir with generic names. Only the `outputs/` dir is uploaded to GCS
|
||||
`finals/`, and the orchestrator's `_download_gce_encoded_files` only maps back 5 named
|
||||
finals (`lossless_4k`, `lossy_4k`, `mkv`, `720p`, `with_vocals`). The standalone `.mov`s
|
||||
are never returned.
|
||||
|
||||
### Original input audio — never copied into `output_dir` in the distributed pipeline
|
||||
- Audio is downloaded by `audio_worker` early and stored in GCS:
|
||||
- Uploaded files → persisted to `jobs/{job_id}/input/{filename}` (because `uploads/` has a
|
||||
7-day lifecycle; `jobs/` is permanent).
|
||||
- URL/flacfetch jobs → `input_media_gcs_path` / `file_urls['input']`.
|
||||
- The old monolith left this file in the working dir → it ended up in the Dropbox folder.
|
||||
- The new orchestrator never copies it into `output_dir`.
|
||||
|
||||
## Decisions (from user, 2026-06-17)
|
||||
- **Scope:** Forward fix for all future jobs **+ backfill original audio** for past jobs where
|
||||
it still exists in GCS. **No `.mov` backfill** (can't regenerate without re-encoding).
|
||||
- **Audio in Dropbox:** Include the full original audio file (it's the archival master), always.
|
||||
|
||||
## Fix design
|
||||
|
||||
Both fixes converge on "ensure the file is in `output_dir` before `_upload_to_dropbox`."
|
||||
|
||||
### Part A — Restore `.mov` screen videos (forward only)
|
||||
|
||||
Extend the existing GCE-finals mechanism so the standalone `.mov`s come back like any other final.
|
||||
|
||||
1. **GCE worker** (`backend/services/gce_encoding/main.py`, `run_encoding`):
|
||||
After the title/end `.mov`s are generated (they already are, for concat), copy them into the
|
||||
`outputs/` dir with proper names `{base_name} (Title).mov` / `{base_name} (End).mov` before
|
||||
`output_files` is collected. They then upload to GCS `finals/` automatically via
|
||||
`output_dir.glob("*")`.
|
||||
2. **`EncodingOutput`** (`backend/services/encoding_interface.py`): add `title_mov_path`,
|
||||
`end_mov_path`.
|
||||
3. **`GCEEncodingBackend.encode`** (same file): in the filename→key mapping, match
|
||||
`(title).mov` / `(end).mov` → new keys (`title_mov`, `end_mov`); populate the new
|
||||
`EncodingOutput` fields.
|
||||
4. **Orchestrator** (`_download_gce_encoded_files`): add `('title_mov_path', ...)`,
|
||||
`('end_mov_path', ...)` to `file_mappings` so they download into `output_dir`. Failure to
|
||||
download is non-fatal (consistent with existing per-file handling).
|
||||
5. **Local encoding path** (`LocalEncodingService` / `LocalEncodingBackend`): verify during
|
||||
implementation whether the local fallback already leaves the `.mov`s in `output_dir`; if not,
|
||||
mirror the behavior. Production is GCE, so this is secondary.
|
||||
|
||||
### Part B — Restore original input audio (forward)
|
||||
|
||||
In the orchestrator's distribution stage, **before** `_upload_to_dropbox`, fetch the original
|
||||
source audio from GCS into `output_dir` with the historical source-tagged name.
|
||||
|
||||
- New helper (e.g. `_stage_original_audio_for_upload`) that:
|
||||
- Resolves the GCS source: `job.input_media_gcs_path` (uploads persisted to `jobs/`), else
|
||||
`file_urls['input']`/`['input']['audio']`.
|
||||
- Derives the source suffix from `job.audio_source_type`:
|
||||
- `file_upload` → `(uploaded)`
|
||||
- `audio_search` → `(flacfetch)`
|
||||
- `youtube_url` → `(YouTube)`
|
||||
- (matches the historical monolith convention: `{artist_title} (flacfetch)` etc.)
|
||||
- Downloads to `output_dir/{base_name} ({suffix}){ext}`, preserving the real extension
|
||||
(`.flac`/`.mp3`/`.webm`/...).
|
||||
- Non-fatal on failure (warn, continue) — Dropbox is already best-effort.
|
||||
|
||||
### Part C — Backfill original audio for past jobs (audio only)
|
||||
|
||||
One-off script (`backend/scripts/` or `scripts/`) — dry-run by default:
|
||||
- Query completed jobs since the cutoff (~Mar 2026) that have a `dropbox_link`/`brand_code`.
|
||||
- For each: locate original audio in GCS (skip if gone). Locate the Dropbox folder via
|
||||
`{dropbox_path}/{brand_code} - {artist} - {title}`. Upload the audio with the source-tagged
|
||||
name **only if not already present**.
|
||||
- Log a summary (restored / skipped-missing-audio / skipped-already-present / errors).
|
||||
|
||||
## Test plan
|
||||
- **Unit:** `GCEEncodingBackend.encode` maps `.mov` filenames → new `EncodingOutput` fields;
|
||||
source-suffix derivation for each `audio_source_type`; helper builds correct GCS source path
|
||||
and output filename per source type.
|
||||
- **Orchestrator:** `_download_gce_encoded_files` downloads the two new `.mov` mappings;
|
||||
`_stage_original_audio_for_upload` places the file in `output_dir` before upload (assert the
|
||||
whole-folder upload then includes it). Mock storage/Dropbox.
|
||||
- **GCE worker:** `run_encoding` copies `.mov`s into `outputs/` with proper names (assert
|
||||
collected `output_files` includes them).
|
||||
- **Manual:** run one real job end-to-end, confirm the Dropbox folder now contains
|
||||
`(Title).mov`, `(End).mov`, and `(flacfetch).flac`/`(uploaded).mp3`. Backfill dry-run on a
|
||||
small batch, then live on a couple of known folders.
|
||||
|
||||
## Files to touch
|
||||
- `backend/services/gce_encoding/main.py` (A1)
|
||||
- `backend/services/encoding_interface.py` (A2, A3)
|
||||
- `backend/workers/video_worker_orchestrator.py` (A4, B)
|
||||
- `backend/services/local_encoding_service.py` (A5, verify)
|
||||
- new backfill script (C)
|
||||
- tests under `backend/tests/`
|
||||
|
||||
## Bundled fix: ffmpeg interactive-prompt hang in `--finalise-only` (CLI)
|
||||
|
||||
Found while regenerating the missing `.mov`s locally. `karaoke_finalise.py` only added
|
||||
`-y` to `ffmpeg_base_command` when `non_interactive=True`. In interactive mode, a
|
||||
pre-existing output (e.g. a prior `(With Vocals).mp4`) made ffmpeg emit
|
||||
`... already exists. Overwrite? [y/N]` to captured stderr and block on stdin until the
|
||||
600s subprocess timeout — silently aborting finalisation at step 2/6 (only CDG/TXT zips
|
||||
produced; no Final video files). The output's mtime never changed, proving no encode ran.
|
||||
|
||||
Fix (in `karaoke_gen/karaoke_finalise/karaoke_finalise.py`):
|
||||
1. `-y` is now **unconditional** (re-runs overwrite intermediates idempotently).
|
||||
2. All ffmpeg `subprocess.run` calls pass `stdin=subprocess.DEVNULL` (defense-in-depth so
|
||||
ffmpeg can never block on a prompt — `execute_command` + both branches of
|
||||
`execute_command_with_fallback`).
|
||||
|
||||
Tests: `tests/unit/test_karaoke_finalise_ffmpeg_prompt.py`; updated two existing tests that
|
||||
asserted the old conditional-`-y` / no-stdin behaviour.
|
||||
|
||||
## Daily E2E verification (added per request)
|
||||
|
||||
So the daily GHA E2E catches this class of regression automatically:
|
||||
- `audio_download_worker` now records the original audio in `file_urls['input']['audio']`
|
||||
(URL/search jobs previously only set `input_media_gcs_path`), matching the upload path —
|
||||
so original audio shows consistently in the admin files manifest.
|
||||
- `_upload_results` (video_worker) registers `title_mov`/`end_mov` under `file_urls['finals']`
|
||||
(uploaded to `jobs/{id}/finals/title_mov.mov` etc.), so the screen MOVs are queryable +
|
||||
downloadable in the admin UI.
|
||||
- `happy-path-real-user.spec.ts` (daily E2E Stage 2) gained **STEP 10.5**: after completion it
|
||||
calls `GET /api/admin/jobs/{id}/files` and asserts the manifest contains
|
||||
`finals/title_mov`, `finals/end_mov`, `input/audio`, and `finals/lossless_4k_mp4` — failing
|
||||
loudly if any expected output is missing (vs. the old check that only opened one download).
|
||||
|
||||
Tests: `test_upload_results_screen_movs.py` (mov registration + skip-when-missing),
|
||||
extended `test_audio_download_worker.py` (input/audio recorded).
|
||||
|
||||
## Implementation notes (as built)
|
||||
- Part A files: `gce_encoding/main.py` (copy MOVs into `outputs/`), `encoding_interface.py`
|
||||
(`title_mov_path`/`end_mov_path` + list→dict mapping), `video_worker_orchestrator.py`
|
||||
(`OrchestratorResult.title_mov/end_mov` + download mappings).
|
||||
- Part B: `backend/services/original_audio.py` (new helper), orchestrator
|
||||
`_stage_original_audio_for_upload` + two `OrchestratorConfig` fields wired in
|
||||
`create_orchestrator_config_from_job`. Staged only when a folder upload will occur.
|
||||
- Part C: `backend/scripts/backfill_original_audio.py` (dry-run default; `--live`),
|
||||
`DropboxService.file_exists`.
|
||||
- Local encoding backend leaves `title_mov_path`/`end_mov_path` as None (production is GCE;
|
||||
the local CLI/monolith already writes `.mov`s into the track dir itself).
|
||||
|
||||
## Risks / notes
|
||||
- Dropbox storage grows (large FLACs re-included) — intended per decision.
|
||||
- `.mov` regeneration on GCE adds a couple of small copies, negligible cost.
|
||||
- Backfill depends on original audio still existing in GCS; older jobs may have none → skipped.
|
||||
- Keep all new steps non-fatal so distribution never fails for an archival-file hiccup.
|
||||
@@ -1,177 +0,0 @@
|
||||
# Lyrics Review: Auto-Applied Corrections UX
|
||||
|
||||
**Date:** 2026-06-18
|
||||
**Status:** Shipped (iterated live against prod backend)
|
||||
**Worktree:** `karaoke-gen-lyrics-autocorrect-ux` · branch `feat/sess-20260618-0022-lyrics-autocorrect-ux`
|
||||
|
||||
## Final shipped scope (beyond the original design below)
|
||||
|
||||
The design below captured the initial auto-correct-display work. The shipped PR
|
||||
also includes, from live iteration:
|
||||
|
||||
- **Toolbar consolidation:** the applied-corrections row was removed; the toolbar
|
||||
button reads **"Auto-corrected · N"** and opens the details panel on demand
|
||||
(per-item undo, **Re-run**, and **Revert all** auto-corrections).
|
||||
- **Long-word duration badge** moved *inside* the word pill, right-aligned.
|
||||
- **Timeline view replaced:** the old Text/Timeline + Simple/Advanced toggles are
|
||||
now a single **Simple / Advanced** toggle (`DurationTimelineView` deleted).
|
||||
Inline **>2s word / >2s gap** warnings show in both modes. **Advanced** mode
|
||||
stretches each word pill by its duration (flex-grow) so a segment fills the
|
||||
full width as a readable timeline, with gap **spacers** you can click to play
|
||||
from that point (hover shows a play icon).
|
||||
- **Auto-corrections are the review baseline:** the on-load apply rebases history
|
||||
(not an undoable edit), so no session/restore prompt appears unless there are
|
||||
genuine manual edits.
|
||||
- **Unified session restore:** removed the ad-hoc `window.confirm` localStorage
|
||||
path; the same `SessionRestoreDialog` is used everywhere — server-backed in
|
||||
cloud mode, localStorage-backed (`localSessionStore`) when running locally.
|
||||
- **Crash-reporter localhost guard:** local dev errors no longer POST to the prod
|
||||
error monitor.
|
||||
|
||||
## Problem
|
||||
|
||||
Since the AI auto-correct suggestions feature shipped (PR #809+, v0.177.0), the
|
||||
suggestions are good enough that the operator always clicks **Accept All**. The
|
||||
manual review of a separate suggestions panel (Image #1) is pure friction. We
|
||||
want the corrections applied automatically, and the *review* effort redirected
|
||||
to where it's actually needed: **re-checking word timing on the segments the AI
|
||||
touched** — especially where timing was estimated.
|
||||
|
||||
## Goals (operator's 5 points)
|
||||
|
||||
1. Remove the always-visible suggestions panel; collapse it behind a
|
||||
**"Show auto-corrections (N)"** toggle (details on demand).
|
||||
2. **Auto-apply** all suggestions on load — exactly today's *Accept All*
|
||||
semantics (apply all pending, conflict-group winners by consensus then
|
||||
confidence, default run settings).
|
||||
3. **Distinct colour** for AI-corrected words (purple) vs human-edited (green).
|
||||
4. **Compact, always-visible annotation** of what changed: a small bubble above
|
||||
each corrected span showing the *original transcription text* (Image #2),
|
||||
with extra vertical line spacing to fit.
|
||||
5. **Guidance + scrutiny**: tell operators to play and re-check sync on every
|
||||
edited/auto-corrected segment, and **visually flag words whose timing was
|
||||
estimated** (one word split into N evenly-spaced words) — those almost always
|
||||
need a timing nudge. A 1:1 word replacement keeps the original word's real
|
||||
timing and needs less scrutiny.
|
||||
|
||||
## Current architecture (what we build on)
|
||||
|
||||
- `useAutoCorrect` already **auto-runs one pass on load** (`autoRunOnLoad`);
|
||||
backend pre-generates + caches, so it's normally an instant cache hit.
|
||||
Suggestions land as a **pending layer** in `AutoCorrectPanel` (Image #1).
|
||||
- `acceptAll()` applies pending suggestions via `applySuggestion`, choosing
|
||||
conflict-group winners. Applied words are **new `Word`s** with
|
||||
`created_during_correction: true`.
|
||||
- `editedWordIds` (in `LyricsAnalyzer`) is a **diff of current data vs
|
||||
`history[0]`** (initial state). New AI word IDs fall into this set → they
|
||||
render with the same green/lime "edited" highlight as human edits. *This is
|
||||
why there's no visual distinction today.*
|
||||
- `autoCorrectApply.ts:distributeTimings` is the **estimated-timing signal**:
|
||||
for a replace, it spreads the removed span's `[start,end]` evenly across the
|
||||
new words. `newTexts.length > 1` ⇒ estimated. A 1:1 replace (or N→1 merge)
|
||||
inherits a real range ⇒ trustworthy. `insert_after` words are always synthetic
|
||||
⇒ estimated.
|
||||
- Re-applying a suggestion is **naturally idempotent**: `isSuggestionStale`
|
||||
checks the original word IDs still exist; once replaced they don't, so a
|
||||
re-run on reload applies nothing. This de-risks auto-apply-on-load against
|
||||
reloads and restored sessions.
|
||||
|
||||
## Data model
|
||||
|
||||
Stamp new fields on AI-applied `Word`s at apply time (`autoCorrectApply.ts`):
|
||||
|
||||
| Field | Meaning | Where set |
|
||||
|-------|---------|-----------|
|
||||
| `ai_corrected?: boolean` | This word came from an AI correction → purple + bubble | every new word in a replace/insert |
|
||||
| `original_text?: string` | The original transcription text for the whole span → bubble content | the **first** new word of the span only |
|
||||
| `timing_estimated?: boolean` | Timing was guessed by even-split / insert → scrutiny marker | per new word (`true` when `newTexts.length > 1` or `insert_after`) |
|
||||
| `correction_span_id?: string` | Groups the new words of one suggestion (= suggestion id) → one bubble per span, inline-undo lookup | every new word in the span |
|
||||
|
||||
`validation.ts` (zod) gains the same optional fields so saved/restored data
|
||||
round-trips.
|
||||
|
||||
**Purple vs green rule:** purple = `ai_corrected === true`. `editedWordIds`
|
||||
(green) excludes `ai_corrected` words. If an operator later hand-edits an AI
|
||||
word, it stays purple — the bubble (original transcription) and estimated marker
|
||||
remain accurate; this is an acceptable v1 simplification (rare, not harmful).
|
||||
|
||||
## Auto-apply flow
|
||||
|
||||
- Add an `autoApplyOnLoad` behaviour to `useAutoCorrect`: after the initial
|
||||
auto-run reaches `reviewing`, immediately run `acceptAll()` once (guarded by a
|
||||
ref), then leave the panel collapsed.
|
||||
- On reload of an already-corrected job: the stamped words are present (purple
|
||||
renders from the stamps, independent of the history diff); the re-run is stale
|
||||
⇒ `acceptAll` applies 0 ⇒ no spurious history entry. Idempotent.
|
||||
- **EditLog** still records `ai_suggestion_accept` per applied suggestion (now
|
||||
automatic). The meaningful negative signal becomes `ai_suggestion_undo`.
|
||||
|
||||
## Details panel + undo
|
||||
|
||||
- `AutoCorrectPanel` starts **collapsed**; header becomes
|
||||
*"Show auto-corrections (N)"*. Expanded: the existing list, each row with
|
||||
**Undo** (the accept/reject buttons are gone from the main flow).
|
||||
- **Inline undo:** clicking a purple word looks up its `correction_span_id` →
|
||||
`undoAccept(suggestionId)`. Works within the active review session (where the
|
||||
hook holds `undoInfos`). On a fresh reload the corrections are "baked"; the
|
||||
panel still lists them, and undo falls back to normal manual editing if no
|
||||
in-memory undo info exists. (v1 limitation — operators review in one sitting.)
|
||||
|
||||
## Rendering
|
||||
|
||||
**Text view only for v1** (`TranscriptionView` → `HighlightedText` →
|
||||
`WordComponent`). Thread the AI word data down:
|
||||
|
||||
- **Purple highlight** for `ai_corrected` words (new constant, e.g.
|
||||
`bg-purple-500/30`), visually distinct from green (`bg-green-500/25`) and
|
||||
user-edited lime (`bg-lime-400/40`).
|
||||
- **Bubble** above the first word of each span: tiny muted text = `original_text`
|
||||
with a small connector. `TranscriptionView` row gets extra top padding when a
|
||||
segment contains AI corrections (point 4: "more space between lines").
|
||||
- **Estimated-timing marker** on `timing_estimated` words: a distinct treatment
|
||||
(e.g. dashed amber underline/ring) vs the solid purple of trustworthy 1:1
|
||||
replacements. *Exact styling tuned live in the browser.*
|
||||
|
||||
The Duration/Timeline view keeps its current rendering for v1 (timing is already
|
||||
visible there); colour-only follow-up if wanted.
|
||||
|
||||
## Guidance (`GuidancePanel`)
|
||||
|
||||
- Add **purple → "AI-corrected"** to the colour legend.
|
||||
- Rewrite the workflow tips: instruct operators to **play each edited/AI-corrected
|
||||
segment and confirm the words still line up**, calling out that
|
||||
**[estimated]-marked words had their timing guessed and usually need a nudge**,
|
||||
while 1:1 replacements keep the original timing.
|
||||
- Optional summary line: *"N words auto-corrected · X with estimated timing —
|
||||
check these."*
|
||||
|
||||
## i18n
|
||||
|
||||
All new user-facing strings go in `frontend/messages/en.json` and are translated
|
||||
to all 33 locales via `python scripts/translate.py --messages-dir ./messages
|
||||
--target all` (CI enforces completeness).
|
||||
|
||||
## Testing
|
||||
|
||||
- **Unit (`autoCorrectApply`)**: stamping correctness for replace 1:1 (not
|
||||
estimated, original_text on first), replace 1→N (estimated), `insert_after`
|
||||
(estimated), `delete` (no new words), N→1 merge (not estimated).
|
||||
- **Unit (`editedWordIds`)**: excludes `ai_corrected` words; includes a
|
||||
hand-edited AI word if/where we decide it flips (v1: stays purple).
|
||||
- **Unit (auto-apply)**: applies all winners on load; idempotent when stale.
|
||||
- **Component**: `WordComponent` renders purple + bubble + estimated marker;
|
||||
`AutoCorrectPanel` collapsed by default, toggle reveals list with undo.
|
||||
- **Prod E2E** (`frontend/e2e/production/`): load a job with references, assert
|
||||
purple words + bubbles render and the panel is collapsed.
|
||||
|
||||
## Files
|
||||
|
||||
types.ts · validation.ts · utils/autoCorrectApply.ts · hooks/useAutoCorrect.ts ·
|
||||
LyricsAnalyzer.tsx · AutoCorrectPanel.tsx · TranscriptionView.tsx ·
|
||||
shared/HighlightedText.tsx · shared/Word.tsx · constants.ts · GuidancePanel.tsx ·
|
||||
messages/en.json (+ locales) · tests.
|
||||
|
||||
## Out of scope (v1)
|
||||
|
||||
Backend changes (auto-apply is frontend-only); purple/bubble in the Timeline
|
||||
view; durable cross-reload inline-undo of baked corrections.
|
||||
@@ -1,280 +0,0 @@
|
||||
# Bulk Mode — Design
|
||||
|
||||
**Date:** 2026-06-18
|
||||
**Status:** Approved (design); implementation pending
|
||||
**Author:** Andrew + Claude
|
||||
**Repos touched:** `karaoke-gen` (primary), `karaoke-decide` (one new endpoint)
|
||||
|
||||
## Problem
|
||||
|
||||
Andrew frequently wants to make karaoke versions of *whole albums* by an artist he
|
||||
loves, but:
|
||||
|
||||
1. He doesn't want to make a track if a **community version already exists** (he
|
||||
normally checks karaokenerds.com manually).
|
||||
2. He doesn't want the **"extra" tracks** often tacked onto albums (live versions,
|
||||
remixes, bonus tracks).
|
||||
3. He may want to **skip one or two songs** he dislikes.
|
||||
|
||||
Today the web UI only creates **one** karaoke job at a time through a 4-step wizard
|
||||
(Song Info → Choose Audio → Visibility → Customize & Create). Submitting an album
|
||||
means repeating that wizard ~12–20 times.
|
||||
|
||||
## Goal
|
||||
|
||||
Add a **"Bulk Mode"** tab to the job-submission flow that lets a user submit up to
|
||||
**100** jobs at once, with convenience settings that make a popular full-FLAC album
|
||||
submit with **no further prompts**, while obscure tracks fall into a short
|
||||
review queue.
|
||||
|
||||
## Decisions (locked with Andrew)
|
||||
|
||||
1. **Completion model:** *Auto + review queue.* Batch settings auto-complete every
|
||||
song they can: auto-pick the audio **only** when there is a confident
|
||||
lossless/FLAC match (tier 1), apply visibility, skip edit/customize. Songs
|
||||
without a confident lossless match are parked for a quick per-song selection.
|
||||
2. **KaraokeNerds availability source:** ~~the karaoke-decide BigQuery catalog via a
|
||||
new decide endpoint~~ **REVISED during implementation (2026-06-18):** reuse
|
||||
karaoke-gen's existing `karaokenerds_service.check_community_versions` scraper
|
||||
(ported from kjbox, already in prod) via a new **batch** helper. Rationale: it
|
||||
already exists and is tested, it carries the **`is_community` flag** that
|
||||
precisely matches rule #1 ("community-*created* version"), it has a 1h cache +
|
||||
graceful degradation, and it avoids a cross-repo deploy. decide's catalog is
|
||||
BigQuery *search*-based (no clean batch key-lookup) and lacks the community
|
||||
distinction. **No karaoke-decide change is needed.** (Flagged to Andrew.)
|
||||
3. **Credit gate:** **1 credit/song minimum** in both modes. Duration deltas for
|
||||
long tracks are charged per-song during processing as today.
|
||||
4. **Release selection (album mode):** **auto-pick the canonical release**, with a
|
||||
"different edition" switcher.
|
||||
5. **Search orchestration:** **backend batch.** A new endpoint creates one job per
|
||||
song, a worker runs each search server-side, auto-selects confident-lossless
|
||||
matches and parks the rest in the **existing `AWAITING_AUDIO_SELECTION` state**.
|
||||
The tab can be closed; searches continue server-side.
|
||||
|
||||
## Non-goals (v1 / YAGNI)
|
||||
|
||||
- Per-song customization or per-song visibility overrides (batch-wide only).
|
||||
- Reordering tracks; saved batch templates.
|
||||
- Non-album MusicBrainz sources (e.g. arbitrary playlists).
|
||||
- A "retry all failed" UI (individual job retry already exists).
|
||||
- A dedicated batch entity/collection (batch state is derived from `batch_id`).
|
||||
|
||||
---
|
||||
|
||||
## User experience
|
||||
|
||||
A new **Bulk Mode** tab sits next to the existing single-song "Create Karaoke
|
||||
Video" wizard. It has two sub-modes:
|
||||
|
||||
### By text
|
||||
- A repeatable list of artist/title rows (add / remove), max 100.
|
||||
- Each row gets an inline **KaraokeNerds availability badge** ("✓ community version
|
||||
exists — KV, KaraFun") so the user can deselect, but **nothing is auto-unchecked**
|
||||
(no album context to trust auto-deselection).
|
||||
|
||||
### By album / release
|
||||
1. **Artist lookup** (MusicBrainz artist search, reusing decide's pattern).
|
||||
2. **Canonical release auto-picked**; tracklist shown immediately. A "different
|
||||
edition" dropdown lets the user switch release (deluxe/remaster/region).
|
||||
3. **Tracklist table** with a checkbox per track. Default checked, **except:**
|
||||
- **Extras** (live/remix/bonus/compilation) start **unchecked** (rule #2).
|
||||
- Tracks with an **existing community version** start **unchecked** (rule #1),
|
||||
with a badge showing the brands.
|
||||
- User can re-tick anything (rule #3 — skip songs you dislike — is just
|
||||
unticking).
|
||||
|
||||
### Shared: batch settings + submit
|
||||
- **Batch settings** apply to the whole batch:
|
||||
- *Auto-pick best audio when a lossless/FLAC match is found* (the tier-1 rule;
|
||||
off → every song goes to the review queue).
|
||||
- *Visibility*: Public / Private (batch-wide).
|
||||
- *Skip audio edit* (on by default for bulk).
|
||||
- *Skip customization* (on by default; theme defaults).
|
||||
- **Live credit total** ("12 songs = 12 credits; you have 40").
|
||||
- **Submit** is disabled until `credits >= N`; if short, show the buy-credits
|
||||
dialog with the shortfall. **No jobs are created until the gate passes.**
|
||||
|
||||
### After submit
|
||||
- The user lands on a **batch progress** view (counts by state + per-job status).
|
||||
- Parked songs surface as the existing **"Select Audio"** button on each `JobCard`,
|
||||
opening the existing `AudioSearchDialog`. The "review queue" is just a filtered
|
||||
view of the batch's `awaiting_audio_selection` jobs.
|
||||
- Auto-selected songs proceed to completion, skipping edit/customize per settings.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Flow
|
||||
|
||||
```
|
||||
Select songs ──▶ Batch settings ──▶ Credit gate (N credits) ──▶ POST /api/bulk/submit
|
||||
│
|
||||
creates N jobs (1 credit each), stamps batch_id,
|
||||
triggers ONE bulk-search Cloud Run Job
|
||||
│
|
||||
bulk_search_worker iterates jobs (bounded concurrency)
|
||||
│
|
||||
┌──────────────────────────────────────────────────┴──────────────┐
|
||||
confident lossless (tier 1) no confident lossless
|
||||
auto-select + trigger_audio_download_worker park: AWAITING_AUDIO_SELECTION
|
||||
│ │
|
||||
normal processing Review queue (JobCard "Select
|
||||
(skip edit/customize per settings) Audio" → AudioSearchDialog)
|
||||
```
|
||||
|
||||
### Backend (karaoke-gen)
|
||||
|
||||
**Existing machinery reused (confirmed in research):**
|
||||
- `POST /api/audio-search/search` (`backend/api/routes/audio_search.py:583`) already
|
||||
creates a job, runs `audio_search_service.search_async`, stores results in
|
||||
`state_data.audio_search_results` (with `is_lossless` + `quality_data`), and parks
|
||||
in `AWAITING_AUDIO_SELECTION` when `auto_download=False`. The bulk worker mirrors
|
||||
this per song rather than calling the HTTP endpoint N times.
|
||||
- `POST /api/audio-search/{job_id}/select` (`:1132`) + `_validate_and_prepare_selection`
|
||||
(`:306`) + `_download_audio_and_trigger_workers` (`:372`) — used for the auto path.
|
||||
- `audio_search_service.select_best(...)` — best-result picker (extend with a
|
||||
tier/lossless check).
|
||||
- `worker_service._trigger_worker_cloud_run_job(job_id, cloud_run_job_name,
|
||||
worker_module)` — Cloud Run Job dispatch (survives instance shutdown).
|
||||
- `made_for_you` (`backend/api/routes/users.py:821` `_handle_made_for_you_order`) is
|
||||
the closest precedent: create job → search inline → park in
|
||||
`AWAITING_AUDIO_SELECTION`. Bulk is the multi-song, worker-driven version.
|
||||
- Credits: `user_service.check_credits` / `deduct_credits`; `job_manager.create_job`
|
||||
charges 1 credit atomically and raises `InsufficientCreditsError` if short.
|
||||
|
||||
**New:**
|
||||
- `POST /api/bulk/submit` — body: `{ mode, songs: [{artist,title,display_artist?,
|
||||
display_title?}], settings: {auto_select_if_lossless, is_private, skip_audio_edit,
|
||||
skip_customization} }`. Steps:
|
||||
1. Validate count (1..100) and `check_credits(user) >= N` (admin bypass as today).
|
||||
2. For each song, `job_manager.create_job(...)` with: display values, theme
|
||||
defaults, `auto_download=False`, `is_private`, plus `state_data.batch_id`,
|
||||
`state_data.bulk_settings`, `state_data.bulk_auto_select_if_lossless`,
|
||||
`state_data.bulk_skip_audio_edit`, `state_data.bulk_skip_customization`.
|
||||
(Each create charges 1 credit — this *is* the gate.)
|
||||
3. Trigger **one** `bulk-search` Cloud Run Job with the `batch_id`.
|
||||
4. Return `{ batch_id, job_ids, total }` quickly.
|
||||
- `bulk_search_worker` (`backend/workers/bulk_search_worker.py`, new) — takes a
|
||||
`batch_id`, queries its jobs needing search, processes them with bounded
|
||||
concurrency. Per job:
|
||||
- `transition_to_state(SEARCHING_AUDIO)`.
|
||||
- `audio_search_service.search_async(artist, title)`; on
|
||||
`NoResultsError`/`AudioSearchError` → park in `AWAITING_AUDIO_SELECTION`.
|
||||
- store results in `state_data` (same shape as `search_audio`).
|
||||
- **tier check** (see below): if confident lossless **and** auto-select enabled →
|
||||
`_validate_and_prepare_selection` + `trigger_audio_download_worker`; else
|
||||
`transition_to_state(AWAITING_AUDIO_SELECTION)`.
|
||||
- Worker is dispatched as a Cloud Run Job (new `bulk-search-job`) so it survives
|
||||
API instance scale-down; processes the whole batch in one execution.
|
||||
- `GET /api/bulk/{batch_id}` — returns counts by state + per-job `{job_id, artist,
|
||||
title, status, auto_selected}` for the batch progress UI. Derived by querying jobs
|
||||
with `state_data.batch_id == batch_id` (owned by the requesting user; admin sees
|
||||
all).
|
||||
|
||||
**Tier check (backend port):** a focused helper
|
||||
`audio_search_service.pick_auto_selection(results) -> Optional[int]` that returns the
|
||||
index to auto-select **only** when the best result is confidently lossless
|
||||
(tier-1-equivalent), else `None`. Mirrors the frontend rule in
|
||||
`frontend/lib/audio-search-utils.ts` (`getSearchConfidence` tier 1 = `BEST CHOICE`
|
||||
lossless category, no filename mismatch). Backend already has `is_lossless` +
|
||||
`quality_data`. **Maintenance seam:** two copies of the rule; add a fixture-based
|
||||
parity test.
|
||||
|
||||
**Job model / data:**
|
||||
- Add `batch_id: str | None` to the Job model (or keep entirely in `state_data`).
|
||||
If surfaced to the dashboard, **add `batch_id` to BOTH**:
|
||||
- `SUMMARY_FIELD_PATHS` in `backend/services/firestore_service.py`
|
||||
- `_SUMMARY_STATE_DATA_KEYS` in `backend/api/routes/jobs.py`
|
||||
and add a regression test (known summary-projection gotcha).
|
||||
|
||||
### karaoke-decide (one new endpoint)
|
||||
|
||||
- `POST /api/catalog/check-availability` — body `{tracks: [{artist,title}]}` →
|
||||
`{results: [{artist,title,available,brands,brand_count}]}`. Reuses the existing
|
||||
normalized in-memory catalog lookup (`karaoke_decide/services/catalog_lookup.py` /
|
||||
`track_matcher.py` `_make_key` normalization). Bounded input size (≤100).
|
||||
- karaoke-gen calls this server-side (during album tracklist load and text-row
|
||||
enrichment). On failure, degrade gracefully: mark availability "unknown", leave
|
||||
tracks checked.
|
||||
|
||||
### MusicBrainz release lookup (new, in karaoke-gen)
|
||||
|
||||
- New service `backend/services/musicbrainz_service.py` (httpx async, `User-Agent:
|
||||
"NomadKaraoke/1.0 (contact@nomadkaraoke.com)"`, polite ~1 req/s):
|
||||
- `search_artist(name) -> [{mbid,name,disambiguation}]`
|
||||
- `get_releases_for_artist(artist_mbid) -> [release-group summaries]` and
|
||||
canonical-release resolution (official, primary-type=Album, earliest standard
|
||||
edition).
|
||||
- `get_release_tracklist(release_mbid) -> {release, tracks: [{position,title,
|
||||
recording_mbid,disambiguation,length_ms,is_extra,extra_reason}]}` via
|
||||
`/ws/2/release/{mbid}?inc=recordings`.
|
||||
- **Extras detection** (`is_extra`): release secondary-types
|
||||
(`Live`/`Remix`/`Compilation`) + recording `disambiguation` + title regex
|
||||
(`(live)`, `(remix)`, `- Remastered`, `(bonus track)`, etc.). Conservative.
|
||||
- Exposed via `GET /api/bulk/album/artists?q=` and
|
||||
`GET /api/bulk/album/releases?artist_mbid=` and
|
||||
`GET /api/bulk/album/tracklist?release_mbid=` (or a single grouped route).
|
||||
Tracklist response is enriched with KaraokeNerds availability (decide call).
|
||||
|
||||
### Frontend (karaoke-gen)
|
||||
|
||||
- New tab in the job submission UI (alongside the guided wizard).
|
||||
- New components under `frontend/components/job/bulk/`:
|
||||
- `BulkMode.tsx` (container + tab switch text/album)
|
||||
- `BulkTextMode.tsx` (artist/title row list, max 100, availability badges)
|
||||
- `BulkAlbumMode.tsx` (artist search → release switcher → tracklist table with
|
||||
extras + availability defaults)
|
||||
- `BulkBatchSettings.tsx` (the four batch toggles)
|
||||
- `BulkSubmitBar.tsx` (live credit total + gated submit)
|
||||
- `BulkBatchProgress.tsx` (uses `GET /api/bulk/{batch_id}`)
|
||||
- **Review queue reuses** existing `JobCard` "Select Audio" → `AudioSearchDialog`
|
||||
(`frontend/components/audio-search/AudioSearchDialog.tsx`,
|
||||
`api.getAudioSearchResults` / `api.selectAudioResult`). Batch progress links to the
|
||||
jobs list filtered by `batch_id`.
|
||||
- New `api.ts` methods: `bulkSubmit`, `getBulkBatch`, `searchAlbumArtists`,
|
||||
`getAlbumReleases`, `getAlbumTracklist`.
|
||||
- All user-facing strings → `frontend/messages/en.json`, then
|
||||
`python frontend/scripts/translate.py --messages-dir frontend/messages
|
||||
--target all` (33 locales). decide endpoint returns data, not display strings.
|
||||
|
||||
---
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **Insufficient credits:** gate before any job created; show shortfall. (Admin
|
||||
bypasses, as elsewhere.)
|
||||
- **MusicBrainz / decide unavailable:** album lookup shows an error and falls back to
|
||||
text mode; availability marked "unknown" and tracks stay checked.
|
||||
- **No audio results for a song:** job parks in `AWAITING_AUDIO_SELECTION` with a
|
||||
"no automatic sources" message (same as made_for_you) — appears in review queue.
|
||||
- **Track too long (> 60 min):** that one job fails on duration pricing as today;
|
||||
rest of batch unaffected.
|
||||
- **Duplicate songs in the list:** allowed (user choice); no dedup in v1.
|
||||
- **Tab closed mid-search:** searches continue (Cloud Run Job); user returns to the
|
||||
batch view / dashboard later.
|
||||
- **Partial create failure** (credit race after gate): stop, report which jobs were
|
||||
created; created jobs are valid and proceed.
|
||||
|
||||
## Testing strategy
|
||||
|
||||
Per `docs/TESTING.md`:
|
||||
- **Backend unit:** `pick_auto_selection` tier rule (lossless→index, lossy→None,
|
||||
filename-mismatch→None); credit-gate math; extras detection; bulk worker
|
||||
auto-vs-park branching; `batch_id` summary-projection regression.
|
||||
- **Backend integration:** `POST /api/bulk/submit` happy path; insufficient-credits
|
||||
rejection (no jobs created); `GET /api/bulk/{batch_id}` shape.
|
||||
- **MusicBrainz service:** mocked-HTTP tests for canonical-release selection +
|
||||
tracklist parsing + extras flags.
|
||||
- **decide:** `check-availability` matching (hit/miss/normalization).
|
||||
- **Frontend Jest:** selection state, credit-total computation, default
|
||||
checked/unchecked logic.
|
||||
- **Production E2E (Playwright):** submit a small text batch; assert N jobs created
|
||||
with correct `batch_id` and states; assert credit gate blocks when short.
|
||||
|
||||
## Open maintenance notes
|
||||
|
||||
- Backend tier rule duplicates frontend `audio-search-utils.ts` — fixture parity
|
||||
test required; revisit if the rule grows.
|
||||
- MusicBrainz rate limits (1 req/s) — album lookups are interactive and low-volume;
|
||||
add simple in-process throttle + short cache.
|
||||
@@ -1,263 +0,0 @@
|
||||
# Bulk Mode Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use superpowers:executing-plans / subagent-driven-development. Steps use checkbox (`- [ ]`) syntax. TDD throughout: failing test → run → implement → run → commit.
|
||||
|
||||
**Goal:** Add a "Bulk Mode" tab to karaoke-gen that submits up to 100 karaoke jobs at once (by text or by album), auto-completing every song with a confident lossless match and parking the rest in the existing audio-selection review queue.
|
||||
|
||||
**Architecture:** A new backend `/api/bulk/submit` creates one job per song (1 credit each, gated upfront), then a `bulk_search_worker` Cloud Run Job runs each audio search server-side and either auto-selects (confident lossless) or parks the job in the existing `AWAITING_AUDIO_SELECTION` state. Album mode adds a MusicBrainz release-lookup service; KaraokeNerds availability comes from a new karaoke-decide endpoint. The frontend adds a Bulk Mode UI and reuses the existing `JobCard` → `AudioSearchDialog` for the review queue.
|
||||
|
||||
**Tech Stack:** FastAPI + Firestore + GCS + Cloud Run Jobs (gen backend), Next.js + next-intl (gen frontend), httpx (MusicBrainz), karaoke-decide BigQuery catalog.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- **Credit gate:** 1 credit/song minimum; check `>= N` before creating any job; admin bypasses (matches existing `job_manager.create_job`).
|
||||
- **Max batch size:** 100 songs (reject otherwise).
|
||||
- **i18n:** no hardcoded user-facing strings; add to `frontend/messages/en.json`, run `python frontend/scripts/translate.py --messages-dir frontend/messages --target all` (33 locales). CI fails on missing keys.
|
||||
- **Versioning:** bump `tool.poetry.version` in `pyproject.toml` (gen) and decide's version for code changes.
|
||||
- **Summary projection gotcha:** any job field the dashboard reads must be in BOTH `SUMMARY_FIELD_PATHS` (`backend/services/firestore_service.py`) and `_SUMMARY_STATE_DATA_KEYS` (`backend/api/routes/jobs.py`).
|
||||
- **Infra:** all GCP changes via Pulumi PRs; run `pulumi up` locally before merge.
|
||||
- **Tests:** `make test` must pass; user-facing features get a production Playwright E2E.
|
||||
- **MusicBrainz politeness:** `User-Agent: "NomadKaraoke/1.0 (contact@nomadkaraoke.com)"`, ~1 req/s throttle, short cache.
|
||||
- **No frontend/backend tier-rule divergence:** the backend `pick_auto_selection` rule mirrors `frontend/lib/audio-search-utils.ts` `getSearchConfidence` tier-1; fixture parity test required.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — karaoke-decide: KaraokeNerds availability endpoint (separate repo/PR)
|
||||
|
||||
Independent and shippable first. Work in a **new decide worktree** (`/startnomad decide bulk-availability` or `git worktree add`).
|
||||
|
||||
### Task 0.1: `POST /api/catalog/check-availability`
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke-decide/backend/api/routes/catalog.py` (add route)
|
||||
- Reuse: `karaoke_decide/services/catalog_lookup.py` / `track_matcher.py` (`_make_key` normalization, in-memory O(1) lookup)
|
||||
- Test: `karaoke-decide/tests/...` (mirror existing catalog route tests)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing catalog service singleton + normalized lookup.
|
||||
- Produces: `POST /api/catalog/check-availability` body `{ "tracks": [{"artist": str, "title": str}] }` (≤100) → `{ "results": [{"artist","title","available": bool, "brands": [str], "brand_count": int}] }`.
|
||||
|
||||
- [ ] **Step 1:** Write failing test: posting 2 tracks (one known-present in catalog fixture, one absent) returns `available=true` w/ brands for the first, `available=false` for the second; >100 tracks → 422.
|
||||
- [ ] **Step 2:** Run test, verify fail.
|
||||
- [ ] **Step 3:** Implement route: validate size, normalize each `artist/title` via existing `_make_key`, look up in in-memory catalog, map to `{available, brands, brand_count}` (brands from the catalog song's `brands`/`sources`).
|
||||
- [ ] **Step 4:** Run test, verify pass.
|
||||
- [ ] **Step 5:** Add API doc note in decide docs if applicable; bump version.
|
||||
- [ ] **Step 6:** Commit (`feat(catalog): batch karaoke availability check endpoint`).
|
||||
- [ ] **Step 7:** Ship decide PR (`/shipit` in decide worktree). Record prod URL of endpoint.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — gen backend foundations
|
||||
|
||||
### Task 1.1: `batch_id` on Job + summary projection
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/models/job.py` (add `batch_id: Optional[str] = None` to JobCreate/Job, or rely on `state_data`)
|
||||
- Modify: `backend/services/firestore_service.py` (`SUMMARY_FIELD_PATHS` += batch_id path)
|
||||
- Modify: `backend/api/routes/jobs.py` (`_SUMMARY_STATE_DATA_KEYS` += `batch_id` and bulk flags if in state_data)
|
||||
- Test: `backend/tests/test_*summary*` (regression asserting `batch_id` in `SUMMARY_FIELD_PATHS`)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: jobs carry `state_data.batch_id`, `state_data.bulk_settings` (`{auto_select_if_lossless, is_private, skip_audio_edit, skip_customization}`), surfaced in job summaries.
|
||||
|
||||
- [ ] **Step 1:** Failing test: a job created with `state_data.batch_id="b1"` appears with `batch_id` in its summary projection; assert `"...batch_id"` present in `SUMMARY_FIELD_PATHS`.
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Add field + both projection entries.
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Commit (`feat(jobs): add batch_id to job summary projection`).
|
||||
|
||||
### Task 1.2: `pick_auto_selection` tier helper (backend port of tier-1 rule)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/services/audio_search_service.py` (add `pick_auto_selection(results) -> Optional[int]`)
|
||||
- Reference: `frontend/lib/audio-search-utils.ts` (`categorizeResult`, `getBestResult`, `getSearchConfidence`)
|
||||
- Test: `backend/tests/test_audio_search_auto_selection.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: stored search-result dicts (with `is_lossless`, `quality_data`, `seeders`, `release_type`, `filename`/`target_file`).
|
||||
- Produces: `pick_auto_selection(results: list[dict]) -> Optional[int]` — returns index to auto-select **only** when best result is confidently lossless (tier-1: lossless "BEST CHOICE" category, non-vinyl, no filename mismatch); else `None`.
|
||||
|
||||
- [ ] **Step 1:** Failing tests (fixtures mirroring frontend cases): (a) lossless 50+ seeders studio album → returns its index; (b) only-lossy results → `None`; (c) lossless but filename mismatch → `None`; (d) only vinyl-rip lossless → `None` (surface noise); (e) empty → `None`.
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Implement the rule (port categorization + best-pick + tier-1 gate). Keep it small and pure.
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Commit (`feat(audio-search): backend tier-1 auto-selection helper`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — gen MusicBrainz service + album lookup endpoints
|
||||
|
||||
### Task 2.1: MusicBrainz service
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/services/musicbrainz_service.py`
|
||||
- Test: `backend/tests/test_musicbrainz_service.py` (mock httpx responses)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `search_artist(name: str) -> list[{mbid,name,disambiguation}]`
|
||||
- `get_releases_for_artist(artist_mbid: str) -> list[{release_group_mbid, title, primary_type, secondary_types, first_release_date, canonical_release_mbid}]`
|
||||
- `get_release_tracklist(release_mbid: str) -> {release:{mbid,title,...}, tracks:[{position,title,recording_mbid,disambiguation,length_ms,is_extra,extra_reason}]}`
|
||||
- `is_extra_track(release_secondary_types, recording_disambiguation, title) -> (bool, reason)`
|
||||
|
||||
- [ ] **Step 1:** Failing tests with recorded MusicBrainz JSON fixtures: artist search parse; canonical-release selection (official + primary-type=Album + earliest standard edition over a deluxe); tracklist parse with `length_ms`; `is_extra_track` flags live/remix/bonus via secondary-type, disambiguation, and title regex; conservative (plain studio track → not extra).
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Implement httpx async client (User-Agent, ~1 req/s throttle, small TTL cache), parsing + extras heuristics.
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Commit (`feat(musicbrainz): release lookup + extras detection service`).
|
||||
|
||||
### Task 2.2: decide availability client + album lookup routes
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/services/karaokenerds_availability_service.py` (httpx client → decide `check-availability`, graceful degrade to "unknown")
|
||||
- Create: `backend/api/routes/bulk.py` (album lookup routes; bulk submit added in Phase 3)
|
||||
- Modify: `backend/api/main.py` (register router) — confirm actual router registration file
|
||||
- Test: `backend/tests/test_bulk_album_lookup.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces (auth-required):
|
||||
- `GET /api/bulk/album/artists?q=` → `[{mbid,name,disambiguation}]`
|
||||
- `GET /api/bulk/album/releases?artist_mbid=` → release list incl canonical flag
|
||||
- `GET /api/bulk/album/tracklist?release_mbid=` → tracklist enriched with `{available,brands}` per track (decide call); on decide failure each track `available=null`.
|
||||
|
||||
- [ ] **Step 1:** Failing tests: artists route returns parsed list; tracklist route merges availability; decide-down → `available=null`, tracks still returned.
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Implement client + routes (decide base URL via settings/env; ≤100 tracks per availability call).
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Commit (`feat(bulk): album lookup routes with KaraokeNerds availability`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — gen bulk submit endpoint + credit gate
|
||||
|
||||
### Task 3.1: `POST /api/bulk/submit`
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/api/routes/bulk.py`
|
||||
- Reuse: `backend/services/job_manager.py` (`create_job`), `backend/services/user_service.py` (`check_credits`), `backend/services/worker_service.py` (new `trigger_bulk_search_worker` from Phase 4)
|
||||
- Test: `backend/tests/test_bulk_submit.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `pick_auto_selection` (1.2), `trigger_bulk_search_worker` (4.1).
|
||||
- Produces: `POST /api/bulk/submit` body `{ songs:[{artist,title,display_artist?,display_title?}], settings:{auto_select_if_lossless,is_private,skip_audio_edit,skip_customization} }` → `{ batch_id, job_ids, total }`.
|
||||
|
||||
- [ ] **Step 1:** Failing tests: (a) N songs with `credits>=N` → creates N jobs each tagged `batch_id` + bulk settings, returns ids, triggers one bulk-search worker (mock); (b) `credits<N` (non-admin) → 402, **zero jobs created**; (c) >100 → 422; (d) admin bypasses gate.
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Implement: validate; `check_credits` gate; generate `batch_id` (uuid); loop `create_job(auto_download=False, is_private, state_data{batch_id,bulk_settings})`; trigger worker; return.
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Commit (`feat(bulk): submit endpoint with upfront credit gate`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — gen bulk search worker + Cloud Run Job
|
||||
|
||||
### Task 4.1: `bulk_search_worker` + trigger
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/workers/bulk_search_worker.py` (mirror `audio_download_worker.py`)
|
||||
- Modify: `backend/services/worker_service.py` (add `trigger_bulk_search_worker(batch_id)` via `_trigger_worker_cloud_run_job`-style dispatch; note: keyed by batch_id not job_id — adapt or pass batch_id in payload)
|
||||
- Modify: `infrastructure/` (Pulumi: add `bulk-search-job` Cloud Run Job)
|
||||
- Test: `backend/tests/test_bulk_search_worker.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `audio_search_service.search_async`, `pick_auto_selection`, `_validate_and_prepare_selection` + `_download_audio_and_trigger_workers` (from `audio_search.py` — extract shared helpers if needed), `trigger_audio_download_worker`.
|
||||
- Produces: processes all jobs with `state_data.batch_id == batch_id` needing search.
|
||||
|
||||
- [ ] **Step 1:** Failing tests: (a) job whose search yields confident-lossless → auto-selected + download worker triggered; (b) job whose search yields only lossy → parked in `AWAITING_AUDIO_SELECTION` with results stored; (c) `NoResultsError` → parked with "no sources" message; (d) `auto_select_if_lossless=false` → always parked even if lossless.
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Implement worker loop (bounded concurrency, e.g. 4); per-job: search → store results → `pick_auto_selection` (respecting batch setting) → auto-select or park. Reuse existing select/download helpers (refactor `audio_search.py` to expose them if currently inline).
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Add Cloud Run Job in Pulumi; `pulumi up` locally (or note for ship step).
|
||||
- [ ] **Step 6:** Commit (`feat(bulk): server-side search worker with auto-select/park`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — gen batch progress endpoint
|
||||
|
||||
### Task 5.1: `GET /api/bulk/{batch_id}`
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/api/routes/bulk.py`
|
||||
- Test: `backend/tests/test_bulk_progress.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `{ batch_id, total, counts:{searching,awaiting_selection,processing,complete,failed}, jobs:[{job_id,artist,title,status,auto_selected}] }`. Scoped to requesting user (admin sees any).
|
||||
|
||||
- [ ] **Step 1:** Failing test: jobs in mixed states under a batch_id summarize correctly; other users can't read another's batch.
|
||||
- [ ] **Step 2:** Run, fail.
|
||||
- [ ] **Step 3:** Implement query by `state_data.batch_id` + ownership check.
|
||||
- [ ] **Step 4:** Run, pass.
|
||||
- [ ] **Step 5:** Commit (`feat(bulk): batch progress endpoint`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — gen frontend Bulk Mode UI
|
||||
|
||||
### Task 6.1: api client methods + types
|
||||
|
||||
**Files:** Modify `frontend/lib/api.ts`; Test `frontend/__tests__/...`
|
||||
- [ ] Add `bulkSubmit`, `getBulkBatch`, `searchAlbumArtists`, `getAlbumReleases`, `getAlbumTracklist` + types. Commit.
|
||||
|
||||
### Task 6.2: Bulk Mode tab + container
|
||||
|
||||
**Files:** Create `frontend/components/job/bulk/BulkMode.tsx`; modify the job-submission parent to add the tab next to the guided wizard.
|
||||
- [ ] Tab switch (Single / Bulk); Bulk has Text/Album sub-tabs. Strings → en.json. Commit.
|
||||
|
||||
### Task 6.3: Text mode
|
||||
|
||||
**Files:** Create `frontend/components/job/bulk/BulkTextMode.tsx`; Test (Jest).
|
||||
- [ ] Add/remove artist/title rows (max 100); per-row availability badge (debounced decide check via gen route); selection state. Tests for cap + selection. Commit.
|
||||
|
||||
### Task 6.4: Album mode
|
||||
|
||||
**Files:** Create `frontend/components/job/bulk/BulkAlbumMode.tsx`; Test (Jest).
|
||||
- [ ] Artist search → canonical release auto-loaded + edition switcher → tracklist table; default-unchecked for `is_extra` and `available` tracks; badges; re-tick allowed. Tests for default check/uncheck logic. Commit.
|
||||
|
||||
### Task 6.5: Batch settings + submit bar
|
||||
|
||||
**Files:** Create `frontend/components/job/bulk/BulkBatchSettings.tsx`, `BulkSubmitBar.tsx`; Test (Jest).
|
||||
- [ ] Four toggles (auto-pick lossless, visibility, skip edit, skip customize); live credit total; submit disabled until `credits>=N`, else buy-credits dialog. Tests for credit-total + gate. Commit.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7 — gen frontend batch progress + review queue
|
||||
|
||||
### Task 7.1: Batch progress + review queue wiring
|
||||
|
||||
**Files:** Create `frontend/components/job/bulk/BulkBatchProgress.tsx`; reuse `JobCard` "Select Audio" → `AudioSearchDialog`; link to jobs list filtered by `batch_id`.
|
||||
- [ ] After submit, show batch progress (poll `getBulkBatch`); parked jobs reachable via existing Select Audio dialog. Strings → en.json. Commit.
|
||||
|
||||
---
|
||||
|
||||
## Phase 8 — i18n, E2E, docs, ship
|
||||
|
||||
- [ ] **8.1** Run `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`; commit locale files.
|
||||
- [ ] **8.2** Production Playwright E2E (`frontend/e2e/production/bulk-mode.spec.ts`): submit a small **text** batch (2–3 songs) as admin; assert N jobs created with the shared `batch_id` and expected states; assert credit gate blocks when short (separate low-credit user or mocked). Commit.
|
||||
- [ ] **8.3** Docs: update `docs/API.md` (new routes), `docs/README.md` (feature status), add `docs/LESSONS-LEARNED.md` note re: backend/frontend tier-rule seam. Commit.
|
||||
- [ ] **8.4** Bump `pyproject.toml` version.
|
||||
- [ ] **8.5** `make test` green; `/test-review`; `/docs-review`; `/coderabbit`; `/pr` (gen). Ensure decide PR (Phase 0) merged + deployed first so availability works in prod.
|
||||
- [ ] **8.6** `/shipit` → merge → wait for deploy → verify prod (`pulumi up` applied for the new Cloud Run Job) → run the prod E2E.
|
||||
|
||||
---
|
||||
|
||||
## Self-review (coverage check)
|
||||
|
||||
- Rule #1 (skip community versions) → Phase 0 + 2.2 + 6.3/6.4 default-uncheck. ✓
|
||||
- Rule #2 (skip extras) → 2.1 `is_extra_track` + 6.4 default-uncheck. ✓
|
||||
- Rule #3 (skip disliked) → 6.3/6.4 manual untick. ✓
|
||||
- Auto + review queue → 4.1 auto/park + 7.1 review queue reuse. ✓
|
||||
- decide BigQuery source → Phase 0. ✓
|
||||
- 1 credit/song gate → 3.1. ✓
|
||||
- Canonical release + switch → 2.1 + 6.4. ✓
|
||||
- Backend batch + closeable tab → 4.1 Cloud Run Job. ✓
|
||||
- Max 100 → 3.1 + 6.3. ✓
|
||||
- Summary projection gotcha → 1.1. ✓
|
||||
- i18n 33 locales → 8.1. ✓
|
||||
- Production E2E → 8.2. ✓
|
||||
|
||||
## Notes for executor
|
||||
|
||||
- `_validate_and_prepare_selection` / `_download_audio_and_trigger_workers` currently live in `backend/api/routes/audio_search.py`; if reused by the worker, extract to a service to avoid importing route internals.
|
||||
- `trigger_bulk_search_worker` is keyed by `batch_id` (not `job_id`); the existing `_trigger_worker_cloud_run_job` passes `job_id` — adapt the dispatch to pass `batch_id` in the worker payload/args.
|
||||
- Confirm the FastAPI router registration file before adding `bulk.py` (search for where `audio_search` router is included).
|
||||
- decide base URL for gen → add a setting/env var; default to prod decide.
|
||||
@@ -1,96 +0,0 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Tests that the API client attaches the X-Tenant-ID header on white-label tenant
|
||||
* portals (sourced from window.__TENANT_CONFIG__) and omits it on the consumer build.
|
||||
*
|
||||
* Regression guard for the root-cause bug: the frontend never sent X-Tenant-ID, so the
|
||||
* shared api.nomadkaraoke.com backend could not detect the tenant and every tenant-portal
|
||||
* job/sign-in silently fell back to consumer behavior (0 tenant jobs ever ran in prod).
|
||||
*/
|
||||
|
||||
import { api, getTenantId } from '@/lib/api'
|
||||
|
||||
function setEdgeTenant(id: string | null) {
|
||||
if (id) {
|
||||
;(window as any).__TENANT_CONFIG__ = {
|
||||
tenant: { id, name: id, subdomain: `${id}.nomadkaraoke.com` },
|
||||
is_default: false,
|
||||
}
|
||||
} else {
|
||||
delete (window as any).__TENANT_CONFIG__
|
||||
}
|
||||
}
|
||||
|
||||
describe('getTenantId', () => {
|
||||
afterEach(() => setEdgeTenant(null))
|
||||
|
||||
it('returns null when no tenant config is present (consumer build)', () => {
|
||||
setEdgeTenant(null)
|
||||
expect(getTenantId()).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the tenant id from window.__TENANT_CONFIG__', () => {
|
||||
setEdgeTenant('vocalstar')
|
||||
expect(getTenantId()).toBe('vocalstar')
|
||||
})
|
||||
|
||||
it('returns null when the injected config has no tenant (default/consumer domain)', () => {
|
||||
;(window as any).__TENANT_CONFIG__ = { tenant: null, is_default: true }
|
||||
expect(getTenantId()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('X-Tenant-ID header attachment', () => {
|
||||
const fetchMock = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
;(global as any).fetch = fetchMock
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) })
|
||||
})
|
||||
|
||||
afterEach(() => setEdgeTenant(null))
|
||||
|
||||
it('attaches X-Tenant-ID to authenticated requests (createJobWithUploadUrls) on a tenant portal', async () => {
|
||||
setEdgeTenant('vocalstar')
|
||||
window.localStorage.setItem('karaoke_access_token', 'tok-123')
|
||||
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ job_id: 'j1', upload_urls: [] }),
|
||||
})
|
||||
|
||||
await api.createJobWithUploadUrls('Adele', 'Hello', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.headers['X-Tenant-ID']).toBe('vocalstar')
|
||||
expect(init.headers['Authorization']).toBe('Bearer tok-123')
|
||||
|
||||
window.localStorage.removeItem('karaoke_access_token')
|
||||
})
|
||||
|
||||
it('attaches X-Tenant-ID to the magic-link request on a tenant portal', async () => {
|
||||
setEdgeTenant('singa')
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
|
||||
|
||||
await api.sendMagicLink('user@singa.com')
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toMatch(/\/api\/users\/auth\/magic-link$/)
|
||||
expect(init.headers['X-Tenant-ID']).toBe('singa')
|
||||
})
|
||||
|
||||
it('does NOT attach X-Tenant-ID on the consumer build', async () => {
|
||||
setEdgeTenant(null)
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
|
||||
|
||||
await api.sendMagicLink('user@example.com')
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.headers['X-Tenant-ID']).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
import { shouldSelectTrack, canSubmitBatch } from "@/components/job/bulk/types"
|
||||
|
||||
describe("shouldSelectTrack", () => {
|
||||
it("selects a plain studio track by default", () => {
|
||||
expect(shouldSelectTrack({ is_extra: false, available: false })).toBe(true)
|
||||
})
|
||||
it("does NOT select an extra (live/remix/bonus) track", () => {
|
||||
expect(shouldSelectTrack({ is_extra: true, available: false })).toBe(false)
|
||||
})
|
||||
it("does NOT select a track that already has a community version", () => {
|
||||
expect(shouldSelectTrack({ is_extra: false, available: true })).toBe(false)
|
||||
})
|
||||
it("treats unknown availability as selectable", () => {
|
||||
expect(shouldSelectTrack({ is_extra: false, available: null })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("canSubmitBatch", () => {
|
||||
it("blocks when nothing selected", () => {
|
||||
expect(canSubmitBatch(0, 10, false, 100)).toBe(false)
|
||||
})
|
||||
it("blocks over the max", () => {
|
||||
expect(canSubmitBatch(101, 1000, false, 100)).toBe(false)
|
||||
})
|
||||
it("blocks when credits are short", () => {
|
||||
expect(canSubmitBatch(5, 4, false, 100)).toBe(false)
|
||||
})
|
||||
it("allows when credits cover the count", () => {
|
||||
expect(canSubmitBatch(5, 5, false, 100)).toBe(true)
|
||||
})
|
||||
it("admins bypass the credit gate", () => {
|
||||
expect(canSubmitBatch(50, 0, true, 100)).toBe(true)
|
||||
})
|
||||
it("unknown balance does not block", () => {
|
||||
expect(canSubmitBatch(5, null, false, 100)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -94,15 +94,6 @@ describe('crash-reporter.reportClientError', () => {
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not report errors from a localhost origin', async () => {
|
||||
await reportClientError({
|
||||
error: new TypeError('dev boom'),
|
||||
source: 'test',
|
||||
context: { href: 'http://localhost:3000/en/app/jobs/', userAgent: 'ua' },
|
||||
})
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not throw on fetch failure', async () => {
|
||||
fetchMock.mockRejectedValueOnce(new Error('offline'))
|
||||
await expect(
|
||||
|
||||
@@ -22,7 +22,6 @@ import { sortJobsByDate } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { BulkMode } from "@/components/job/bulk/BulkMode"
|
||||
import { TenantJobFlow } from "@/components/job/TenantJobFlow"
|
||||
import { AutoProcessor } from "@/components/AutoProcessor"
|
||||
import { VersionFooter } from "@/components/version-footer"
|
||||
@@ -50,7 +49,6 @@ function AppPageContent() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [allJobs, setAllJobs] = useState<Job[]>([])
|
||||
const [submitMode, setSubmitMode] = useState<"single" | "bulk">("single")
|
||||
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true)
|
||||
const [hasFetchedSuccessfully, setHasFetchedSuccessfully] = useState(false)
|
||||
@@ -338,52 +336,18 @@ function AppPageContent() {
|
||||
{/* Submit Job Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<CardTitle style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? t('createKaraokeVideo') : t('submitTrack')}
|
||||
</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{isDefaultTenant
|
||||
? t('createDescription')
|
||||
: t('submitDescription')}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{isDefaultTenant && (
|
||||
<div
|
||||
className="shrink-0 inline-flex rounded-md p-0.5"
|
||||
style={{ backgroundColor: 'rgba(255,255,255,0.06)' }}
|
||||
role="tablist"
|
||||
aria-label={t('submitModeToggle')}
|
||||
>
|
||||
{(['single', 'bulk'] as const).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={submitMode === m}
|
||||
onClick={() => setSubmitMode(m)}
|
||||
className="px-2.5 py-1 rounded text-xs font-medium transition-colors"
|
||||
style={
|
||||
submitMode === m
|
||||
? { backgroundColor: 'var(--card)', color: 'var(--text)' }
|
||||
: { color: 'var(--text-muted)', background: 'transparent' }
|
||||
}
|
||||
>
|
||||
{m === 'single' ? t('singleMode') : t('bulkMode')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? t('createKaraokeVideo') : t('submitTrack')}
|
||||
</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{isDefaultTenant
|
||||
? t('createDescription')
|
||||
: t('submitDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isDefaultTenant ? (
|
||||
submitMode === 'bulk' ? (
|
||||
<BulkMode onJobsChanged={loadJobs} />
|
||||
) : (
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
)
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
) : (
|
||||
<TenantJobFlow onJobCreated={loadJobs} />
|
||||
)}
|
||||
|
||||
@@ -384,12 +384,6 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
? (audioInfo?.original_duration_seconds ?? 0)
|
||||
: (audioInfo?.current_duration_seconds ?? 0)
|
||||
|
||||
// Trim/Fade are edge actions — only valid when the selection touches the
|
||||
// very start or very end of the track (1s tolerance, matching the
|
||||
// server-side anchoring in audio_edit_service.fade_region).
|
||||
const atStartEdge = !!selection && selection.startSeconds < 1
|
||||
const atEndEdge = !!selection && selection.endSeconds > currentDuration - 1
|
||||
|
||||
// ─── Auto-save ─────────────────────────────────────────────────
|
||||
|
||||
const { saveSession } = useAudioEditAutoSave({
|
||||
@@ -890,52 +884,54 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
{formatTimePrecise(selection.startSeconds)} - {formatTimePrecise(selection.endSeconds)}
|
||||
({formatTimePrecise(selection.endSeconds - selection.startSeconds)})
|
||||
</span>
|
||||
{/* Trim/Fade are edge actions: enabled only when the selection
|
||||
touches the very start (start) or very end (end) of the track.
|
||||
Always rendered (disabled off-edge) so the actions stay
|
||||
discoverable, with a tooltip explaining how to enable them. */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atStartEdge}
|
||||
onClick={handleTrimStart}
|
||||
className="text-xs h-7"
|
||||
title={atStartEdge ? t('trimStartSelection') : t('trimStartDisabledHint')}
|
||||
>
|
||||
{t('trimStart')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atStartEdge}
|
||||
onClick={handleFadeIn}
|
||||
className="text-xs h-7"
|
||||
title={atStartEdge ? t('fadeInSelection') : t('fadeInDisabledHint')}
|
||||
>
|
||||
<TrendingUp className="w-3 h-3 mr-1" />
|
||||
{t('fadeIn')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atEndEdge}
|
||||
onClick={handleTrimEnd}
|
||||
className="text-xs h-7"
|
||||
title={atEndEdge ? t('trimEndSelection') : t('trimEndDisabledHint')}
|
||||
>
|
||||
{t('trimEnd')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating || !atEndEdge}
|
||||
onClick={handleFadeOut}
|
||||
className="text-xs h-7"
|
||||
title={atEndEdge ? t('fadeOutSelection') : t('fadeOutDisabledHint')}
|
||||
>
|
||||
<TrendingDown className="w-3 h-3 mr-1" />
|
||||
{t('fadeOut')}
|
||||
</Button>
|
||||
{selection.startSeconds < 1 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating}
|
||||
onClick={handleTrimStart}
|
||||
className="text-xs h-7"
|
||||
>
|
||||
{t('trimStart')}
|
||||
</Button>
|
||||
)}
|
||||
{selection.startSeconds < 1 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating}
|
||||
onClick={handleFadeIn}
|
||||
className="text-xs h-7"
|
||||
title={t('fadeInSelection')}
|
||||
>
|
||||
<TrendingUp className="w-3 h-3 mr-1" />
|
||||
{t('fadeIn')}
|
||||
</Button>
|
||||
)}
|
||||
{selection.endSeconds > currentDuration - 1 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating}
|
||||
onClick={handleTrimEnd}
|
||||
className="text-xs h-7"
|
||||
>
|
||||
{t('trimEnd')}
|
||||
</Button>
|
||||
)}
|
||||
{selection.endSeconds > currentDuration - 1 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isOperating}
|
||||
onClick={handleFadeOut}
|
||||
className="text-xs h-7"
|
||||
title={t('fadeOutSelection')}
|
||||
>
|
||||
<TrendingDown className="w-3 h-3 mr-1" />
|
||||
{t('fadeOut')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
@@ -391,36 +391,6 @@ describe("AudioEditor", () => {
|
||||
})
|
||||
})
|
||||
|
||||
it("renders Trim/Fade buttons disabled for a mid-track selection", async () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const canvas = document.querySelector("canvas") as HTMLCanvasElement
|
||||
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
|
||||
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect)
|
||||
|
||||
// Drag a mid-track region (duration 200, width 1000 → 100px≈20s, 300px≈60s)
|
||||
fireEvent.mouseDown(canvas, { clientX: 100 })
|
||||
fireEvent.mouseMove(canvas, { clientX: 300 })
|
||||
fireEvent.mouseUp(canvas, { clientX: 300 })
|
||||
|
||||
// Buttons stay visible (discoverable) but disabled off-edge
|
||||
const fadeIn = (await screen.findByText("Fade In")).closest("button")
|
||||
const fadeOut = screen.getByText("Fade Out").closest("button")
|
||||
const trimStart = screen.getByText("Trim Start").closest("button")
|
||||
const trimEnd = screen.getByText("Trim End").closest("button")
|
||||
expect(fadeIn).toBeDisabled()
|
||||
expect(fadeOut).toBeDisabled()
|
||||
expect(trimStart).toBeDisabled()
|
||||
expect(trimEnd).toBeDisabled()
|
||||
})
|
||||
|
||||
it("shows playback controls", async () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useState, useCallback } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
|
||||
interface KaraokeBackgroundPreviewProps {
|
||||
backgroundUrl?: string // Object URL from File, or undefined for solid color
|
||||
@@ -11,25 +9,9 @@ interface KaraokeBackgroundPreviewProps {
|
||||
unsungColor?: string // Color for unsung lyrics
|
||||
}
|
||||
|
||||
// 4K coordinate space (the sample lyrics are laid out in it); the canvas renders at
|
||||
// the much smaller preview resolution below via a scale transform.
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
const PREVIEW_W = 960
|
||||
const PREVIEW_H = 540
|
||||
const MAX_DPR = 2
|
||||
|
||||
// Low-res background for the preview (the 4K asset stays for the real render path).
|
||||
const KARAOKE_BG_SRC = "/karaoke-bg-preview.png"
|
||||
|
||||
/** Warm the karaoke background cache ahead of time (e.g. on Step 2). */
|
||||
export function preloadKaraokeBg(): void {
|
||||
if (typeof window === "undefined") return
|
||||
const img = new Image()
|
||||
img.src = KARAOKE_BG_SRC
|
||||
}
|
||||
|
||||
// 4 sample lines to match real karaoke video rendering
|
||||
const SAMPLE_LINES = [
|
||||
"Don't say that you don't understand",
|
||||
@@ -48,9 +30,7 @@ export function KaraokeBackgroundPreview({
|
||||
sungColor,
|
||||
unsungColor,
|
||||
}: KaraokeBackgroundPreviewProps) {
|
||||
const t = useTranslations("karaokeBackgroundPreview")
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
const effectiveSungColor = sungColor || DEFAULT_SUNG_COLOR
|
||||
const effectiveUnsungColor = unsungColor || DEFAULT_UNSUNG_COLOR
|
||||
@@ -58,21 +38,11 @@ export function KaraokeBackgroundPreview({
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
// Size the backing store to the preview resolution (dpr-aware, capped) and
|
||||
// scale the 4K coordinate space down to it.
|
||||
const dpr = Math.min((typeof window !== "undefined" && window.devicePixelRatio) || 1, MAX_DPR)
|
||||
const cw = Math.round(PREVIEW_W * dpr)
|
||||
const ch = Math.round(PREVIEW_H * dpr)
|
||||
if (canvas.width !== cw) canvas.width = cw
|
||||
if (canvas.height !== ch) canvas.height = ch
|
||||
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
ctx.setTransform(cw / CANVAS_W, 0, 0, ch / CANVAS_H, 0, 0)
|
||||
|
||||
// Draw background: custom image > solid color > default Nomad theme image
|
||||
const bgSrc = backgroundUrl || (backgroundColor ? null : KARAOKE_BG_SRC)
|
||||
const bgSrc = backgroundUrl || (backgroundColor ? null : "/karaoke-bg.png")
|
||||
if (bgSrc) {
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
@@ -146,8 +116,6 @@ export function KaraokeBackgroundPreview({
|
||||
ctx.fillText(line, centerX, y)
|
||||
}
|
||||
})
|
||||
|
||||
setReady(true)
|
||||
}, [backgroundUrl, backgroundColor, effectiveSungColor, effectiveUnsungColor])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -155,26 +123,15 @@ export function KaraokeBackgroundPreview({
|
||||
}, [draw])
|
||||
|
||||
return (
|
||||
<div className="relative w-full" style={{ aspectRatio: "16/9" }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={PREVIEW_W}
|
||||
height={PREVIEW_H}
|
||||
className="w-full h-full rounded-lg"
|
||||
style={{
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
{!ready && (
|
||||
<div
|
||||
className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg"
|
||||
style={{ backgroundColor: "var(--secondary)", color: "var(--text-muted)" }}
|
||||
data-testid="karaoke-background-preview-loading"
|
||||
>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span className="text-xs">{t('loading')}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={CANVAS_W}
|
||||
height={CANVAS_H}
|
||||
className="w-full rounded-lg"
|
||||
style={{
|
||||
aspectRatio: "16/9",
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useState, useCallback } from "react"
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
interface TitleCardPreviewProps {
|
||||
artist: string
|
||||
@@ -20,19 +19,9 @@ interface TitleCardPreviewProps {
|
||||
// - Title: white (#ffffff), uppercase, region 370,980,3100,350
|
||||
// - Artist: golden yellow (#ffdf6b), uppercase, region 370,1400,3100,450
|
||||
|
||||
// Coordinate space the title-card layout is authored in (style_params.json is in
|
||||
// 4K). All region/font constants below are in this space; the canvas renders at a
|
||||
// much smaller preview resolution (see PREVIEW_*) via a scale transform, so a small
|
||||
// thumbnail no longer allocates a 4K (3840×2160) backing store + 4K PNG.
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
// Actual canvas backing-store resolution for the preview (multiplied by the
|
||||
// device pixel ratio, capped, at draw time). Plenty sharp for the thumbnail.
|
||||
const PREVIEW_W = 960
|
||||
const PREVIEW_H = 540
|
||||
const MAX_DPR = 2
|
||||
|
||||
// Title region: x=370, y=980, w=3100, h=350
|
||||
const TITLE_X = 370
|
||||
const TITLE_Y = 980
|
||||
@@ -48,9 +37,6 @@ const ARTIST_H = 450
|
||||
const TITLE_COLOR = "#ffffff"
|
||||
const ARTIST_COLOR = "#ffdf6b"
|
||||
|
||||
// Low-res background sized for the preview (the full 4K asset stays for the real
|
||||
// render path). Cached at module scope so it loads once per session.
|
||||
const TITLE_CARD_BG_SRC = "/title-card-bg-preview.png"
|
||||
let bgImageCache: HTMLImageElement | null = null
|
||||
|
||||
function loadBgImage(): Promise<HTMLImageElement> {
|
||||
@@ -62,21 +48,10 @@ function loadBgImage(): Promise<HTMLImageElement> {
|
||||
resolve(img)
|
||||
}
|
||||
img.onerror = reject
|
||||
img.src = TITLE_CARD_BG_SRC
|
||||
img.src = "/title-card-bg.png"
|
||||
})
|
||||
}
|
||||
|
||||
/** Warm the title-card background cache ahead of time (e.g. on Step 2) so the
|
||||
* Step 4 preview paints instantly. Safe to call repeatedly; failures are ignored. */
|
||||
export function preloadTitleCardBg(): void {
|
||||
void loadBgImage().catch(() => {})
|
||||
}
|
||||
|
||||
/** Test-only: clear the module-level bg cache so each test starts from a cold load. */
|
||||
export function __resetTitleCardBgCacheForTest(): void {
|
||||
bgImageCache = null
|
||||
}
|
||||
|
||||
function fitText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
@@ -151,7 +126,6 @@ function drawTextBlock(
|
||||
export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroundColor, titleColor, artistColor }: TitleCardPreviewProps) {
|
||||
const t = useTranslations('titleCardPreview')
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
const effectiveTitleColor = titleColor || TITLE_COLOR
|
||||
const effectiveArtistColor = artistColor || ARTIST_COLOR
|
||||
@@ -159,18 +133,8 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
// Size the backing store to the preview resolution (dpr-aware, capped) and
|
||||
// scale the 4K coordinate space down to it, so we never allocate a 4K canvas.
|
||||
const dpr = Math.min((typeof window !== "undefined" && window.devicePixelRatio) || 1, MAX_DPR)
|
||||
const cw = Math.round(PREVIEW_W * dpr)
|
||||
const ch = Math.round(PREVIEW_H * dpr)
|
||||
if (canvas.width !== cw) canvas.width = cw
|
||||
if (canvas.height !== ch) canvas.height = ch
|
||||
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
ctx.setTransform(cw / CANVAS_W, 0, 0, ch / CANVAS_H, 0, 0)
|
||||
|
||||
// Draw background: custom image > solid color > default image
|
||||
try {
|
||||
@@ -230,8 +194,6 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
|
||||
artist ? effectiveArtistColor : "rgba(255,223,107,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
|
||||
setReady(true)
|
||||
}, [artist, title, customBackgroundUrl, backgroundColor, effectiveTitleColor, effectiveArtistColor, t])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -239,26 +201,15 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
|
||||
}, [draw])
|
||||
|
||||
return (
|
||||
<div className="relative w-full" style={{ aspectRatio: "16/9" }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={PREVIEW_W}
|
||||
height={PREVIEW_H}
|
||||
className="w-full h-full rounded-lg"
|
||||
style={{
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
{!ready && (
|
||||
<div
|
||||
className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg"
|
||||
style={{ backgroundColor: "var(--secondary)", color: "var(--text-muted)" }}
|
||||
data-testid="title-card-preview-loading"
|
||||
>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span className="text-xs">{t('loading')}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={CANVAS_W}
|
||||
height={CANVAS_H}
|
||||
className="w-full rounded-lg"
|
||||
style={{
|
||||
aspectRatio: "16/9",
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -23,7 +23,6 @@ jest.mock("@/lib/api", () => ({
|
||||
searchStandalone: jest.fn(),
|
||||
searchCatalogTracks: jest.fn(),
|
||||
checkCommunityVersions: jest.fn(),
|
||||
matchJudge: jest.fn(),
|
||||
createJobFromSearch: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
@@ -76,46 +75,10 @@ const defaultProps = {
|
||||
onUrlReady: jest.fn(),
|
||||
onFileReady: jest.fn(),
|
||||
onBack: jest.fn(),
|
||||
onAudioEditChange: jest.fn(),
|
||||
noCredits: false,
|
||||
}
|
||||
|
||||
function verdict(overrides: Partial<import("@/lib/api").MatchJudgeVerdict> = {}) {
|
||||
return {
|
||||
kind: "none" as const,
|
||||
confident: true,
|
||||
canonical_artist: "ABBA",
|
||||
canonical_title: "Waterloo",
|
||||
alternatives: [],
|
||||
engine: "catalog" as const,
|
||||
reason: "",
|
||||
needs_ai: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Stage-aware matchJudge mock: the component fires a "fast" pass on mount and a
|
||||
* "full" pass (with the tier) only when the fast pass is inconclusive / weak. */
|
||||
function setJudgeVerdicts(opts: {
|
||||
fast?: Partial<import("@/lib/api").MatchJudgeVerdict>
|
||||
full?: Partial<import("@/lib/api").MatchJudgeVerdict>
|
||||
}) {
|
||||
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
|
||||
const isFast = callOpts?.stage === "fast"
|
||||
return Promise.resolve(verdict(isFast ? opts.fast : opts.full))
|
||||
})
|
||||
}
|
||||
|
||||
function setupMocks() {
|
||||
// Reset confidence to the tier-1 default each test (mockReturnValue otherwise
|
||||
// persists across tests because clearAllMocks only clears call history).
|
||||
mockGetSearchConfidence.mockReturnValue({
|
||||
tier: 1,
|
||||
bestResult: { index: 0, title: "Waterloo", artist: "ABBA", provider: "YouTube", url: "https://yt.com/1" },
|
||||
bestCategory: "LOSSLESS",
|
||||
reason: "Perfect match",
|
||||
warnings: [],
|
||||
})
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: "sess-123",
|
||||
results: [
|
||||
@@ -129,8 +92,6 @@ function setupMocks() {
|
||||
songs: [],
|
||||
best_youtube_url: null,
|
||||
})
|
||||
// Default: catalog says "already canonical" on both passes (no change).
|
||||
setJudgeVerdicts({ fast: {}, full: {} })
|
||||
}
|
||||
|
||||
describe("AudioSourceStep", () => {
|
||||
@@ -147,63 +108,11 @@ describe("AudioSourceStep", () => {
|
||||
})
|
||||
})
|
||||
|
||||
it("fires a fast catalog-only pass on mount (parallel with search)", async () => {
|
||||
it("calls searchCatalogTracks on mount in parallel", async () => {
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith("ABBA", "Waterloo", { stage: "fast" })
|
||||
})
|
||||
})
|
||||
|
||||
it("fires a full pass with the tier when the fast pass is inconclusive", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "none", confident: false, needs_ai: true, engine: "catalog" },
|
||||
full: { kind: "none", confident: true },
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith(
|
||||
"ABBA", "Waterloo", { stage: "full", audioConfidenceTier: 1 }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it("does NOT fire a full pass when the fast pass is confident and audio is strong", async () => {
|
||||
// Default mocks: fast returns a confident catalog verdict, tier 1.
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith("ABBA", "Waterloo", { stage: "fast" })
|
||||
})
|
||||
// Give the coordinating effect a chance to (not) fire the full call.
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(mockApi.matchJudge).not.toHaveBeenCalledWith(
|
||||
"ABBA", "Waterloo", expect.objectContaining({ stage: "full" })
|
||||
)
|
||||
})
|
||||
|
||||
it("fires a full pass to verify a catalog match when audio results are weak (tier 3)", async () => {
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: "sess-empty", results: [], results_count: 0,
|
||||
})
|
||||
mockGetSearchConfidence.mockReturnValue({
|
||||
tier: 3, bestResult: null, bestCategory: null, reason: "", warnings: [],
|
||||
})
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "none", confident: true, engine: "catalog" }, // catalog "matched"
|
||||
full: { kind: "content", confident: true, canonical_title: "Waterloo (Fixed)", engine: "ai" },
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalledWith(
|
||||
"ABBA", "Waterloo", { stage: "full", audioConfidenceTier: 3 }
|
||||
)
|
||||
expect(mockApi.searchCatalogTracks).toHaveBeenCalledWith("Waterloo", "ABBA", 5)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -238,119 +147,16 @@ describe("AudioSourceStep", () => {
|
||||
expect(screen.getByText("ABBA - Waterloo")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("auto-applies a cosmetic tidy from the fast pass and shows the tidy notice", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: {
|
||||
kind: "cosmetic",
|
||||
confident: true,
|
||||
canonical_title: "Waterloo (Remastered)",
|
||||
engine: "catalog",
|
||||
},
|
||||
})
|
||||
it("renders SongSuggestionPanel when catalog returns results", async () => {
|
||||
mockApi.searchCatalogTracks.mockResolvedValue([
|
||||
{ artist_name: "ABBA", track_name: "Waterloo (Remastered)" },
|
||||
])
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("ABBA", "Waterloo (Remastered)")
|
||||
expect(screen.getByTestId("song-suggestion-panel")).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByTestId("match-tidy-notice")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not auto-apply an ambiguous match — shows an ask instead", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "none", confident: false, needs_ai: true, engine: "catalog" },
|
||||
full: {
|
||||
kind: "ambiguous",
|
||||
confident: false,
|
||||
canonical_artist: "Lewis Capaldi",
|
||||
canonical_title: "Bruises",
|
||||
alternatives: [{ artist: "Fox Stevenson", title: "Bruises" }],
|
||||
engine: "ai",
|
||||
},
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("match-didyoumean")).toBeInTheDocument()
|
||||
})
|
||||
expect(defaultProps.onArtistTitleCorrection).not.toHaveBeenCalled()
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByText("Lewis Capaldi — Bruises"))
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("Lewis Capaldi", "Bruises")
|
||||
})
|
||||
|
||||
it("gates the pick button until the judge settles, then enables it", async () => {
|
||||
// Fast pass is inconclusive; full pass resolves after a tick → gate releases.
|
||||
let resolveFull: (v: import("@/lib/api").MatchJudgeVerdict) => void = () => {}
|
||||
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
|
||||
if (callOpts?.stage === "fast") {
|
||||
return Promise.resolve(verdict({ kind: "none", confident: false, needs_ai: true }))
|
||||
}
|
||||
return new Promise<import("@/lib/api").MatchJudgeVerdict>((res) => { resolveFull = res })
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// Pick button rendered but disabled while the full pass is in flight.
|
||||
const pickButton = await screen.findByRole("button", { name: /Use This Audio/i })
|
||||
expect(pickButton).toBeDisabled()
|
||||
expect(screen.getByTestId("match-gate-checking")).toBeInTheDocument()
|
||||
|
||||
// Resolve the full pass → gate releases, button enables.
|
||||
await act(async () => {
|
||||
resolveFull(verdict({ kind: "none", confident: true }))
|
||||
})
|
||||
await waitFor(() => expect(pickButton).toBeEnabled())
|
||||
expect(screen.queryByTestId("match-gate-checking")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("releases the gate via the safety timeout if the judge hangs", async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
|
||||
if (callOpts?.stage === "fast") {
|
||||
return Promise.resolve(verdict({ kind: "none", confident: false, needs_ai: true }))
|
||||
}
|
||||
return new Promise(() => {}) // full pass never resolves
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// Let the fast pass + coordinating effect run.
|
||||
await act(async () => { await Promise.resolve() })
|
||||
const pickButton = await screen.findByRole("button", { name: /Use This Audio/i })
|
||||
expect(pickButton).toBeDisabled()
|
||||
|
||||
// Advance past the 12s safety timeout → gate releases.
|
||||
await act(async () => { jest.advanceTimersByTime(12000) })
|
||||
await waitFor(() => expect(pickButton).toBeEnabled())
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("toggles a cosmetic tidy back and forth (two-way)", async () => {
|
||||
setJudgeVerdicts({
|
||||
fast: { kind: "cosmetic", confident: true, canonical_title: "Waterloo (Remastered)", engine: "catalog" },
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("ABBA", "Waterloo (Remastered)")
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
// Revert to what the user typed.
|
||||
await user.click(screen.getByText("keep what I typed"))
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenLastCalledWith("ABBA", "Waterloo")
|
||||
expect(screen.getByText(/Using what you typed/)).toBeInTheDocument()
|
||||
|
||||
// Switch back to the tidied version.
|
||||
await user.click(screen.getByText("use tidied version"))
|
||||
expect(defaultProps.onArtistTitleCorrection).toHaveBeenLastCalledWith("ABBA", "Waterloo (Remastered)")
|
||||
})
|
||||
|
||||
it("renders CommunityVersionBanner when community data has results", async () => {
|
||||
@@ -433,8 +239,8 @@ describe("AudioSourceStep", () => {
|
||||
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("silently handles matchJudge failure (does not show error)", async () => {
|
||||
mockApi.matchJudge.mockRejectedValue(new Error("judge down"))
|
||||
it("silently handles catalog search failure (does not show error)", async () => {
|
||||
mockApi.searchCatalogTracks.mockRejectedValue(new Error("catalog down"))
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
@@ -442,8 +248,8 @@ describe("AudioSourceStep", () => {
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// No error shown for judge failure — it's a nice-to-have
|
||||
expect(screen.queryByText("judge down")).not.toBeInTheDocument()
|
||||
// No error shown for catalog failure — it's a nice-to-have
|
||||
expect(screen.queryByText("catalog down")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("silently handles community check failure", async () => {
|
||||
@@ -458,15 +264,16 @@ describe("AudioSourceStep", () => {
|
||||
expect(screen.queryByText("community down")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows no match notice for a 'none' verdict", async () => {
|
||||
it("does not show SongSuggestionPanel when catalog returns empty array", async () => {
|
||||
mockApi.searchCatalogTracks.mockResolvedValue([])
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApi.matchJudge).toHaveBeenCalled()
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
expect(screen.queryByTestId("match-tidy-notice")).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId("match-didyoumean")).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId("song-suggestion-panel")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not show CommunityVersionBanner when has_community is false", async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { render, act, screen } from "@testing-library/react"
|
||||
import { TitleCardPreview, preloadTitleCardBg, __resetTitleCardBgCacheForTest } from "../TitleCardPreview"
|
||||
import { render, act } from "@testing-library/react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
|
||||
// Module-level state shared with mock closures via reference
|
||||
const state = {
|
||||
@@ -32,7 +32,6 @@ function setupMocks() {
|
||||
state.fontLoadResolve = null
|
||||
|
||||
HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
|
||||
setTransform: jest.fn(),
|
||||
drawImage: jest.fn(),
|
||||
fillRect: jest.fn(),
|
||||
fillText: jest.fn((text: string) => {
|
||||
@@ -75,7 +74,6 @@ function setupMocks() {
|
||||
|
||||
beforeEach(() => {
|
||||
setupMocks()
|
||||
__resetTitleCardBgCacheForTest()
|
||||
})
|
||||
|
||||
describe("TitleCardPreview", () => {
|
||||
@@ -156,7 +154,6 @@ describe("TitleCardPreview", () => {
|
||||
let _fillStyle = ""
|
||||
let _font = ""
|
||||
return {
|
||||
setTransform: jest.fn(),
|
||||
drawImage: jest.fn(),
|
||||
fillRect: jest.fn(),
|
||||
fillText: jest.fn((text: string) => {
|
||||
@@ -190,66 +187,6 @@ describe("TitleCardPreview", () => {
|
||||
expect(fillStyles).toContain("#00ff00")
|
||||
})
|
||||
|
||||
it("renders the canvas at preview resolution, not 4K", async () => {
|
||||
let result: ReturnType<typeof render>
|
||||
await act(async () => {
|
||||
result = render(<TitleCardPreview title="Test" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
const canvasEl = result!.container.querySelector("canvas")
|
||||
expect(canvasEl).not.toBeNull()
|
||||
// dpr defaults to 1 in jsdom → 960×540 backing store (was 3840×2160).
|
||||
expect(canvasEl!.width).toBe(960)
|
||||
expect(canvasEl!.height).toBe(540)
|
||||
})
|
||||
|
||||
it("loads the low-res preview background by default", async () => {
|
||||
const loadedSrcs: string[] = []
|
||||
global.Image = class MockImageDefault {
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
_src = ""
|
||||
complete = true
|
||||
get src() { return this._src }
|
||||
set src(v: string) {
|
||||
this._src = v
|
||||
loadedSrcs.push(v)
|
||||
Promise.resolve().then(() => this.onload?.())
|
||||
}
|
||||
} as unknown as typeof Image
|
||||
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="Test" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
expect(loadedSrcs).toContain("/title-card-bg-preview.png")
|
||||
expect(loadedSrcs).not.toContain("/title-card-bg.png")
|
||||
})
|
||||
|
||||
it("shows a loading spinner before the first draw completes", () => {
|
||||
// Hold the font load open so draw() never reaches setReady(true).
|
||||
state.fontCheckReturn = false
|
||||
render(<TitleCardPreview title="Song" artist="Artist" />)
|
||||
expect(screen.getByTestId("title-card-preview-loading")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("preloadTitleCardBg loads the low-res asset without throwing", () => {
|
||||
const loadedSrcs: string[] = []
|
||||
global.Image = class MockImagePreload {
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
_src = ""
|
||||
complete = false
|
||||
get src() { return this._src }
|
||||
set src(v: string) { this._src = v; loadedSrcs.push(v) }
|
||||
} as unknown as typeof Image
|
||||
|
||||
expect(() => preloadTitleCardBg()).not.toThrow()
|
||||
expect(loadedSrcs).toContain("/title-card-bg-preview.png")
|
||||
})
|
||||
|
||||
it("loads custom background image when customBackgroundUrl is provided", async () => {
|
||||
const loadedSrcs: string[] = []
|
||||
global.Image = class MockImageCustom {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Check } from "lucide-react"
|
||||
|
||||
interface AvailabilityBadgeProps {
|
||||
available?: boolean | null
|
||||
brands?: string[]
|
||||
}
|
||||
|
||||
/** Shows "community version exists" when a track is already on KaraokeNerds. */
|
||||
export function AvailabilityBadge({ available, brands }: AvailabilityBadgeProps) {
|
||||
const t = useTranslations("bulk")
|
||||
if (!available) return null
|
||||
const brandList = (brands || []).slice(0, 3).join(", ")
|
||||
return (
|
||||
<Badge variant="outline" className="text-amber-500 border-amber-500/40 gap-1">
|
||||
<Check className="w-3 h-3" />
|
||||
{brandList ? t("communityExistsWithBrands", { brands: brandList }) : t("communityExists")}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { api, BulkArtist, BulkAlbum, BulkTracklist } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import {
|
||||
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Loader2, Search, ChevronLeft } from "lucide-react"
|
||||
import { AvailabilityBadge } from "./AvailabilityBadge"
|
||||
import { BulkSongRow, newRow, shouldSelectTrack } from "./types"
|
||||
|
||||
interface BulkAlbumModeProps {
|
||||
rows: BulkSongRow[]
|
||||
onChange: (rows: BulkSongRow[]) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
function fmtLen(ms?: number | null): string {
|
||||
if (!ms) return ""
|
||||
const s = Math.round(ms / 1000)
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`
|
||||
}
|
||||
|
||||
export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const [query, setQuery] = useState("")
|
||||
const [artists, setArtists] = useState<BulkArtist[]>([])
|
||||
const [artist, setArtist] = useState<BulkArtist | null>(null)
|
||||
const [albums, setAlbums] = useState<BulkAlbum[]>([])
|
||||
const [tracklist, setTracklist] = useState<BulkTracklist | null>(null)
|
||||
const [loading, setLoading] = useState<"" | "artists" | "albums" | "tracks">("")
|
||||
const [error, setError] = useState("")
|
||||
|
||||
async function searchArtists() {
|
||||
if (query.trim().length < 2) return
|
||||
setLoading("artists"); setError(""); setArtists([]); setArtist(null); setAlbums([]); setTracklist(null)
|
||||
try {
|
||||
setArtists(await api.searchAlbumArtists(query.trim()))
|
||||
} catch {
|
||||
setError(t("lookupFailed"))
|
||||
} finally {
|
||||
setLoading("")
|
||||
}
|
||||
}
|
||||
|
||||
async function pickArtist(a: BulkArtist) {
|
||||
if (!a.mbid) return
|
||||
setArtist(a); setLoading("albums"); setError(""); setAlbums([]); setTracklist(null)
|
||||
try {
|
||||
setAlbums(await api.getAlbums(a.mbid))
|
||||
} catch {
|
||||
setError(t("lookupFailed"))
|
||||
} finally {
|
||||
setLoading("")
|
||||
}
|
||||
}
|
||||
|
||||
function buildRows(tl: BulkTracklist): BulkSongRow[] {
|
||||
return tl.tracks.map((tr) =>
|
||||
newRow({
|
||||
artist: artist?.name || "",
|
||||
title: tr.title,
|
||||
// Default-uncheck extras and tracks that already have a community version.
|
||||
selected: shouldSelectTrack(tr),
|
||||
available: tr.available,
|
||||
brands: tr.brands,
|
||||
is_extra: tr.is_extra,
|
||||
length_ms: tr.length_ms,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
async function pickAlbum(album: BulkAlbum) {
|
||||
if (!artist?.name) return
|
||||
setLoading("tracks"); setError("")
|
||||
try {
|
||||
const tl = await api.getAlbumTracklist({
|
||||
artist: artist.name, releaseGroupMbid: album.release_group_mbid,
|
||||
})
|
||||
setTracklist(tl)
|
||||
onChange(buildRows(tl))
|
||||
} catch {
|
||||
setError(t("lookupFailed"))
|
||||
} finally {
|
||||
setLoading("")
|
||||
}
|
||||
}
|
||||
|
||||
async function switchEdition(releaseMbid: string) {
|
||||
if (!artist?.name) return
|
||||
setLoading("tracks"); setError("")
|
||||
try {
|
||||
const tl = await api.getAlbumTracklist({ artist: artist.name, releaseMbid })
|
||||
setTracklist(tl)
|
||||
onChange(buildRows(tl))
|
||||
} catch {
|
||||
setError(t("lookupFailed"))
|
||||
} finally {
|
||||
setLoading("")
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = (key: string, checked: boolean) =>
|
||||
onChange(rows.map((r) => (r.key === key ? { ...r, selected: checked } : r)))
|
||||
|
||||
// --- Render: tracklist view ---
|
||||
if (tracklist && artist) {
|
||||
const editionValue = tracklist.release_mbid || tracklist.canonical_release_mbid || ""
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={() => setTracklist(null)} disabled={disabled}>
|
||||
<ChevronLeft className="w-4 h-4 me-1" />{t("backToAlbums")}
|
||||
</Button>
|
||||
{tracklist.editions.length > 1 && (
|
||||
<Select value={editionValue} onValueChange={switchEdition} disabled={disabled}>
|
||||
<SelectTrigger className="h-8 w-[200px] text-xs">
|
||||
<SelectValue placeholder={t("edition")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{tracklist.editions.map((e) => (
|
||||
<SelectItem key={e.release_mbid} value={e.release_mbid}>
|
||||
{(e.date || "?")} · {e.country || "—"} · {t("trackCount", { count: e.track_count })}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>
|
||||
{artist.name} — {tracklist.title}
|
||||
</p>
|
||||
<p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("tracklistHint")}</p>
|
||||
|
||||
<div className="space-y-1 max-h-[420px] overflow-y-auto pe-1">
|
||||
{rows.map((row) => (
|
||||
<label
|
||||
key={row.key}
|
||||
className="flex items-center gap-2 rounded-md px-2 py-1.5 cursor-pointer hover:bg-white/5"
|
||||
>
|
||||
<Checkbox
|
||||
checked={row.selected}
|
||||
onCheckedChange={(v) => toggle(row.key, v === true)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="flex-1 min-w-0 text-sm truncate" style={{ color: "var(--text)" }}>
|
||||
{row.title}
|
||||
</span>
|
||||
{row.is_extra && (
|
||||
<Badge variant="outline" className="text-pink-400 border-pink-400/40">{t("extra")}</Badge>
|
||||
)}
|
||||
<AvailabilityBadge available={row.available} brands={row.brands} />
|
||||
<span className="text-xs w-10 text-end shrink-0" style={{ color: "var(--text-muted)" }}>
|
||||
{fmtLen(row.length_ms)}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Render: album list view ---
|
||||
if (artist) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => { setArtist(null); setAlbums([]) }} disabled={disabled}>
|
||||
<ChevronLeft className="w-4 h-4 me-1" />{t("backToArtists")}
|
||||
</Button>
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>{artist.name}</p>
|
||||
{loading === "albums" ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" style={{ color: "var(--text-muted)" }} />
|
||||
) : (
|
||||
<div className="space-y-1 max-h-[420px] overflow-y-auto pe-1">
|
||||
{albums.map((a) => (
|
||||
<button
|
||||
key={a.release_group_mbid}
|
||||
onClick={() => pickAlbum(a)}
|
||||
disabled={disabled}
|
||||
className="w-full text-start rounded-md px-2 py-1.5 hover:bg-white/5 flex items-center gap-2"
|
||||
>
|
||||
<span className="flex-1 min-w-0 text-sm truncate" style={{ color: "var(--text)" }}>{a.title}</span>
|
||||
{!a.is_studio && a.secondary_types[0] && (
|
||||
<Badge variant="outline" className="text-xs">{a.secondary_types[0]}</Badge>
|
||||
)}
|
||||
<span className="text-xs shrink-0" style={{ color: "var(--text-muted)" }}>
|
||||
{a.first_release_date?.slice(0, 4)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{albums.length === 0 && <p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("noAlbums")}</p>}
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="text-xs" style={{ color: "#ef4444" }}>{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Render: artist search view ---
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("albumModeHint")}</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder={t("artistSearchPlaceholder")}
|
||||
value={query}
|
||||
disabled={disabled}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && searchArtists()}
|
||||
/>
|
||||
<Button onClick={searchArtists} disabled={disabled || query.trim().length < 2}>
|
||||
{loading === "artists" ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-1 max-h-[420px] overflow-y-auto pe-1">
|
||||
{artists.map((a) => (
|
||||
<button
|
||||
key={a.mbid || a.name}
|
||||
onClick={() => pickArtist(a)}
|
||||
disabled={disabled || !a.mbid}
|
||||
className="w-full text-start rounded-md px-2 py-1.5 hover:bg-white/5 flex items-center gap-2"
|
||||
>
|
||||
<span className="text-sm" style={{ color: "var(--text)" }}>{a.name}</span>
|
||||
{a.disambiguation && (
|
||||
<span className="text-xs" style={{ color: "var(--text-muted)" }}>({a.disambiguation})</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{error && <p className="text-xs" style={{ color: "#ef4444" }}>{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { api, BulkBatch, BulkBatchJob } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Loader2, Music2, CheckCircle2, AlertCircle } from "lucide-react"
|
||||
import { AudioSearchDialog } from "@/components/audio-search/AudioSearchDialog"
|
||||
|
||||
interface BulkBatchProgressProps {
|
||||
batchId: string
|
||||
onStartAnother: () => void
|
||||
onJobsChanged?: () => void
|
||||
}
|
||||
|
||||
export function BulkBatchProgress({ batchId, onStartAnother, onJobsChanged }: BulkBatchProgressProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const [batch, setBatch] = useState<BulkBatch | null>(null)
|
||||
const [error, setError] = useState("")
|
||||
const [selectingJob, setSelectingJob] = useState<BulkBatchJob | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setBatch(await api.getBulkBatch(batchId))
|
||||
} catch {
|
||||
setError(t("progressError"))
|
||||
}
|
||||
}, [batchId, t])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
const interval = setInterval(load, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [load])
|
||||
|
||||
if (error) return <p className="text-sm" style={{ color: "#ef4444" }}>{error}</p>
|
||||
if (!batch) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />{t("loadingBatch")}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const c = batch.counts
|
||||
const awaiting = batch.jobs.filter((j) => j.status === "awaiting_audio_selection")
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-lg border p-3" style={{ borderColor: "var(--card-border)" }}>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>
|
||||
{t("batchProgressTitle", { total: batch.total })}
|
||||
</p>
|
||||
<Button variant="outline" size="sm" onClick={onStartAnother}>{t("startAnother")}</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 text-xs">
|
||||
{c.searching > 0 && <Badge variant="outline" className="gap-1"><Loader2 className="w-3 h-3 animate-spin" />{t("countSearching", { count: c.searching })}</Badge>}
|
||||
{c.awaiting_selection > 0 && <Badge variant="outline" className="text-amber-500 border-amber-500/40">{t("countAwaiting", { count: c.awaiting_selection })}</Badge>}
|
||||
{c.processing > 0 && <Badge variant="outline">{t("countProcessing", { count: c.processing })}</Badge>}
|
||||
{c.complete > 0 && <Badge variant="outline" className="text-green-500 border-green-500/40 gap-1"><CheckCircle2 className="w-3 h-3" />{t("countComplete", { count: c.complete })}</Badge>}
|
||||
{c.failed > 0 && <Badge variant="outline" className="text-red-500 border-red-500/40 gap-1"><AlertCircle className="w-3 h-3" />{t("countFailed", { count: c.failed })}</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{awaiting.length > 0 && (
|
||||
<div className="rounded-lg border p-3 space-y-2" style={{ borderColor: "var(--card-border)" }}>
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>{t("reviewQueueTitle")}</p>
|
||||
<p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("reviewQueueHint")}</p>
|
||||
{awaiting.map((j) => (
|
||||
<div key={j.job_id} className="flex items-center gap-2">
|
||||
<Music2 className="w-4 h-4 shrink-0" style={{ color: "var(--text-muted)" }} />
|
||||
<span className="flex-1 min-w-0 text-sm truncate" style={{ color: "var(--text)" }}>
|
||||
{j.artist} — {j.title}
|
||||
</span>
|
||||
<Button size="sm" onClick={() => setSelectingJob(j)}>{t("chooseAudio")}</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectingJob && (
|
||||
<AudioSearchDialog
|
||||
jobId={selectingJob.job_id}
|
||||
open={true}
|
||||
searchTitle={selectingJob.title}
|
||||
onClose={() => setSelectingJob(null)}
|
||||
onSelect={() => {
|
||||
setSelectingJob(null)
|
||||
load()
|
||||
onJobsChanged?.()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import type { BulkSettings } from "@/lib/api"
|
||||
|
||||
interface BulkBatchSettingsProps {
|
||||
settings: BulkSettings
|
||||
onChange: (settings: BulkSettings) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
function Row({ id, label, hint, checked, onChange, disabled }: {
|
||||
id: string; label: string; hint: string; checked: boolean
|
||||
onChange: (v: boolean) => void; disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<Label htmlFor={id} className="text-sm" style={{ color: "var(--text)" }}>{label}</Label>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>{hint}</p>
|
||||
</div>
|
||||
<Switch id={id} checked={checked} onCheckedChange={onChange} disabled={disabled} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function BulkBatchSettings({ settings, onChange, disabled }: BulkBatchSettingsProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const set = (patch: Partial<BulkSettings>) => onChange({ ...settings, ...patch })
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border p-3" style={{ borderColor: "var(--card-border)" }}>
|
||||
<p className="text-sm font-medium mb-1" style={{ color: "var(--text)" }}>{t("batchSettings")}</p>
|
||||
<Row
|
||||
id="bulk-auto-lossless"
|
||||
label={t("autoPickLossless")}
|
||||
hint={t("autoPickLosslessHint")}
|
||||
checked={settings.auto_select_if_lossless}
|
||||
onChange={(v) => set({ auto_select_if_lossless: v })}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Row
|
||||
id="bulk-private"
|
||||
label={t("makePrivate")}
|
||||
hint={t("makePrivateHint")}
|
||||
checked={settings.is_private}
|
||||
onChange={(v) => set({ is_private: v })}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Row
|
||||
id="bulk-skip-edit"
|
||||
label={t("skipAudioEdit")}
|
||||
hint={t("skipAudioEditHint")}
|
||||
checked={settings.skip_audio_edit}
|
||||
onChange={(v) => set({ skip_audio_edit: v })}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Row
|
||||
id="bulk-skip-custom"
|
||||
label={t("skipCustomization")}
|
||||
hint={t("skipCustomizationHint")}
|
||||
checked={settings.skip_customization}
|
||||
onChange={(v) => set({ skip_customization: v })}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { api, BulkSettings } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
|
||||
import { BulkTextMode } from "./BulkTextMode"
|
||||
import { BulkAlbumMode } from "./BulkAlbumMode"
|
||||
import { BulkBatchSettings } from "./BulkBatchSettings"
|
||||
import { BulkSubmitBar } from "./BulkSubmitBar"
|
||||
import { BulkBatchProgress } from "./BulkBatchProgress"
|
||||
import { BulkSongRow } from "./types"
|
||||
|
||||
const MAX_SONGS = 100
|
||||
|
||||
const DEFAULT_SETTINGS: BulkSettings = {
|
||||
auto_select_if_lossless: true,
|
||||
is_private: false,
|
||||
skip_audio_edit: true,
|
||||
skip_customization: true,
|
||||
}
|
||||
|
||||
interface BulkModeProps {
|
||||
onJobsChanged?: () => void
|
||||
onBuyCredits?: () => void
|
||||
}
|
||||
|
||||
export function BulkMode({ onJobsChanged, onBuyCredits }: BulkModeProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const { user } = useAuth()
|
||||
const isAdmin = user?.role === "admin" || !!user?.email?.endsWith("@nomadkaraoke.com")
|
||||
const credits = user?.credits ?? null
|
||||
|
||||
const [subMode, setSubMode] = useState<"text" | "album">("album")
|
||||
const [textRows, setTextRows] = useState<BulkSongRow[]>([])
|
||||
const [albumRows, setAlbumRows] = useState<BulkSongRow[]>([])
|
||||
const [settings, setSettings] = useState<BulkSettings>(DEFAULT_SETTINGS)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
// Persist the last batch so a returning user can finish its review queue
|
||||
// (parked awaiting-selection jobs are hidden from the main jobs list).
|
||||
const [batchId, setBatchId] = useState<string | null>(() => {
|
||||
if (typeof window === "undefined") return null
|
||||
try {
|
||||
return localStorage.getItem("nomad-bulk-last-batch")
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
const [error, setError] = useState("")
|
||||
|
||||
const activeRows = subMode === "text" ? textRows : albumRows
|
||||
const selectedRows = useMemo(
|
||||
() => activeRows.filter((r) => r.selected && r.artist.trim() && r.title.trim()),
|
||||
[activeRows]
|
||||
)
|
||||
|
||||
async function handleSubmit() {
|
||||
setIsSubmitting(true)
|
||||
setError("")
|
||||
try {
|
||||
const resp = await api.bulkSubmit({
|
||||
songs: selectedRows.map((r) => ({
|
||||
artist: r.artist.trim(),
|
||||
title: r.title.trim(),
|
||||
display_artist: r.display_artist?.trim() || undefined,
|
||||
display_title: r.display_title?.trim() || undefined,
|
||||
})),
|
||||
settings,
|
||||
})
|
||||
setBatchId(resp.batch_id)
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
localStorage.setItem("nomad-bulk-last-batch", resp.batch_id)
|
||||
} catch {
|
||||
// Non-fatal: progress still shows this session; just won't survive refresh.
|
||||
}
|
||||
}
|
||||
onJobsChanged?.()
|
||||
} catch (e: any) {
|
||||
setError(e?.message || t("submitError"))
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function startAnother() {
|
||||
setBatchId(null)
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
localStorage.removeItem("nomad-bulk-last-batch")
|
||||
} catch {
|
||||
// Non-fatal: React state is already cleared.
|
||||
}
|
||||
}
|
||||
setTextRows([])
|
||||
setAlbumRows([])
|
||||
}
|
||||
|
||||
if (batchId) {
|
||||
return (
|
||||
<BulkBatchProgress
|
||||
batchId={batchId}
|
||||
onStartAnother={startAnother}
|
||||
onJobsChanged={onJobsChanged}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Tabs value={subMode} onValueChange={(v) => setSubMode(v as "text" | "album")}>
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="album">{t("byAlbum")}</TabsTrigger>
|
||||
<TabsTrigger value="text">{t("byText")}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="album" className="mt-3">
|
||||
<BulkAlbumMode rows={albumRows} onChange={setAlbumRows} disabled={isSubmitting} />
|
||||
</TabsContent>
|
||||
<TabsContent value="text" className="mt-3">
|
||||
<BulkTextMode rows={textRows} onChange={setTextRows} maxSongs={MAX_SONGS} disabled={isSubmitting} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<BulkBatchSettings settings={settings} onChange={setSettings} disabled={isSubmitting} />
|
||||
|
||||
{error && <p className="text-sm" style={{ color: "#ef4444" }}>{error}</p>}
|
||||
|
||||
<BulkSubmitBar
|
||||
selectedCount={selectedRows.length}
|
||||
credits={credits}
|
||||
isAdmin={isAdmin}
|
||||
isSubmitting={isSubmitting}
|
||||
onSubmit={handleSubmit}
|
||||
onBuyCredits={onBuyCredits}
|
||||
maxSongs={MAX_SONGS}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { canSubmitBatch } from "./types"
|
||||
|
||||
interface BulkSubmitBarProps {
|
||||
selectedCount: number
|
||||
credits: number | null
|
||||
isAdmin: boolean
|
||||
isSubmitting: boolean
|
||||
onSubmit: () => void
|
||||
onBuyCredits?: () => void
|
||||
maxSongs: number
|
||||
}
|
||||
|
||||
export function BulkSubmitBar({
|
||||
selectedCount, credits, isAdmin, isSubmitting, onSubmit, onBuyCredits, maxSongs,
|
||||
}: BulkSubmitBarProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const overLimit = selectedCount > maxSongs
|
||||
// Gate: 1 credit/song minimum. Admins bypass.
|
||||
const enoughCredits = isAdmin || credits === null || credits >= selectedCount
|
||||
const canSubmit = canSubmitBatch(selectedCount, credits, isAdmin, maxSongs) && !isSubmitting
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border p-3 space-y-2" style={{ borderColor: "var(--card-border)" }}>
|
||||
<div className="flex items-center justify-between text-sm" style={{ color: "var(--text)" }}>
|
||||
<span>{t("selectedCount", { count: selectedCount })}</span>
|
||||
{!isAdmin && credits !== null && (
|
||||
<span style={{ color: enoughCredits ? "var(--text-muted)" : "#ef4444" }}>
|
||||
{t("creditsCost", { cost: selectedCount, balance: credits })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{overLimit && (
|
||||
<p className="text-xs" style={{ color: "#ef4444" }}>{t("overLimit", { max: maxSongs })}</p>
|
||||
)}
|
||||
|
||||
{!enoughCredits && !overLimit && (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs" style={{ color: "#ef4444" }}>
|
||||
{t("notEnoughCredits", { needed: selectedCount, have: credits ?? 0 })}
|
||||
</p>
|
||||
{onBuyCredits && (
|
||||
<Button size="sm" variant="outline" onClick={onBuyCredits}>{t("buyCredits")}</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button className="w-full" onClick={onSubmit} disabled={!canSubmit}>
|
||||
{isSubmitting ? (
|
||||
<><Loader2 className="w-4 h-4 me-2 animate-spin" />{t("submitting")}</>
|
||||
) : (
|
||||
t("createBatch", { count: selectedCount })
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { api } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus, X } from "lucide-react"
|
||||
import { AvailabilityBadge } from "./AvailabilityBadge"
|
||||
import { BulkSongRow, newRow } from "./types"
|
||||
|
||||
interface BulkTextModeProps {
|
||||
rows: BulkSongRow[]
|
||||
onChange: (rows: BulkSongRow[]) => void
|
||||
maxSongs: number
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function BulkTextMode({ rows, onChange, maxSongs, disabled }: BulkTextModeProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const [checking, setChecking] = useState(false)
|
||||
|
||||
// Ensure at least one empty row exists.
|
||||
useEffect(() => {
|
||||
if (rows.length === 0) onChange([newRow()])
|
||||
}, [rows.length, onChange])
|
||||
|
||||
const update = (key: string, patch: Partial<BulkSongRow>) =>
|
||||
onChange(rows.map((r) => (r.key === key ? { ...r, ...patch } : r)))
|
||||
|
||||
const addRow = () => {
|
||||
if (rows.length >= maxSongs) return
|
||||
onChange([...rows, newRow()])
|
||||
}
|
||||
|
||||
const removeRow = (key: string) => {
|
||||
const next = rows.filter((r) => r.key !== key)
|
||||
onChange(next.length ? next : [newRow()])
|
||||
}
|
||||
|
||||
// Debounced availability check for fully-filled rows lacking a result.
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
const pending = rows.filter(
|
||||
(r) => r.artist.trim() && r.title.trim() && r.available == null
|
||||
)
|
||||
if (pending.length === 0) return
|
||||
debounceRef.current = setTimeout(async () => {
|
||||
setChecking(true)
|
||||
try {
|
||||
const resp = await api.checkBulkAvailability(
|
||||
pending.map((r) => ({ artist: r.artist.trim(), title: r.title.trim() }))
|
||||
)
|
||||
// Map results back to rows by (artist,title).
|
||||
const byKey = new Map(resp.results.map((r) => [`${r.artist}|||${r.title}`, r]))
|
||||
onChange(
|
||||
rows.map((r) => {
|
||||
const hit = byKey.get(`${r.artist.trim()}|||${r.title.trim()}`)
|
||||
return hit ? { ...r, available: hit.available, brands: hit.brands } : r
|
||||
})
|
||||
)
|
||||
} catch {
|
||||
// Non-fatal: leave availability unknown.
|
||||
} finally {
|
||||
setChecking(false)
|
||||
}
|
||||
}, 700)
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [rows])
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("textModeHint", { max: maxSongs })}</p>
|
||||
{rows.map((row) => (
|
||||
<div key={row.key} className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder={t("artist")}
|
||||
value={row.artist}
|
||||
disabled={disabled}
|
||||
onChange={(e) => update(row.key, { artist: e.target.value, available: null })}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
placeholder={t("title")}
|
||||
value={row.title}
|
||||
disabled={disabled}
|
||||
onChange={(e) => update(row.key, { title: e.target.value, available: null })}
|
||||
className="flex-1"
|
||||
/>
|
||||
<div className="w-40 shrink-0">
|
||||
<AvailabilityBadge available={row.available} brands={row.brands} />
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost" size="sm" disabled={disabled}
|
||||
onClick={() => removeRow(row.key)}
|
||||
aria-label={t("removeRow")}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex items-center justify-between">
|
||||
<Button variant="outline" size="sm" onClick={addRow} disabled={disabled || rows.length >= maxSongs}>
|
||||
<Plus className="w-4 h-4 me-1" />{t("addSong")}
|
||||
</Button>
|
||||
{checking && <span className="text-xs" style={{ color: "var(--text-muted)" }}>{t("checking")}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user