mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 17:16:04 +09:00
Compare commits
No files matched your search
+58
-25
@@ -516,7 +516,10 @@ jobs:
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
# 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
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
@@ -831,7 +834,12 @@ jobs:
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
# 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
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -925,7 +933,6 @@ jobs:
|
||||
prerelease: false
|
||||
files: |
|
||||
dist/*.whl
|
||||
dist/*.tar.gz
|
||||
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (Cloudflare Pages)"
|
||||
@@ -1399,29 +1406,47 @@ 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)
|
||||
|
||||
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")
|
||||
# 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
|
||||
}
|
||||
|
||||
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
|
||||
# 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"
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
@@ -1658,8 +1683,8 @@ 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,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 "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"
|
||||
--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-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
|
||||
run: |
|
||||
@@ -1676,6 +1701,14 @@ 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,8 +54,14 @@ 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/", 36),
|
||||
("Firestore", "firestore/", 192),
|
||||
("GCS job files", "gcs/job-files/", 36),
|
||||
("Encrypted secrets", "secrets/", 36),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192),
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
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 }}
|
||||
@@ -1709,6 +1709,12 @@ async def delete_job_outputs(
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too (prefix-keyed
|
||||
# by brand_code, covers renames). Non-fatal, Nomad-only, no-op otherwise.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
|
||||
# Clean up GCS finals folder - prevents stale files from being picked up during re-encoding
|
||||
try:
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
"""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 Literal, 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 BulkEditionVariant(BaseModel):
|
||||
"""A distinct tracklist variant (country pressings collapsed by track count)."""
|
||||
|
||||
representative_release_mbid: str
|
||||
label: Literal["Original", "Reissue"] = "Original"
|
||||
track_count: int = 0
|
||||
year: str = ""
|
||||
pressing_count: int = 0
|
||||
delta_vs_original: int = 0
|
||||
|
||||
|
||||
class CommunityVersion(BaseModel):
|
||||
"""An existing community karaoke version the user can preview on YouTube."""
|
||||
|
||||
brand: str
|
||||
url: str
|
||||
|
||||
|
||||
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] = []
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
class BulkTracklistResponse(BaseModel):
|
||||
release_mbid: Optional[str] = None
|
||||
canonical_release_mbid: Optional[str] = None
|
||||
selected_variant_mbid: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
date: str = ""
|
||||
tracks: list[BulkTrack] = []
|
||||
editions: list[BulkEdition] = []
|
||||
variants: list[BulkEditionVariant] = []
|
||||
|
||||
|
||||
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
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
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"),
|
||||
locale: Optional[str] = Query(None, description="UI locale → biases representative-pressing choice"),
|
||||
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.
|
||||
|
||||
Response shape note: ``variants`` is only populated on the ``release_group_mbid``
|
||||
path (the initial album load). When loading a specific edition via
|
||||
``release_mbid`` it is intentionally ``[]`` — the client already holds the
|
||||
variant list from the initial load and only needs the chosen edition's tracks.
|
||||
"""
|
||||
from backend.services.musicbrainz_service import (
|
||||
get_musicbrainz_service,
|
||||
country_prefs_for_locale,
|
||||
)
|
||||
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:
|
||||
# Loading a specific variant — variants already known to the client.
|
||||
tracklist = await mb.get_release_tracklist(release_mbid)
|
||||
tracklist.setdefault("editions", [])
|
||||
tracklist.setdefault("canonical_release_mbid", release_mbid)
|
||||
tracklist.setdefault("variants", [])
|
||||
tracklist.setdefault("selected_variant_mbid", release_mbid)
|
||||
else:
|
||||
tracklist = await mb.get_album_tracklist(
|
||||
release_group_mbid, preferred_countries=country_prefs_for_locale(locale)
|
||||
)
|
||||
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"]
|
||||
t["versions"] = a.get("versions", [])
|
||||
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"),
|
||||
selected_variant_mbid=tracklist.get("selected_variant_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", [])],
|
||||
variants=[BulkEditionVariant(**v) for v in tracklist.get("variants", [])],
|
||||
)
|
||||
|
||||
|
||||
@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 Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -103,6 +103,38 @@ 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 ---
|
||||
|
||||
|
||||
@@ -161,3 +193,31 @@ 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()
|
||||
@@ -2,13 +2,21 @@
|
||||
Encoding worker lifecycle endpoints.
|
||||
|
||||
Provides warmup and heartbeat endpoints for the blue-green
|
||||
encoding worker VMs. Called by the frontend to ensure the
|
||||
primary VM is running before encoding requests.
|
||||
encoding worker VMs. Called by the lyrics-review frontend to ensure the
|
||||
primary VM is running before the reviewer previews a render.
|
||||
|
||||
Auth: these are gated on ``require_review_auth`` (review access to a specific
|
||||
job), NOT ``require_admin``. The callers are ordinary customers on the
|
||||
lyrics-review page — gating on admin makes every non-admin caller 403, which
|
||||
silently defeats the JIT pre-warm. Scoping to the job being reviewed keeps the
|
||||
abuse posture identical to the rest of the review surface: you can only warm
|
||||
the shared encoding VM if you already have review access to a real job.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Tuple
|
||||
from fastapi import APIRouter, Depends
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.dependencies import require_review_auth
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
|
||||
@@ -36,12 +44,17 @@ def get_worker_manager():
|
||||
return _manager
|
||||
|
||||
|
||||
@router.post("/warmup")
|
||||
@router.post("/warmup/{job_id}")
|
||||
async def warmup_encoding_worker(
|
||||
_admin=Depends(require_admin),
|
||||
job_id: str,
|
||||
_auth: Tuple[str, str] = Depends(require_review_auth),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Start the primary encoding worker VM if it's stopped."""
|
||||
"""Start the primary encoding worker VM if it's stopped.
|
||||
|
||||
Called on lyrics-review page load so the VM is warm by the time the
|
||||
reviewer previews a render. ``job_id`` scopes auth to the job under review.
|
||||
"""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
@@ -64,12 +77,17 @@ async def warmup_encoding_worker(
|
||||
return {"started": False, "error": str(e)}
|
||||
|
||||
|
||||
@router.post("/heartbeat")
|
||||
@router.post("/heartbeat/{job_id}")
|
||||
async def heartbeat_encoding_worker(
|
||||
_admin=Depends(require_admin),
|
||||
job_id: str,
|
||||
_auth: Tuple[str, str] = Depends(require_review_auth),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Update activity timestamp to prevent idle shutdown."""
|
||||
"""Update activity timestamp to prevent idle shutdown.
|
||||
|
||||
Called periodically while the reviewer works. ``job_id`` scopes auth to the
|
||||
job under review.
|
||||
"""
|
||||
try:
|
||||
manager.update_activity()
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -57,6 +57,19 @@ 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,
|
||||
@@ -67,12 +80,20 @@ 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:
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- 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)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload
|
||||
- Disables YouTube upload (tenants never publish to YouTube)
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
@@ -81,14 +102,12 @@ def _apply_tenant_overrides(
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
features = tenant_config.features
|
||||
|
||||
# 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
|
||||
# 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
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
@@ -1382,12 +1401,14 @@ 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]
|
||||
|
||||
@@ -1560,11 +1581,140 @@ def _validate_url(url: Optional[str]) -> bool:
|
||||
for supported in supported_domains:
|
||||
if domain == supported or domain.endswith('.' + supported):
|
||||
return True
|
||||
|
||||
|
||||
# For other URLs, let yt-dlp try (it supports many more sites)
|
||||
return True
|
||||
|
||||
|
||||
# Streaming services whose catalogue is DRM-protected and therefore cannot be
|
||||
# downloaded by yt-dlp / flacfetch. Submitting one of these only creates a job
|
||||
# that fails deep in the download stage with a cryptic "Unsupported URL" error
|
||||
# (and lets the user trigger a futile retry), so we reject them at submission
|
||||
# time with a clear, actionable message. Maps host -> friendly platform name;
|
||||
# matching is suffix-based, so e.g. "spotify.com" also covers open./play.
|
||||
_UNSUPPORTED_DRM_HOSTS = {
|
||||
'music.apple.com': 'Apple Music',
|
||||
'itunes.apple.com': 'Apple Music',
|
||||
'spotify.com': 'Spotify',
|
||||
'tidal.com': 'Tidal',
|
||||
'deezer.com': 'Deezer',
|
||||
'pandora.com': 'Pandora',
|
||||
}
|
||||
|
||||
# Third-party tools that can download audio from a DRM platform, which the user
|
||||
# can then upload to us. Listed where we know of working options; platforms
|
||||
# without an entry fall back to a web-search link for "<platform> downloader".
|
||||
_DRM_DOWNLOADER_SUGGESTIONS = {
|
||||
'Apple Music': ['https://am-dl.pages.dev', 'https://aplmate.com'],
|
||||
'Spotify': ['https://spotdown.org', 'https://spotmate.online'],
|
||||
}
|
||||
|
||||
|
||||
def _drm_unsupported_detail(locale: str, platform: str) -> str:
|
||||
"""
|
||||
Build the user-facing 400 message for a rejected DRM streaming URL.
|
||||
|
||||
Platforms with known downloader tools get a "download from {tools}, then
|
||||
upload" message linking each tool; everything else gets a "search the web
|
||||
for a '<platform> downloader'" message linking a Google search. Either way
|
||||
the goal is to guide the user to obtain the audio and upload it themselves.
|
||||
"""
|
||||
downloaders = _DRM_DOWNLOADER_SUGGESTIONS.get(platform)
|
||||
if downloaders:
|
||||
# Join with commas (locale-neutral) rather than an English "or"; the
|
||||
# message wording frames them as options and LinkifiedText makes each
|
||||
# URL clickable in the frontend.
|
||||
return t(
|
||||
locale, "audioSearch.drmUrlUnsupportedWithLink",
|
||||
platform=platform, downloader=", ".join(downloaders),
|
||||
)
|
||||
|
||||
from urllib.parse import quote_plus
|
||||
search_url = "https://www.google.com/search?q=" + quote_plus(f"{platform} downloader")
|
||||
return t(
|
||||
locale, "audioSearch.drmUrlUnsupportedSearch",
|
||||
platform=platform, searchUrl=search_url,
|
||||
)
|
||||
|
||||
|
||||
def _unsupported_url_platform(url: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
Return a friendly platform name if the URL belongs to a known DRM-protected
|
||||
streaming service that cannot be downloaded, else None.
|
||||
|
||||
These links (Apple Music, Spotify, Tidal, Amazon Music, Deezer, Pandora) are
|
||||
rejected at submission time instead of being allowed to create a job that
|
||||
always fails deep in the download stage. Note: YouTube Music
|
||||
(music.youtube.com) is downloadable and is deliberately NOT included.
|
||||
"""
|
||||
if not url or not isinstance(url, str):
|
||||
return None
|
||||
|
||||
from urllib.parse import urlparse
|
||||
try:
|
||||
# .hostname is already lowercased and strips userinfo, port, and IPv6
|
||||
# brackets, so it's safer than parsing .netloc by hand.
|
||||
domain = (urlparse(url).hostname or "").lower()
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
if not domain:
|
||||
return None
|
||||
# Normalise leading www.
|
||||
if domain.startswith('www.'):
|
||||
domain = domain[4:]
|
||||
|
||||
for host, platform in _UNSUPPORTED_DRM_HOSTS.items():
|
||||
if domain == host or domain.endswith('.' + host):
|
||||
return platform
|
||||
|
||||
# Amazon Music spans many country domains (music.amazon.com, .co.uk, .co.jp,
|
||||
# .fr, .de, ...), so match the music.amazon.* prefix generically.
|
||||
if domain == 'music.amazon' or domain.startswith('music.amazon.'):
|
||||
return 'Amazon Music'
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class ValidateUrlRequest(BaseModel):
|
||||
"""Request to pre-validate a URL before submitting a job."""
|
||||
url: str = Field(..., description="The URL the user intends to submit")
|
||||
|
||||
|
||||
class ValidateUrlResponse(BaseModel):
|
||||
"""Whether a URL can be used for a job, with a friendly reason if not."""
|
||||
supported: bool
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
|
||||
async def validate_job_url(
|
||||
request: Request,
|
||||
body: ValidateUrlRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
) -> ValidateUrlResponse:
|
||||
"""
|
||||
Lightweight pre-flight check for a job URL, used by the guided submission
|
||||
flow so unsupported links are caught at the "Use this URL" step instead of
|
||||
only at final submit. Mirrors the URL validation in create_job_from_url.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
platform = _unsupported_url_platform(body.url)
|
||||
if platform:
|
||||
return ValidateUrlResponse(
|
||||
supported=False, detail=_drm_unsupported_detail(locale, platform)
|
||||
)
|
||||
|
||||
if not _validate_url(body.url):
|
||||
return ValidateUrlResponse(
|
||||
supported=False,
|
||||
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL.",
|
||||
)
|
||||
|
||||
return ValidateUrlResponse(supported=True)
|
||||
|
||||
|
||||
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
|
||||
async def create_job_from_url(
|
||||
request: Request,
|
||||
@@ -1598,6 +1748,17 @@ async def create_job_from_url(
|
||||
)
|
||||
|
||||
try:
|
||||
# Reject DRM-protected streaming links upfront (Apple Music, Spotify,
|
||||
# Tidal, etc.). These can never be downloaded, so creating a job would
|
||||
# only fail deep in the pipeline with a cryptic error and tempt the user
|
||||
# into a futile retry storm.
|
||||
unsupported_platform = _unsupported_url_platform(body.url)
|
||||
if unsupported_platform:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=_drm_unsupported_detail(locale, unsupported_platform),
|
||||
)
|
||||
|
||||
# Validate URL
|
||||
if not _validate_url(body.url):
|
||||
raise HTTPException(
|
||||
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
@@ -227,6 +228,48 @@ 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,
|
||||
|
||||
@@ -396,6 +396,11 @@ async def edit_completed_track(
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
# Also remove the Nomad 720p master from the GCS fast-sync mirror
|
||||
# (prefix-keyed by brand_code, so it covers renames). Non-fatal,
|
||||
# Nomad-brand only, no-op otherwise.
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
except Exception as e:
|
||||
@@ -576,6 +581,8 @@ _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']
|
||||
@@ -1112,6 +1119,18 @@ async def submit_corrections(
|
||||
from backend.services.storage_service import StorageService
|
||||
storage = StorageService()
|
||||
|
||||
# Safety net: never persist word timings that fall outside their segment.
|
||||
# Frontend should already prevent this; this guarantees clean stored data
|
||||
# (the render worker reads corrections_updated.json verbatim).
|
||||
from backend.services.timing_sanitizer import sanitize_corrections
|
||||
sanitized, clamp_count = sanitize_corrections(submission.corrections)
|
||||
if clamp_count:
|
||||
logger.warning(
|
||||
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
|
||||
f"in submitted corrections before persisting"
|
||||
)
|
||||
submission.corrections = sanitized
|
||||
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, submission.corrections)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
@@ -1463,6 +1482,13 @@ 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}")
|
||||
@@ -1961,9 +1987,18 @@ async def retry_job(
|
||||
"retry_stage": "screens_generation"
|
||||
}
|
||||
|
||||
# If we have input audio (uploaded or from URL), restart from beginning
|
||||
elif job.input_media_gcs_path or job.url:
|
||||
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
|
||||
# If the input audio is already in GCS (an uploaded file, or a URL whose
|
||||
# download succeeded), restart from beginning — the audio/lyrics workers
|
||||
# re-fetch it from GCS.
|
||||
#
|
||||
# A URL job whose download never succeeded has only `job.url` and NO
|
||||
# audio in GCS, so it must NOT take this branch: triggering the workers
|
||||
# would just fail with "Failed to download audio file" and Cloud Run
|
||||
# would retry them repeatedly (see job 7f36304a — an Apple Music link).
|
||||
# Such jobs fall through to the "resubmit" refusal below, since there is
|
||||
# no worker that re-downloads a generic URL.
|
||||
elif job.input_media_gcs_path:
|
||||
logger.info(f"Job {job_id}: Has input audio in GCS, restarting from beginning")
|
||||
|
||||
# Clear error state and any partial progress
|
||||
job_manager.update_job(job_id, {
|
||||
@@ -2252,6 +2287,14 @@ async def cleanup_distribution(
|
||||
"status": "skipped",
|
||||
"reason": "no files found to delete",
|
||||
}
|
||||
|
||||
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too, so a
|
||||
# re-finalise (incl. artist/title rename) doesn't leave the old cut on
|
||||
# kjbox. Prefix-keyed by brand_code (covers renames); the subsequent
|
||||
# re-run's push re-adds the new master. Non-fatal, Nomad-only.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
else:
|
||||
results["gdrive"] = {
|
||||
"status": "failed",
|
||||
@@ -2422,11 +2465,21 @@ 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
|
||||
# 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.
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_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
|
||||
|
||||
tenant_id = session.get('tenant_id') or ""
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""POST /api/parse-karaoke-titles — batch karaoke-filename → artist/title.
|
||||
|
||||
Internal admin endpoint used by kjbox to canonicalise downloaded-file names.
|
||||
Reuses the Vertex Gemini parser; never blocks the caller (kjbox degrades to a
|
||||
deterministic guess when this is unavailable).
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.parse_titles import parse_titles
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["parse-titles"])
|
||||
|
||||
|
||||
class ParseItem(BaseModel):
|
||||
id: str
|
||||
filename: str
|
||||
channel: Optional[str] = None
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
class ParseRequest(BaseModel):
|
||||
items: list[ParseItem]
|
||||
|
||||
|
||||
class ParseResult(BaseModel):
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
confidence: float
|
||||
|
||||
|
||||
class ParseResponse(BaseModel):
|
||||
results: list[ParseResult]
|
||||
|
||||
|
||||
@router.post("/parse-karaoke-titles", response_model=ParseResponse)
|
||||
async def parse_karaoke_titles(
|
||||
body: ParseRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
items = [i.model_dump() for i in body.items]
|
||||
results = await parse_titles(items)
|
||||
logger.info("parse-karaoke-titles: %d items", len(items))
|
||||
return {"results": results}
|
||||
@@ -44,6 +44,11 @@ from backend.services.custom_lyrics_service import (
|
||||
CustomLyricsServiceError,
|
||||
get_custom_lyrics_service,
|
||||
)
|
||||
from backend.services.auto_correct import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
|
||||
class LineMetadataResponse(_PydBaseModel):
|
||||
@@ -70,11 +75,49 @@ class CustomLyricsResponse(_PydBaseModel):
|
||||
model: str
|
||||
|
||||
|
||||
class AutoCorrectRequest(_PydBaseModel):
|
||||
segments: list[dict] # client's current working corrected_segments
|
||||
reference_lyrics: dict # client's reference sources (incl. user-added)
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
settings: Optional[dict] = None # AutoCorrectSettings knobs
|
||||
|
||||
|
||||
class AutoCorrectSuggestionResponse(_PydBaseModel):
|
||||
id: str
|
||||
op: str # "replace" | "delete" | "insert_after"
|
||||
word_ids: list[str]
|
||||
segment_ids: list[str]
|
||||
original_text: str
|
||||
new_text: str
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
models: list[str]
|
||||
consensus: int
|
||||
total_models: int
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
class AutoCorrectResponse(_PydBaseModel):
|
||||
suggestions: list[AutoCorrectSuggestionResponse]
|
||||
model: str
|
||||
elapsed_seconds: float
|
||||
settings_applied: dict
|
||||
warnings: list[str]
|
||||
cached: bool = False
|
||||
|
||||
|
||||
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_custom_lyrics_service()
|
||||
|
||||
|
||||
def _get_auto_correct_service_dep() -> AutoCorrectService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_auto_correct_service()
|
||||
|
||||
|
||||
async def _load_target_segments_for_custom_lyrics(
|
||||
job_id: str,
|
||||
target_lines: list[str],
|
||||
@@ -142,6 +185,7 @@ def _synthesized_segments(target_lines: list[str]) -> list[dict]:
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.output.timing_validation import LyricsTimingError
|
||||
|
||||
# Import from the unified style loader
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
@@ -636,6 +680,79 @@ async def generate_custom_lyrics(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/auto-correct", response_model=AutoCorrectResponse)
|
||||
async def auto_correct_suggestions(
|
||||
job_id: str,
|
||||
body: AutoCorrectRequest,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
service: AutoCorrectService = Depends(_get_auto_correct_service_dep),
|
||||
) -> AutoCorrectResponse:
|
||||
"""Generate AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless and strictly opt-in: one whole-song LLM call comparing the
|
||||
client's current working transcription against the reference lyrics.
|
||||
Returns word-id-keyed suggestions; nothing is applied server-side —
|
||||
the reviewer accepts or rejects each suggestion individually and
|
||||
persistence happens via the existing corrections/complete paths.
|
||||
"""
|
||||
from backend.services.auto_correct.settings import settings_from_dict
|
||||
|
||||
try:
|
||||
settings = settings_from_dict(body.settings or {})
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
|
||||
|
||||
with job_log_context(job_id), create_span("auto_correct_suggestions"):
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("segment_count", len(body.segments))
|
||||
logger.info(
|
||||
"auto-correct requested job=%s segments=%d sources=%d",
|
||||
job_id, len(body.segments), len(body.reference_lyrics),
|
||||
)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=body.segments,
|
||||
reference_lyrics=body.reference_lyrics,
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
settings=settings,
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
logger.info(
|
||||
"auto-correct completed job=%s suggestions=%d model=%s elapsed=%.1fs",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
|
||||
return AutoCorrectResponse(
|
||||
suggestions=[
|
||||
AutoCorrectSuggestionResponse(
|
||||
id=s.id,
|
||||
op=s.op,
|
||||
word_ids=s.word_ids,
|
||||
segment_ids=s.segment_ids,
|
||||
original_text=s.original_text,
|
||||
new_text=s.new_text,
|
||||
reason=s.reason,
|
||||
category=s.category,
|
||||
confidence=s.confidence,
|
||||
models=s.models,
|
||||
consensus=s.consensus,
|
||||
total_models=s.total_models,
|
||||
conflict_group=s.conflict_group,
|
||||
)
|
||||
for s in result.suggestions
|
||||
],
|
||||
model=result.model,
|
||||
elapsed_seconds=result.elapsed_seconds,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
warnings=result.warnings,
|
||||
cached=result.cached,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(
|
||||
job_id: str,
|
||||
@@ -1110,6 +1227,13 @@ async def generate_preview_video(
|
||||
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError as timing_err:
|
||||
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
|
||||
# user-fixable input problem, not a server fault. Return 422 with an
|
||||
# actionable message instead of a cryptic 500.
|
||||
logger.warning(f"Job {job_id}: Preview blocked — lyrics not synchronized: {timing_err}")
|
||||
span.set_attribute("error", "lyrics_not_synchronized")
|
||||
raise HTTPException(status_code=422, detail=str(timing_err)) from timing_err
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to generate preview video: {e}", exc_info=True)
|
||||
span.set_attribute("error", str(e))
|
||||
@@ -1817,7 +1941,8 @@ async def apply_audio_edit(
|
||||
"""
|
||||
Apply an edit operation to the input audio.
|
||||
|
||||
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
|
||||
Supported operations: trim_start, trim_end, cut, mute, fade_in, fade_out,
|
||||
join_start, join_end.
|
||||
Returns updated waveform data and playback URL.
|
||||
"""
|
||||
import uuid
|
||||
@@ -1831,7 +1956,7 @@ async def apply_audio_edit(
|
||||
if not operation:
|
||||
raise HTTPException(status_code=400, detail="Missing 'operation' field")
|
||||
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "fade_in", "fade_out", "join_start", "join_end"}
|
||||
if operation not in valid_operations:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
|
||||
|
||||
|
||||
@@ -481,6 +481,32 @@ async def verify_magic_link(
|
||||
)
|
||||
|
||||
|
||||
class MagicLinkStatusResponse(BaseModel):
|
||||
status: str # "valid" | "used" | "expired" | "invalid"
|
||||
|
||||
|
||||
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
|
||||
async def magic_link_status(
|
||||
token: str,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Read-only status of a magic link — does NOT consume it.
|
||||
|
||||
The verify page calls this on load so it can show the correct UI upfront:
|
||||
the "Complete Sign-In" gate for a valid link, or an "already used / expired"
|
||||
message for a dead one — without making the user click only to then fail.
|
||||
|
||||
This endpoint is intentionally non-mutating so that an email link-scanner
|
||||
which renders the verify page (and triggers this read) cannot burn a still-
|
||||
valid token before the real user clicks. Token consumption happens only in
|
||||
the separate GET /auth/verify, which requires an explicit user click.
|
||||
"""
|
||||
if not token or not token.strip():
|
||||
return MagicLinkStatusResponse(status="invalid")
|
||||
return MagicLinkStatusResponse(status=user_service.get_magic_link_status(token))
|
||||
|
||||
|
||||
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
|
||||
async def resend_magic_link_from_token(
|
||||
request: ResendFromTokenRequest,
|
||||
|
||||
@@ -20,6 +20,13 @@ class Settings(BaseSettings):
|
||||
gcs_temp_bucket: str = os.getenv("GCS_TEMP_BUCKET", "karaoke-gen-temp")
|
||||
gcs_output_bucket: str = os.getenv("GCS_OUTPUT_BUCKET", "karaoke-gen-outputs")
|
||||
firestore_collection: str = os.getenv("FIRESTORE_COLLECTION", "jobs")
|
||||
|
||||
# Nomad master fast-sync: push freshly-published Nomad 720p masters straight to the
|
||||
# Divebar GCS mirror so kjbox (which mirrors that folder every 5 min) picks them up
|
||||
# within minutes instead of waiting for the nightly Drive->GCS VM. Nomad-brand only.
|
||||
divebar_files_bucket: str = os.getenv("DIVEBAR_FILES_BUCKET", "nomadkaraoke-divebar-files")
|
||||
nomad_master_gcs_prefix: str = os.getenv("NOMAD_MASTER_GCS_PREFIX", "files/Nomad Karaoke/MP4-720p")
|
||||
nomad_master_fast_sync_enabled: bool = os.getenv("NOMAD_MASTER_FAST_SYNC_ENABLED", "true").lower() == "true"
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
@@ -88,6 +95,48 @@ class Settings(BaseSettings):
|
||||
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
|
||||
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
|
||||
|
||||
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
|
||||
# review UI. Stateless: one whole-song LLM call returning word-level
|
||||
# suggestions the reviewer accepts/rejects individually.
|
||||
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
|
||||
# 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"))
|
||||
|
||||
# Batch karaoke-filename parser (kjbox download-naming). Reuses the Vertex
|
||||
# Gemini stack. Larger timeout than match_judge because it batches ~200 items.
|
||||
parse_titles_enabled: bool = os.getenv("PARSE_TITLES_ENABLED", "true").lower() in (
|
||||
"1", "true", "yes",
|
||||
)
|
||||
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.5-flash")
|
||||
parse_titles_timeout_ms: int = int(os.getenv("PARSE_TITLES_TIMEOUT_MS", "20000"))
|
||||
parse_titles_max_items: int = int(os.getenv("PARSE_TITLES_MAX_ITEMS", "200"))
|
||||
# Items per Gemini call: large client batches are split into concurrent
|
||||
# chunks of this size so one call never outgrows parse_titles_timeout_ms
|
||||
# (a 100-item single call did, blanking the whole batch).
|
||||
parse_titles_chunk_size: int = int(os.getenv("PARSE_TITLES_CHUNK_SIZE", "10"))
|
||||
|
||||
# Cloud Tasks (for scalable worker coordination)
|
||||
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
|
||||
+3
-1
@@ -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
|
||||
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, parse_titles
|
||||
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,6 +187,8 @@ 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(parse_titles.router, prefix="/api") # kjbox karaoke-filename parser
|
||||
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)
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Operational and maintenance scripts for the karaoke-gen backend."""
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/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()
|
||||
@@ -106,6 +106,54 @@ class AudioEditService:
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
# Fades must be anchored to a clip edge — FFmpeg's afade silences audio outside
|
||||
# the ramp, so a mid-clip fade would unexpectedly mute the rest of the track.
|
||||
# The tolerance matches the editor UI's edge gating (start < 1s / end within 1s).
|
||||
FADE_ANCHOR_TOLERANCE_SECONDS = 1.0
|
||||
|
||||
def fade_region(
|
||||
self, input_path: str, start: float, end: float, direction: str, output_path: str
|
||||
) -> AudioMetadata:
|
||||
"""Apply a fade in or out anchored to a clip edge (preserves duration).
|
||||
|
||||
direction='in' ramps the volume from silence to full over [0, end];
|
||||
direction='out' ramps from full to silence over [start, clip_end].
|
||||
|
||||
Anchoring is enforced server-side (not just in the UI) because FFmpeg's
|
||||
afade filter silences audio outside the ramp window: a fade-in is forced
|
||||
to begin at the clip start, and a fade-out to finish at the clip end, so a
|
||||
non-anchored request can never silently mute the rest of the track.
|
||||
"""
|
||||
if direction not in ("in", "out"):
|
||||
raise ValueError(f"Invalid fade direction: {direction}")
|
||||
if start < 0 or end <= start:
|
||||
raise ValueError(f"Invalid fade region: start={start}, end={end}")
|
||||
|
||||
total = self.get_metadata(input_path).duration_seconds
|
||||
tol = self.FADE_ANCHOR_TOLERANCE_SECONDS
|
||||
if end > total + tol:
|
||||
raise ValueError(f"Fade region exceeds clip duration ({end} > {total})")
|
||||
|
||||
if direction == "in":
|
||||
if start > tol:
|
||||
raise ValueError(f"fade_in must be anchored to the clip start (got start={start})")
|
||||
fade_start, fade_duration = 0.0, end
|
||||
else:
|
||||
if end < total - tol:
|
||||
raise ValueError(f"fade_out must be anchored to the clip end (got end={end}, duration={total})")
|
||||
fade_start, fade_duration = start, total - start
|
||||
|
||||
if fade_duration <= 0:
|
||||
raise ValueError(f"Fade region must have positive duration (got {fade_duration})")
|
||||
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-af", f"afade=t={direction}:st={fade_start}:d={fade_duration}",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
|
||||
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
|
||||
if position == "start":
|
||||
@@ -156,6 +204,11 @@ class AudioEditService:
|
||||
metadata = self.mute_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], local_output
|
||||
)
|
||||
elif operation in ("fade_in", "fade_out"):
|
||||
direction = "in" if operation == "fade_in" else "out"
|
||||
metadata = self.fade_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], direction, local_output
|
||||
)
|
||||
elif operation in ("join_start", "join_end"):
|
||||
# Download the upload file
|
||||
upload_gcs_path = params["upload_gcs_path"]
|
||||
|
||||
@@ -18,7 +18,8 @@ downloads since Cloud Run doesn't support BitTorrent peer connections.
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Optional
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import nest_asyncio
|
||||
|
||||
@@ -47,6 +48,151 @@ 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.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless suggestion generation: the client posts its current working
|
||||
segments, the service returns word-level suggestions (replace / delete /
|
||||
insert_after) referencing word ids. Nothing is applied server-side — the
|
||||
reviewer accepts or rejects each suggestion in the UI.
|
||||
"""
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AutoCorrectService",
|
||||
"AutoCorrectServiceError",
|
||||
"get_auto_correct_service",
|
||||
]
|
||||
@@ -0,0 +1,94 @@
|
||||
"""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
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Prompt construction for AI auto-correction suggestions.
|
||||
|
||||
Kept in sync with the offline eval harness
|
||||
(lyrics-alignment-eval-dataset/auto-correct-eval/harness.py) — changes here
|
||||
should be re-scored against the 30-job ground-truth dataset.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"suggestions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"op": {
|
||||
"type": "string",
|
||||
"enum": ["replace", "delete", "insert_after"],
|
||||
},
|
||||
"start_idx": {"type": "integer"},
|
||||
"end_idx": {"type": "integer"},
|
||||
"new_text": {"type": "string"},
|
||||
"reason": {"type": "string"},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
],
|
||||
},
|
||||
"confidence": {"type": "number"},
|
||||
},
|
||||
"required": [
|
||||
"op",
|
||||
"start_idx",
|
||||
"end_idx",
|
||||
"new_text",
|
||||
"reason",
|
||||
"category",
|
||||
"confidence",
|
||||
],
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["suggestions"],
|
||||
}
|
||||
|
||||
_BASE_SYSTEM_PROMPT = """\
|
||||
You are an expert lyrics transcription reviewer for a karaoke video company. \
|
||||
You are given an automatic speech transcription of a song's vocals (already \
|
||||
segmented into lines, each word tagged with a numeric index) plus lyrics for \
|
||||
the same song from internet sources. Internet sources are usually (not always) \
|
||||
closer to the true lyrics, but lack the transcription's timing and line layout.
|
||||
|
||||
Propose word-level corrections to the TRANSCRIPTION so its words match what is \
|
||||
actually sung. A human reviewer who has listened to the song will accept or \
|
||||
reject each suggestion individually, so precision matters far more than \
|
||||
recall: only suggest a change when you are confident a careful human reviewer \
|
||||
would make it. If reference sources disagree and you have no other evidence, \
|
||||
make no suggestion.
|
||||
|
||||
Guidelines:
|
||||
- Transcription errors are usually sound-alike mishearings: the wrong words \
|
||||
sound similar to the true lyric (e.g. "glory" vs "chlorine", "ladder" vs \
|
||||
"matter"). Prefer corrections that are phonetically plausible.
|
||||
- The same mishearing often repeats in every chorus; correct every occurrence.
|
||||
- Keep the transcription's line structure. NEVER suggest timing changes.
|
||||
- Match the casing and punctuation style of the surrounding transcription.
|
||||
- Do not censor or bowdlerise explicit lyrics.
|
||||
- Do not rewrite lines wholesale unless the transcription is clearly garbled \
|
||||
and a reference line is unambiguously what is sung at that point.
|
||||
- new_text may contain multiple words, or differ in word count from the span \
|
||||
it replaces.
|
||||
"""
|
||||
|
||||
_ADLIB_ALLOWED = """\
|
||||
- Parenthesised backing vocals / adlibs that the transcription contains but \
|
||||
references omit may be real (references often drop them). Only suggest \
|
||||
deleting them when they look like transcription hallucinations or the \
|
||||
references make clear they are not sung lead lines; use category \
|
||||
"adlib_removal" and lower confidence.
|
||||
"""
|
||||
|
||||
_ADLIB_FORBIDDEN = """\
|
||||
- NEVER suggest deleting backing vocals or adlibs solely because the \
|
||||
references omit them; references often drop adlibs that are really sung.
|
||||
"""
|
||||
|
||||
_INSERTIONS_FORBIDDEN = """\
|
||||
- NEVER use the "insert_after" operation; only suggest "replace" and \
|
||||
"delete" operations.
|
||||
"""
|
||||
|
||||
_OUTPUT_SPEC = """\
|
||||
Output JSON only, matching this shape exactly:
|
||||
{"suggestions": [{"op": "replace"|"delete"|"insert_after",
|
||||
"start_idx": <int>, "end_idx": <int>,
|
||||
"new_text": "<replacement, empty for delete>",
|
||||
"reason": "<short justification>",
|
||||
"category": "mishearing"|"grammar"|"adlib_removal"|"repeated_chorus_fix"|"formatting"|"other",
|
||||
"confidence": <0.0-1.0>}]}
|
||||
start_idx and end_idx are inclusive word indices. For "insert_after", \
|
||||
start_idx == end_idx == the index of the word the new text should follow. \
|
||||
If nothing needs changing, return {"suggestions": []}.
|
||||
"""
|
||||
|
||||
|
||||
def build_system_prompt(settings: AutoCorrectSettings) -> str:
|
||||
parts = [_BASE_SYSTEM_PROMPT]
|
||||
parts.append(_ADLIB_ALLOWED if settings.suggest_adlib_removal else _ADLIB_FORBIDDEN)
|
||||
if not settings.allow_insertions:
|
||||
parts.append(_INSERTIONS_FORBIDDEN)
|
||||
parts.append(_OUTPUT_SPEC)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def build_user_prompt(
|
||||
*,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: str | None,
|
||||
title: str | None,
|
||||
) -> str:
|
||||
"""Render segments (with global word indices) + reference sources."""
|
||||
lines = [f"ARTIST: {artist or 'unknown'}", f"TITLE: {title or 'unknown'}", "", "TRANSCRIPTION:"]
|
||||
idx = 0
|
||||
for li, seg in enumerate(segments):
|
||||
toks = []
|
||||
for w in seg.get("words") or []:
|
||||
toks.append(f"{idx}:{w.get('text', '')}")
|
||||
idx += 1
|
||||
lines.append(f"[L{li:03d}] " + " ".join(toks))
|
||||
for source, ref in (reference_lyrics or {}).items():
|
||||
lines.append("")
|
||||
lines.append(f"REFERENCE LYRICS ({source}):")
|
||||
for seg in ref.get("segments") or []:
|
||||
lines.append(seg.get("text", ""))
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,621 @@
|
||||
"""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 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,
|
||||
build_user_prompt,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_OPS = {"replace", "delete", "insert_after"}
|
||||
VALID_CATEGORIES = {
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
}
|
||||
|
||||
|
||||
class AutoCorrectServiceError(Exception):
|
||||
def __init__(self, message: str, *, status_code: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
@dataclass
|
||||
class Suggestion:
|
||||
id: str
|
||||
op: str # replace | delete | insert_after
|
||||
word_ids: list[str] # targeted words (replace/delete); [anchor] for insert_after
|
||||
segment_ids: list[str] # segments containing the targeted words
|
||||
original_text: str # current text of the targeted span ("" for insert_after)
|
||||
new_text: str # replacement text ("" for delete)
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
# Multi-model compare metadata. In single-model mode models has one
|
||||
# entry and consensus == total_models == 1.
|
||||
models: list[str] = field(default_factory=list)
|
||||
consensus: int = 1
|
||||
total_models: int = 1
|
||||
# Set when other suggestions target overlapping words with a different
|
||||
# outcome — the UI lets the reviewer pick at most one per group.
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoCorrectResult:
|
||||
suggestions: list[Suggestion]
|
||||
model: str # comma-joined when compare mode queried several models
|
||||
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:
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
|
||||
def suggest(
|
||||
self,
|
||||
*,
|
||||
job_id: str,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> AutoCorrectResult:
|
||||
if not segments:
|
||||
raise AutoCorrectServiceError("segments is empty")
|
||||
if not reference_lyrics:
|
||||
raise AutoCorrectServiceError(
|
||||
"no reference lyrics available — auto-correction needs at least "
|
||||
"one internet/reference source to compare against",
|
||||
status_code=422,
|
||||
)
|
||||
|
||||
# Flat word list mirrors the prompt's global indices.
|
||||
flat: list[tuple[str, str, str]] = [] # (word_id, word_text, segment_id)
|
||||
for seg in segments:
|
||||
if not seg.get("id"):
|
||||
raise AutoCorrectServiceError("all segments must have ids")
|
||||
for w in seg.get("words") or []:
|
||||
if not w.get("id"):
|
||||
raise AutoCorrectServiceError("all words must have ids")
|
||||
flat.append((w["id"], w.get("text", ""), seg["id"]))
|
||||
|
||||
system_prompt = build_system_prompt(settings)
|
||||
user_prompt = build_user_prompt(
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
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
|
||||
)
|
||||
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
|
||||
|
||||
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
|
||||
futures = {
|
||||
ex.submit(
|
||||
self._call_model, m, system_prompt, user_prompt, job_id=job_id
|
||||
): m
|
||||
for m in models
|
||||
}
|
||||
for fut, m in futures.items():
|
||||
try:
|
||||
raw, usage = fut.result()
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
except AutoCorrectServiceError as exc:
|
||||
# One model failing (call OR malformed output) must not
|
||||
# abort compare mode; the rest still return results.
|
||||
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(
|
||||
"all AI models failed", status_code=502
|
||||
)
|
||||
|
||||
merged = self._merge(per_model, flat)
|
||||
elapsed = time.time() - t0
|
||||
model_label = ", ".join(per_model.keys())
|
||||
logger.info(
|
||||
"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(
|
||||
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:
|
||||
configured = [
|
||||
m.strip()
|
||||
for m in self.settings.auto_correct_compare_models.replace(",", ";").split(";")
|
||||
if m.strip()
|
||||
]
|
||||
# De-dupe while preserving order.
|
||||
seen: set[str] = set()
|
||||
models = [m for m in configured if not (m in seen or seen.add(m))]
|
||||
if len(models) >= 2:
|
||||
return models
|
||||
logger.warning(
|
||||
"compare_models requested but AUTO_CORRECT_COMPARE_MODELS has "
|
||||
"%d usable entries; falling back to single model", len(models),
|
||||
)
|
||||
return [self.settings.auto_correct_model]
|
||||
|
||||
@staticmethod
|
||||
def _merge(
|
||||
per_model: dict[str, list[Suggestion]],
|
||||
flat: list[tuple[str, str, str]],
|
||||
) -> list[Suggestion]:
|
||||
"""Deduplicate identical suggestions across models, tag consensus,
|
||||
assign conflict groups to overlapping non-identical suggestions, and
|
||||
sort by document position."""
|
||||
total = len(per_model)
|
||||
merged: dict[tuple, Suggestion] = {}
|
||||
for model, suggestions in per_model.items():
|
||||
for s in suggestions:
|
||||
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
|
||||
existing = merged.get(key)
|
||||
if existing is None:
|
||||
s.models = [model]
|
||||
s.consensus = 1
|
||||
s.total_models = total
|
||||
merged[key] = s
|
||||
else:
|
||||
existing.models.append(model)
|
||||
existing.consensus += 1
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
|
||||
result = list(merged.values())
|
||||
|
||||
# Conflict groups: suggestions sharing any target word but not merged
|
||||
# above disagree about the same span — reviewer picks at most one.
|
||||
# (insert_after anchors are excluded: inserting after a word does not
|
||||
# conflict with editing that word.)
|
||||
by_word: dict[str, list[int]] = {}
|
||||
for i, s in enumerate(result):
|
||||
if s.op == "insert_after":
|
||||
continue
|
||||
for wid in s.word_ids:
|
||||
by_word.setdefault(wid, []).append(i)
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
parent[find(other)] = find(overlapping[0])
|
||||
roots: dict[int, list[int]] = {}
|
||||
for i in range(len(result)):
|
||||
roots.setdefault(find(i), []).append(i)
|
||||
for members in roots.values():
|
||||
if len(members) < 2:
|
||||
continue
|
||||
group = str(uuid.uuid4())
|
||||
for i in members:
|
||||
result[i].conflict_group = group
|
||||
|
||||
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
|
||||
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
|
||||
return result
|
||||
|
||||
# ---- internals ----
|
||||
|
||||
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."""
|
||||
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]]:
|
||||
import os
|
||||
|
||||
import anthropic
|
||||
|
||||
if not os.environ.get("ANTHROPIC_API_KEY"):
|
||||
# No silent fallback to another provider — surface the
|
||||
# misconfiguration so it gets fixed, not masked.
|
||||
logger.error(
|
||||
"auto-correct model %s requires ANTHROPIC_API_KEY which is not set "
|
||||
"(job=%s)", model, job_id,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is not configured", status_code=502
|
||||
)
|
||||
|
||||
# Structured outputs require additionalProperties: false on objects;
|
||||
# the Vertex variant of the schema omits it, so inject here. Deep-copy
|
||||
# because the google-genai SDK mutates schema dicts in place (it adds
|
||||
# 'property_ordering', which the Anthropic API rejects).
|
||||
import copy
|
||||
|
||||
base = copy.deepcopy(RESPONSE_SCHEMA)
|
||||
for obj in (base, base["properties"]["suggestions"]["items"]):
|
||||
obj.pop("property_ordering", None)
|
||||
obj.pop("propertyOrdering", None)
|
||||
obj["additionalProperties"] = False
|
||||
strict_schema = base
|
||||
client = anthropic.Anthropic(timeout=120.0)
|
||||
try:
|
||||
response = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=16000,
|
||||
system=system_prompt,
|
||||
messages=[{"role": "user", "content": user_prompt}],
|
||||
thinking={"type": "adaptive"},
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
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
|
||||
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
# Milliseconds; bounds the call so a hung model never strands the UI.
|
||||
http_options=types.HttpOptions(timeout=120_000),
|
||||
)
|
||||
# Deep-copy: the google-genai SDK mutates the schema dict in place,
|
||||
# which would poison the shared module-level constant for other
|
||||
# providers running in the same process.
|
||||
import copy
|
||||
|
||||
try:
|
||||
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),
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._gemini_usage(response)
|
||||
try:
|
||||
return json.loads(response.text), usage
|
||||
except (json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _validate(
|
||||
self,
|
||||
raw: Any,
|
||||
flat: list[tuple[str, str, str]],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> tuple[list[Suggestion], list[str]]:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("suggestions"), list):
|
||||
raise AutoCorrectServiceError(
|
||||
"AI response missing 'suggestions' list", status_code=502
|
||||
)
|
||||
n = len(flat)
|
||||
out: list[Suggestion] = []
|
||||
warnings: list[str] = []
|
||||
for i, s in enumerate(raw["suggestions"]):
|
||||
problem = self._check(s, n, settings)
|
||||
if problem:
|
||||
warnings.append(f"dropped suggestion {i}: {problem}")
|
||||
continue
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
if s["op"] == "insert_after":
|
||||
word_ids = [flat[start][0]]
|
||||
segment_ids = [flat[start][2]]
|
||||
original_text = ""
|
||||
else:
|
||||
span = flat[start : end + 1]
|
||||
word_ids = [w[0] for w in span]
|
||||
segment_ids = sorted({w[2] for w in span})
|
||||
original_text = " ".join(w[1] for w in span)
|
||||
out.append(
|
||||
Suggestion(
|
||||
id=str(uuid.uuid4()),
|
||||
op=s["op"],
|
||||
word_ids=word_ids,
|
||||
segment_ids=segment_ids,
|
||||
original_text=original_text,
|
||||
new_text="" if s["op"] == "delete" else str(s["new_text"]).strip(),
|
||||
reason=str(s.get("reason", "")),
|
||||
category=s["category"] if s.get("category") in VALID_CATEGORIES else "other",
|
||||
confidence=max(0.0, min(1.0, float(s["confidence"]))),
|
||||
)
|
||||
)
|
||||
return out, warnings
|
||||
|
||||
@staticmethod
|
||||
def _check(s: Any, n_words: int, settings: AutoCorrectSettings) -> Optional[str]:
|
||||
if not isinstance(s, dict):
|
||||
return "not an object"
|
||||
op = s.get("op")
|
||||
if op not in VALID_OPS:
|
||||
return f"invalid op {op!r}"
|
||||
try:
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
confidence = float(s["confidence"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return "missing/invalid indices or confidence"
|
||||
if not (0 <= start <= end < n_words):
|
||||
return f"indices out of range ({start}..{end} of {n_words})"
|
||||
if op == "insert_after" and not settings.allow_insertions:
|
||||
return "insertions disabled by settings"
|
||||
if op == "insert_after" and start != end:
|
||||
return "insert_after requires start_idx == end_idx"
|
||||
new_text = str(s.get("new_text", "")).strip()
|
||||
if op in ("replace", "insert_after") and not new_text:
|
||||
return f"{op} with empty new_text"
|
||||
if op == "delete" and new_text:
|
||||
return "delete with non-empty new_text"
|
||||
if confidence < settings.min_confidence:
|
||||
return f"confidence {confidence:.2f} below threshold"
|
||||
if (
|
||||
s.get("category") == "adlib_removal"
|
||||
and not settings.suggest_adlib_removal
|
||||
):
|
||||
return "adlib removal disabled by settings"
|
||||
return None
|
||||
|
||||
|
||||
_service_instance: Optional[AutoCorrectService] = None
|
||||
|
||||
|
||||
def get_auto_correct_service() -> AutoCorrectService:
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = AutoCorrectService()
|
||||
return _service_instance
|
||||
@@ -0,0 +1,47 @@
|
||||
"""User-facing knobs for AI auto-correction suggestions."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoCorrectSettings:
|
||||
"""Reviewer-tunable behaviour for a suggestion run.
|
||||
|
||||
suggest_adlib_removal: allow suggestions that delete transcribed
|
||||
backing-vocal / adlib phrases absent from the references.
|
||||
allow_insertions: allow suggestions that insert words the
|
||||
transcription missed entirely.
|
||||
min_confidence: drop suggestions below this confidence server-side
|
||||
(the UI can filter further client-side).
|
||||
compare_models: query every configured compare model in parallel,
|
||||
deduplicate identical suggestions and report per-suggestion
|
||||
model consensus (slower, costs one call per model).
|
||||
"""
|
||||
|
||||
suggest_adlib_removal: bool = True
|
||||
allow_insertions: bool = True
|
||||
min_confidence: float = 0.0
|
||||
compare_models: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def settings_from_dict(data: dict) -> AutoCorrectSettings:
|
||||
known = {f for f in AutoCorrectSettings.__dataclass_fields__}
|
||||
unknown = set(data) - known
|
||||
if unknown:
|
||||
raise ValueError(f"unknown settings: {sorted(unknown)}")
|
||||
merged = {**AutoCorrectSettings().to_dict(), **data}
|
||||
if not isinstance(merged["suggest_adlib_removal"], bool):
|
||||
raise ValueError("suggest_adlib_removal must be a boolean")
|
||||
if not isinstance(merged["allow_insertions"], bool):
|
||||
raise ValueError("allow_insertions must be a boolean")
|
||||
if not isinstance(merged["compare_models"], bool):
|
||||
raise ValueError("compare_models must be a boolean")
|
||||
mc = merged["min_confidence"]
|
||||
if isinstance(mc, bool) or not isinstance(mc, (int, float)) or not 0.0 <= float(mc) <= 1.0:
|
||||
raise ValueError("min_confidence must be a number between 0 and 1")
|
||||
merged["min_confidence"] = float(mc)
|
||||
return AutoCorrectSettings(**merged)
|
||||
@@ -15,6 +15,9 @@ class StopReason(str, Enum):
|
||||
MAX_ITERS_REACHED = "max_iters_reached"
|
||||
LINE_COUNT_MISMATCH = "line_count_mismatch"
|
||||
VERBATIM_SKIP = "verbatim_skip"
|
||||
# A repair iteration failed (e.g. the model returned an empty/blocked
|
||||
# response); we keep the best result found so far instead of failing.
|
||||
REPAIR_FAILED = "repair_failed"
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -247,11 +247,20 @@ class CustomLyricsService:
|
||||
settings=settings,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
# Repair is a best-effort *improvement* step. If a repair call
|
||||
# fails (e.g. the model returned an empty/blocked response, or a
|
||||
# transient Vertex error), we must NOT throw away the successful
|
||||
# initial result — that turned a working generation into a 500 and
|
||||
# a browser "NetworkError". Keep the best candidate found so far.
|
||||
# WARNING (not exception/ERROR): this is now a handled, non-fatal
|
||||
# degradation, so it should not trip the production error monitor.
|
||||
logger.warning(
|
||||
"custom_lyrics_repair_call_failed",
|
||||
exc_info=True,
|
||||
extra={"job_id": job_id, "iteration": iter_num, "stage": "repair"},
|
||||
)
|
||||
raise
|
||||
stop_reason = StopReason.REPAIR_FAILED
|
||||
break
|
||||
validations = self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=params.tolerance, fixed=settings.fixed_line_count,
|
||||
@@ -564,7 +573,40 @@ class CustomLyricsService:
|
||||
},
|
||||
),
|
||||
)
|
||||
return self._parse_lines(response.text)
|
||||
# The model can return no text (safety block, MAX_TOKENS with no content,
|
||||
# empty candidate). `response.text` is then None and json.loads(None) would
|
||||
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
|
||||
# reports a confusing "NetworkError". Surface a clean, diagnosable error.
|
||||
text = response.text
|
||||
if text is None:
|
||||
raise CustomLyricsServiceError(
|
||||
f"The AI returned an empty response ({self._describe_empty_response(response)}). "
|
||||
f"Please try again.",
|
||||
status_code=502,
|
||||
)
|
||||
return self._parse_lines(text)
|
||||
|
||||
@staticmethod
|
||||
def _describe_empty_response(response: Any) -> str:
|
||||
"""Best-effort reason for an empty model response, for logs and messages."""
|
||||
parts: list[str] = []
|
||||
try:
|
||||
block_reason = getattr(getattr(response, "prompt_feedback", None), "block_reason", None)
|
||||
if block_reason:
|
||||
parts.append(f"prompt_block={getattr(block_reason, 'name', block_reason)}")
|
||||
except Exception: # pragma: no cover - defensive
|
||||
pass
|
||||
try:
|
||||
candidates = getattr(response, "candidates", None) or []
|
||||
if candidates:
|
||||
finish = getattr(candidates[0], "finish_reason", None)
|
||||
if finish is not None:
|
||||
parts.append(f"finish_reason={getattr(finish, 'name', finish)}")
|
||||
else:
|
||||
parts.append("no_candidates")
|
||||
except Exception: # pragma: no cover - defensive
|
||||
pass
|
||||
return ", ".join(parts) if parts else "unknown"
|
||||
|
||||
@staticmethod
|
||||
def _parse_lines(text: str) -> list[str]:
|
||||
|
||||
@@ -151,6 +151,37 @@ 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,6 +65,12 @@ 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)
|
||||
|
||||
@@ -385,6 +391,10 @@ 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 {}
|
||||
@@ -396,6 +406,8 @@ 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,6 +350,7 @@ 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.
|
||||
@@ -371,6 +372,13 @@ 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:
|
||||
@@ -392,7 +400,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 path and warmup_ran and self._worker_manager is not None:
|
||||
if allow_failover and path and warmup_ran and self._worker_manager is not None:
|
||||
resolved = f"{self._get_worker_url()}{path}"
|
||||
if resolved != url:
|
||||
logger.info(
|
||||
@@ -424,7 +432,7 @@ class EncodingService:
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if attempt == 0:
|
||||
if allow_failover and attempt == 0:
|
||||
try:
|
||||
await self._warmup_encoding_worker_fallback(job_id)
|
||||
warmup_ran = True
|
||||
@@ -530,12 +538,23 @@ class EncodingService:
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
|
||||
async def get_job_status(
|
||||
self, job_id: str, worker_url: Optional[str] = None
|
||||
) -> 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
|
||||
@@ -546,7 +565,10 @@ class EncodingService:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = f"/status/{job_id}"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
if worker_url:
|
||||
url = f"{worker_url}{path}"
|
||||
else:
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
@@ -555,7 +577,10 @@ class EncodingService:
|
||||
headers=headers,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
# 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,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -573,6 +598,7 @@ 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.
|
||||
@@ -587,6 +613,11 @@ 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
|
||||
@@ -607,7 +638,7 @@ class EncodingService:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
status = await self.get_job_status(job_id, worker_url=worker_url)
|
||||
# Reset failure counter on successful poll
|
||||
consecutive_failures = 0
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
|
||||
@@ -708,11 +739,14 @@ 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
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
|
||||
async def submit_preview_encoding_job(
|
||||
@@ -837,11 +871,15 @@ 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(
|
||||
@@ -961,11 +999,18 @@ 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
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
|
||||
@@ -177,7 +177,23 @@ 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',
|
||||
@@ -194,6 +210,8 @@ 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,6 +827,20 @@ 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
|
||||
|
||||
@@ -266,6 +266,7 @@ class GoogleDriveService:
|
||||
brand_code: str,
|
||||
base_name: str,
|
||||
output_files: dict,
|
||||
warnings: Optional[list] = None,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Upload final files to public share folder structure.
|
||||
@@ -322,6 +323,18 @@ class GoogleDriveService:
|
||||
uploaded_files["mp4_720p"] = file_id
|
||||
logger.info(f"Uploaded 720p MP4 to MP4-720p/ folder")
|
||||
|
||||
# Fast-sync the 720p master straight to the Divebar GCS mirror so kjbox
|
||||
# (which mirrors that folder every 5 min) picks it up within minutes,
|
||||
# instead of waiting for the nightly Drive->GCS VM. Nomad-brand only,
|
||||
# best-effort, never fatal to the Drive upload. A failure is surfaced as
|
||||
# a distribution warning (drives the admin alert) so this can't silently
|
||||
# rot into "nightly VM only" — the nightly VM stays the backfill net.
|
||||
fast_sync_warning = self._fast_sync_nomad_master(
|
||||
brand_code, mp4_720p_path, f"{filename_base}.mp4"
|
||||
)
|
||||
if fast_sync_warning and warnings is not None:
|
||||
warnings.append(fast_sync_warning)
|
||||
|
||||
# Upload CDG ZIP to CDG/
|
||||
cdg_zip_path = output_files.get("final_karaoke_cdg_zip")
|
||||
if cdg_zip_path and os.path.exists(cdg_zip_path):
|
||||
@@ -337,6 +350,42 @@ class GoogleDriveService:
|
||||
logger.info(f"Public share upload complete: {len(uploaded_files)} files uploaded")
|
||||
return uploaded_files
|
||||
|
||||
def _fast_sync_nomad_master(
|
||||
self, brand_code: str, local_720p_path: str, filename: str
|
||||
) -> Optional[str]:
|
||||
"""Best-effort push of a freshly-published Nomad 720p master to the Divebar
|
||||
GCS mirror so kjbox picks it up within minutes (vs the nightly VM).
|
||||
|
||||
No-op unless the fast-sync is enabled and this is a public Nomad release
|
||||
(``NOMAD-####``, excluding ``NOMADNP`` private tracks). Never raises — the
|
||||
Drive upload has already succeeded and the nightly VM is the backfill net.
|
||||
|
||||
Returns a human-readable warning string on failure (so the caller can surface
|
||||
it via ``distribution_warnings`` / the admin alert), or ``None`` on
|
||||
success or when skipped.
|
||||
"""
|
||||
try:
|
||||
from backend.config import settings
|
||||
from backend.services.nomad_master_mirror import (
|
||||
NomadMasterMirror,
|
||||
is_nomad_public_brand,
|
||||
)
|
||||
|
||||
if not settings.nomad_master_fast_sync_enabled:
|
||||
return None
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return None
|
||||
|
||||
if NomadMasterMirror().push_720p(local_720p_path, filename):
|
||||
return None
|
||||
return (
|
||||
f"Nomad master fast-sync to the GCS mirror failed for {filename} "
|
||||
f"(the nightly Drive->GCS VM will backfill it)"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning(f"Nomad master fast-sync skipped (unexpected error): {e}")
|
||||
return f"Nomad master fast-sync errored for {filename}: {e}"
|
||||
|
||||
def delete_file(self, file_id: str) -> bool:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
@@ -387,6 +436,69 @@ class GoogleDriveService:
|
||||
results[file_id] = self.delete_file(file_id)
|
||||
return results
|
||||
|
||||
def _search_subfolder_for_brand(
|
||||
self, root_folder_id: str, subfolder: str, brand_code: str
|
||||
) -> list[str]:
|
||||
"""Return file IDs in ``subfolder`` whose name starts with ``{brand_code} - ``.
|
||||
|
||||
Read-only Drive lookups, wrapped in retry-with-backoff so transient
|
||||
connection drops (SSL EOF / BrokenPipe against idle Cloud Run containers)
|
||||
self-heal instead of surfacing as "GDrive brand_code search incomplete".
|
||||
Non-transient errors reraise immediately for the caller to record.
|
||||
"""
|
||||
|
||||
def _do_search() -> list[str]:
|
||||
ids: list[str] = []
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
return ids
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
return ids
|
||||
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
return _do_search()
|
||||
|
||||
return [] # pragma: no cover - Retrying always returns or raises
|
||||
|
||||
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
|
||||
"""
|
||||
Search for files in public share subfolders matching a brand code prefix.
|
||||
@@ -411,43 +523,9 @@ class GoogleDriveService:
|
||||
|
||||
for subfolder in subfolders:
|
||||
try:
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
found_ids.extend(
|
||||
self._search_subfolder_for_brand(root_folder_id, subfolder, brand_code)
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
continue
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
found_ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
|
||||
|
||||
@@ -189,6 +189,10 @@ 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,6 +5,7 @@ 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
|
||||
@@ -14,12 +15,22 @@ from urllib.parse import urlencode
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# karaokenerds.com's search silently returns zero results once a query exceeds
|
||||
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
|
||||
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
|
||||
# artist blow past this, so the song is falsely reported as having no community
|
||||
# version. When that happens we retry with the title alone (the highest-signal
|
||||
# term) and keep only results whose artist matches.
|
||||
MAX_RELIABLE_QUERY_TERMS = 10
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
@@ -145,6 +156,45 @@ def parse_results(html: str) -> list[dict]:
|
||||
return songs
|
||||
|
||||
|
||||
async def _search_songs(query: str) -> list[dict] | None:
|
||||
"""Run a single karaokenerds search and parse the results.
|
||||
|
||||
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
|
||||
caller can distinguish "search errored" from "search returned nothing").
|
||||
"""
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
return None
|
||||
return parse_results(resp.text)
|
||||
|
||||
|
||||
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
|
||||
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
|
||||
community_songs: list[dict] = []
|
||||
best_youtube_url: str | None = None
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
return community_songs, best_youtube_url
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
@@ -160,39 +210,32 @@ async def check_community_versions(artist: str, title: str) -> dict:
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
songs = await _search_songs(query)
|
||||
if songs is None:
|
||||
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
|
||||
# site, matching prior behaviour.
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
songs = parse_results(resp.text)
|
||||
# karaokenerds chokes on overlong queries and returns nothing. If the
|
||||
# combined "artist title" query was too long AND came back empty, retry with
|
||||
# the title alone, then keep only results whose artist matches (title-only is
|
||||
# broader, so this guards against same-titled songs by other artists).
|
||||
if (
|
||||
not songs
|
||||
and title.strip()
|
||||
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
|
||||
):
|
||||
fallback = await _search_songs(title)
|
||||
if fallback:
|
||||
key_artist = normalize_for_match(artist)
|
||||
songs = [
|
||||
s for s in fallback
|
||||
if normalize_for_match(s.get("artist") or "") == key_artist
|
||||
]
|
||||
|
||||
# Filter to only songs that have community tracks with YouTube URLs
|
||||
community_songs = []
|
||||
best_youtube_url = None
|
||||
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
community_songs, best_youtube_url = _extract_community_songs(songs)
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
@@ -201,3 +244,54 @@ 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, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
|
||||
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
|
||||
uses to render clickable links; ``brands``/``brand_count`` are retained for
|
||||
back-compat. 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, "versions": []}
|
||||
async with sem:
|
||||
res = await check_community_versions(artist, title)
|
||||
versions: list[dict] = []
|
||||
versioned_brands: set[str] = set()
|
||||
brands: list[str] = []
|
||||
for matched in res.get("songs", []):
|
||||
for track in matched.get("community_tracks", []):
|
||||
name = track.get("brand_name")
|
||||
if not name:
|
||||
continue
|
||||
if name not in brands:
|
||||
brands.append(name)
|
||||
# A clickable version needs a URL; brand still counts as "exists" without one.
|
||||
url = track.get("youtube_url")
|
||||
if url and name not in versioned_brands:
|
||||
versioned_brands.add(name)
|
||||
versions.append({"brand": name, "url": url})
|
||||
return {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"available": bool(res.get("has_community")),
|
||||
"brands": brands,
|
||||
"brand_count": len(brands),
|
||||
"versions": versions,
|
||||
}
|
||||
|
||||
return await asyncio.gather(*[_one(s) for s in songs])
|
||||
@@ -0,0 +1,8 @@
|
||||
"""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"]
|
||||
@@ -0,0 +1,174 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""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
|
||||
@@ -0,0 +1,128 @@
|
||||
"""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"
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""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,
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
"""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"]
|
||||
|
||||
# Locale → ordered country preference for picking which pressing backs a variant.
|
||||
# Biases the representative release toward the user's likely region; falls back to
|
||||
# the worldwide default for anything unmapped. Keyed by the language part of the
|
||||
# locale (region suffix is ignored, e.g. "en-US" → "en").
|
||||
_LOCALE_COUNTRY_PREFS: Dict[str, List[str]] = {
|
||||
"en": ["GB", "US", "AU", "CA", "IE", "NZ"],
|
||||
"es": ["ES", "MX", "AR"],
|
||||
"fr": ["FR", "CA", "BE"],
|
||||
"de": ["DE", "AT", "CH"],
|
||||
"it": ["IT"],
|
||||
"pt": ["PT", "BR"],
|
||||
"nl": ["NL", "BE"],
|
||||
"sv": ["SE"],
|
||||
"ja": ["JP"],
|
||||
"ko": ["KR"],
|
||||
"zh": ["CN", "TW", "HK"],
|
||||
}
|
||||
|
||||
|
||||
def country_prefs_for_locale(locale: Optional[str]) -> List[str]:
|
||||
"""Map a next-intl locale to an ordered country preference list.
|
||||
|
||||
Returns a copy of the worldwide default (``_PREFERRED_COUNTRIES``) for an
|
||||
empty/unknown locale so callers can mutate freely.
|
||||
"""
|
||||
if not locale:
|
||||
return list(_PREFERRED_COUNTRIES)
|
||||
base = re.split(r"[-_]", locale)[0].lower()
|
||||
return list(_LOCALE_COUNTRY_PREFS.get(base, _PREFERRED_COUNTRIES))
|
||||
|
||||
# "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]],
|
||||
preferred_countries: Optional[List[str]] = None,
|
||||
) -> 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. ``preferred_countries`` overrides the default
|
||||
worldwide-first tie-break (used for locale-aware selection).
|
||||
"""
|
||||
if not editions:
|
||||
return None
|
||||
prefs = preferred_countries or _PREFERRED_COUNTRIES
|
||||
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 prefs.index(c) if c in prefs else len(prefs)
|
||||
|
||||
candidates.sort(key=lambda e: (e.get("date") or "9999", country_rank(e)))
|
||||
return candidates[0]
|
||||
|
||||
@staticmethod
|
||||
def build_variants(
|
||||
editions: List[Dict[str, Any]],
|
||||
preferred_countries: Optional[List[str]] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Collapse a release-group's editions into distinct tracklist *variants*.
|
||||
|
||||
Country pressings are irrelevant for karaoke (we only need the track names),
|
||||
so editions are grouped by ``track_count`` — within one release-group, same
|
||||
count ≈ same songs. Each variant exposes a representative release (earliest +
|
||||
preferred-country), the earliest year, how many pressings collapsed in, and a
|
||||
label/delta relative to the "Original" (earliest) variant. Editions without a
|
||||
track count are dropped. See
|
||||
``docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md``.
|
||||
"""
|
||||
if not editions:
|
||||
return []
|
||||
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") or 0) > 0]
|
||||
if not with_tracks:
|
||||
return []
|
||||
|
||||
groups: Dict[int, List[Dict[str, Any]]] = {}
|
||||
for e in with_tracks:
|
||||
groups.setdefault(e["track_count"], []).append(e)
|
||||
|
||||
variants: List[Dict[str, Any]] = []
|
||||
for track_count, group in groups.items():
|
||||
rep = MusicBrainzService.pick_canonical_edition(group, preferred_countries)
|
||||
earliest = min((e.get("date") or "9999") for e in group)
|
||||
year = earliest[:4] if earliest and earliest != "9999" else ""
|
||||
variants.append(
|
||||
{
|
||||
"representative_release_mbid": rep["release_mbid"],
|
||||
"track_count": track_count,
|
||||
"year": year,
|
||||
"pressing_count": len(group),
|
||||
"_earliest": earliest,
|
||||
}
|
||||
)
|
||||
|
||||
# Original = earliest release, then most pressings, then fewest tracks.
|
||||
variants.sort(key=lambda v: (v["_earliest"], -v["pressing_count"], v["track_count"]))
|
||||
original = variants[0]
|
||||
original_tc = original["track_count"]
|
||||
for v in variants:
|
||||
v["delta_vs_original"] = v["track_count"] - original_tc
|
||||
v["label"] = "Original" if v is original else "Reissue"
|
||||
del v["_earliest"]
|
||||
|
||||
# Display order: Original first, then by year ascending, then track count.
|
||||
variants.sort(key=lambda v: (v["label"] != "Original", v["year"] or "9999", v["track_count"]))
|
||||
return variants
|
||||
|
||||
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,
|
||||
preferred_countries: Optional[List[str]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Resolve the canonical edition of an album and return its tracklist, the raw
|
||||
editions, and the collapsed tracklist ``variants``. ``preferred_countries``
|
||||
biases representative selection (locale-aware)."""
|
||||
editions = await self._list_editions(release_group_mbid)
|
||||
canonical = self.pick_canonical_edition(editions, preferred_countries)
|
||||
variants = self.build_variants(editions, preferred_countries)
|
||||
if not canonical:
|
||||
return {
|
||||
"release_mbid": None,
|
||||
"title": None,
|
||||
"tracks": [],
|
||||
"editions": editions,
|
||||
"variants": variants,
|
||||
"selected_variant_mbid": None,
|
||||
}
|
||||
tracklist = await self.get_release_tracklist(canonical["release_mbid"])
|
||||
tracklist["editions"] = editions
|
||||
tracklist["canonical_release_mbid"] = canonical["release_mbid"]
|
||||
tracklist["variants"] = variants
|
||||
tracklist["selected_variant_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
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
Fast-path mirror of freshly-published Nomad masters into the Divebar GCS bucket.
|
||||
|
||||
New Nomad releases are uploaded to Google Drive at finalize time, but the Drive->GCS
|
||||
byte-sync VM only runs nightly, so kjbox (which mirrors that GCS folder every 5 min)
|
||||
would otherwise wait up to ~24h for a new master. This pushes the 720p master straight
|
||||
to the exact GCS object the nightly VM would produce, so kjbox picks it up within minutes.
|
||||
|
||||
Idempotent with the nightly VM: identical object name + size means its additive
|
||||
`gcloud storage rsync` sees the file already present and skips it.
|
||||
|
||||
Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding the
|
||||
``NOMADNP`` private-track prefix). Every operation is best-effort / non-fatal: a failure
|
||||
here must never break the distribution pipeline — the nightly VM remains the safety net.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import storage
|
||||
from google.cloud.exceptions import NotFound
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
|
||||
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
|
||||
if not brand_code:
|
||||
return False
|
||||
prefix = brand_code.split("-", 1)[0].strip().upper()
|
||||
return prefix == "NOMAD"
|
||||
|
||||
|
||||
class NomadMasterMirror:
|
||||
"""Push/remove Nomad 720p masters in the Divebar GCS bucket that kjbox mirrors."""
|
||||
|
||||
def __init__(self, client: Optional[storage.Client] = None):
|
||||
self._client = client or storage.Client(project=settings.google_cloud_project)
|
||||
self._bucket = self._client.bucket(settings.divebar_files_bucket)
|
||||
|
||||
def _blob_name(self, filename: str) -> str:
|
||||
prefix = settings.nomad_master_gcs_prefix.strip("/")
|
||||
return f"{prefix}/{filename}"
|
||||
|
||||
def push_720p(self, local_path: str, filename: str) -> bool:
|
||||
"""Upload a 720p master to the divebar GCS mirror. Best-effort; returns success."""
|
||||
blob_name = self._blob_name(filename)
|
||||
try:
|
||||
blob = self._bucket.blob(blob_name)
|
||||
blob.upload_from_filename(local_path)
|
||||
logger.info(
|
||||
"Fast-synced Nomad master to gs://%s/%s",
|
||||
settings.divebar_files_bucket,
|
||||
blob_name,
|
||||
)
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Nomad master fast-sync push failed for %s: %s", blob_name, e)
|
||||
return False
|
||||
|
||||
def delete_720p(self, filename: str) -> bool:
|
||||
"""Delete a 720p master from the mirror. Best-effort; 404 == already gone."""
|
||||
blob_name = self._blob_name(filename)
|
||||
try:
|
||||
self._bucket.blob(blob_name).delete()
|
||||
logger.info(
|
||||
"Removed Nomad master from gs://%s/%s",
|
||||
settings.divebar_files_bucket,
|
||||
blob_name,
|
||||
)
|
||||
return True
|
||||
except NotFound:
|
||||
logger.debug("Nomad master already absent in mirror: %s", blob_name)
|
||||
return False
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Nomad master mirror delete failed for %s: %s", blob_name, e)
|
||||
return False
|
||||
|
||||
def delete_masters_by_brand(self, brand_code: str) -> int:
|
||||
"""Delete ALL 720p master objects for a Nomad release, matched by the unique
|
||||
``{brand_code} - `` filename prefix.
|
||||
|
||||
Keying on the brand_code prefix (rather than a reconstructed title) covers
|
||||
renames for free: every artist/title variant a release was ever published
|
||||
under shares the same ``NOMAD-#### - `` prefix. Best-effort; returns the count
|
||||
deleted. Refuses to run for a non-Nomad / empty brand code so a broad prefix
|
||||
can never match unrelated objects.
|
||||
"""
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return 0
|
||||
# Require a full ``NOMAD-####`` code (non-empty suffix after the hyphen) so the
|
||||
# delete prefix is always specific to one release — never a bare ``NOMAD``.
|
||||
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
|
||||
if not suffix.strip():
|
||||
return 0
|
||||
prefix = f"{settings.nomad_master_gcs_prefix.strip('/')}/{brand_code} - "
|
||||
deleted = 0
|
||||
try:
|
||||
for blob in self._bucket.list_blobs(prefix=prefix):
|
||||
try:
|
||||
blob.delete()
|
||||
deleted += 1
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
|
||||
if deleted:
|
||||
logger.info(
|
||||
"Removed %d Nomad master object(s) from gs://%s/%s*",
|
||||
deleted, settings.divebar_files_bucket, prefix,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Nomad master mirror prefix-delete failed for %s: %s", prefix, e)
|
||||
return deleted
|
||||
|
||||
|
||||
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
|
||||
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
|
||||
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
|
||||
brands or when fast-sync is disabled. Never raises — a cleanup failure must not
|
||||
break job delete/edit flows (the object just lingers until overwritten). Call this
|
||||
wherever the pipeline deletes a job's Drive/Dropbox outputs.
|
||||
"""
|
||||
try:
|
||||
if not settings.nomad_master_fast_sync_enabled:
|
||||
return 0
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return 0
|
||||
return NomadMasterMirror().delete_masters_by_brand(brand_code)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the caller
|
||||
logger.warning("Nomad master mirror cleanup skipped: %s", e)
|
||||
return 0
|
||||
@@ -0,0 +1,73 @@
|
||||
"""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}"
|
||||
@@ -0,0 +1,2 @@
|
||||
"""Batch karaoke-filename → {artist, title, confidence} parser (Vertex Gemini)."""
|
||||
from backend.services.parse_titles.service import parse_titles # noqa: F401
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Vertex-Gemini layer for batch karaoke-filename parsing.
|
||||
|
||||
Turns messy karaoke *filenames* (YouTube titles, community/producer naming,
|
||||
KaraFun-reversed order) into canonical {artist, title, confidence}. Distinct
|
||||
from match_judge (which judges an already-split artist/title). The model call
|
||||
is injectable for tests.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You extract canonical song metadata from karaoke video/file names for a "
|
||||
"karaoke library. Each item has an id and a filename (sometimes a channel or "
|
||||
"source). Filenames are noisy: they carry karaoke markers ('(Karaoke Version)', "
|
||||
"'KARAOKE', '[karaoke]', 'Instrumental', producer/brand tags), YouTube ids or "
|
||||
"channel names, and inconsistent separators. Crucially the artist/title ORDER "
|
||||
"is inconsistent — most are 'Artist - Title' but some sources (e.g. KaraFun) are "
|
||||
"'Title - Artist'. Use your knowledge of real songs to put artist and title in "
|
||||
"the correct fields.\n"
|
||||
"Return JSON: {\"results\": [{\"id\", \"artist\", \"title\", \"confidence\"}]}. "
|
||||
"Return exactly one result per input id, echoing the id verbatim.\n"
|
||||
"artist/title: official formatting, karaoke noise removed, no brand codes or "
|
||||
"YouTube ids. If you cannot identify one field, return it as an empty string.\n"
|
||||
"confidence: 0.0-1.0 — your certainty the artist/title (and their order) are "
|
||||
"correct. Be honest; low confidence for ambiguous or unknown songs. Never invent "
|
||||
"a song; if unsure, return best-effort split with low confidence."
|
||||
)
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
"confidence": {"type": "number"},
|
||||
},
|
||||
"required": ["id"],
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["results"],
|
||||
}
|
||||
|
||||
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "parse_titles_model", "gemini-3.5-flash")
|
||||
except Exception: # pragma: no cover - config guard
|
||||
return "gemini-3.5-flash"
|
||||
|
||||
|
||||
def build_prompts(items: list[dict]) -> tuple[str, str]:
|
||||
lines = ["Parse these karaoke filenames:"]
|
||||
for it in items:
|
||||
parts = [f'id={it.get("id")!r}', f'filename={it.get("filename", "")!r}']
|
||||
if it.get("channel"):
|
||||
parts.append(f'channel={it["channel"]!r}')
|
||||
if it.get("source"):
|
||||
parts.append(f'source={it["source"]!r}')
|
||||
lines.append("- " + " ".join(parts))
|
||||
return _SYSTEM_PROMPT, "\n".join(lines)
|
||||
|
||||
|
||||
def _clean(v) -> str:
|
||||
return (v or "").strip() if isinstance(v, str) else ""
|
||||
|
||||
|
||||
def _conf(v) -> float:
|
||||
try:
|
||||
f = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
return max(0.0, min(1.0, f))
|
||||
|
||||
|
||||
def parse_map_from_response(data: object, items: list[dict]) -> list[dict]:
|
||||
"""Return one id-aligned result per input, filling any misses with blanks."""
|
||||
by_id: dict[str, dict] = {}
|
||||
if isinstance(data, dict):
|
||||
for r in data.get("results") or []:
|
||||
if isinstance(r, dict) and r.get("id") is not None:
|
||||
by_id[str(r["id"])] = r
|
||||
out = []
|
||||
for it in items:
|
||||
rid = str(it.get("id"))
|
||||
r = by_id.get(rid, {})
|
||||
out.append({
|
||||
"id": rid,
|
||||
"artist": _clean(r.get("artist")),
|
||||
"title": _clean(r.get("title")),
|
||||
"confidence": _conf(r.get("confidence")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
async def ai_parse(
|
||||
items: list[dict], *, model: Optional[str] = None,
|
||||
generate: Optional[Generate] = None,
|
||||
) -> list[dict]:
|
||||
gen = generate or _default_generate
|
||||
system, user = build_prompts(items)
|
||||
data = await gen(model or _model(), system, user)
|
||||
return parse_map_from_response(data, items)
|
||||
|
||||
|
||||
async def _default_generate(model: str, system: str, user: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system, user)
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
|
||||
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],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Batch orchestration + graceful degrade for karaoke-filename parsing."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from backend.services.parse_titles import ai
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _blanks(items: list[dict]) -> list[dict]:
|
||||
return [
|
||||
{"id": str(it.get("id")), "artist": "", "title": "", "confidence": 0.0}
|
||||
for it in items
|
||||
]
|
||||
|
||||
|
||||
async def parse_titles(
|
||||
items: list[dict], *, model=None, generate=None
|
||||
) -> list[dict]:
|
||||
"""Parse a batch of filenames → id-aligned {id, artist, title, confidence}.
|
||||
|
||||
Large batches are split into concurrent chunks of parse_titles_chunk_size
|
||||
so a single Gemini call never outgrows parse_titles_timeout_ms (a 100-item
|
||||
single call did, and the timeout blanked the whole batch).
|
||||
|
||||
Never raises: a disabled kill-switch or any model failure yields blank
|
||||
results — per chunk, so one bad chunk doesn't blank its neighbours — and
|
||||
the (kjbox) caller keeps its deterministic guess.
|
||||
"""
|
||||
if not items:
|
||||
return []
|
||||
try:
|
||||
from backend.config import settings
|
||||
enabled = getattr(settings, "parse_titles_enabled", True)
|
||||
max_items = int(getattr(settings, "parse_titles_max_items", 200))
|
||||
chunk_size = max(1, int(getattr(settings, "parse_titles_chunk_size", 10)))
|
||||
except Exception: # pragma: no cover
|
||||
# Fail closed: if config can't load, don't reach for the external AI.
|
||||
logger.warning("parse_titles settings unavailable; disabling parser")
|
||||
enabled, max_items, chunk_size = False, 200, 10
|
||||
if not enabled:
|
||||
return _blanks(items)
|
||||
|
||||
head, tail = items[:max_items], items[max_items:]
|
||||
chunks = [head[i:i + chunk_size] for i in range(0, len(head), chunk_size)]
|
||||
parsed = await asyncio.gather(
|
||||
*(_parse_chunk(chunk, model=model, generate=generate) for chunk in chunks)
|
||||
)
|
||||
return [r for chunk_results in parsed for r in chunk_results] + _blanks(tail)
|
||||
|
||||
|
||||
async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
|
||||
"""One Gemini call; any failure degrades to blanks for this chunk only."""
|
||||
try:
|
||||
results = await ai.ai_parse(chunk, model=model, generate=generate)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
|
||||
return _blanks(chunk)
|
||||
# ai_parse is id-aligned by construction; guard the contract defensively so a
|
||||
# future refactor can't silently return a mis-aligned/short batch.
|
||||
if len(results) != len(chunk):
|
||||
logger.warning(
|
||||
"parse_titles chunk length mismatch; blanks for %d items", len(chunk))
|
||||
return _blanks(chunk)
|
||||
return results
|
||||
@@ -59,6 +59,17 @@ 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.
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Sanitize submitted review corrections so word timings stay within their segment.
|
||||
|
||||
Mirrors the frontend sanitizeWordTimings.ts and the render-time
|
||||
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
|
||||
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
|
||||
segment window or is inverted. Segments whose own bounds are non-finite are left
|
||||
untouched (the editor derives bounds from words elsewhere). Mutates and returns the
|
||||
same dict for caller convenience, plus the number of fields clamped."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
|
||||
def _finite(v: Any) -> bool:
|
||||
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|
||||
|
||||
|
||||
def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
|
||||
segments = corrections.get("corrected_segments")
|
||||
if not isinstance(segments, list):
|
||||
return corrections, 0
|
||||
|
||||
changes = 0
|
||||
for seg in segments:
|
||||
if not isinstance(seg, dict):
|
||||
continue
|
||||
seg_start = seg.get("start_time")
|
||||
seg_end = seg.get("end_time")
|
||||
# If the segment's own bounds aren't finite, don't touch its words.
|
||||
if not _finite(seg_start) or not _finite(seg_end):
|
||||
continue
|
||||
seg_end = max(seg_end, seg_start)
|
||||
|
||||
prev_end = seg_start
|
||||
for w in seg.get("words", []):
|
||||
if not isinstance(w, dict):
|
||||
continue
|
||||
start = w.get("start_time")
|
||||
end = w.get("end_time")
|
||||
|
||||
# Invalid start = missing/non-finite OR outside the segment window.
|
||||
if _finite(start) and seg_start <= start <= seg_end:
|
||||
new_start = start
|
||||
else:
|
||||
new_start = min(max(prev_end, seg_start), seg_end)
|
||||
|
||||
# Invalid end = missing/non-finite, before start, or past segment end.
|
||||
if _finite(end) and new_start <= end <= seg_end:
|
||||
new_end = end
|
||||
else:
|
||||
new_end = min(max(new_start, end if _finite(end) else new_start), seg_end)
|
||||
if new_end < new_start:
|
||||
new_end = new_start
|
||||
|
||||
if new_start != start:
|
||||
w["start_time"] = new_start
|
||||
changes += 1
|
||||
if new_end != end:
|
||||
w["end_time"] = new_end
|
||||
changes += 1
|
||||
prev_end = new_end
|
||||
|
||||
return corrections, changes
|
||||
@@ -373,6 +373,36 @@ class UserService:
|
||||
logger.exception("Error verifying magic link")
|
||||
return False, None, "An error occurred during verification"
|
||||
|
||||
def get_magic_link_status(self, token: str) -> str:
|
||||
"""
|
||||
Read-only check of a magic link's status WITHOUT consuming it.
|
||||
|
||||
Used by the verify page on load to decide whether to show the
|
||||
"Complete Sign-In" gate (valid) or a dead-link message (used/expired).
|
||||
Crucially this must never mutate the token: an email link-scanner that
|
||||
renders the verify page triggers this read, but must not burn a still-
|
||||
valid link before the real user clicks.
|
||||
|
||||
Returns one of: "valid", "used", "expired", "invalid".
|
||||
"""
|
||||
try:
|
||||
if not token or not token.strip():
|
||||
return "invalid"
|
||||
|
||||
doc = self.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
|
||||
if not doc.exists:
|
||||
return "invalid"
|
||||
|
||||
magic_link = MagicLinkToken(**doc.to_dict())
|
||||
if magic_link.used:
|
||||
return "used"
|
||||
if datetime.utcnow() > magic_link.expires_at:
|
||||
return "expired"
|
||||
return "valid"
|
||||
except Exception:
|
||||
logger.exception("Error checking magic link status")
|
||||
return "invalid"
|
||||
|
||||
def grant_welcome_credits_if_eligible(
|
||||
self,
|
||||
email: str,
|
||||
|
||||
@@ -269,6 +269,12 @@ class VisibilityChangeService:
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Google Drive files: {e}")
|
||||
|
||||
# A track going private should also leave the public Nomad GCS fast-sync mirror
|
||||
# (and thus kjbox). Prefix-keyed by brand_code, non-fatal, Nomad-only.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
|
||||
# Delete GCS finals if requested
|
||||
if not keep_gcs_finals:
|
||||
try:
|
||||
|
||||
@@ -379,6 +379,47 @@ 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.
|
||||
@@ -410,6 +451,34 @@ 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.
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Route-level tests for POST /api/jobs/{job_id}/corrections — timing sanitizer integration.
|
||||
|
||||
Verifies that out-of-bounds word timings submitted by the frontend are clamped
|
||||
before corrections_updated.json is written to GCS.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def review_job():
|
||||
"""A job in AWAITING_REVIEW state owned by the test admin user."""
|
||||
job = Job(
|
||||
job_id="review-job-001",
|
||||
status=JobStatus.AWAITING_REVIEW,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(review_job):
|
||||
manager = MagicMock()
|
||||
manager.get_job.return_value = review_job
|
||||
manager.update_state_data.return_value = None
|
||||
manager.update_file_url.return_value = None
|
||||
manager.transition_to_state.return_value = None
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service():
|
||||
return MagicMock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_theme_service():
|
||||
svc = MagicMock()
|
||||
svc.get_default_theme_id.return_value = "nomad"
|
||||
svc.get_theme.return_value = None
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_job_manager, mock_worker_service, mock_theme_service):
|
||||
"""FastAPI TestClient with mocked dependencies."""
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = "googleapis.com"
|
||||
|
||||
def _jm_factory(*args, **kwargs):
|
||||
return mock_job_manager
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager), \
|
||||
patch("backend.api.routes.jobs.worker_service", mock_worker_service), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", _jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
yield TestClient(app)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _bad_corrections():
|
||||
"""Corrections payload whose words fall outside segment bounds (start=0, end<0).
|
||||
|
||||
Must include the 'lines' and 'metadata' keys required by CorrectionsSubmission
|
||||
validation before the sanitizer runs.
|
||||
"""
|
||||
return {
|
||||
"lines": [],
|
||||
"metadata": {"source": "test"},
|
||||
"corrected_segments": [
|
||||
{
|
||||
"id": "s1",
|
||||
"text": "A whiskey and a beer,",
|
||||
"start_time": 15.18,
|
||||
"end_time": 18.04,
|
||||
"words": [
|
||||
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
|
||||
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
|
||||
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
|
||||
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
|
||||
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _good_corrections():
|
||||
"""Corrections payload whose word timings are already valid."""
|
||||
return {
|
||||
"lines": [],
|
||||
"metadata": {"source": "test"},
|
||||
"corrected_segments": [
|
||||
{
|
||||
"id": "s1",
|
||||
"text": "Filling up",
|
||||
"start_time": 21.4,
|
||||
"end_time": 22.1,
|
||||
"words": [
|
||||
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
|
||||
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSubmitCorrectionsTimingSanitizer:
|
||||
"""Verify that submit_corrections clamps out-of-bounds word timings before GCS upload."""
|
||||
|
||||
def test_sanitized_timings_uploaded_to_gcs(self, client, auth_headers):
|
||||
"""Words with start_time/end_time outside segment bounds must be clamped
|
||||
before corrections_updated.json is written to GCS.
|
||||
|
||||
Patch StorageService at the class level in its source module so the local
|
||||
import inside submit_corrections picks up the mock.
|
||||
"""
|
||||
uploaded_payload = {}
|
||||
|
||||
with patch("backend.services.storage_service.StorageService") as MockStorage:
|
||||
storage_instance = MockStorage.return_value
|
||||
# Capture what gets passed to upload_json
|
||||
def capture_upload(path, data):
|
||||
uploaded_payload.update(data)
|
||||
storage_instance.upload_json.side_effect = capture_upload
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/review-job-001/corrections",
|
||||
json={"corrections": _bad_corrections()},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
assert uploaded_payload, "upload_json was never called — capture failed"
|
||||
|
||||
# All uploaded word timings must be within their segment bounds
|
||||
words = uploaded_payload["corrected_segments"][0]["words"]
|
||||
seg_start = 15.18
|
||||
seg_end = 18.04
|
||||
for w in words:
|
||||
assert w["start_time"] >= seg_start, f"word start_time {w['start_time']} < seg start {seg_start}"
|
||||
assert w["end_time"] >= w["start_time"], f"word end_time {w['end_time']} < start_time {w['start_time']}"
|
||||
assert w["end_time"] <= seg_end + 1e-9, f"word end_time {w['end_time']} > seg end {seg_end}"
|
||||
|
||||
def test_valid_timings_uploaded_unchanged(self, client, auth_headers):
|
||||
"""Word timings already within bounds must not be modified."""
|
||||
uploaded_payload = {}
|
||||
|
||||
with patch("backend.services.storage_service.StorageService") as MockStorage:
|
||||
storage_instance = MockStorage.return_value
|
||||
def capture_upload(path, data):
|
||||
uploaded_payload.update(data)
|
||||
storage_instance.upload_json.side_effect = capture_upload
|
||||
|
||||
response = client.post(
|
||||
"/api/jobs/review-job-001/corrections",
|
||||
json={"corrections": _good_corrections()},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
assert uploaded_payload, "upload_json was never called — capture failed"
|
||||
|
||||
words = uploaded_payload["corrected_segments"][0]["words"]
|
||||
assert words[0]["start_time"] == 21.4
|
||||
assert words[0]["end_time"] == 21.82
|
||||
assert words[1]["start_time"] == 21.86
|
||||
assert words[1]["end_time"] == 22.1
|
||||
|
||||
|
||||
class TestSubmitCorrectionsContract:
|
||||
"""Minimal contract test — does not require the full FastAPI test harness."""
|
||||
|
||||
def test_sanitize_contract_bad_timings(self):
|
||||
"""sanitize_corrections clamps words with start/end outside segment bounds."""
|
||||
from backend.services.timing_sanitizer import sanitize_corrections
|
||||
|
||||
bad = {
|
||||
"corrected_segments": [
|
||||
{
|
||||
"id": "s", "start_time": 15.18, "end_time": 18.04, "text": "A",
|
||||
"words": [{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005}],
|
||||
}
|
||||
]
|
||||
}
|
||||
cleaned, count = sanitize_corrections(bad)
|
||||
assert count >= 1
|
||||
w = cleaned["corrected_segments"][0]["words"][0]
|
||||
assert w["start_time"] >= 15.18
|
||||
assert w["end_time"] >= w["start_time"]
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Route tests for POST /api/review/{job_id}/auto-correct."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectResult,
|
||||
AutoCorrectServiceError,
|
||||
Suggestion,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def bypass_auth(monkeypatch):
|
||||
"""Bypass require_review_auth for these tests."""
|
||||
from backend.api.dependencies import require_review_auth as real_dep
|
||||
|
||||
async def fake_dep():
|
||||
return ("test-job", "full")
|
||||
|
||||
app.dependency_overrides[real_dep] = fake_dep
|
||||
yield
|
||||
app.dependency_overrides.pop(real_dep, None)
|
||||
|
||||
|
||||
def _override_service(result_or_exc):
|
||||
from backend.api.routes.review import _get_auto_correct_service_dep
|
||||
|
||||
mock_service = MagicMock()
|
||||
if isinstance(result_or_exc, Exception):
|
||||
mock_service.suggest.side_effect = result_or_exc
|
||||
else:
|
||||
mock_service.suggest.return_value = result_or_exc
|
||||
app.dependency_overrides[_get_auto_correct_service_dep] = lambda: mock_service
|
||||
return mock_service
|
||||
|
||||
|
||||
def teardown_function(_): # noqa: ANN001
|
||||
from backend.api.routes.review import _get_auto_correct_service_dep
|
||||
|
||||
app.dependency_overrides.pop(_get_auto_correct_service_dep, None)
|
||||
|
||||
|
||||
def _make_result(suggestions=None) -> AutoCorrectResult:
|
||||
return AutoCorrectResult(
|
||||
suggestions=suggestions
|
||||
if suggestions is not None
|
||||
else [
|
||||
Suggestion(
|
||||
id="sug-1",
|
||||
op="replace",
|
||||
word_ids=["w3"],
|
||||
segment_ids=["seg-1"],
|
||||
original_text="glory",
|
||||
new_text="chlorine",
|
||||
reason="matches reference",
|
||||
category="mishearing",
|
||||
confidence=0.95,
|
||||
)
|
||||
],
|
||||
model="gemini-test",
|
||||
elapsed_seconds=12.3,
|
||||
settings_applied=AutoCorrectSettings(),
|
||||
warnings=["dropped suggestion 3: out of range"],
|
||||
)
|
||||
|
||||
|
||||
BODY = {
|
||||
"segments": [{"id": "seg-1", "words": [{"id": "w3", "text": "glory"}]}],
|
||||
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
|
||||
"artist": "Twenty One Pilots",
|
||||
"title": "Chlorine",
|
||||
}
|
||||
|
||||
|
||||
def test_happy_path(client: TestClient) -> None:
|
||||
mock = _override_service(_make_result())
|
||||
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["model"] == "gemini-test"
|
||||
assert len(data["suggestions"]) == 1
|
||||
s = data["suggestions"][0]
|
||||
assert s["op"] == "replace"
|
||||
assert s["word_ids"] == ["w3"]
|
||||
assert s["new_text"] == "chlorine"
|
||||
assert data["warnings"] == ["dropped suggestion 3: out of range"]
|
||||
assert data["settings_applied"]["suggest_adlib_removal"] is True
|
||||
mock.suggest.assert_called_once()
|
||||
|
||||
|
||||
def test_settings_passed_through(client: TestClient) -> None:
|
||||
mock = _override_service(_make_result([]))
|
||||
resp = client.post(
|
||||
"/api/review/test-job/auto-correct",
|
||||
json={**BODY, "settings": {"suggest_adlib_removal": False, "min_confidence": 0.8}},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
settings = mock.suggest.call_args.kwargs["settings"]
|
||||
assert settings.suggest_adlib_removal is False
|
||||
assert settings.min_confidence == 0.8
|
||||
|
||||
|
||||
def test_invalid_settings_400(client: TestClient) -> None:
|
||||
_override_service(_make_result([]))
|
||||
resp = client.post(
|
||||
"/api/review/test-job/auto-correct",
|
||||
json={**BODY, "settings": {"bogus_knob": True}},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert "invalid settings" in resp.json()["detail"]
|
||||
|
||||
|
||||
def test_no_references_422_propagates(client: TestClient) -> None:
|
||||
_override_service(AutoCorrectServiceError("no reference lyrics", status_code=422))
|
||||
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_model_failure_502_propagates(client: TestClient) -> None:
|
||||
_override_service(AutoCorrectServiceError("AI model call failed", status_code=502))
|
||||
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
|
||||
assert resp.status_code == 502
|
||||
|
||||
|
||||
def test_missing_body_fields_422(client: TestClient) -> None:
|
||||
_override_service(_make_result([]))
|
||||
resp = client.post("/api/review/test-job/auto-correct", json={"segments": []})
|
||||
assert resp.status_code == 422 # reference_lyrics is required
|
||||
Whitespace-only changes.
@@ -0,0 +1,203 @@
|
||||
"""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
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Tests for multi-model compare: parallel calls, dedup, consensus, conflicts."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
SEGMENTS = [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"words": [
|
||||
{"id": "w0", "text": "Sippin'"},
|
||||
{"id": "w1", "text": "on"},
|
||||
{"id": "w2", "text": "straight"},
|
||||
{"id": "w3", "text": "glory"},
|
||||
{"id": "w4", "text": "today"},
|
||||
],
|
||||
},
|
||||
]
|
||||
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
|
||||
COMPARE = AutoCorrectSettings(compare_models=True)
|
||||
|
||||
|
||||
def _sugg(start, end, text, op="replace", confidence=0.9):
|
||||
return {
|
||||
"op": op,
|
||||
"start_idx": start,
|
||||
"end_idx": end,
|
||||
"new_text": text,
|
||||
"reason": "r",
|
||||
"category": "mishearing",
|
||||
"confidence": confidence,
|
||||
}
|
||||
|
||||
|
||||
def _run_compare(responses_by_model, compare_models_env="model-a;model-b",
|
||||
settings=COMPARE, single_model="gemini-3.1-pro-preview"):
|
||||
"""responses_by_model: model name -> raw dict response or Exception."""
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
resp = responses_by_model[model]
|
||||
if isinstance(resp, Exception):
|
||||
raise resp
|
||||
# _call_model now returns (parsed_json, token_usage).
|
||||
return resp, None
|
||||
|
||||
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):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
def test_identical_suggestions_deduped_with_consensus() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.9)]},
|
||||
"model-b": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.95)]},
|
||||
})
|
||||
assert len(result.suggestions) == 1
|
||||
s = result.suggestions[0]
|
||||
assert sorted(s.models) == ["model-a", "model-b"]
|
||||
assert s.consensus == 2
|
||||
assert s.total_models == 2
|
||||
assert s.confidence == 0.95 # max across models
|
||||
assert s.conflict_group is None
|
||||
assert result.model == "model-a, model-b"
|
||||
|
||||
|
||||
def test_conflicting_suggestions_share_group() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"suggestions": [_sugg(2, 3, "straight chlorine gas")]},
|
||||
})
|
||||
assert len(result.suggestions) == 2
|
||||
groups = {s.conflict_group for s in result.suggestions}
|
||||
assert len(groups) == 1 and None not in groups
|
||||
assert all(s.consensus == 1 and s.total_models == 2 for s in result.suggestions)
|
||||
|
||||
|
||||
def test_non_overlapping_suggestions_have_no_group() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"suggestions": [_sugg(0, 0, "Sipping")]},
|
||||
})
|
||||
assert all(s.conflict_group is None for s in result.suggestions)
|
||||
# sorted by document position
|
||||
assert [s.word_ids[0] for s in result.suggestions] == ["w0", "w3"]
|
||||
|
||||
|
||||
def test_insert_after_does_not_conflict_with_replace_on_anchor() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"suggestions": [_sugg(3, 3, "up", op="insert_after")]},
|
||||
})
|
||||
assert all(s.conflict_group is None for s in result.suggestions)
|
||||
|
||||
|
||||
def test_one_model_failing_produces_warning_not_error() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": AutoCorrectServiceError("AI model call failed", status_code=502),
|
||||
})
|
||||
assert len(result.suggestions) == 1
|
||||
assert result.suggestions[0].total_models == 1 # only one model answered
|
||||
assert any("model-b failed" in w for w in result.warnings)
|
||||
assert result.model == "model-a"
|
||||
|
||||
|
||||
def test_malformed_model_output_warns_instead_of_aborting_compare() -> None:
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
|
||||
"model-b": {"not_suggestions": []}, # malformed -> _validate raises
|
||||
})
|
||||
assert len(result.suggestions) == 1
|
||||
assert any("model-b failed" in w for w in result.warnings)
|
||||
assert result.model == "model-a"
|
||||
|
||||
|
||||
def test_all_models_failing_raises_502() -> None:
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
_run_compare({
|
||||
"model-a": AutoCorrectServiceError("boom", status_code=502),
|
||||
"model-b": AutoCorrectServiceError("boom", status_code=502),
|
||||
})
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
def test_compare_falls_back_to_single_when_unconfigured() -> None:
|
||||
result = _run_compare(
|
||||
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
|
||||
compare_models_env="",
|
||||
)
|
||||
s = result.suggestions[0]
|
||||
assert s.total_models == 1
|
||||
assert s.consensus == 1
|
||||
|
||||
|
||||
def test_single_model_mode_unchanged() -> None:
|
||||
result = _run_compare(
|
||||
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
|
||||
settings=AutoCorrectSettings(), # compare off
|
||||
)
|
||||
assert len(result.suggestions) == 1
|
||||
assert result.suggestions[0].models == ["gemini-3.1-pro-preview"]
|
||||
|
||||
|
||||
def test_three_way_conflict_chain_unifies_groups() -> None:
|
||||
# a: w2-w3, b: w3-w4, c: w4 — chained overlaps must land in ONE group
|
||||
result = _run_compare({
|
||||
"model-a": {"suggestions": [_sugg(2, 3, "x y")]},
|
||||
"model-b": {"suggestions": [_sugg(3, 4, "y z"), _sugg(4, 4, "z")]},
|
||||
})
|
||||
groups = {s.conflict_group for s in result.suggestions}
|
||||
assert len(groups) == 1 and None not in groups
|
||||
@@ -0,0 +1,173 @@
|
||||
"""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
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Tests for auto-correct prompt construction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.services.auto_correct.prompts import (
|
||||
build_system_prompt,
|
||||
build_user_prompt,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
def test_system_prompt_default_allows_adlib_suggestions() -> None:
|
||||
p = build_system_prompt(AutoCorrectSettings())
|
||||
assert "adlib_removal" in p
|
||||
assert "NEVER suggest deleting backing vocals" not in p
|
||||
assert "insert_after" in p
|
||||
|
||||
|
||||
def test_system_prompt_adlib_disabled() -> None:
|
||||
p = build_system_prompt(AutoCorrectSettings(suggest_adlib_removal=False))
|
||||
assert "NEVER suggest deleting backing vocals" in p
|
||||
|
||||
|
||||
def test_system_prompt_insertions_disabled() -> None:
|
||||
p = build_system_prompt(AutoCorrectSettings(allow_insertions=False))
|
||||
assert 'NEVER use the "insert_after" operation' in p
|
||||
|
||||
|
||||
def test_user_prompt_word_indices_are_global_and_sequential() -> None:
|
||||
segments = [
|
||||
{"id": "s1", "words": [{"id": "a", "text": "Hello"}, {"id": "b", "text": "there"}]},
|
||||
{"id": "s2", "words": [{"id": "c", "text": "world"}]},
|
||||
]
|
||||
refs = {
|
||||
"genius": {"segments": [{"text": "Hello there"}, {"text": "world"}]},
|
||||
"lrclib": {"segments": [{"text": "Hello their world"}]},
|
||||
}
|
||||
p = build_user_prompt(
|
||||
segments=segments, reference_lyrics=refs, artist="Artist", title="Title"
|
||||
)
|
||||
assert "ARTIST: Artist" in p
|
||||
assert "[L000] 0:Hello 1:there" in p
|
||||
assert "[L001] 2:world" in p
|
||||
assert "REFERENCE LYRICS (genius):" in p
|
||||
assert "REFERENCE LYRICS (lrclib):" in p
|
||||
assert "Hello their world" in p
|
||||
|
||||
|
||||
def test_user_prompt_handles_missing_metadata() -> None:
|
||||
p = build_user_prompt(
|
||||
segments=[{"id": "s1", "words": []}],
|
||||
reference_lyrics={},
|
||||
artist=None,
|
||||
title=None,
|
||||
)
|
||||
assert "ARTIST: unknown" in p
|
||||
assert "TITLE: unknown" in p
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Tests for AutoCorrectService validation and suggestion mapping."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
SEGMENTS = [
|
||||
{
|
||||
"id": "seg-1",
|
||||
"words": [
|
||||
{"id": "w0", "text": "Sippin'"},
|
||||
{"id": "w1", "text": "on"},
|
||||
{"id": "w2", "text": "straight"},
|
||||
{"id": "w3", "text": "glory"},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "seg-2",
|
||||
"words": [
|
||||
{"id": "w4", "text": "yeah"},
|
||||
{"id": "w5", "text": "yeah"},
|
||||
],
|
||||
},
|
||||
]
|
||||
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"):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics=REFS,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=settings or AutoCorrectSettings(),
|
||||
)
|
||||
|
||||
|
||||
def _raw(op="replace", start=3, end=3, text="chlorine", category="mishearing",
|
||||
confidence=0.95):
|
||||
return {
|
||||
"suggestions": [
|
||||
{
|
||||
"op": op,
|
||||
"start_idx": start,
|
||||
"end_idx": end,
|
||||
"new_text": text,
|
||||
"reason": "matches reference",
|
||||
"category": category,
|
||||
"confidence": confidence,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_replace_maps_indices_to_word_ids() -> None:
|
||||
result = _suggest(_raw())
|
||||
assert len(result.suggestions) == 1
|
||||
s = result.suggestions[0]
|
||||
assert s.op == "replace"
|
||||
assert s.word_ids == ["w3"]
|
||||
assert s.segment_ids == ["seg-1"]
|
||||
assert s.original_text == "glory"
|
||||
assert s.new_text == "chlorine"
|
||||
assert result.warnings == []
|
||||
|
||||
|
||||
def test_multi_word_span_crossing_segments() -> None:
|
||||
result = _suggest(_raw(start=3, end=4, text="chlorine yeah"))
|
||||
s = result.suggestions[0]
|
||||
assert s.word_ids == ["w3", "w4"]
|
||||
assert sorted(s.segment_ids) == ["seg-1", "seg-2"]
|
||||
assert s.original_text == "glory yeah"
|
||||
|
||||
|
||||
def test_delete_suggestion() -> None:
|
||||
result = _suggest(_raw(op="delete", start=4, end=5, text=""))
|
||||
s = result.suggestions[0]
|
||||
assert s.op == "delete"
|
||||
assert s.new_text == ""
|
||||
assert s.word_ids == ["w4", "w5"]
|
||||
|
||||
|
||||
def test_insert_after_uses_anchor_word() -> None:
|
||||
result = _suggest(_raw(op="insert_after", start=2, end=2, text="up"))
|
||||
s = result.suggestions[0]
|
||||
assert s.op == "insert_after"
|
||||
assert s.word_ids == ["w2"]
|
||||
|
||||
|
||||
def test_out_of_range_indices_dropped_with_warning() -> None:
|
||||
result = _suggest(_raw(start=99, end=99))
|
||||
assert result.suggestions == []
|
||||
assert len(result.warnings) == 1
|
||||
assert "out of range" in result.warnings[0]
|
||||
|
||||
|
||||
def test_replace_with_empty_text_dropped() -> None:
|
||||
result = _suggest(_raw(text=" "))
|
||||
assert result.suggestions == []
|
||||
assert "empty new_text" in result.warnings[0]
|
||||
|
||||
|
||||
def test_below_min_confidence_dropped() -> None:
|
||||
result = _suggest(
|
||||
_raw(confidence=0.4), settings=AutoCorrectSettings(min_confidence=0.6)
|
||||
)
|
||||
assert result.suggestions == []
|
||||
assert "below threshold" in result.warnings[0]
|
||||
|
||||
|
||||
def test_adlib_removal_dropped_when_disabled() -> None:
|
||||
result = _suggest(
|
||||
_raw(op="delete", start=4, end=5, text="", category="adlib_removal"),
|
||||
settings=AutoCorrectSettings(suggest_adlib_removal=False),
|
||||
)
|
||||
assert result.suggestions == []
|
||||
assert "adlib removal disabled" in result.warnings[0]
|
||||
|
||||
|
||||
def test_insertions_dropped_when_disabled() -> None:
|
||||
result = _suggest(
|
||||
_raw(op="insert_after", start=2, end=2, text="up"),
|
||||
settings=AutoCorrectSettings(allow_insertions=False),
|
||||
)
|
||||
assert result.suggestions == []
|
||||
assert "insertions disabled" in result.warnings[0]
|
||||
|
||||
|
||||
def test_unknown_category_coerced_to_other() -> None:
|
||||
result = _suggest(_raw(category="weird"))
|
||||
assert result.suggestions[0].category == "other"
|
||||
|
||||
|
||||
def test_confidence_clamped() -> None:
|
||||
result = _suggest(_raw(confidence=1.7))
|
||||
assert result.suggestions[0].confidence == 1.0
|
||||
|
||||
|
||||
def test_no_reference_lyrics_raises_422() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=SEGMENTS,
|
||||
reference_lyrics={},
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert exc_info.value.status_code == 422
|
||||
|
||||
|
||||
def test_empty_segments_raises_400() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=[],
|
||||
reference_lyrics=REFS,
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
def test_missing_segment_ids_raises() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError, match="segments must have ids"):
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=[{"words": [{"id": "w0", "text": "hi"}]}],
|
||||
reference_lyrics=REFS,
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
|
||||
|
||||
def test_missing_word_ids_raises() -> None:
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError, match="ids"):
|
||||
service.suggest(
|
||||
job_id="job-1",
|
||||
segments=[{"id": "s", "words": [{"text": "no-id"}]}],
|
||||
reference_lyrics=REFS,
|
||||
artist=None,
|
||||
title=None,
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
|
||||
|
||||
def test_malformed_model_response_raises_502() -> None:
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
_suggest({"not_suggestions": []})
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
def test_non_dict_suggestion_entries_dropped() -> None:
|
||||
result = _suggest({"suggestions": ["bogus", 42]})
|
||||
assert result.suggestions == []
|
||||
assert len(result.warnings) == 2
|
||||
|
||||
|
||||
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:
|
||||
service._call_model("claude-fable-5", "s", "u", job_id="j")
|
||||
anth.assert_called_once()
|
||||
gem.assert_not_called()
|
||||
service._call_model("gemini-3.1-pro-preview", "s", "u", job_id="j")
|
||||
gem.assert_called_once()
|
||||
|
||||
|
||||
def test_anthropic_schema_strips_genai_pollution(monkeypatch) -> None:
|
||||
"""google-genai mutates schema dicts in place (adds property_ordering);
|
||||
the anthropic path must send a clean strict schema regardless."""
|
||||
from unittest.mock import MagicMock
|
||||
import backend.services.auto_correct.service as svc_mod
|
||||
|
||||
import copy
|
||||
|
||||
monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
|
||||
# Deep copy so this test never mutates the real module-level schema.
|
||||
polluted = copy.deepcopy(svc_mod.RESPONSE_SCHEMA)
|
||||
polluted["property_ordering"] = ["suggestions"]
|
||||
polluted["properties"]["suggestions"]["items"]["property_ordering"] = ["op"]
|
||||
monkeypatch.setattr(svc_mod, "RESPONSE_SCHEMA", polluted)
|
||||
|
||||
captured = {}
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **kwargs):
|
||||
self.messages = MagicMock()
|
||||
|
||||
def create(**ckwargs):
|
||||
captured.update(ckwargs)
|
||||
block = MagicMock()
|
||||
block.type = "text"
|
||||
block.text = '{"suggestions": []}'
|
||||
resp = MagicMock()
|
||||
resp.content = [block]
|
||||
return resp
|
||||
|
||||
self.messages.create = create
|
||||
|
||||
import anthropic as anthropic_sdk
|
||||
|
||||
monkeypatch.setattr(anthropic_sdk, "Anthropic", FakeClient)
|
||||
service = AutoCorrectService()
|
||||
raw, _usage = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
|
||||
assert raw == {"suggestions": []}
|
||||
schema = captured["output_config"]["format"]["schema"]
|
||||
assert "property_ordering" not in schema
|
||||
assert "property_ordering" not in schema["properties"]["suggestions"]["items"]
|
||||
assert schema["additionalProperties"] is False
|
||||
# and the polluted module constant was not further mutated
|
||||
assert "property_ordering" in polluted
|
||||
|
||||
|
||||
def test_anthropic_without_api_key_raises_502(monkeypatch) -> None:
|
||||
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
|
||||
service = AutoCorrectService()
|
||||
with pytest.raises(AutoCorrectServiceError) as exc_info:
|
||||
service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
|
||||
assert exc_info.value.status_code == 502
|
||||
assert "not configured" in str(exc_info.value)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Tests for AutoCorrectSettings parsing/validation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.settings import (
|
||||
AutoCorrectSettings,
|
||||
settings_from_dict,
|
||||
)
|
||||
|
||||
|
||||
def test_default_settings() -> None:
|
||||
s = AutoCorrectSettings()
|
||||
assert s.suggest_adlib_removal is True
|
||||
assert s.allow_insertions is True
|
||||
assert s.min_confidence == 0.0
|
||||
|
||||
|
||||
def test_settings_from_dict_defaults_when_empty() -> None:
|
||||
assert settings_from_dict({}) == AutoCorrectSettings()
|
||||
|
||||
|
||||
def test_settings_from_dict_partial() -> None:
|
||||
s = settings_from_dict({"suggest_adlib_removal": False})
|
||||
assert s.suggest_adlib_removal is False
|
||||
assert s.allow_insertions is True
|
||||
|
||||
|
||||
def test_settings_from_dict_full() -> None:
|
||||
s = settings_from_dict(
|
||||
{
|
||||
"suggest_adlib_removal": False,
|
||||
"allow_insertions": False,
|
||||
"min_confidence": 0.75,
|
||||
}
|
||||
)
|
||||
assert s == AutoCorrectSettings(
|
||||
suggest_adlib_removal=False, allow_insertions=False, min_confidence=0.75
|
||||
)
|
||||
|
||||
|
||||
def test_settings_from_dict_unknown_key_raises() -> None:
|
||||
with pytest.raises(ValueError, match="unknown settings"):
|
||||
settings_from_dict({"bogus": 1})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [-0.1, 1.5, "high", None, True, False])
|
||||
def test_settings_from_dict_invalid_confidence_raises(value) -> None:
|
||||
with pytest.raises(ValueError, match="min_confidence"):
|
||||
settings_from_dict({"min_confidence": value})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["suggest_adlib_removal", "allow_insertions"])
|
||||
def test_settings_from_dict_non_bool_flag_raises(key) -> None:
|
||||
with pytest.raises(ValueError, match=key):
|
||||
settings_from_dict({key: "yes"})
|
||||
|
||||
|
||||
def test_to_dict_round_trip() -> None:
|
||||
s = AutoCorrectSettings(suggest_adlib_removal=False, min_confidence=0.5)
|
||||
assert settings_from_dict(s.to_dict()) == s
|
||||
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from backend.services.custom_lyrics.result import StopReason
|
||||
from backend.services.custom_lyrics.service import CustomLyricsService
|
||||
from backend.services.custom_lyrics.service import CustomLyricsService, CustomLyricsServiceError
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings, StrictnessLevel
|
||||
|
||||
|
||||
@@ -97,6 +97,67 @@ def test_repairs_one_line(service: CustomLyricsService) -> None:
|
||||
assert result.stop_reason is StopReason.SUCCESS
|
||||
|
||||
|
||||
def test_repair_failure_falls_back_to_best(service: CustomLyricsService) -> None:
|
||||
"""A failed repair call must keep the successful initial result, not 500.
|
||||
|
||||
Regression for job dc60ebf4: the initial generation succeeded but the repair
|
||||
Gemini call returned response.text=None -> json.loads(None) TypeError ->
|
||||
uncaught 500 (no CORS headers) -> browser "NetworkError". The whole good
|
||||
generation was thrown away by a best-effort improvement step.
|
||||
"""
|
||||
target_segments = [_segment(0.0, 1.0, "aa"), _segment(1.0, 2.0, "bb")]
|
||||
target_lines = ["aa", "bb"]
|
||||
calls = {"n": 0}
|
||||
|
||||
def _fake_call(*args, **kwargs):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
return ["xx yy zz qq", "yy"] # initial: 1 violation → triggers a repair
|
||||
raise RuntimeError("Gemini returned an empty response") # repair blows up
|
||||
|
||||
with patch.object(CustomLyricsService, "_call_gemini", side_effect=_fake_call):
|
||||
result = service.generate(
|
||||
job_id="j1",
|
||||
target_lines=target_lines,
|
||||
target_segments=target_segments,
|
||||
artist=None, title=None, custom_text="c",
|
||||
file_bytes=None, file_mime=None, file_name=None,
|
||||
notes=None,
|
||||
settings=GenerationSettings(strictness=StrictnessLevel.BALANCED),
|
||||
)
|
||||
|
||||
assert result.stop_reason is StopReason.REPAIR_FAILED
|
||||
assert result.lines == ["xx yy zz qq", "yy"] # fell back to the initial (best)
|
||||
assert calls["n"] == 2 # initial + exactly one failed repair, then stop
|
||||
|
||||
|
||||
def test_empty_gemini_response_raises_clean_error(service: CustomLyricsService) -> None:
|
||||
"""response.text=None -> CustomLyricsServiceError(502), never a raw TypeError.
|
||||
|
||||
The endpoint maps CustomLyricsServiceError to a proper HTTP error (with CORS);
|
||||
a raw TypeError escapes to a 500 with no CORS headers, which the browser shows
|
||||
as an opaque "NetworkError".
|
||||
"""
|
||||
fake_response = MagicMock()
|
||||
fake_response.text = None
|
||||
fake_response.candidates = []
|
||||
fake_response.prompt_feedback = None
|
||||
fake_client = MagicMock()
|
||||
fake_client.models.generate_content.return_value = fake_response
|
||||
|
||||
with patch("backend.services.custom_lyrics.service.genai.Client", return_value=fake_client):
|
||||
with pytest.raises(CustomLyricsServiceError) as exc:
|
||||
service._call_gemini(
|
||||
system_prompt="s",
|
||||
user_prompt="u",
|
||||
pdf_bytes=None,
|
||||
settings=GenerationSettings(),
|
||||
)
|
||||
|
||||
assert exc.value.status_code == 502
|
||||
assert "empty response" in str(exc.value).lower()
|
||||
|
||||
|
||||
def test_plateau_detection(service: CustomLyricsService) -> None:
|
||||
target_segments = [_segment(0.0, 1.0, "aa")]
|
||||
target_lines = ["aa"]
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,103 @@
|
||||
"""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"
|
||||
@@ -0,0 +1,66 @@
|
||||
"""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
|
||||
@@ -0,0 +1,272 @@
|
||||
"""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"
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Tests for backend.services.timing_sanitizer."""
|
||||
import pytest
|
||||
|
||||
from backend.services.timing_sanitizer import sanitize_corrections
|
||||
|
||||
|
||||
def _sample_corrections():
|
||||
return {
|
||||
"corrected_segments": [
|
||||
{
|
||||
"id": "s1",
|
||||
"text": "A whiskey and a beer,",
|
||||
"start_time": 15.18,
|
||||
"end_time": 18.04,
|
||||
"words": [
|
||||
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
|
||||
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
|
||||
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
|
||||
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
|
||||
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_clamps_out_of_bounds_words():
|
||||
cleaned, count = sanitize_corrections(_sample_corrections())
|
||||
words = cleaned["corrected_segments"][0]["words"]
|
||||
for w in words:
|
||||
assert w["start_time"] >= 15.18
|
||||
assert w["end_time"] >= w["start_time"]
|
||||
assert w["end_time"] <= 18.04 + 1e-9
|
||||
assert count >= 4
|
||||
|
||||
|
||||
def test_valid_corrections_unchanged():
|
||||
payload = {
|
||||
"corrected_segments": [
|
||||
{
|
||||
"id": "s", "text": "Filling up", "start_time": 21.4, "end_time": 22.1,
|
||||
"words": [
|
||||
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
|
||||
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
cleaned, count = sanitize_corrections(payload)
|
||||
assert count == 0
|
||||
assert cleaned == payload
|
||||
|
||||
|
||||
def test_missing_segments_key_is_noop():
|
||||
cleaned, count = sanitize_corrections({"foo": "bar"})
|
||||
assert count == 0
|
||||
assert cleaned == {"foo": "bar"}
|
||||
|
||||
|
||||
def test_non_finite_segment_bounds_left_untouched():
|
||||
payload = {"corrected_segments": [
|
||||
{"id": "s", "start_time": None, "end_time": None, "text": "x",
|
||||
"words": [{"id": "w", "text": "x", "start_time": 3, "end_time": 5}]}
|
||||
]}
|
||||
cleaned, count = sanitize_corrections(payload)
|
||||
assert count == 0
|
||||
assert cleaned["corrected_segments"][0]["words"][0]["start_time"] == 3
|
||||
|
||||
|
||||
def test_start_past_segment_end_uses_prev_end():
|
||||
"""A word whose start_time is far outside [seg_start, seg_end] must be repaired
|
||||
to prev_end (clamped into the segment window), not silently collapsed to seg_end."""
|
||||
payload = {"corrected_segments": [{
|
||||
"id": "s", "start_time": 10.0, "end_time": 12.0, "text": "hello world",
|
||||
"words": [
|
||||
{"id": "w0", "text": "hello", "start_time": 10.0, "end_time": 11.0},
|
||||
{"id": "w1", "text": "world", "start_time": 99.0, "end_time": 100.0},
|
||||
],
|
||||
}]}
|
||||
cleaned, count = sanitize_corrections(payload)
|
||||
assert count >= 2 # both start and end of w1 were repaired
|
||||
w = cleaned["corrected_segments"][0]["words"][1]
|
||||
# start must fall inside the segment window
|
||||
assert 10.0 <= w["start_time"] <= 12.0
|
||||
# end must be >= start and within the segment
|
||||
assert w["end_time"] >= w["start_time"]
|
||||
assert w["end_time"] <= 12.0
|
||||
# start should be prev_end (11.0), not collapsed to seg_end (12.0)
|
||||
assert w["start_time"] == 11.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_value", [True, False, float("inf"), float("-inf"), float("nan"), None])
|
||||
def test_non_finite_word_timing_is_clamped(bad_value):
|
||||
payload = {"corrected_segments": [{
|
||||
"id": "s", "start_time": 10.0, "end_time": 12.0, "text": "x",
|
||||
"words": [{"id": "w", "text": "x", "start_time": bad_value, "end_time": bad_value}]
|
||||
}]}
|
||||
cleaned, count = sanitize_corrections(payload)
|
||||
assert count >= 1
|
||||
w = cleaned["corrected_segments"][0]["words"][0]
|
||||
assert 10.0 <= w["start_time"] <= 12.0
|
||||
assert w["end_time"] >= w["start_time"]
|
||||
@@ -108,6 +108,24 @@ class TestDeleteOutputsSuccess:
|
||||
assert data["job_id"] == "test-job-123"
|
||||
assert "outputs_deleted_at" in data
|
||||
|
||||
def test_delete_outputs_removes_nomad_gcs_master(self, client, mock_complete_job):
|
||||
"""Deleting a NOMAD job's outputs must also remove its 720p master from the
|
||||
GCS fast-sync mirror (wiring guard for the delete side)."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.nomad_master_mirror.cleanup_nomad_masters') as mock_cleanup:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job # brand_code = "NOMAD-1234"
|
||||
mock_jm_class.return_value = mock_jm
|
||||
mock_db = Mock()
|
||||
mock_db.collection.return_value.document.return_value = Mock()
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_cleanup.assert_called_once_with("NOMAD-1234")
|
||||
|
||||
def test_delete_outputs_clears_state_data_keys(self, client, mock_complete_job):
|
||||
"""Test that output-related state_data keys are listed as cleared."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
|
||||
@@ -124,6 +124,11 @@ 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")
|
||||
|
||||
@@ -314,6 +314,24 @@ class TestApplyAudioEdit:
|
||||
assert resp.status_code == 400
|
||||
assert "Invalid operation" in resp.json()["detail"]
|
||||
|
||||
@pytest.mark.parametrize("operation", ["fade_in", "fade_out"])
|
||||
def test_apply_fade_operations_accepted(self, operation, test_client, mock_job_manager, mock_services, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
mock_services["edit"].apply_edit.return_value = (
|
||||
AudioMetadata(duration_seconds=180.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=25000000),
|
||||
"jobs/edit-job-1/audio_edit/edit_fade.flac",
|
||||
)
|
||||
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"operation": operation,
|
||||
"params": {"start_seconds": 0.0, "end_seconds": 3.0},
|
||||
})
|
||||
|
||||
assert resp.status_code == 200
|
||||
called_op = mock_services["edit"].apply_edit.call_args.kwargs["operation"]
|
||||
assert called_op == operation
|
||||
|
||||
def test_apply_wrong_status(self, test_client, mock_job_manager):
|
||||
job = _job(job_id="wrong-status", status=JobStatus.COMPLETE,
|
||||
input_media_gcs_path="jobs/x/input/song.flac", state_data={})
|
||||
|
||||
@@ -152,6 +152,84 @@ class TestFFmpegOperations:
|
||||
assert "volume=enable='between(t,10.0,15.0)':volume=0" in af_str
|
||||
assert result.duration_seconds == 245.0 # Duration preserved
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_fade_in(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=245.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=35000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.fade_region("/tmp/input.flac", 0.0, 3.0, "in", "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-af" in cmd
|
||||
af_str = cmd[cmd.index("-af") + 1]
|
||||
assert "afade=t=in:st=0.0:d=3.0" in af_str
|
||||
assert result.duration_seconds == 245.0 # Duration preserved
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_fade_out(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=245.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=35000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.fade_region("/tmp/input.flac", 240.0, 245.0, "out", "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-af" in cmd
|
||||
af_str = cmd[cmd.index("-af") + 1]
|
||||
assert "afade=t=out:st=240.0:d=5.0" in af_str
|
||||
assert result.duration_seconds == 245.0 # Duration preserved
|
||||
|
||||
def test_fade_region_rejects_invalid_direction(self):
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(ValueError, match="Invalid fade direction"):
|
||||
service.fade_region("/tmp/input.flac", 0.0, 3.0, "sideways", "/tmp/output.flac")
|
||||
|
||||
def test_fade_region_rejects_inverted_region(self):
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(ValueError, match="Invalid fade region"):
|
||||
service.fade_region("/tmp/input.flac", 3.0, 3.0, "in", "/tmp/output.flac")
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
def test_fade_in_rejects_unanchored_start(self, mock_meta):
|
||||
# Backend must reject a fade-in that isn't anchored to the clip start,
|
||||
# even if a caller bypasses the UI gating (afade would silence the lead-in).
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=245.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=35000000,
|
||||
)
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(ValueError, match="anchored to the clip start"):
|
||||
service.fade_region("/tmp/input.flac", 50.0, 53.0, "in", "/tmp/output.flac")
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
def test_fade_out_rejects_unanchored_end(self, mock_meta):
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=245.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=35000000,
|
||||
)
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(ValueError, match="anchored to the clip end"):
|
||||
service.fade_region("/tmp/input.flac", 50.0, 55.0, "out", "/tmp/output.flac")
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
def test_fade_region_rejects_end_beyond_duration(self, mock_meta):
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=245.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=35000000,
|
||||
)
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(ValueError, match="exceeds clip duration"):
|
||||
service.fade_region("/tmp/input.flac", 0.0, 300.0, "in", "/tmp/output.flac")
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_join_audio_end(self, mock_run, mock_meta):
|
||||
@@ -229,6 +307,61 @@ class TestApplyEdit:
|
||||
assert result_path == "jobs/123/audio_edit/edit_abc.flac"
|
||||
assert metadata.duration_seconds == 200.0
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
def test_apply_edit_fade_in(self, mock_tmpdir, mock_run, mock_meta):
|
||||
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
|
||||
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioEditService(storage_service=mock_storage)
|
||||
|
||||
metadata, result_path = service.apply_edit(
|
||||
input_gcs_path="jobs/123/input/song.flac",
|
||||
operation="fade_in",
|
||||
params={"start_seconds": 0.0, "end_seconds": 3.0},
|
||||
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
|
||||
job_id="123",
|
||||
)
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
af_str = cmd[cmd.index("-af") + 1]
|
||||
assert "afade=t=in:st=0.0:d=3.0" in af_str
|
||||
assert metadata.duration_seconds == 200.0 # Duration preserved
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
def test_apply_edit_fade_out(self, mock_tmpdir, mock_run, mock_meta):
|
||||
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
|
||||
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioEditService(storage_service=mock_storage)
|
||||
|
||||
service.apply_edit(
|
||||
input_gcs_path="jobs/123/input/song.flac",
|
||||
operation="fade_out",
|
||||
params={"start_seconds": 197.0, "end_seconds": 200.0},
|
||||
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
|
||||
job_id="123",
|
||||
)
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
af_str = cmd[cmd.index("-af") + 1]
|
||||
assert "afade=t=out:st=197.0:d=3.0" in af_str
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
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)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""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
|
||||
@@ -0,0 +1,173 @@
|
||||
"""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, preferred_countries=None):
|
||||
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
|
||||
|
||||
|
||||
class TestVariantsAndVersions:
|
||||
def test_tracklist_returns_variants_versions_and_passes_locale(self, client, monkeypatch):
|
||||
from backend.services import musicbrainz_service as mbs
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
captured = {}
|
||||
|
||||
class FakeMB:
|
||||
async def get_album_tracklist(self, rg, preferred_countries=None):
|
||||
captured["prefs"] = preferred_countries
|
||||
return {
|
||||
"release_mbid": "rel1", "canonical_release_mbid": "rel1",
|
||||
"selected_variant_mbid": "rel1", "title": "Arrival", "date": "1976",
|
||||
"tracks": [{"position": 1, "title": "Dancing Queen", "recording_mbid": "r1",
|
||||
"length_ms": 230000, "is_extra": False, "extra_reason": ""}],
|
||||
"editions": [],
|
||||
"variants": [
|
||||
{"representative_release_mbid": "rel1", "label": "Original",
|
||||
"track_count": 10, "year": "1976", "pressing_count": 6, "delta_vs_original": 0},
|
||||
{"representative_release_mbid": "rel2", "label": "Reissue",
|
||||
"track_count": 12, "year": "2014", "pressing_count": 1, "delta_vs_original": 2},
|
||||
],
|
||||
}
|
||||
|
||||
async def fake_batch(songs, concurrency=5):
|
||||
return [{"artist": s["artist"], "title": s["title"], "available": True,
|
||||
"brands": ["SNDL Karaoke"], "brand_count": 1,
|
||||
"versions": [{"brand": "SNDL Karaoke", "url": "https://youtu.be/x"}]}
|
||||
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": "ABBA", "release_group_mbid": "rg", "locale": "ja"})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["variants"]) == 2
|
||||
assert data["variants"][0]["label"] == "Original"
|
||||
assert data["variants"][1]["delta_vs_original"] == 2
|
||||
assert data["selected_variant_mbid"] == "rel1"
|
||||
assert data["tracks"][0]["versions"] == [{"brand": "SNDL Karaoke", "url": "https://youtu.be/x"}]
|
||||
# Japanese locale → JP country preference threaded to MB service.
|
||||
assert captured["prefs"] == ["JP"]
|
||||
|
||||
def test_availability_returns_versions(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,
|
||||
"versions": [{"brand": "KV", "url": "https://youtu.be/kv"}]} 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]["versions"] == [{"brand": "KV", "url": "https://youtu.be/kv"}]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""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
|
||||
@@ -0,0 +1,84 @@
|
||||
"""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
|
||||
@@ -0,0 +1,178 @@
|
||||
"""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
|
||||
@@ -0,0 +1,150 @@
|
||||
"""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,3 +471,63 @@ 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,6 +394,48 @@ 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):
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
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):
|
||||
async def always_fail(job_id, worker_url=None):
|
||||
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):
|
||||
async def intermittent_failures(job_id, worker_url=None):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
# Fail for 2, succeed (running), fail for 2 more, succeed (complete)
|
||||
@@ -752,3 +752,128 @@ 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"]
|
||||
@@ -2,6 +2,12 @@
|
||||
Unit tests for encoding worker lifecycle endpoints.
|
||||
|
||||
Tests the warmup and heartbeat API endpoints.
|
||||
|
||||
These endpoints are called from the customer-facing lyrics-review page to
|
||||
pre-warm the encoding VM. They are therefore gated on ``require_review_auth``
|
||||
(review access to a specific job), NOT ``require_admin`` — otherwise every
|
||||
non-admin customer 403s and the pre-warm silently never happens (the bug this
|
||||
suite guards against).
|
||||
"""
|
||||
import logging
|
||||
|
||||
@@ -10,16 +16,24 @@ from unittest.mock import MagicMock
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.api.routes.encoding_worker import router, get_worker_manager
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.dependencies import require_admin, require_review_auth
|
||||
from backend.services.encoding_errors import (
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
)
|
||||
|
||||
JOB_ID = "test-job-123"
|
||||
WARMUP_URL = f"/api/internal/encoding-worker/warmup/{JOB_ID}"
|
||||
HEARTBEAT_URL = f"/api/internal/encoding-worker/heartbeat/{JOB_ID}"
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
return ("admin-token", "admin", 0)
|
||||
|
||||
async def fake_review_auth():
|
||||
"""Override for require_review_auth — stands in for a review user.
|
||||
|
||||
Deliberately returns a *non-admin* auth result (auth_type="full") so the
|
||||
tests exercise the review-scoped path, not admin access.
|
||||
"""
|
||||
return (JOB_ID, "full")
|
||||
|
||||
|
||||
class TestWarmupEndpoint:
|
||||
@@ -27,7 +41,7 @@ class TestWarmupEndpoint:
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_admin] = get_mock_admin
|
||||
self.app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
@@ -37,7 +51,7 @@ class TestWarmupEndpoint:
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["started"] is True
|
||||
@@ -49,7 +63,7 @@ class TestWarmupEndpoint:
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
|
||||
@@ -57,7 +71,7 @@ class TestWarmupEndpoint:
|
||||
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
|
||||
"VM not found"
|
||||
)
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
assert "error" in response.json()
|
||||
@@ -78,7 +92,7 @@ class TestWarmupEndpoint:
|
||||
)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
warmup_records = [
|
||||
@@ -106,7 +120,7 @@ class TestWarmupEndpoint:
|
||||
)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert not [
|
||||
r
|
||||
@@ -121,7 +135,7 @@ class TestWarmupEndpoint:
|
||||
"misconfigured service account"
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
error_records = [
|
||||
r
|
||||
@@ -137,12 +151,12 @@ class TestHeartbeatEndpoint:
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_admin] = get_mock_admin
|
||||
self.app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_heartbeat_updates_activity(self):
|
||||
response = self.client.post("/api/internal/encoding-worker/heartbeat")
|
||||
response = self.client.post(HEARTBEAT_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
self.mock_manager.update_activity.assert_called_once()
|
||||
@@ -151,6 +165,55 @@ class TestHeartbeatEndpoint:
|
||||
self.mock_manager.update_activity.side_effect = RuntimeError(
|
||||
"Firestore error"
|
||||
)
|
||||
response = self.client.post("/api/internal/encoding-worker/heartbeat")
|
||||
response = self.client.post(HEARTBEAT_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "error"
|
||||
|
||||
|
||||
class TestReviewAuthGating:
|
||||
"""Regression guard: these endpoints must be review-auth gated, not admin.
|
||||
|
||||
Before this fix they used ``require_admin``, so every non-admin customer on
|
||||
the lyrics-review page got a 403 and the JIT pre-warm never happened.
|
||||
"""
|
||||
|
||||
def test_routes_depend_on_review_auth_not_admin(self):
|
||||
"""The route dependencies reference require_review_auth, never require_admin."""
|
||||
deps = set()
|
||||
for route in router.routes:
|
||||
dependant = getattr(route, "dependant", None)
|
||||
if dependant is None:
|
||||
continue
|
||||
# Flatten the whole dependency tree for the route.
|
||||
stack = list(dependant.dependencies)
|
||||
while stack:
|
||||
d = stack.pop()
|
||||
deps.add(d.call)
|
||||
stack.extend(d.dependencies)
|
||||
assert require_review_auth in deps, (
|
||||
"warmup/heartbeat must be gated on require_review_auth"
|
||||
)
|
||||
assert require_admin not in deps, (
|
||||
"warmup/heartbeat must NOT require admin (regresses pre-warm for "
|
||||
"all non-admin customers)"
|
||||
)
|
||||
|
||||
def test_unauthenticated_request_is_rejected(self):
|
||||
"""With real auth (no override, no token), warmup is rejected — not 200/500."""
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
|
||||
client = TestClient(app, raise_server_exceptions=False)
|
||||
response = client.post(WARMUP_URL)
|
||||
# require_review_auth with no credentials raises 401.
|
||||
assert response.status_code == 401
|
||||
|
||||
def test_job_id_is_required_in_path(self):
|
||||
"""The old job-less path no longer exists (404), forcing job scoping."""
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
|
||||
client = TestClient(app)
|
||||
response = client.post("/api/internal/encoding-worker/warmup")
|
||||
assert response.status_code == 404
|
||||
@@ -1249,7 +1249,7 @@ class TestURLValidation:
|
||||
def test_other_supported_platforms(self):
|
||||
"""Test other supported video platforms."""
|
||||
from backend.api.routes.file_upload import _validate_url
|
||||
|
||||
|
||||
valid_urls = [
|
||||
"https://twitter.com/user/status/123",
|
||||
"https://x.com/user/status/123",
|
||||
@@ -1257,11 +1257,155 @@ class TestURLValidation:
|
||||
"https://www.instagram.com/reel/abc123/",
|
||||
"https://www.tiktok.com/@user/video/123",
|
||||
]
|
||||
|
||||
|
||||
for url in valid_urls:
|
||||
assert _validate_url(url), f"URL should be valid: {url}"
|
||||
|
||||
|
||||
class TestUnsupportedDrmUrl:
|
||||
"""Test detection of DRM-protected streaming URLs that can't be downloaded."""
|
||||
|
||||
def test_apple_music_urls_detected(self):
|
||||
from backend.api.routes.file_upload import _unsupported_url_platform
|
||||
|
||||
urls = [
|
||||
# The exact URL from the prod incident (job 7f36304a)
|
||||
"https://music.apple.com/us/album/gone-country-apple-music-sessions/1752594347?i=1752594711",
|
||||
"https://music.apple.com/gb/album/whatever/123",
|
||||
"https://itunes.apple.com/us/album/whatever/123",
|
||||
]
|
||||
for url in urls:
|
||||
assert _unsupported_url_platform(url) == "Apple Music", url
|
||||
|
||||
def test_spotify_urls_detected(self):
|
||||
from backend.api.routes.file_upload import _unsupported_url_platform
|
||||
|
||||
urls = [
|
||||
"https://open.spotify.com/track/abc123",
|
||||
"https://play.spotify.com/track/abc123",
|
||||
"https://spotify.com/track/abc123",
|
||||
]
|
||||
for url in urls:
|
||||
assert _unsupported_url_platform(url) == "Spotify", url
|
||||
|
||||
def test_other_drm_platforms_detected(self):
|
||||
from backend.api.routes.file_upload import _unsupported_url_platform
|
||||
|
||||
cases = {
|
||||
"https://tidal.com/browse/track/123": "Tidal",
|
||||
"https://listen.tidal.com/track/123": "Tidal",
|
||||
"https://music.amazon.com/albums/B0ABC": "Amazon Music",
|
||||
"https://music.amazon.co.uk/albums/B0ABC": "Amazon Music",
|
||||
"https://music.amazon.co.jp/albums/B0ABC": "Amazon Music",
|
||||
"https://music.amazon.fr/albums/B0ABC": "Amazon Music",
|
||||
"https://www.deezer.com/track/123": "Deezer",
|
||||
"https://www.pandora.com/artist/song": "Pandora",
|
||||
}
|
||||
for url, platform in cases.items():
|
||||
assert _unsupported_url_platform(url) == platform, url
|
||||
|
||||
def test_supported_urls_not_flagged(self):
|
||||
from backend.api.routes.file_upload import _unsupported_url_platform
|
||||
|
||||
# YouTube Music IS downloadable and must NOT be flagged.
|
||||
ok_urls = [
|
||||
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"https://youtu.be/dQw4w9WgXcQ",
|
||||
"https://music.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
"https://vimeo.com/123",
|
||||
"https://soundcloud.com/artist/track",
|
||||
"https://example.com/some/audio.mp3",
|
||||
"",
|
||||
None,
|
||||
]
|
||||
for url in ok_urls:
|
||||
assert _unsupported_url_platform(url) is None, url
|
||||
|
||||
def test_downloader_suggestions_are_valid(self):
|
||||
"""Every downloader suggestion maps a real platform to a list of https URLs."""
|
||||
from backend.api.routes.file_upload import (
|
||||
_DRM_DOWNLOADER_SUGGESTIONS,
|
||||
_UNSUPPORTED_DRM_HOSTS,
|
||||
)
|
||||
|
||||
known_platforms = set(_UNSUPPORTED_DRM_HOSTS.values()) | {"Amazon Music"}
|
||||
for platform, urls in _DRM_DOWNLOADER_SUGGESTIONS.items():
|
||||
assert platform in known_platforms, f"{platform} is not a known DRM platform"
|
||||
assert isinstance(urls, list) and urls, f"{platform} must list downloaders"
|
||||
for url in urls:
|
||||
assert url.startswith("https://"), f"{platform} downloader must be https"
|
||||
|
||||
# The verified cases driving this feature.
|
||||
assert "https://am-dl.pages.dev" in _DRM_DOWNLOADER_SUGGESTIONS["Apple Music"]
|
||||
assert "https://aplmate.com" in _DRM_DOWNLOADER_SUGGESTIONS["Apple Music"]
|
||||
assert "https://spotdown.org" in _DRM_DOWNLOADER_SUGGESTIONS["Spotify"]
|
||||
assert "https://spotmate.online" in _DRM_DOWNLOADER_SUGGESTIONS["Spotify"]
|
||||
|
||||
def test_drm_detail_links_known_downloaders(self):
|
||||
"""Platforms with known tools get a message naming each downloader URL."""
|
||||
from backend.api.routes.file_upload import _drm_unsupported_detail
|
||||
|
||||
apple = _drm_unsupported_detail("en", "Apple Music")
|
||||
assert "https://am-dl.pages.dev" in apple
|
||||
assert "https://aplmate.com" in apple
|
||||
|
||||
spotify = _drm_unsupported_detail("en", "Spotify")
|
||||
assert "https://spotdown.org" in spotify
|
||||
assert "https://spotmate.online" in spotify
|
||||
|
||||
def test_drm_detail_falls_back_to_web_search(self):
|
||||
"""Platforms without a known tool get a Google search link for a downloader."""
|
||||
from backend.api.routes.file_upload import _drm_unsupported_detail
|
||||
|
||||
detail = _drm_unsupported_detail("en", "Tidal")
|
||||
assert "https://www.google.com/search?q=Tidal+downloader" in detail
|
||||
assert "Tidal" in detail
|
||||
|
||||
|
||||
class TestValidateJobUrlEndpoint:
|
||||
"""The /jobs/validate-url pre-flight check used by the guided submission flow."""
|
||||
|
||||
def _call(self, url):
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock, patch
|
||||
from backend.api.routes.file_upload import validate_job_url, ValidateUrlRequest
|
||||
|
||||
req = MagicMock()
|
||||
req.headers = {}
|
||||
with patch("backend.api.routes.file_upload.get_locale_from_request", return_value="en"):
|
||||
return asyncio.run(
|
||||
validate_job_url(
|
||||
request=req,
|
||||
body=ValidateUrlRequest(url=url),
|
||||
auth_result=MagicMock(),
|
||||
)
|
||||
)
|
||||
|
||||
def test_apple_music_rejected_with_links(self):
|
||||
r = self._call("https://music.apple.com/us/album/x/1?i=2")
|
||||
assert r.supported is False
|
||||
assert "am-dl.pages.dev" in r.detail
|
||||
|
||||
def test_spotify_rejected_with_links(self):
|
||||
r = self._call("https://open.spotify.com/track/abc")
|
||||
assert r.supported is False
|
||||
assert "spotdown.org" in r.detail
|
||||
|
||||
def test_tidal_rejected_with_search_link(self):
|
||||
r = self._call("https://tidal.com/browse/track/123")
|
||||
assert r.supported is False
|
||||
assert "google.com/search" in r.detail
|
||||
|
||||
def test_youtube_supported(self):
|
||||
r = self._call("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
|
||||
assert r.supported is True
|
||||
assert r.detail is None
|
||||
|
||||
def test_garbage_url_rejected(self):
|
||||
r = self._call("not a real url")
|
||||
assert r.supported is False
|
||||
|
||||
|
||||
class TestCreateJobFromUrlRequest:
|
||||
"""Test CreateJobFromUrlRequest Pydantic model."""
|
||||
|
||||
|
||||
@@ -508,3 +508,50 @@ 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()
|
||||
@@ -419,10 +419,11 @@ class TestUploadToPublicShare:
|
||||
cdg_file.write_bytes(b"cdg package")
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
|
||||
# Mock methods
|
||||
with patch.object(service, "get_or_create_folder") as mock_get_folder:
|
||||
with patch.object(service, "upload_file") as mock_upload:
|
||||
with patch.object(service, "get_or_create_folder") as mock_get_folder, \
|
||||
patch.object(service, "upload_file") as mock_upload, \
|
||||
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
|
||||
mock_get_folder.side_effect = [
|
||||
"mp4-folder-id",
|
||||
"mp4-720-folder-id",
|
||||
@@ -433,30 +434,96 @@ class TestUploadToPublicShare:
|
||||
"720p-file-id",
|
||||
"cdg-file-id",
|
||||
]
|
||||
|
||||
|
||||
output_files = {
|
||||
"final_karaoke_lossy_mp4": str(mp4_file),
|
||||
"final_karaoke_lossy_720p_mp4": str(mp4_720_file),
|
||||
"final_karaoke_cdg_zip": str(cdg_file),
|
||||
}
|
||||
|
||||
|
||||
result = service.upload_to_public_share(
|
||||
root_folder_id="root-123",
|
||||
brand_code="NOMAD-1163",
|
||||
base_name="Artist - Title",
|
||||
output_files=output_files,
|
||||
)
|
||||
|
||||
|
||||
# Should have created/found 3 folders
|
||||
assert mock_get_folder.call_count == 3
|
||||
|
||||
|
||||
# Should have uploaded 3 files
|
||||
assert mock_upload.call_count == 3
|
||||
|
||||
|
||||
# Check result
|
||||
assert result["mp4"] == "mp4-file-id"
|
||||
assert result["mp4_720p"] == "720p-file-id"
|
||||
assert result["cdg"] == "cdg-file-id"
|
||||
|
||||
# Nomad brand → the 720p master is fast-synced to the Divebar GCS
|
||||
# mirror with the exact "{brand_code} - {base_name}.mp4" object name.
|
||||
mock_mirror_cls.return_value.push_720p.assert_called_once_with(
|
||||
str(mp4_720_file), "NOMAD-1163 - Artist - Title.mp4"
|
||||
)
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_public_share_no_fast_sync_for_non_nomad_brand(self, mock_get_settings, tmp_path):
|
||||
"""Non-Nomad brands (and NOMADNP privates) must NOT touch the divebar mirror."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
mp4_720_file = tmp_path / "output_720p.mp4"
|
||||
mp4_720_file.write_bytes(b"720p video")
|
||||
|
||||
service = GoogleDriveService()
|
||||
with patch.object(service, "get_or_create_folder", return_value="f"), \
|
||||
patch.object(service, "upload_file", return_value="id"), \
|
||||
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
|
||||
for brand in ("VOCALSTAR-12", "NOMADNP-1163"):
|
||||
service.upload_to_public_share(
|
||||
root_folder_id="root-123",
|
||||
brand_code=brand,
|
||||
base_name="Artist - Title",
|
||||
output_files={"final_karaoke_lossy_720p_mp4": str(mp4_720_file)},
|
||||
)
|
||||
mock_mirror_cls.assert_not_called()
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_public_share_fast_sync_failure_is_non_fatal(self, mock_get_settings, tmp_path):
|
||||
"""A mirror failure must never break the (already-succeeded) Drive upload."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
mp4_720_file = tmp_path / "output_720p.mp4"
|
||||
mp4_720_file.write_bytes(b"720p video")
|
||||
|
||||
service = GoogleDriveService()
|
||||
warnings: list = []
|
||||
with patch.object(service, "get_or_create_folder", return_value="f"), \
|
||||
patch.object(service, "upload_file", return_value="720p-file-id"), \
|
||||
patch("backend.services.nomad_master_mirror.NomadMasterMirror",
|
||||
side_effect=RuntimeError("gcs down")):
|
||||
result = service.upload_to_public_share(
|
||||
root_folder_id="root-123",
|
||||
brand_code="NOMAD-1163",
|
||||
base_name="Artist - Title",
|
||||
output_files={"final_karaoke_lossy_720p_mp4": str(mp4_720_file)},
|
||||
warnings=warnings,
|
||||
)
|
||||
# Drive upload still reports success despite the mirror blowing up...
|
||||
assert result["mp4_720p"] == "720p-file-id"
|
||||
# ...and the failure is surfaced as a distribution warning (admin alert),
|
||||
# not silently swallowed.
|
||||
assert any("fast-sync" in w for w in warnings)
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_upload_to_public_share_skips_missing_files(
|
||||
@@ -928,6 +995,56 @@ class TestFindFilesByBrandCode:
|
||||
with pytest.raises(RuntimeError, match="search incomplete"):
|
||||
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_recovers_from_transient_connection_error(self, mock_get_settings):
|
||||
"""A transient BrokenPipe/SSL EOF within a subfolder search is retried, not fatal.
|
||||
|
||||
Regression for the "GDrive brand_code search incomplete: 2/3 subfolder(s) failed"
|
||||
alerts caused by [SSL: UNEXPECTED_EOF_WHILE_READING] / [Errno 32] Broken pipe
|
||||
against idle Cloud Run containers.
|
||||
"""
|
||||
service = self._make_service(mock_get_settings)
|
||||
# Prevent _reset_service (called in before_sleep) from nulling our mock.
|
||||
service._reset_service = Mock()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
|
||||
BrokenPipeError("Errno 32 Broken pipe"), # transient drop mid-search
|
||||
{"files": [{"id": "cdg-folder"}]}, # retry: subfolder found again
|
||||
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
|
||||
{"files": []}, # MP4 not found
|
||||
{"files": []}, # MP4-720p not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == ["cdg-file-1"]
|
||||
service._reset_service.assert_called() # a retry actually happened
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_persistent_transient_error_still_raises_incomplete(self, mock_get_settings):
|
||||
"""If retries are exhausted, the search is still reported as incomplete (not clean)."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
service._reset_service = Mock()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# Every call drops the connection — retries exhaust for all subfolders.
|
||||
mock_list_result.execute.side_effect = BrokenPipeError("Errno 32 Broken pipe")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
with pytest.raises(RuntimeError, match="search incomplete"):
|
||||
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
|
||||
class TestGetGdriveService:
|
||||
"""Test get_gdrive_service singleton."""
|
||||
|
||||
@@ -9,6 +9,8 @@ from backend.services.karaokenerds_service import (
|
||||
parse_results,
|
||||
_clean_youtube_url,
|
||||
_parse_single_track,
|
||||
check_community_versions,
|
||||
check_community_versions_batch,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
@@ -207,3 +209,168 @@ def test_parse_results_empty_html():
|
||||
|
||||
def test_parse_results_no_table():
|
||||
assert parse_results("<div>No results</div>") == []
|
||||
|
||||
|
||||
# --- Batch availability: per-version data with YouTube URLs (Bulk Mode) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_returns_versions_with_urls_deduped_by_brand(monkeypatch):
|
||||
"""Each result carries `versions: [{brand, url}]` (community only), deduped by
|
||||
brand keeping the first URL, alongside the existing brands/brand_count."""
|
||||
|
||||
async def fake_check(artist, title):
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [
|
||||
{
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"community_tracks": [
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=aaa", "is_community": True},
|
||||
{"brand_name": "Nomad Karaoke", "brand_code": "NK",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=bbb", "is_community": True},
|
||||
# Duplicate brand — should be collapsed, keeping the first URL.
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=ccc", "is_community": True},
|
||||
],
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=aaa",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service.check_community_versions", fake_check
|
||||
)
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": "ABBA", "title": "Dancing Queen"}]
|
||||
)
|
||||
|
||||
assert len(results) == 1
|
||||
r = results[0]
|
||||
assert r["available"] is True
|
||||
assert r["versions"] == [
|
||||
{"brand": "SNDL Karaoke", "url": "https://www.youtube.com/watch?v=aaa"},
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=bbb"},
|
||||
]
|
||||
# Back-compat retained.
|
||||
assert r["brands"] == ["SNDL Karaoke", "Nomad Karaoke"]
|
||||
assert r["brand_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_empty_song_has_empty_versions():
|
||||
results = await check_community_versions_batch([{"artist": "", "title": ""}])
|
||||
assert results[0]["available"] is False
|
||||
assert results[0]["versions"] == []
|
||||
|
||||
|
||||
# --- check_community_versions: overlong-query fallback (KaraokeNerds term cap) ---
|
||||
|
||||
|
||||
def _community_song(title, artist, brand="Nomad Karaoke", url="https://youtu.be/x"):
|
||||
return {
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": [
|
||||
{"brand_name": brand, "brand_code": "NK", "youtube_url": url, "is_community": True}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_community_cache():
|
||||
"""check_community_versions caches in-process; isolate each test."""
|
||||
from backend.services import karaokenerds_service as svc
|
||||
svc._cache.clear()
|
||||
yield
|
||||
svc._cache.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_overlong_query_falls_back_to_title_only(monkeypatch):
|
||||
"""An overlong "artist title" query that returns nothing retries title-only
|
||||
and matches by artist (the ABBA 'I Do, I Do, I Do, I Do, I Do' bug)."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
if query == f"ABBA {title}":
|
||||
return [] # combined query is too long -> KaraokeNerds returns nothing
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
assert result["has_community"] is True
|
||||
assert result["songs"][0]["artist"] == "ABBA"
|
||||
assert calls == [f"ABBA {title}", title] # combined first, then title-only fallback
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_filters_out_wrong_artist(monkeypatch):
|
||||
"""Title-only fallback is broader, so same-titled songs by other artists
|
||||
must be discarded — no false positive."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
|
||||
async def fake_search(query):
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "Some Other Band")]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
assert result["has_community"] is False
|
||||
assert result["songs"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_empty_query_does_not_fall_back(monkeypatch):
|
||||
"""A short query that legitimately returns nothing must NOT trigger a second
|
||||
request (avoids doubling load for songs with no community version)."""
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", "Dancing Queen")
|
||||
|
||||
assert result["has_community"] is False
|
||||
assert calls == ["ABBA Dancing Queen"] # no fallback request
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nonempty_combined_result_skips_fallback(monkeypatch):
|
||||
"""If the combined query returns results, never fall back even when long."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
assert result["has_community"] is True
|
||||
assert calls == [f"ABBA {title}"] # only the combined query ran
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
Unit tests for UserService.get_magic_link_status.
|
||||
|
||||
This is a READ-ONLY status check used by the verify page to decide, on load,
|
||||
whether to show the "Complete Sign-In" gate (valid link) or an "already used /
|
||||
expired" message (dead link). It must NEVER consume the token — otherwise an
|
||||
email link-scanner that renders the verify page would burn a valid link before
|
||||
the real user clicks, which is exactly the bug this whole feature prevents.
|
||||
"""
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# Mock Firestore before importing modules that use it.
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def _service_with_doc(mock_fs, mock_settings, doc_dict, exists=True):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = exists
|
||||
mock_doc.to_dict.return_value = doc_dict
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
from backend.services.user_service import UserService
|
||||
return UserService(), mock_db
|
||||
|
||||
|
||||
def _link_dict(**overrides):
|
||||
d = {
|
||||
'token': 'tok123',
|
||||
'email': 'user@example.com',
|
||||
'created_at': datetime.utcnow(),
|
||||
'expires_at': datetime.utcnow() + timedelta(hours=1),
|
||||
'used': False,
|
||||
'used_at': None,
|
||||
}
|
||||
d.update(overrides)
|
||||
return d
|
||||
|
||||
|
||||
class TestGetMagicLinkStatus:
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_valid_link_returns_valid(self, mock_fs, mock_settings):
|
||||
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
|
||||
assert service.get_magic_link_status('tok123') == 'valid'
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_valid_link_is_not_consumed(self, mock_fs, mock_settings):
|
||||
"""The scanner-safety guarantee: a status check must not mutate the token."""
|
||||
service, mock_db = _service_with_doc(mock_fs, mock_settings, _link_dict())
|
||||
service.get_magic_link_status('tok123')
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
doc_ref.update.assert_not_called()
|
||||
doc_ref.set.assert_not_called()
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_used_link_returns_used(self, mock_fs, mock_settings):
|
||||
service, _ = _service_with_doc(
|
||||
mock_fs, mock_settings, _link_dict(used=True, used_at=datetime.utcnow())
|
||||
)
|
||||
assert service.get_magic_link_status('tok123') == 'used'
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_expired_link_returns_expired(self, mock_fs, mock_settings):
|
||||
service, _ = _service_with_doc(
|
||||
mock_fs, mock_settings, _link_dict(expires_at=datetime.utcnow() - timedelta(minutes=1))
|
||||
)
|
||||
assert service.get_magic_link_status('tok123') == 'expired'
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_missing_link_returns_invalid(self, mock_fs, mock_settings):
|
||||
service, _ = _service_with_doc(mock_fs, mock_settings, {}, exists=False)
|
||||
assert service.get_magic_link_status('missing') == 'invalid'
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_empty_token_returns_invalid(self, mock_fs, mock_settings):
|
||||
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
|
||||
assert service.get_magic_link_status(' ') == 'invalid'
|
||||
|
||||
|
||||
class TestLinkStatusEndpoint:
|
||||
"""GET /api/users/auth/link-status — thin, read-only wrapper over the service."""
|
||||
|
||||
def _client(self, status_value):
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
svc = MagicMock()
|
||||
svc.get_magic_link_status.return_value = status_value
|
||||
app.dependency_overrides[get_user_service] = lambda: svc
|
||||
return TestClient(app), app, svc
|
||||
|
||||
def test_endpoint_returns_status_for_valid(self):
|
||||
client, app, svc = self._client("valid")
|
||||
try:
|
||||
r = client.get("/api/users/auth/link-status", params={"token": "tok123"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "valid"
|
||||
svc.get_magic_link_status.assert_called_once_with("tok123")
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_endpoint_returns_used(self):
|
||||
client, app, svc = self._client("used")
|
||||
try:
|
||||
r = client.get("/api/users/auth/link-status", params={"token": "burned"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "used"
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_endpoint_returns_invalid_for_empty_token_without_touching_firestore(self):
|
||||
client, app, svc = self._client("valid") # service would say valid, but route must short-circuit
|
||||
try:
|
||||
r = client.get("/api/users/auth/link-status", params={"token": " "})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["status"] == "invalid"
|
||||
svc.get_magic_link_status.assert_not_called()
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""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
|
||||
@@ -0,0 +1,278 @@
|
||||
"""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
|
||||
|
||||
|
||||
class TestBuildVariants:
|
||||
"""Collapse a release-group's editions into distinct tracklist variants."""
|
||||
|
||||
def test_same_track_count_editions_collapse_to_one_variant(self):
|
||||
editions = [
|
||||
{"release_mbid": "us76", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
|
||||
{"release_mbid": "se76", "status": "Official", "date": "1976", "country": "SE", "track_count": 10},
|
||||
{"release_mbid": "nl76", "status": "Official", "date": "1976", "country": "NL", "track_count": 10},
|
||||
]
|
||||
variants = MusicBrainzService.build_variants(editions)
|
||||
assert len(variants) == 1
|
||||
v = variants[0]
|
||||
assert v["track_count"] == 10
|
||||
assert v["pressing_count"] == 3
|
||||
assert v["label"] == "Original"
|
||||
assert v["year"] == "1976"
|
||||
assert v["delta_vs_original"] == 0
|
||||
# earliest date (all 1976) then preferred country US over SE/NL
|
||||
assert v["representative_release_mbid"] == "us76"
|
||||
|
||||
def test_distinct_track_counts_form_separate_variants_sorted_original_first(self):
|
||||
editions = [
|
||||
{"release_mbid": "reissue2014", "status": "Official", "date": "2014", "country": "XW", "track_count": 12},
|
||||
{"release_mbid": "orig1976", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
|
||||
]
|
||||
variants = MusicBrainzService.build_variants(editions)
|
||||
assert [v["representative_release_mbid"] for v in variants] == ["orig1976", "reissue2014"]
|
||||
assert variants[0]["label"] == "Original"
|
||||
assert variants[0]["delta_vs_original"] == 0
|
||||
assert variants[1]["label"] == "Reissue"
|
||||
assert variants[1]["delta_vs_original"] == 2
|
||||
assert variants[1]["year"] == "2014"
|
||||
|
||||
def test_single_edition_is_one_original_variant(self):
|
||||
editions = [{"release_mbid": "only", "status": "Official", "date": "1990", "country": "GB", "track_count": 11}]
|
||||
variants = MusicBrainzService.build_variants(editions)
|
||||
assert len(variants) == 1
|
||||
assert variants[0]["label"] == "Original"
|
||||
assert variants[0]["pressing_count"] == 1
|
||||
|
||||
def test_no_editions_no_variants(self):
|
||||
assert MusicBrainzService.build_variants([]) == []
|
||||
|
||||
def test_editions_without_tracks_excluded(self):
|
||||
editions = [
|
||||
{"release_mbid": "real", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
|
||||
{"release_mbid": "empty", "status": "Official", "date": "1976", "country": "GB", "track_count": 0},
|
||||
]
|
||||
variants = MusicBrainzService.build_variants(editions)
|
||||
assert len(variants) == 1
|
||||
assert variants[0]["representative_release_mbid"] == "real"
|
||||
|
||||
def test_preferred_countries_override_picks_representative(self):
|
||||
editions = [
|
||||
{"release_mbid": "us76", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
|
||||
{"release_mbid": "jp76", "status": "Official", "date": "1976", "country": "JP", "track_count": 10},
|
||||
]
|
||||
variants = MusicBrainzService.build_variants(editions, preferred_countries=["JP"])
|
||||
assert variants[0]["representative_release_mbid"] == "jp76"
|
||||
|
||||
|
||||
class TestLocaleCountryPrefs:
|
||||
def test_english_locale_prefers_anglophone_countries(self):
|
||||
from backend.services.musicbrainz_service import country_prefs_for_locale
|
||||
assert country_prefs_for_locale("en") == ["GB", "US", "AU", "CA", "IE", "NZ"]
|
||||
|
||||
def test_region_suffix_is_stripped(self):
|
||||
from backend.services.musicbrainz_service import country_prefs_for_locale
|
||||
assert country_prefs_for_locale("en-US") == ["GB", "US", "AU", "CA", "IE", "NZ"]
|
||||
|
||||
def test_japanese_locale(self):
|
||||
from backend.services.musicbrainz_service import country_prefs_for_locale
|
||||
assert country_prefs_for_locale("ja") == ["JP"]
|
||||
|
||||
def test_unknown_and_none_fall_back_to_default(self):
|
||||
from backend.services.musicbrainz_service import country_prefs_for_locale
|
||||
default = ["XW", "XE", "US", "GB"]
|
||||
assert country_prefs_for_locale("zz") == default
|
||||
assert country_prefs_for_locale(None) == default
|
||||
assert country_prefs_for_locale("") == default
|
||||
|
||||
|
||||
@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
|
||||
# Variants: 3-track original + 5-track reissue; selected = canonical.
|
||||
variants = result["variants"]
|
||||
assert len(variants) == 2
|
||||
assert variants[0]["label"] == "Original"
|
||||
assert variants[0]["track_count"] == 3
|
||||
assert variants[1]["label"] == "Reissue"
|
||||
assert variants[1]["delta_vs_original"] == 2
|
||||
assert result["selected_variant_mbid"] == result["canonical_release_mbid"]
|
||||
|
||||
|
||||
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")
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Unit tests for the Nomad master fast-sync mirror (Phase 1)."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from google.cloud.exceptions import NotFound
|
||||
|
||||
from backend.services.nomad_master_mirror import (
|
||||
NomadMasterMirror,
|
||||
is_nomad_public_brand,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"brand_code, expected",
|
||||
[
|
||||
("NOMAD-1500", True),
|
||||
("NOMAD-0001", True),
|
||||
("NOMAD-1500", True),
|
||||
("NOMADNP-1234", False), # private tracks must never enter the public mirror
|
||||
("nomadnp-1", False),
|
||||
("TRACK-0000", False),
|
||||
("VOCALSTAR-12", False),
|
||||
("", False),
|
||||
(None, False),
|
||||
],
|
||||
)
|
||||
def test_is_nomad_public_brand(brand_code, expected):
|
||||
assert is_nomad_public_brand(brand_code) is expected
|
||||
|
||||
|
||||
def _mirror_with_mock():
|
||||
"""NomadMasterMirror wired to a mock GCS client; returns (mirror, blob)."""
|
||||
blob = MagicMock()
|
||||
bucket = MagicMock()
|
||||
bucket.blob.return_value = blob
|
||||
client = MagicMock()
|
||||
client.bucket.return_value = bucket
|
||||
mirror = NomadMasterMirror(client=client)
|
||||
return mirror, bucket, blob
|
||||
|
||||
|
||||
def test_push_720p_uses_exact_divebar_object_name_and_uploads():
|
||||
mirror, bucket, blob = _mirror_with_mock()
|
||||
|
||||
ok = mirror.push_720p(
|
||||
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
|
||||
"NOMAD-1500 - Rush - The Spirit of Radio.mp4",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
# Object name MUST match the nightly VM's layout exactly (idempotency).
|
||||
bucket.blob.assert_called_once_with(
|
||||
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
|
||||
)
|
||||
blob.upload_from_filename.assert_called_once_with(
|
||||
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
|
||||
)
|
||||
|
||||
|
||||
def test_push_720p_is_non_fatal_on_error():
|
||||
mirror, _bucket, blob = _mirror_with_mock()
|
||||
blob.upload_from_filename.side_effect = RuntimeError("boom")
|
||||
|
||||
# Must not raise; returns False so the pipeline continues.
|
||||
assert mirror.push_720p("/tmp/x.mp4", "NOMAD-1 - A - B.mp4") is False
|
||||
|
||||
|
||||
def test_delete_720p_removes_blob():
|
||||
mirror, bucket, blob = _mirror_with_mock()
|
||||
|
||||
assert mirror.delete_720p("NOMAD-1500 - Rush - The Spirit of Radio.mp4") is True
|
||||
bucket.blob.assert_called_once_with(
|
||||
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
|
||||
)
|
||||
blob.delete.assert_called_once()
|
||||
|
||||
|
||||
def test_delete_720p_missing_is_noop():
|
||||
mirror, _bucket, blob = _mirror_with_mock()
|
||||
blob.delete.side_effect = NotFound("gone")
|
||||
|
||||
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
|
||||
|
||||
|
||||
def test_delete_720p_is_non_fatal_on_error():
|
||||
mirror, _bucket, blob = _mirror_with_mock()
|
||||
blob.delete.side_effect = RuntimeError("boom")
|
||||
|
||||
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
|
||||
|
||||
|
||||
# --- delete_masters_by_brand (prefix delete; covers renames) ---
|
||||
|
||||
def _mirror_with_blobs(names):
|
||||
blobs = []
|
||||
for n in names:
|
||||
b = MagicMock()
|
||||
b.name = n
|
||||
blobs.append(b)
|
||||
bucket = MagicMock()
|
||||
bucket.list_blobs.return_value = blobs
|
||||
client = MagicMock()
|
||||
client.bucket.return_value = bucket
|
||||
return NomadMasterMirror(client=client), bucket, blobs
|
||||
|
||||
|
||||
def test_delete_masters_by_brand_deletes_all_matching_by_prefix():
|
||||
# Two objects for the same release (e.g. an old + renamed title) both go.
|
||||
mirror, bucket, blobs = _mirror_with_blobs([
|
||||
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - Spirit of Radio.mp4",
|
||||
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
|
||||
])
|
||||
n = mirror.delete_masters_by_brand("NOMAD-1500")
|
||||
assert n == 2
|
||||
bucket.list_blobs.assert_called_once_with(
|
||||
prefix="files/Nomad Karaoke/MP4-720p/NOMAD-1500 - "
|
||||
)
|
||||
for b in blobs:
|
||||
b.delete.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
|
||||
def test_delete_masters_by_brand_refuses_non_nomad_or_bare(brand):
|
||||
# Must never list/delete for a non-Nomad or bare brand — a broad prefix could
|
||||
# wipe unrelated objects.
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
assert mirror.delete_masters_by_brand(brand) == 0
|
||||
bucket.list_blobs.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_masters_by_brand_is_non_fatal_on_list_error():
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
bucket.list_blobs.side_effect = RuntimeError("gcs down")
|
||||
assert mirror.delete_masters_by_brand("NOMAD-1500") == 0
|
||||
|
||||
|
||||
def test_cleanup_nomad_masters_delegates_for_nomad(monkeypatch):
|
||||
from backend.services import nomad_master_mirror as mod
|
||||
|
||||
called = {}
|
||||
inst = MagicMock()
|
||||
inst.delete_masters_by_brand.return_value = 3
|
||||
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: inst)
|
||||
|
||||
assert mod.cleanup_nomad_masters("NOMAD-1500") == 3
|
||||
inst.delete_masters_by_brand.assert_called_once_with("NOMAD-1500")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("brand", ["NOMADNP-1", "OTHER-1", "", None])
|
||||
def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
|
||||
from backend.services import nomad_master_mirror as mod
|
||||
|
||||
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
|
||||
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
|
||||
assert mod.cleanup_nomad_masters(brand) == 0
|
||||
@@ -0,0 +1,78 @@
|
||||
"""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
|
||||
@@ -0,0 +1,174 @@
|
||||
import asyncio
|
||||
|
||||
from backend.services.parse_titles import ai
|
||||
from backend.services.parse_titles import service
|
||||
|
||||
|
||||
def test_settings_parse_titles_defaults():
|
||||
from backend.config import Settings
|
||||
s = Settings()
|
||||
assert s.parse_titles_enabled is True
|
||||
assert s.parse_titles_model == "gemini-3.5-flash"
|
||||
assert s.parse_titles_timeout_ms == 20000
|
||||
assert s.parse_titles_max_items == 200
|
||||
|
||||
|
||||
def test_build_prompts_lists_items_with_ids():
|
||||
system, user = ai.build_prompts(
|
||||
[{"id": "a", "filename": "Santeria - Sublime _ Karaoke _ KaraFun.mp4",
|
||||
"channel": "KaraFun", "source": "youtube"}]
|
||||
)
|
||||
assert "artist" in system.lower() and "title" in system.lower()
|
||||
assert "id='a'" in user or '"a"' in user or "id=a" in user # id must be echoed
|
||||
assert "Santeria" in user
|
||||
|
||||
|
||||
def test_parse_map_from_response_aligns_by_id_and_fills_misses():
|
||||
items = [{"id": "a", "filename": "x"}, {"id": "b", "filename": "y"}]
|
||||
data = {"results": [{"id": "a", "artist": "Sublime", "title": "Santeria",
|
||||
"confidence": 0.9}]}
|
||||
out = ai.parse_map_from_response(data, items)
|
||||
assert {r["id"] for r in out} == {"a", "b"}
|
||||
a = next(r for r in out if r["id"] == "a")
|
||||
assert (a["artist"], a["title"]) == ("Sublime", "Santeria")
|
||||
b = next(r for r in out if r["id"] == "b")
|
||||
assert b["artist"] == "" and b["title"] == "" and b["confidence"] == 0.0
|
||||
|
||||
|
||||
def test_ai_parse_uses_injected_generate():
|
||||
items = [{"id": "a", "filename": "Bella Kay - iloveit (Karaoke Version).mp4"}]
|
||||
|
||||
async def fake_generate(model, system, user):
|
||||
return {"results": [{"id": "a", "artist": "Bella Kay",
|
||||
"title": "iloveit", "confidence": 0.82}]}
|
||||
|
||||
out = asyncio.run(ai.ai_parse(items, generate=fake_generate))
|
||||
assert out[0]["artist"] == "Bella Kay" and out[0]["confidence"] == 0.82
|
||||
|
||||
|
||||
def test_parse_map_handles_garbage_response():
|
||||
items = [{"id": "a", "filename": "x"}]
|
||||
assert ai.parse_map_from_response("not a dict", items) == [
|
||||
{"id": "a", "artist": "", "title": "", "confidence": 0.0}
|
||||
]
|
||||
|
||||
|
||||
def test_parse_titles_disabled_returns_blanks(monkeypatch):
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", False)
|
||||
out = asyncio.run(service.parse_titles([{"id": "a", "filename": "x"}]))
|
||||
assert out == [{"id": "a", "artist": "", "title": "", "confidence": 0.0}]
|
||||
|
||||
|
||||
def test_parse_titles_degrades_on_generate_error(monkeypatch):
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", True)
|
||||
|
||||
async def boom(model, system, user):
|
||||
raise RuntimeError("vertex down")
|
||||
|
||||
out = asyncio.run(service.parse_titles(
|
||||
[{"id": "a", "filename": "x"}], generate=boom))
|
||||
assert out == [{"id": "a", "artist": "", "title": "", "confidence": 0.0}]
|
||||
|
||||
|
||||
def test_parse_titles_happy_path(monkeypatch):
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", True)
|
||||
|
||||
async def gen(model, system, user):
|
||||
return {"results": [{"id": "a", "artist": "Queen",
|
||||
"title": "Bohemian Rhapsody", "confidence": 0.95}]}
|
||||
|
||||
out = asyncio.run(service.parse_titles([{"id": "a", "filename": "x"}], generate=gen))
|
||||
assert out[0]["artist"] == "Queen" and out[0]["confidence"] == 0.95
|
||||
|
||||
|
||||
def test_parse_titles_empty_returns_empty():
|
||||
assert asyncio.run(service.parse_titles([])) == []
|
||||
|
||||
|
||||
# --- auto-chunking: large batches must not ride one >20s Gemini call ---
|
||||
|
||||
def _items(n):
|
||||
return [{"id": str(i), "filename": f"file {i}.mp4"} for i in range(n)]
|
||||
|
||||
|
||||
def _ok_results(model, system, user):
|
||||
"""Echo one parsed result per '- id=' line in the user prompt."""
|
||||
ids = [line.split("id='", 1)[1].split("'", 1)[0]
|
||||
for line in user.splitlines() if line.startswith("- id=")]
|
||||
return {"results": [{"id": i, "artist": f"A{i}", "title": f"T{i}",
|
||||
"confidence": 0.9} for i in ids]}
|
||||
|
||||
|
||||
def test_settings_parse_titles_chunk_size_default():
|
||||
from backend.config import Settings
|
||||
assert Settings().parse_titles_chunk_size == 10
|
||||
|
||||
|
||||
def test_parse_titles_chunks_large_batches(monkeypatch):
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", True)
|
||||
calls = []
|
||||
|
||||
async def gen(model, system, user):
|
||||
n = sum(1 for line in user.splitlines() if line.startswith("- id="))
|
||||
calls.append(n)
|
||||
return _ok_results(model, system, user)
|
||||
|
||||
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
|
||||
assert sorted(calls, reverse=True) == [10, 10, 5] # 25 items -> 3 Gemini calls
|
||||
assert [r["id"] for r in out] == [str(i) for i in range(25)] # id-aligned
|
||||
assert all(r["artist"] == f'A{r["id"]}' for r in out)
|
||||
|
||||
|
||||
def test_parse_titles_chunk_failure_degrades_only_that_chunk(monkeypatch):
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", True)
|
||||
|
||||
async def gen(model, system, user):
|
||||
if "id='10'" in user: # the middle chunk (items 10-19)
|
||||
raise RuntimeError("vertex timeout")
|
||||
return _ok_results(model, system, user)
|
||||
|
||||
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
|
||||
assert out[0]["artist"] == "A0" and out[24]["artist"] == "A24"
|
||||
assert all(out[i]["artist"] == "" and out[i]["confidence"] == 0.0
|
||||
for i in range(10, 20)) # only that chunk blank
|
||||
assert [r["id"] for r in out] == [str(i) for i in range(25)]
|
||||
|
||||
|
||||
def test_parse_titles_chunks_run_concurrently(monkeypatch):
|
||||
"""The chunks must be issued in parallel — a 100-item batch shouldn't pay
|
||||
10 sequential Gemini round-trips."""
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", True)
|
||||
started = 0
|
||||
all_started = asyncio.Event()
|
||||
|
||||
async def gen(model, system, user):
|
||||
nonlocal started
|
||||
started += 1
|
||||
if started == 3:
|
||||
all_started.set()
|
||||
# Sequential execution would deadlock here on the first chunk.
|
||||
await asyncio.wait_for(all_started.wait(), timeout=5)
|
||||
return _ok_results(model, system, user)
|
||||
|
||||
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
|
||||
assert len(out) == 25 and out[0]["artist"] == "A0"
|
||||
|
||||
|
||||
def test_parse_titles_respects_configured_chunk_size(monkeypatch):
|
||||
from backend.config import settings
|
||||
monkeypatch.setattr(settings, "parse_titles_enabled", True)
|
||||
monkeypatch.setattr(settings, "parse_titles_chunk_size", 4, raising=False)
|
||||
calls = []
|
||||
|
||||
async def gen(model, system, user):
|
||||
calls.append(sum(1 for line in user.splitlines() if line.startswith("- id=")))
|
||||
return _ok_results(model, system, user)
|
||||
|
||||
asyncio.run(service.parse_titles(_items(10), generate=gen))
|
||||
assert sorted(calls, reverse=True) == [4, 4, 2]
|
||||
@@ -0,0 +1,59 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
|
||||
def _admin_result():
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=-1,
|
||||
message="ok", user_email="a@nomadkaraoke.com", is_admin=True)
|
||||
|
||||
|
||||
def test_parse_route_happy_path(monkeypatch):
|
||||
# Self-contained: set our own admin override rather than relying on the
|
||||
# conftest autouse fixture (which can be disturbed by earlier tests in a
|
||||
# full-suite run and leave the endpoint returning 401).
|
||||
from backend.api.routes import parse_titles as route
|
||||
|
||||
async def fake_parse(items, **kw):
|
||||
return [{"id": str(it["id"]), "artist": "Queen",
|
||||
"title": "Bohemian Rhapsody", "confidence": 0.9} for it in items]
|
||||
|
||||
monkeypatch.setattr(route, "parse_titles", fake_parse)
|
||||
original = app.dependency_overrides.get(require_admin)
|
||||
app.dependency_overrides[require_admin] = _admin_result
|
||||
try:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/parse-karaoke-titles", json={
|
||||
"items": [{"id": "1", "filename": "x.mp4", "source": "youtube"}]})
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["results"][0]["id"] == "1"
|
||||
assert body["results"][0]["artist"] == "Queen"
|
||||
finally:
|
||||
if original is not None:
|
||||
app.dependency_overrides[require_admin] = original
|
||||
else:
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
|
||||
|
||||
def test_parse_route_requires_admin():
|
||||
"""The route is gated by require_admin: a non-admin dependency -> 403."""
|
||||
original = app.dependency_overrides.get(require_admin)
|
||||
|
||||
def non_admin():
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
app.dependency_overrides[require_admin] = non_admin
|
||||
try:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/parse-karaoke-titles",
|
||||
json={"items": [{"id": "1", "filename": "x"}]})
|
||||
assert resp.status_code == 403
|
||||
finally:
|
||||
if original is not None:
|
||||
app.dependency_overrides[require_admin] = original
|
||||
else:
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""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()
|
||||
@@ -397,9 +397,90 @@ class TestRetryEndpoint:
|
||||
file_urls={}
|
||||
)
|
||||
|
||||
# This job has no input audio - should not be retryable
|
||||
has_input = job.input_media_gcs_path or job.url
|
||||
assert not has_input
|
||||
# This job has no input audio - should not be retryable.
|
||||
# Restart-from-beginning is gated on audio actually being in GCS, NOT on
|
||||
# job.url (a URL whose download failed has no audio to re-fetch).
|
||||
has_input_audio_in_gcs = job.input_media_gcs_path
|
||||
assert not has_input_audio_in_gcs
|
||||
|
||||
|
||||
class TestRetryUrlJobWithoutDownload:
|
||||
"""Regression tests for the retry routing fix (incident: job 7f36304a).
|
||||
|
||||
A URL job whose download failed has `job.url` set but NO audio in GCS.
|
||||
Retrying it must NOT trigger the audio/lyrics workers (which would fail with
|
||||
"Failed to download audio file" and be retried by Cloud Run); it must refuse
|
||||
cleanly with a 400 telling the user to resubmit.
|
||||
"""
|
||||
|
||||
def _call_retry(self, job, mock_jm, mock_ws, background_tasks):
|
||||
import asyncio
|
||||
from backend.api.routes.jobs import retry_job
|
||||
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_request = MagicMock()
|
||||
mock_request.headers = {}
|
||||
|
||||
async def _run():
|
||||
return await retry_job(
|
||||
job_id=job.job_id,
|
||||
request=mock_request,
|
||||
background_tasks=background_tasks,
|
||||
auth_result=MagicMock(is_admin=True, user_email="t@t.com"),
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_jm), \
|
||||
patch("backend.api.routes.jobs.worker_service", mock_ws), \
|
||||
patch("backend.api.routes.jobs._check_job_ownership", return_value=True), \
|
||||
patch("backend.api.routes.jobs._is_auto_retry_pending", return_value=False), \
|
||||
patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"):
|
||||
return asyncio.run(_run())
|
||||
|
||||
def _make_url_job(self, *, input_media_gcs_path=None):
|
||||
return Job(
|
||||
job_id="urljob1",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Hailey Whitters",
|
||||
title="Gone Country",
|
||||
url="https://music.apple.com/us/album/gone-country/1752594347?i=1752594711",
|
||||
input_media_gcs_path=input_media_gcs_path,
|
||||
file_urls={},
|
||||
)
|
||||
|
||||
def test_url_job_without_download_refuses_and_triggers_no_workers(self):
|
||||
"""URL job with no downloaded audio → 400 resubmit, no workers triggered."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
job = self._make_url_job(input_media_gcs_path=None)
|
||||
mock_jm, mock_ws = MagicMock(), MagicMock()
|
||||
background_tasks = MagicMock()
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
self._call_retry(job, mock_jm, mock_ws, background_tasks)
|
||||
|
||||
assert exc.value.status_code == 400
|
||||
assert "resubmit" in str(exc.value.detail).lower()
|
||||
# The doomed workers must NOT have been scheduled.
|
||||
scheduled = [c.args[0] for c in background_tasks.add_task.call_args_list]
|
||||
assert mock_ws.trigger_audio_worker not in scheduled
|
||||
assert mock_ws.trigger_lyrics_worker not in scheduled
|
||||
|
||||
def test_url_job_with_downloaded_audio_restarts_from_beginning(self):
|
||||
"""URL job whose download succeeded (audio in GCS) → restarts + workers."""
|
||||
job = self._make_url_job(input_media_gcs_path="uploads/urljob1/audio/in.flac")
|
||||
mock_jm, mock_ws = MagicMock(), MagicMock()
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
background_tasks = MagicMock()
|
||||
|
||||
result = self._call_retry(job, mock_jm, mock_ws, background_tasks)
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["retry_stage"] == "from_beginning"
|
||||
scheduled = [c.args[0] for c in background_tasks.add_task.call_args_list]
|
||||
assert mock_ws.trigger_audio_worker in scheduled
|
||||
assert mock_ws.trigger_lyrics_worker in scheduled
|
||||
|
||||
|
||||
class TestCompleteReviewWithInstrumentalSelection:
|
||||
|
||||
@@ -365,6 +365,44 @@ 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,6 +545,57 @@ 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,9 +38,36 @@ 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,6 +56,43 @@ 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."""
|
||||
|
||||
@@ -125,24 +162,70 @@ class TestApplyTenantOverrides:
|
||||
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert yt_upload is False
|
||||
|
||||
def test_request_values_take_precedence(self):
|
||||
"""Explicit request-level values are not overridden by tenant defaults."""
|
||||
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.
|
||||
"""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
# `dist` arrives pre-seeded with the GLOBAL consumer defaults.
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/Custom/Path",
|
||||
gdrive_folder_id="custom-folder",
|
||||
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized", # global default
|
||||
gdrive_folder_id="global-consumer-folder", # global default
|
||||
discord_webhook_url=None,
|
||||
brand_prefix="CUSTOM",
|
||||
brand_prefix="NOMAD", # global default
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.brand_prefix == "CUSTOM"
|
||||
assert new_dist.dropbox_path == "/Custom/Path"
|
||||
assert new_dist.gdrive_folder_id == "custom-folder"
|
||||
# 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
|
||||
|
||||
def test_no_tenant_config_passthrough(self):
|
||||
"""When no tenant config, all values pass through unchanged."""
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""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,6 +1058,52 @@ 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."""
|
||||
@@ -1405,6 +1451,36 @@ 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.
|
||||
|
||||
@@ -1903,3 +1979,73 @@ 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)
|
||||
@@ -83,6 +83,9 @@
|
||||
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
|
||||
"selectionError": "Error during audio selection for job {job_id}: {error}",
|
||||
"youtubeDownloadError": "YouTube download failed: {error}",
|
||||
"drmUrlUnsupported": "{platform} links are copy-protected, so we can't download them directly. Try downloading the audio with a third-party tool first, then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
|
||||
"drmUrlUnsupportedWithLink": "{platform} links are copy-protected, so we can't download them directly. You can download the track using a tool like {downloader} and then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
|
||||
"drmUrlUnsupportedSearch": "{platform} links are copy-protected, so we can't download them directly. Search the web for a \"{platform} downloader\" to get the audio — for example {searchUrl} — then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
|
||||
"torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.",
|
||||
"remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download",
|
||||
"remoteDownloadCompleteNoPath": "Remote download completed but no file path returned",
|
||||
|
||||
Loaded 100 of 316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user