mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 09:28:25 +09:00
Compare commits
No files matched your search
@@ -1,12 +1,16 @@
|
||||
name: Build GHA Runner Images
|
||||
|
||||
# Produces three custom GCE images used by the ephemeral GitHub Actions runner
|
||||
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu.
|
||||
# Produces the custom GCE images used by the ephemeral GitHub Actions runner
|
||||
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu,
|
||||
# gha-runner-gpu-windows.
|
||||
#
|
||||
# Flow per variant:
|
||||
# 1. Create a temporary build VM from debian-cloud/debian-12 with
|
||||
# infrastructure/scripts/runner-image-provision.sh as metadata-startup-script.
|
||||
# 2. Poll for /opt/runner-image-ready via gcloud ssh (survives kernel-upgrade reboots).
|
||||
# 1. Create a temporary build VM from the variant's base image with the
|
||||
# variant's provisioning script as its startup script:
|
||||
# - Linux variants: debian-12 + runner-image-provision.sh (startup-script)
|
||||
# - gpu-windows: windows-2022 + runner-image-provision.ps1
|
||||
# (windows-startup-script-ps1)
|
||||
# 2. Poll the serial console for the READY/FAILED marker (survives reboots).
|
||||
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
|
||||
# image family with name gha-runner-<variant>-<timestamp>.
|
||||
# 4. Delete the build VM (boot disk auto-deletes).
|
||||
@@ -16,7 +20,7 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variants:
|
||||
description: 'Comma-separated variants to build (general,build,gpu) or "all"'
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
|
||||
required: false
|
||||
default: 'all'
|
||||
skip_prune:
|
||||
@@ -50,7 +54,7 @@ jobs:
|
||||
run: |
|
||||
requested='${{ github.event.inputs.variants || 'all' }}'
|
||||
if [[ "$requested" == "all" || -z "$requested" ]]; then
|
||||
echo 'variants=["general","build","gpu"]' >> "$GITHUB_OUTPUT"
|
||||
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
|
||||
echo "variants=$json" >> "$GITHUB_OUTPUT"
|
||||
@@ -88,6 +92,11 @@ jobs:
|
||||
family="gha-runner-${variant}"
|
||||
vm="gha-image-build-${variant}-${ts}"
|
||||
|
||||
# Per-variant base image + startup-script metadata key: Windows
|
||||
# VMs only execute scripts under windows-startup-script-ps1.
|
||||
image_flag="--image=${{ env.BASE_IMAGE }}"
|
||||
metadata_file="startup-script=infrastructure/scripts/runner-image-provision.sh"
|
||||
|
||||
case "$variant" in
|
||||
general|build)
|
||||
machine="n2-standard-8"
|
||||
@@ -101,6 +110,16 @@ jobs:
|
||||
disk_size="200"
|
||||
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
|
||||
;;
|
||||
gpu-windows)
|
||||
# T4 attached so the GRID driver install can validate WDDM mode
|
||||
# (required for DirectML). Keep disk in sync with the
|
||||
# gpu-windows FamilySpec in runner_manager/ephemeral.py.
|
||||
machine="n1-standard-4"
|
||||
disk_size="100"
|
||||
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
|
||||
image_flag="--image-family=windows-2022 --image-project=windows-cloud"
|
||||
metadata_file="windows-startup-script-ps1=infrastructure/scripts/runner-image-provision.ps1"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown variant: $variant" >&2
|
||||
exit 1
|
||||
@@ -114,6 +133,8 @@ jobs:
|
||||
echo "machine=$machine"
|
||||
echo "disk_size=$disk_size"
|
||||
echo "accel=$accel"
|
||||
echo "image_flag=$image_flag"
|
||||
echo "metadata_file=$metadata_file"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create build VM
|
||||
@@ -123,14 +144,14 @@ jobs:
|
||||
--project='${{ env.GCP_PROJECT }}' \
|
||||
--zone='${{ env.BUILD_ZONE }}' \
|
||||
--machine-type='${{ steps.params.outputs.machine }}' \
|
||||
--image='${{ env.BASE_IMAGE }}' \
|
||||
${{ steps.params.outputs.image_flag }} \
|
||||
--boot-disk-size='${{ steps.params.outputs.disk_size }}GB' \
|
||||
--boot-disk-type=pd-balanced \
|
||||
--boot-disk-auto-delete \
|
||||
--service-account="${{ secrets.GCP_SERVICE_ACCOUNT }}" \
|
||||
--scopes=https://www.googleapis.com/auth/cloud-platform \
|
||||
--metadata=enable-oslogin=TRUE,image-variant='${{ matrix.variant }}' \
|
||||
--metadata-from-file=startup-script=infrastructure/scripts/runner-image-provision.sh \
|
||||
--metadata-from-file='${{ steps.params.outputs.metadata_file }}' \
|
||||
--labels=purpose=gha-runner-image-builder,variant='${{ matrix.variant }}' \
|
||||
${{ steps.params.outputs.accel }}
|
||||
|
||||
|
||||
@@ -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)"
|
||||
@@ -1650,7 +1657,13 @@ jobs:
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
|
||||
# EDGE-SECURITY: the `edge-origin-secret` Secret Manager secret is
|
||||
# referenced in --set-secrets below (created 2026-07-20; has a value).
|
||||
# EDGE_AUTH_MODE=enforce (in --set-env-vars) means the backend rejects
|
||||
# requests to public routes that lack the Cloudflare-injected X-Edge-Auth
|
||||
# header — i.e. direct-to-origin traffic bypassing the edge (health/root
|
||||
# exempt). Cutover done 2026-07-20; validated via prod E2E with 0 blocked
|
||||
# legit callers. To disable, set EDGE_AUTH_MODE=off here and redeploy.
|
||||
- name: Deploy to Cloud Run
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
@@ -1676,8 +1689,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,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"
|
||||
--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,EDGE_AUTH_MODE=enforce,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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
|
||||
@@ -34,10 +34,12 @@ jobs:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
python-version: '3.11'
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
@@ -46,15 +48,38 @@ jobs:
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install google-cloud-storage google-cloud-secret-manager
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Run tenant E2E
|
||||
id: run_test
|
||||
env:
|
||||
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Fetch test audio (private GCS)
|
||||
run: bash scripts/e2e/fetch_test_audio.sh frontend/e2e/fixtures
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted (rate limit)
|
||||
run: |
|
||||
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
|
||||
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run tenant E2E (frontend journey)
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
TENANT_ID: ${{ matrix.tenant }}
|
||||
TENANT_PORTAL_URL: https://${{ matrix.tenant }}.nomadkaraoke.com
|
||||
run: |
|
||||
echo "=== Tenant E2E (frontend): ${{ matrix.tenant }} ==="
|
||||
npx playwright test tenant-happy-path.spec.ts \
|
||||
--config=playwright.production.config.ts --project=chromium \
|
||||
--reporter=list --timeout=2400000 2>&1 | tee e2e-output.log
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
@@ -63,7 +88,10 @@ jobs:
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
|
||||
path: e2e-output.log
|
||||
path: |
|
||||
frontend/e2e-output.log
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
retention-days: 14
|
||||
|
||||
- name: Discord notification (failure)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -11,7 +11,7 @@ Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -55,6 +55,24 @@ class BulkEdition(BaseModel):
|
||||
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
|
||||
@@ -65,15 +83,18 @@ class BulkTrack(BaseModel):
|
||||
# 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):
|
||||
@@ -91,6 +112,7 @@ class AvailabilityResult(BaseModel):
|
||||
available: bool
|
||||
brands: list[str] = []
|
||||
brand_count: int = 0
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
class AvailabilityResponse(BaseModel):
|
||||
@@ -113,7 +135,7 @@ async def album_artists(
|
||||
try:
|
||||
results = await get_musicbrainz_service().search_artists(q, limit=limit)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz artist search failed: %s", e)
|
||||
logger.warning("MusicBrainz artist search failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Artist lookup is temporarily unavailable")
|
||||
return results
|
||||
|
||||
@@ -130,7 +152,7 @@ async def album_albums(
|
||||
try:
|
||||
return await get_musicbrainz_service().get_albums(artist_mbid)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz album list failed: %s", e)
|
||||
logger.warning("MusicBrainz album list failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Album lookup is temporarily unavailable")
|
||||
|
||||
|
||||
@@ -140,11 +162,21 @@ async def album_tracklist(
|
||||
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."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
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:
|
||||
@@ -153,13 +185,18 @@ async def album_tracklist(
|
||||
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)
|
||||
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: %s", e)
|
||||
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", [])
|
||||
@@ -171,16 +208,19 @@ async def album_tracklist(
|
||||
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", [])],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ from backend.services.error_monitor.frontend_ingestion import (
|
||||
FrontendErrorReport,
|
||||
RateLimiter,
|
||||
build_pattern_data,
|
||||
is_bot_user_agent,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -64,6 +66,20 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many reports")
|
||||
|
||||
# Crawler/bot crashes are pure alert noise (bots run headless Chrome and trip
|
||||
# DOM errors no real user hits). Accept the report so the client doesn't retry,
|
||||
# but don't persist/alert on it.
|
||||
if is_bot_user_agent(payload.user_agent):
|
||||
# Log the bot UA (not sensitive) + sanitized URL (query/token stripped)
|
||||
# for visibility into what's being dropped, without persisting/alerting.
|
||||
logger.info(
|
||||
"frontend_crash_ignored_bot ua=%r url=%s source=%s",
|
||||
payload.user_agent[:120],
|
||||
sanitize_url(payload.url),
|
||||
payload.source,
|
||||
)
|
||||
return ClientErrorResponse(pattern_id="bot-ignored", is_new=False)
|
||||
|
||||
report = FrontendErrorReport(
|
||||
message=payload.message,
|
||||
stack=payload.stack,
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -1581,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,
|
||||
@@ -1619,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(
|
||||
|
||||
@@ -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:
|
||||
@@ -1982,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, {
|
||||
@@ -2273,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",
|
||||
|
||||
@@ -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}
|
||||
@@ -185,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
|
||||
@@ -1226,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))
|
||||
|
||||
@@ -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,17 @@ 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"
|
||||
# Original-vocals guide: a padded isolated-vocals file (silence[intro] + vocals) pushed to
|
||||
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
|
||||
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
|
||||
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
@@ -117,6 +128,19 @@ class Settings(BaseSettings):
|
||||
# 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)
|
||||
|
||||
+9
-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, bulk
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, 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
|
||||
@@ -18,6 +18,7 @@ from backend.services.nltk_preloader import preload_all_nltk_resources
|
||||
from backend.services.langfuse_preloader import preload_langfuse_handler
|
||||
from backend.middleware.audit_logging import AuditLoggingMiddleware
|
||||
from backend.middleware.tenant import TenantMiddleware
|
||||
from backend.middleware.edge_auth import EdgeAuthMiddleware
|
||||
from backend.workers.registry import worker_registry
|
||||
|
||||
|
||||
@@ -170,6 +171,12 @@ app.add_middleware(AuditLoggingMiddleware)
|
||||
# Add tenant detection middleware (extracts tenant from subdomain/headers)
|
||||
app.add_middleware(TenantMiddleware)
|
||||
|
||||
# Edge origin lock (added last = outermost, runs first). Rejects direct-to-origin
|
||||
# requests that bypassed the Cloudflare edge, before tenant/audit middleware do
|
||||
# any work. No-op unless EDGE_AUTH_MODE is warn/enforce. See
|
||||
# backend/middleware/edge_auth.py.
|
||||
app.add_middleware(EdgeAuthMiddleware)
|
||||
|
||||
# Include routers
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(jobs.router, prefix="/api")
|
||||
@@ -187,6 +194,7 @@ 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,115 @@
|
||||
"""
|
||||
Edge origin-lock middleware.
|
||||
|
||||
Cloudflare fronts ``api.nomadkaraoke.com`` (WAF + rate limiting). To stop
|
||||
attackers from bypassing the edge by hitting the Cloud Run origin directly
|
||||
(``*.run.app`` / ``ghs.googlehosted.com``), Cloudflare injects a shared-secret
|
||||
header (``X-Edge-Auth``) on every proxied request via a Transform Rule. This
|
||||
middleware rejects public requests that lack the correct header.
|
||||
|
||||
A Cloud Run *domain mapping* can't use ``ingress=internal-and-cloud-load-balancing``
|
||||
(that needs a load balancer), so this app-layer check is how we lock the origin.
|
||||
|
||||
Modes (env ``EDGE_AUTH_MODE``, default ``off``):
|
||||
off - passthrough, no checks (deploy-dormant; behaviour unchanged).
|
||||
warn - log requests missing/failing the header, but ALLOW them. Use to
|
||||
confirm nothing legit is missing the header before enforcing.
|
||||
enforce - reject requests missing/failing the header with 403.
|
||||
|
||||
Secret: env ``EDGE_ORIGIN_SECRET`` (same value Cloudflare injects). If enforce
|
||||
mode is set but the secret is unconfigured, the middleware FAILS CLOSED (503) —
|
||||
a security control must not silently allow direct-origin traffic. (Low risk:
|
||||
Cloud Run won't start a revision whose secret ref is missing, and enforce is
|
||||
only enabled after staging confirms the secret.) In warn mode it still allows.
|
||||
|
||||
Exemptions (always allowed, even in enforce mode):
|
||||
* Health / root endpoints and Cloud Run probes, which hit the origin
|
||||
directly (not via Cloudflare) and legitimately lack the header.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Header Cloudflare injects (must match CloudflareConfig.ORIGIN_AUTH_HEADER in
|
||||
# infrastructure/modules/edge_security.py).
|
||||
EDGE_AUTH_HEADER = "X-Edge-Auth"
|
||||
|
||||
# Paths always allowed without the edge header. These are non-sensitive and are
|
||||
# probed directly on the origin by Cloud Run startup/liveness checks and GCP
|
||||
# uptime monitoring, which don't traverse Cloudflare.
|
||||
_EXEMPT_EXACT = {"/", "/api/health", "/api/health/"}
|
||||
_EXEMPT_PREFIXES = ("/api/health/",)
|
||||
|
||||
_VALID_MODES = {"off", "warn", "enforce"}
|
||||
|
||||
|
||||
def _mode() -> str:
|
||||
mode = os.environ.get("EDGE_AUTH_MODE", "off").lower().strip()
|
||||
return mode if mode in _VALID_MODES else "off"
|
||||
|
||||
|
||||
def _is_exempt(path: str) -> bool:
|
||||
if path in _EXEMPT_EXACT:
|
||||
return True
|
||||
return any(path.startswith(p) for p in _EXEMPT_PREFIXES)
|
||||
|
||||
|
||||
class EdgeAuthMiddleware(BaseHTTPMiddleware):
|
||||
"""Reject origin requests that didn't come through the Cloudflare edge."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
mode = _mode()
|
||||
if mode == "off":
|
||||
return await call_next(request)
|
||||
|
||||
if _is_exempt(request.url.path):
|
||||
return await call_next(request)
|
||||
|
||||
secret = os.environ.get("EDGE_ORIGIN_SECRET", "")
|
||||
if not secret:
|
||||
# Misconfiguration: enforce is requested but no secret is wired up.
|
||||
# In enforce mode, fail CLOSED (503) — a security control must not
|
||||
# silently allow direct-origin traffic when it can't do its job.
|
||||
# This is low-risk operationally: Cloud Run won't even start a
|
||||
# revision whose --set-secrets ref is missing, and enforce is only
|
||||
# turned on after staging confirms the secret. In warn mode we still
|
||||
# allow (observational only).
|
||||
logger.error(
|
||||
"EDGE_AUTH_MODE=%s but EDGE_ORIGIN_SECRET is unset.", mode,
|
||||
)
|
||||
if mode == "enforce":
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"detail": "Origin authentication unavailable"},
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
provided = request.headers.get(EDGE_AUTH_HEADER, "")
|
||||
# Constant-time comparison to avoid leaking the secret via timing.
|
||||
ok = bool(provided) and hmac.compare_digest(provided, secret)
|
||||
|
||||
if ok:
|
||||
return await call_next(request)
|
||||
|
||||
client = request.client.host if request.client else "?"
|
||||
if mode == "warn":
|
||||
logger.warning(
|
||||
"edge-auth: request missing/invalid %s header (warn mode, "
|
||||
"allowing). path=%s ip=%s",
|
||||
EDGE_AUTH_HEADER, request.url.path, client,
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
# enforce
|
||||
logger.warning(
|
||||
"edge-auth: blocked direct-to-origin request. path=%s ip=%s",
|
||||
request.url.path, client,
|
||||
)
|
||||
return JSONResponse(status_code=403, content={"detail": "Forbidden"})
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
@@ -35,9 +36,63 @@ VALID_CATEGORIES = {
|
||||
|
||||
|
||||
class AutoCorrectServiceError(Exception):
|
||||
def __init__(self, message: str, *, status_code: int = 400) -> None:
|
||||
def __init__(
|
||||
self, message: str, *, status_code: int = 400, retryable: bool = False
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
# True for transient provider conditions (rate limits, overload) the
|
||||
# caller may safely retry; drives backoff in _call_model.
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
# Retry knobs for a single model call. Vertex 429 RESOURCE_EXHAUSTED is a
|
||||
# recurring, transient condition; a short app-level backoff lets quota recover
|
||||
# where the SDK's fast internal retry cannot. Kept small so a request never
|
||||
# stalls the review UI for long. Parsed defensively: a malformed env override
|
||||
# clamps to a safe value with a warning rather than crashing the backend at
|
||||
# import or breaking the retry loop.
|
||||
def _env_number(name: str, default: float, *, minimum: float, is_int: bool) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
val: float = int(raw) if is_int else float(raw)
|
||||
except ValueError:
|
||||
logger.warning("invalid %s=%r; using default %s", name, raw, default)
|
||||
return default
|
||||
import math as _math
|
||||
|
||||
if not _math.isfinite(val) or val < minimum:
|
||||
logger.warning(
|
||||
"%s=%s out of range (min %s); clamping to %s", name, val, minimum, minimum
|
||||
)
|
||||
return minimum
|
||||
return val
|
||||
|
||||
|
||||
_MODEL_CALL_MAX_ATTEMPTS = int(
|
||||
_env_number("AUTO_CORRECT_MODEL_MAX_ATTEMPTS", 3, minimum=1, is_int=True)
|
||||
)
|
||||
_MODEL_CALL_BACKOFF_SECONDS = float(
|
||||
_env_number("AUTO_CORRECT_MODEL_BACKOFF_SECONDS", 2.0, minimum=0.0, is_int=False)
|
||||
)
|
||||
|
||||
|
||||
def _is_transient_model_error(exc: BaseException) -> bool:
|
||||
"""True when a provider exception is a retryable rate-limit/overload.
|
||||
|
||||
Matches both structured status codes (google-genai ClientError/ServerError
|
||||
expose ``code``; Anthropic errors expose ``status_code``) and, as a
|
||||
fallback, the textual markers Vertex/Anthropic use — so detection survives
|
||||
SDK exception-class churn.
|
||||
"""
|
||||
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
|
||||
if isinstance(code, int) and code in {429, 500, 502, 503, 529}:
|
||||
return True
|
||||
text = str(exc).upper()
|
||||
markers = ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "OVERLOADED", "429", "503", "529")
|
||||
return any(m in text for m in markers)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -388,10 +443,33 @@ class AutoCorrectService:
|
||||
def _call_model(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
|
||||
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)
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable.
|
||||
|
||||
Transient provider errors (rate limits / overload, flagged
|
||||
``retryable``) are retried with exponential backoff. Permanent errors
|
||||
(misconfig, malformed output) fail fast.
|
||||
"""
|
||||
for attempt in range(1, _MODEL_CALL_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
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
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
if not exc.retryable or attempt == _MODEL_CALL_MAX_ATTEMPTS:
|
||||
raise
|
||||
backoff = _MODEL_CALL_BACKOFF_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
"auto-correct model call transient failure job=%s model=%s "
|
||||
"attempt=%d/%d; retrying in %.1fs (%s)",
|
||||
job_id, model, attempt, _MODEL_CALL_MAX_ATTEMPTS, backoff, exc,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
# Unreachable: the loop either returns or raises on the final attempt.
|
||||
raise AssertionError("retry loop exited without returning or raising")
|
||||
|
||||
@staticmethod
|
||||
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
|
||||
@@ -440,8 +518,6 @@ class AutoCorrectService:
|
||||
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"):
|
||||
@@ -478,6 +554,16 @@ class AutoCorrectService:
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
)
|
||||
except Exception as exc:
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
@@ -520,6 +606,16 @@ class AutoCorrectService:
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -6,6 +6,7 @@ Cloud Run Job handle all alerting / Discord plumbing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
@@ -19,6 +20,35 @@ from backend.services.error_monitor.normalizer import (
|
||||
MAX_SAMPLE_MESSAGE_CHARS = 4000
|
||||
MAX_URL_CHARS = 512
|
||||
|
||||
# Crawlers/bots execute our JS (e.g. bingbot/Googlebot run headless Chrome) and
|
||||
# trip React DOM-reconciliation errors that no real user ever sees. Their reports
|
||||
# are pure alert-channel noise, so we drop them at ingestion. Matches the common
|
||||
# crawler tokens plus the generic bot/crawler/spider/headless markers that
|
||||
# well-behaved automated agents put in their UA string.
|
||||
_BOT_UA_RE = re.compile(
|
||||
# Generic markers. The bot forms are anchored so we never match the "bot"
|
||||
# inside ordinary words like "robot": a standalone "bot" token (\bbot\b does
|
||||
# not match inside "robot" — no word boundary there) or the crawler
|
||||
# "<name>bot/<version>" convention, with "robot/" explicitly excluded.
|
||||
r"\bbot\b|(?<!ro)bot/|spider|crawler|crawl\b|slurp|bingpreview|headless|"
|
||||
# Explicit crawler names (some don't use the "/version" convention).
|
||||
r"googlebot|bingbot|applebot|yandex|baiduspider|duckduckbot|"
|
||||
r"ahrefs|semrush|petalbot|facebookexternalhit|"
|
||||
r"chrome-lighthouse|google page speed|python-requests|curl/|wget/",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def is_bot_user_agent(user_agent: str | None) -> bool:
|
||||
"""Return True if the UA looks like a crawler/bot/automated agent.
|
||||
|
||||
Conservative: only matches explicit bot markers, so a real browser UA (which
|
||||
never contains these tokens) is never misclassified.
|
||||
"""
|
||||
if not user_agent:
|
||||
return False
|
||||
return bool(_BOT_UA_RE.search(user_agent))
|
||||
|
||||
|
||||
@dataclass
|
||||
class FrontendErrorReport:
|
||||
|
||||
@@ -56,6 +56,33 @@ _IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
|
||||
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
|
||||
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
|
||||
),
|
||||
(
|
||||
"encoding_worker_capacity_retry",
|
||||
# Only the TRANSIENT start failures: GCE 503/SERVICE UNAVAILABLE or a
|
||||
# capacity code (ZONE_RESOURCE_POOL_EXHAUSTED / STOCKOUT / QUOTA_EXCEEDED
|
||||
# — see encoding_errors.CAPACITY_ERROR_CODES). The render worker parks
|
||||
# these for auto-retry. A non-transient EncodingWorkerStartError (other /
|
||||
# unknown code) shares the "aborting retries" prefix but must still page,
|
||||
# so we require the transient signal, not just the prefix.
|
||||
# Bind the transient signal to the GCE error CODE field — which appears
|
||||
# immediately after "start failed in <zone>: " / "could not be started in
|
||||
# <zone>: " (see encoding_errors.classify_gce_error). Matching the code in
|
||||
# position (not anywhere in the line) prevents a non-transient failure
|
||||
# whose message text merely contains "503" from being suppressed.
|
||||
re.compile(
|
||||
r"encoding worker start failed, aborting retries:.*?"
|
||||
r"(?:start failed|could not be started) in [\w.-]+:\s*"
|
||||
r"(?:503\b|service unavailable|zone_resource_pool_exhausted"
|
||||
r"|stockout|quota_exceeded)",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
(
|
||||
"GCE encoding worker VM start hit a transient GCP condition (zone "
|
||||
"capacity exhaustion or 503 SERVICE UNAVAILABLE) — the render worker "
|
||||
"parks the job for auto-retry rather than failing it. Non-transient "
|
||||
"start failures still alert."
|
||||
),
|
||||
),
|
||||
(
|
||||
"health_check_404",
|
||||
re.compile(
|
||||
|
||||
@@ -79,6 +79,15 @@ _NORMALIZERS: list[tuple[re.Pattern, str]] = [
|
||||
re.compile(r"/jobs/[A-Za-z0-9]+"),
|
||||
"/jobs/<ID>",
|
||||
),
|
||||
# 9b. Preview render job IDs: preview_<jobid>_<renderid> (underscore-joined
|
||||
# hex runs). The generic hex rule (11) is \b-anchored and '_' is a word
|
||||
# char, so it can't reach these — leaving every preview render of the
|
||||
# same job as a distinct pattern (N alerts for one incident). Collapse
|
||||
# the whole token so they map to a single pattern.
|
||||
(
|
||||
re.compile(r"\bpreview_[0-9a-fA-F]{6,}(?:_[0-9a-fA-F]{6,})+\b"),
|
||||
"preview_<ID>",
|
||||
),
|
||||
# 10. Firebase UIDs (20–28 mixed-case alphanumeric characters)
|
||||
# Firebase Auth UIDs are typically 28 chars; allow 20-28 for flexibility.
|
||||
# Must contain both letters and digits (to avoid replacing plain words).
|
||||
|
||||
@@ -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,30 @@ 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)
|
||||
|
||||
# Push the padded original-vocals guide (silence[intro] + mixed_vocals) to the
|
||||
# vocals prefix in the same Divebar mirror, so kjbox can layer it under the master
|
||||
# at the "Original Vocals" slider. Same Nomad-brand gating + best-effort contract
|
||||
# as the 720p push; the guide was pre-built by the orchestrator when available.
|
||||
guide_path = output_files.get("original_vocals_guide")
|
||||
if guide_path and os.path.exists(guide_path):
|
||||
guide_warning = self._fast_sync_vocals_guide(
|
||||
brand_code, guide_path, f"{filename_base}.flac"
|
||||
)
|
||||
if guide_warning and warnings is not None:
|
||||
warnings.append(guide_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 +362,74 @@ 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 _fast_sync_vocals_guide(
|
||||
self, brand_code: str, local_path: str, filename: str
|
||||
) -> Optional[str]:
|
||||
"""Best-effort push of a freshly-built original-vocals guide to the Divebar GCS
|
||||
mirror's vocals prefix so kjbox can pull it into ``NOMAD-vocals-padded/``.
|
||||
|
||||
No-op unless the fast-sync is enabled and this is a public Nomad release
|
||||
(``NOMAD-####``, excluding ``NOMADNP``). Never raises — nothing downstream
|
||||
depends on the guide. Returns a human-readable warning on failure (surfaced via
|
||||
``distribution_warnings`` / the admin alert), or ``None`` on success or skip.
|
||||
"""
|
||||
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_vocals_guide(local_path, filename):
|
||||
return None
|
||||
return (
|
||||
f"Original-vocals guide sync to the GCS mirror failed for {filename}"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning(f"Original-vocals guide sync skipped (unexpected error): {e}")
|
||||
return f"Original-vocals guide sync errored for {filename}: {e}"
|
||||
|
||||
def delete_file(self, file_id: str) -> bool:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
@@ -387,6 +480,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 +567,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}",
|
||||
|
||||
@@ -15,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
|
||||
@@ -146,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.
|
||||
@@ -161,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,
|
||||
@@ -211,8 +253,11 @@ async def check_community_versions_batch(
|
||||
|
||||
``songs`` is a list of ``{"artist": str, "title": str}``. Returns a list in the
|
||||
same order, each ``{"artist", "title", "available": bool, "brands": [str],
|
||||
"brand_count": int}``. Bounded concurrency keeps us polite to karaokenerds.com;
|
||||
per-song results reuse the existing 1h cache. A failed lookup degrades to
|
||||
"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))
|
||||
@@ -221,21 +266,32 @@ async def check_community_versions_batch(
|
||||
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}
|
||||
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 name and name not in brands:
|
||||
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])
|
||||
@@ -38,10 +38,42 @@ 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 = [
|
||||
@@ -109,16 +141,34 @@ class MusicBrainzService:
|
||||
cached = self._cache.get(cache_key)
|
||||
if cached and (time.monotonic() - cached[0]) < _CACHE_TTL_S:
|
||||
return cached[1]
|
||||
await self._throttle()
|
||||
params = {**params, "fmt": "json"}
|
||||
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}
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
self._cache[cache_key] = (time.monotonic(), data)
|
||||
return data
|
||||
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 --------------------------------------------------------
|
||||
|
||||
@@ -190,14 +240,19 @@ class MusicBrainzService:
|
||||
return editions
|
||||
|
||||
@staticmethod
|
||||
def pick_canonical_edition(editions: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
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.
|
||||
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)
|
||||
@@ -209,11 +264,65 @@ class MusicBrainzService:
|
||||
|
||||
def country_rank(e: Dict[str, Any]) -> int:
|
||||
c = e.get("country")
|
||||
return _PREFERRED_COUNTRIES.index(c) if c in _PREFERRED_COUNTRIES else len(_PREFERRED_COUNTRIES)
|
||||
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"})
|
||||
@@ -244,15 +353,31 @@ class MusicBrainzService:
|
||||
"tracks": tracks,
|
||||
}
|
||||
|
||||
async def get_album_tracklist(self, release_group_mbid: str) -> Dict[str, Any]:
|
||||
"""Resolve the canonical edition of an album and return its tracklist + editions."""
|
||||
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)
|
||||
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}
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
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 _vocals_blob_name(self, filename: str) -> str:
|
||||
prefix = settings.nomad_vocals_guide_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 push_vocals_guide(self, local_path: str, filename: str) -> bool:
|
||||
"""Upload a padded original-vocals guide to the divebar GCS mirror's vocals
|
||||
prefix (which kjbox pulls into ``NOMAD-vocals-padded/``). Best-effort."""
|
||||
blob_name = self._vocals_blob_name(filename)
|
||||
try:
|
||||
blob = self._bucket.blob(blob_name)
|
||||
blob.upload_from_filename(local_path)
|
||||
logger.info(
|
||||
"Pushed original-vocals guide 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("Vocals-guide push failed for %s: %s", blob_name, e)
|
||||
return False
|
||||
|
||||
def delete_vocals_guides_by_brand(self, brand_code: str) -> int:
|
||||
"""Delete ALL original-vocals guide objects for a Nomad release, matched by the
|
||||
unique ``{brand_code} - `` filename prefix (covers renames). Best-effort; returns
|
||||
the count deleted. Refuses a non-Nomad / bare brand code (same guardrail as the
|
||||
master prefix-delete) so a broad prefix can never wipe unrelated objects."""
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return 0
|
||||
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
|
||||
if not suffix.strip():
|
||||
return 0
|
||||
prefix = f"{settings.nomad_vocals_guide_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 vocals-guide object %s: %s", blob.name, e)
|
||||
if deleted:
|
||||
logger.info(
|
||||
"Removed %d original-vocals guide 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("Vocals-guide mirror prefix-delete failed for %s: %s", prefix, e)
|
||||
return deleted
|
||||
|
||||
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
|
||||
mirror = NomadMasterMirror()
|
||||
deleted = mirror.delete_masters_by_brand(brand_code)
|
||||
# A recycled brand must not keep serving its old original-vocals guide, so remove
|
||||
# the GCS guide(s) too. (Note: with the device's additive-only vocals sync this
|
||||
# won't auto-remove an already-downloaded device copy — a documented limitation.)
|
||||
mirror.delete_vocals_guides_by_brand(brand_code)
|
||||
return deleted
|
||||
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,106 @@
|
||||
"""Build the padded original-vocals guide that feeds kjbox's "Original Vocals" slider.
|
||||
|
||||
At render time karaoke-gen already has the isolated ``mixed_vocals`` stem (a byproduct
|
||||
of making the karaoke instrumental) and knows the exact intro offset (the master is
|
||||
``[silent title-card intro] + song + [tail]`` and the intro length is the job's style
|
||||
``intro_video_duration``). So the guide is simply ``silence[intro] + vocals``, capped to
|
||||
the master's duration — no cross-correlation, no human review, no alignment measurement.
|
||||
This is byte-compatible with what the kjbox retro-fit ``pad_vocals.sh`` produced.
|
||||
|
||||
Every function here is best-effort: it returns ``None`` / ``0`` on any failure and never
|
||||
raises, so a guide problem can never break the distribution pipeline.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def probe_duration(path: str, ffprobe_path: str = "ffprobe") -> Optional[float]:
|
||||
"""Return a media file's duration in seconds, or ``None`` if it can't be measured."""
|
||||
try:
|
||||
if not path or not os.path.isfile(path):
|
||||
return None
|
||||
result = subprocess.run(
|
||||
[
|
||||
ffprobe_path, "-v", "error", "-show_entries", "format=duration",
|
||||
"-of", "default=noprint_wrappers=1:nokey=1", path,
|
||||
],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return float(result.stdout.strip())
|
||||
except Exception as e: # noqa: BLE001 - never fatal
|
||||
logger.warning("Could not probe duration for %s: %s", path, e)
|
||||
return None
|
||||
|
||||
|
||||
def build_original_vocals_guide(
|
||||
mixed_vocals_path: str,
|
||||
intro_seconds: float,
|
||||
dest_path: str,
|
||||
master_duration: Optional[float] = None,
|
||||
ffmpeg_path: str = "ffmpeg",
|
||||
) -> Optional[str]:
|
||||
"""Emit ``silence[intro] + mixed_vocals`` as a FLAC guide aligned to the master.
|
||||
|
||||
Args:
|
||||
mixed_vocals_path: The isolated vocals stem (all vocals: lead + backing).
|
||||
intro_seconds: The master's silent title-card length (job's ``intro_video_duration``).
|
||||
dest_path: Where to write the guide (``.flac``).
|
||||
master_duration: If given, the output is capped to this length (``-t``) so the
|
||||
guide can never bleed past the master. Omit to leave the vocals' own length.
|
||||
ffmpeg_path: ffmpeg binary.
|
||||
|
||||
Returns:
|
||||
``dest_path`` on success, else ``None`` (missing input / ffmpeg failure). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not mixed_vocals_path or not os.path.isfile(mixed_vocals_path):
|
||||
logger.warning("Vocals guide: missing mixed-vocals stem %s", mixed_vocals_path)
|
||||
return None
|
||||
if intro_seconds is None or intro_seconds < 0:
|
||||
logger.warning("Vocals guide: invalid intro_seconds %r", intro_seconds)
|
||||
return None
|
||||
|
||||
delay_ms = int(round(float(intro_seconds) * 1000))
|
||||
os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True)
|
||||
tmp_path = dest_path + ".part"
|
||||
|
||||
cmd = [
|
||||
ffmpeg_path, "-y", "-hide_banner", "-nostats", "-loglevel", "error",
|
||||
"-i", mixed_vocals_path,
|
||||
"-af", f"adelay={delay_ms}:all=1",
|
||||
]
|
||||
if master_duration and master_duration > 0:
|
||||
cmd += ["-t", f"{float(master_duration):.3f}"]
|
||||
# ``-f flac`` is mandatory: the ``.part`` extension would otherwise make the
|
||||
# muxer guess the container from the extension and fail.
|
||||
cmd += ["-c:a", "flac", "-f", "flac", tmp_path]
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
|
||||
if result.returncode != 0 or not os.path.isfile(tmp_path):
|
||||
logger.warning(
|
||||
"Vocals guide: ffmpeg failed (rc=%s) for %s: %s",
|
||||
result.returncode, mixed_vocals_path, (result.stderr or "")[-200:].strip(),
|
||||
)
|
||||
_quiet_remove(tmp_path)
|
||||
return None
|
||||
|
||||
os.replace(tmp_path, dest_path)
|
||||
logger.info("Built original-vocals guide: %s", dest_path)
|
||||
return dest_path
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Vocals guide build failed for %s: %s", mixed_vocals_path, e)
|
||||
_quiet_remove(dest_path + ".part")
|
||||
return None
|
||||
|
||||
|
||||
def _quiet_remove(path: str) -> None:
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -55,6 +55,18 @@ def test_accepts_valid_report_and_upserts(client):
|
||||
assert pd.resource_type == "browser"
|
||||
|
||||
|
||||
def test_bot_report_is_accepted_but_not_persisted(client):
|
||||
bot_ua = (
|
||||
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; "
|
||||
"bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/136.0.0.0 Safari/537.36"
|
||||
)
|
||||
resp = client.post("/api/client-errors", json=_payload(user_agent=bot_ua))
|
||||
# Accepted (so the bot won't retry) but never upserted / alerted.
|
||||
assert resp.status_code == 202
|
||||
assert resp.json()["is_new"] is False
|
||||
client.fake_adapter.upsert_pattern.assert_not_called()
|
||||
|
||||
|
||||
def test_rejects_missing_message(client):
|
||||
resp = client.post("/api/client-errors", json=_payload(message=""))
|
||||
assert resp.status_code == 422
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Tests for model-call retry/backoff on transient Vertex/Anthropic errors.
|
||||
|
||||
A Vertex 429 RESOURCE_EXHAUSTED is a recurring, transient condition (other
|
||||
call sites like parse_titles degrade gracefully). Auto-correct should retry
|
||||
with backoff and only surface a distinct, retryable 429 to the caller when
|
||||
the rate limit persists — never a generic 502 that reads as a hard failure.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
_env_number,
|
||||
_is_transient_model_error,
|
||||
)
|
||||
|
||||
|
||||
class _FakeClientError(Exception):
|
||||
"""Mimics google.genai.errors.ClientError (has a numeric ``code``)."""
|
||||
|
||||
def __init__(self, code: int, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _service() -> AutoCorrectService:
|
||||
return AutoCorrectService()
|
||||
|
||||
|
||||
def test_is_transient_detects_429_resource_exhausted() -> None:
|
||||
exc = _FakeClientError(429, "429 RESOURCE_EXHAUSTED. Resource exhausted.")
|
||||
assert _is_transient_model_error(exc) is True
|
||||
|
||||
|
||||
def test_is_transient_detects_503_and_overloaded() -> None:
|
||||
assert _is_transient_model_error(_FakeClientError(503, "UNAVAILABLE")) is True
|
||||
assert _is_transient_model_error(Exception("529 overloaded_error")) is True
|
||||
|
||||
|
||||
def test_is_transient_ignores_permanent_client_errors() -> None:
|
||||
assert _is_transient_model_error(_FakeClientError(400, "INVALID_ARGUMENT")) is False
|
||||
assert _is_transient_model_error(ValueError("bad schema")) is False
|
||||
|
||||
|
||||
def test_env_number_uses_default_when_unset(monkeypatch) -> None:
|
||||
monkeypatch.delenv("AC_TEST_KNOB", raising=False)
|
||||
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 3
|
||||
|
||||
|
||||
def test_env_number_clamps_below_minimum(monkeypatch) -> None:
|
||||
monkeypatch.setenv("AC_TEST_KNOB", "0")
|
||||
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 1
|
||||
|
||||
|
||||
def test_env_number_falls_back_on_garbage(monkeypatch) -> None:
|
||||
monkeypatch.setenv("AC_TEST_KNOB", "not-a-number")
|
||||
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 2.0
|
||||
|
||||
|
||||
def test_env_number_rejects_non_finite(monkeypatch) -> None:
|
||||
monkeypatch.setenv("AC_TEST_KNOB", "inf")
|
||||
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 0.0
|
||||
|
||||
|
||||
def test_retryable_call_retries_then_succeeds() -> None:
|
||||
"""A transient failure is retried; a later success is returned."""
|
||||
service = _service()
|
||||
attempts = {"n": 0}
|
||||
|
||||
def flaky(model, system_prompt, user_prompt, *, job_id):
|
||||
attempts["n"] += 1
|
||||
if attempts["n"] < 3:
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is rate-limited", status_code=429, retryable=True
|
||||
)
|
||||
return {"suggestions": []}, None
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=flaky), \
|
||||
patch.object(service, "_call_anthropic", side_effect=flaky), \
|
||||
patch("backend.services.auto_correct.service.time.sleep") as sleep:
|
||||
raw, usage = service._call_model(
|
||||
"gemini-3.1-pro-preview", "sys", "user", job_id="job-1"
|
||||
)
|
||||
|
||||
assert raw == {"suggestions": []}
|
||||
assert attempts["n"] == 3
|
||||
assert sleep.call_count == 2 # slept before each retry
|
||||
|
||||
|
||||
def test_retryable_call_exhausts_and_raises_429() -> None:
|
||||
"""Persistent rate-limit surfaces a retryable 429, not a generic 502."""
|
||||
service = _service()
|
||||
|
||||
def always_rate_limited(model, system_prompt, user_prompt, *, job_id):
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is rate-limited", status_code=429, retryable=True
|
||||
)
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=always_rate_limited), \
|
||||
patch("backend.services.auto_correct.service.time.sleep"), \
|
||||
patch("backend.services.auto_correct.service._MODEL_CALL_MAX_ATTEMPTS", 3):
|
||||
with pytest.raises(AutoCorrectServiceError) as ei:
|
||||
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
|
||||
|
||||
assert ei.value.status_code == 429
|
||||
assert ei.value.retryable is True
|
||||
|
||||
|
||||
def test_non_retryable_error_fails_fast_without_sleeping() -> None:
|
||||
"""A permanent error (e.g. bad output) is not retried."""
|
||||
service = _service()
|
||||
calls = {"n": 0}
|
||||
|
||||
def bad_output(model, system_prompt, user_prompt, *, job_id):
|
||||
calls["n"] += 1
|
||||
raise AutoCorrectServiceError("AI returned non-JSON output", status_code=502)
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=bad_output), \
|
||||
patch("backend.services.auto_correct.service.time.sleep") as sleep:
|
||||
with pytest.raises(AutoCorrectServiceError) as ei:
|
||||
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
|
||||
|
||||
assert calls["n"] == 1
|
||||
assert ei.value.status_code == 502
|
||||
sleep.assert_not_called()
|
||||
@@ -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"]
|
||||
|
||||
@@ -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, \
|
||||
|
||||
@@ -14,10 +14,41 @@ from backend.workers.audio_download_worker import (
|
||||
process_audio_download,
|
||||
_extract_gcs_path,
|
||||
_download_audio,
|
||||
DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
)
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
|
||||
|
||||
def _cloud_run_task_timeout_seconds() -> int:
|
||||
"""Parse the audio-download-job task timeout from the Pulumi module."""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
src = (
|
||||
pathlib.Path(__file__).resolve().parents[2]
|
||||
/ "infrastructure" / "modules" / "cloud_run.py"
|
||||
).read_text()
|
||||
# The audio-download job block sets timeout="NNNNs" right before max_retries.
|
||||
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,\s*\n\s*vpc_access=', src)
|
||||
assert m, "could not locate audio-download-job timeout in cloud_run.py"
|
||||
return int(m.group(1))
|
||||
|
||||
|
||||
def test_download_wait_timeout_below_cloud_run_task_timeout():
|
||||
"""The in-worker download wait MUST expire before Cloud Run SIGKILLs the task.
|
||||
|
||||
If they are equal (the old 600s/600s), the SIGKILL bypasses graceful
|
||||
failure handling and leaves an in-flight auto-retry racing manual retries
|
||||
(job 1cd29294). Keep meaningful headroom for the final upload + transition.
|
||||
"""
|
||||
task_timeout = _cloud_run_task_timeout_seconds()
|
||||
assert DOWNLOAD_WAIT_TIMEOUT_SECONDS < task_timeout, (
|
||||
f"download wait {DOWNLOAD_WAIT_TIMEOUT_SECONDS}s must be < Cloud Run "
|
||||
f"task timeout {task_timeout}s"
|
||||
)
|
||||
assert task_timeout - DOWNLOAD_WAIT_TIMEOUT_SECONDS >= 60
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id: str = "test-job-123",
|
||||
status=JobStatus.DOWNLOADING_AUDIO,
|
||||
@@ -195,6 +226,83 @@ class TestProcessAudioDownload:
|
||||
mock_ws.trigger_audio_worker.assert_not_awaited()
|
||||
mock_ws.trigger_lyrics_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_run_completing_mid_download_is_idempotent(self):
|
||||
"""A second run finishing while we download must not fail the job.
|
||||
|
||||
Regression for job 1cd29294: a manual /retry raced this task's Cloud
|
||||
Run auto-retry. The loser downloaded, then tried DOWNLOADING ->
|
||||
DOWNLOADING, which raised InvalidStateTransitionError, and the generic
|
||||
except marked a job the winner had already advanced as FAILED. The
|
||||
loser must instead detect the advance and return success without
|
||||
transitioning, failing, or re-triggering downstream workers.
|
||||
"""
|
||||
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
# By the time our download finishes, a concurrent run advanced the job.
|
||||
advanced_job = _make_job(status=JobStatus.DOWNLOADING)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
# Entry sees DOWNLOADING_AUDIO; the pre-transition re-read sees the
|
||||
# concurrent run's advance to DOWNLOADING.
|
||||
mock_jm.get_job.side_effect = [entry_job, advanced_job]
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
|
||||
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
mock_dl.assert_awaited_once() # we did download before detecting the race
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
mock_jm.fail_job.assert_not_called()
|
||||
mock_ws.trigger_audio_worker.assert_not_awaited()
|
||||
mock_ws.trigger_lyrics_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_transition_at_commit_treated_as_success_if_advanced(self):
|
||||
"""A race that slips past the guard still must not fail the job.
|
||||
|
||||
If the job advances between the pre-transition re-read and the
|
||||
transition itself, transition_to_state returns False (raise_on_invalid
|
||||
is off); we re-read, see the advance, and return success.
|
||||
"""
|
||||
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
# Entry + pre-transition guard both see DOWNLOADING_AUDIO (guard
|
||||
# passes); the transition fails; the post-failure re-read sees the
|
||||
# concurrent advance.
|
||||
mock_jm.get_job.side_effect = [
|
||||
entry_job,
|
||||
_make_job(status=JobStatus.DOWNLOADING_AUDIO),
|
||||
_make_job(status=JobStatus.DOWNLOADING),
|
||||
]
|
||||
mock_jm.transition_to_state.return_value = False
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
mock_jm.fail_job.assert_not_called()
|
||||
mock_ws.trigger_audio_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uses_state_data_selection_when_available(self):
|
||||
"""Should prefer state_data search results over job-level params."""
|
||||
|
||||
@@ -75,7 +75,7 @@ class TestAlbumTracklistRoute:
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
class FakeMB:
|
||||
async def get_album_tracklist(self, rg):
|
||||
async def get_album_tracklist(self, rg, preferred_countries=None):
|
||||
return {
|
||||
"release_mbid": "rel1",
|
||||
"canonical_release_mbid": "rel1",
|
||||
@@ -112,3 +112,62 @@ class TestAlbumTracklistRoute:
|
||||
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,139 @@
|
||||
"""
|
||||
Unit tests for EdgeAuthMiddleware (Cloudflare origin lock).
|
||||
|
||||
Exercises the off/warn/enforce modes, header validation, exemptions, and the
|
||||
fail-open-on-misconfiguration behaviour end-to-end via a minimal ASGI app.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from backend.middleware.edge_auth import EdgeAuthMiddleware, EDGE_AUTH_HEADER
|
||||
|
||||
SECRET = "s3cr3t-origin-value"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Minimal app with the middleware installed and a few routes."""
|
||||
app = FastAPI()
|
||||
app.add_middleware(EdgeAuthMiddleware)
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"ok": "root"}
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
return {"ok": "health"}
|
||||
|
||||
@app.get("/api/test")
|
||||
async def protected():
|
||||
return {"ok": "protected"}
|
||||
|
||||
@app.post("/api/internal/recover-stuck-jobs")
|
||||
async def internal():
|
||||
return {"ok": "internal"}
|
||||
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _set(monkeypatch, mode=None, secret=None):
|
||||
for key, val in (("EDGE_AUTH_MODE", mode), ("EDGE_ORIGIN_SECRET", secret)):
|
||||
if val is None:
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
else:
|
||||
monkeypatch.setenv(key, val)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# off mode (default) — pure passthrough
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_off_mode_is_default_passthrough(client, monkeypatch):
|
||||
_set(monkeypatch, mode=None, secret=SECRET) # unset mode -> defaults to off
|
||||
assert client.get("/api/test").status_code == 200
|
||||
|
||||
|
||||
def test_invalid_mode_treated_as_off(client, monkeypatch):
|
||||
_set(monkeypatch, mode="bogus", secret=SECRET)
|
||||
assert client.get("/api/test").status_code == 200
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# enforce mode
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_enforce_blocks_missing_header(client, monkeypatch):
|
||||
_set(monkeypatch, mode="enforce", secret=SECRET)
|
||||
resp = client.get("/api/test")
|
||||
assert resp.status_code == 403
|
||||
assert resp.json()["detail"] == "Forbidden"
|
||||
|
||||
|
||||
def test_enforce_blocks_wrong_header(client, monkeypatch):
|
||||
_set(monkeypatch, mode="enforce", secret=SECRET)
|
||||
resp = client.get("/api/test", headers={EDGE_AUTH_HEADER: "nope"})
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_enforce_allows_valid_header(client, monkeypatch):
|
||||
_set(monkeypatch, mode="enforce", secret=SECRET)
|
||||
resp = client.get("/api/test", headers={EDGE_AUTH_HEADER: SECRET})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["ok"] == "protected"
|
||||
|
||||
|
||||
def test_enforce_internal_path_requires_header(client, monkeypatch):
|
||||
"""Internal endpoints traverse Cloudflare (public host) so they DO get the
|
||||
header — they are not exempt from the origin lock."""
|
||||
_set(monkeypatch, mode="enforce", secret=SECRET)
|
||||
assert client.post("/api/internal/recover-stuck-jobs").status_code == 403
|
||||
ok = client.post(
|
||||
"/api/internal/recover-stuck-jobs", headers={EDGE_AUTH_HEADER: SECRET}
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# exemptions — health/root probes hit the origin directly, no header
|
||||
# --------------------------------------------------------------------------- #
|
||||
@pytest.mark.parametrize("path", ["/", "/api/health"])
|
||||
def test_enforce_exempts_health_and_root(client, monkeypatch, path):
|
||||
_set(monkeypatch, mode="enforce", secret=SECRET)
|
||||
assert client.get(path).status_code == 200
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# warn mode — logs but allows
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_warn_allows_missing_header(client, monkeypatch):
|
||||
_set(monkeypatch, mode="warn", secret=SECRET)
|
||||
assert client.get("/api/test").status_code == 200
|
||||
|
||||
|
||||
def test_warn_allows_valid_header(client, monkeypatch):
|
||||
_set(monkeypatch, mode="warn", secret=SECRET)
|
||||
assert client.get("/api/test", headers={EDGE_AUTH_HEADER: SECRET}).status_code == 200
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# misconfiguration — enforce but no secret set
|
||||
# --------------------------------------------------------------------------- #
|
||||
def test_enforce_without_secret_fails_closed(client, monkeypatch):
|
||||
# A security control must fail closed: enforce with no secret → 503, not open.
|
||||
_set(monkeypatch, mode="enforce", secret=None)
|
||||
resp = client.get("/api/test")
|
||||
assert resp.status_code == 503
|
||||
assert resp.json()["detail"] == "Origin authentication unavailable"
|
||||
|
||||
|
||||
def test_enforce_without_secret_still_exempts_health(client, monkeypatch):
|
||||
# Health/root stay reachable even in the misconfigured state (probes).
|
||||
_set(monkeypatch, mode="enforce", secret=None)
|
||||
assert client.get("/api/health").status_code == 200
|
||||
|
||||
|
||||
def test_warn_without_secret_allows(client, monkeypatch):
|
||||
# warn mode is observational only — never blocks, even with no secret.
|
||||
_set(monkeypatch, mode="warn", secret=None)
|
||||
assert client.get("/api/test").status_code == 200
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -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,31 +434,187 @@ 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_public_share_pushes_vocals_guide_for_nomad(self, mock_get_settings, tmp_path):
|
||||
"""A pre-built original-vocals guide is pushed to the vocals prefix with the exact
|
||||
"{brand_code} - {base_name}.flac" object name (matches the master's naming)."""
|
||||
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")
|
||||
guide_file = tmp_path / "original_vocals_guide.flac"
|
||||
guide_file.write_bytes(b"guide flac")
|
||||
|
||||
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:
|
||||
mock_mirror_cls.return_value.push_vocals_guide.return_value = True
|
||||
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),
|
||||
"original_vocals_guide": str(guide_file),
|
||||
},
|
||||
)
|
||||
mock_mirror_cls.return_value.push_vocals_guide.assert_called_once_with(
|
||||
str(guide_file), "NOMAD-1163 - Artist - Title.flac"
|
||||
)
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_public_share_no_vocals_guide_for_non_nomad(self, mock_get_settings, tmp_path):
|
||||
"""Non-Nomad / NOMADNP brands must never push a guide to the public 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
|
||||
|
||||
guide_file = tmp_path / "original_vocals_guide.flac"
|
||||
guide_file.write_bytes(b"guide flac")
|
||||
|
||||
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:
|
||||
service.upload_to_public_share(
|
||||
root_folder_id="root-123",
|
||||
brand_code="NOMADNP-1163",
|
||||
base_name="Artist - Title",
|
||||
output_files={"original_vocals_guide": str(guide_file)},
|
||||
)
|
||||
mock_mirror_cls.assert_not_called()
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_public_share_vocals_guide_failure_is_non_fatal(self, mock_get_settings, tmp_path):
|
||||
"""A guide push failure surfaces a warning but never breaks the 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
|
||||
|
||||
guide_file = tmp_path / "original_vocals_guide.flac"
|
||||
guide_file.write_bytes(b"guide flac")
|
||||
|
||||
service = GoogleDriveService()
|
||||
warnings: list = []
|
||||
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:
|
||||
mock_mirror_cls.return_value.push_vocals_guide.return_value = False
|
||||
service.upload_to_public_share(
|
||||
root_folder_id="root-123",
|
||||
brand_code="NOMAD-1163",
|
||||
base_name="Artist - Title",
|
||||
output_files={"original_vocals_guide": str(guide_file)},
|
||||
warnings=warnings,
|
||||
)
|
||||
assert any("guide" in w.lower() for w in warnings)
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_upload_to_public_share_skips_missing_files(
|
||||
self, mock_get_settings, tmp_path
|
||||
@@ -928,6 +1085,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()
|
||||
@@ -52,6 +52,88 @@ class TestPickCanonical:
|
||||
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):
|
||||
@@ -129,3 +211,68 @@ class TestServiceCalls:
|
||||
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,208 @@
|
||||
"""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
|
||||
|
||||
|
||||
# --- vocals guide push / delete (parallel to the master methods) ---
|
||||
|
||||
def test_push_vocals_guide_uses_vocals_prefix_and_uploads():
|
||||
mirror, bucket, blob = _mirror_with_mock()
|
||||
|
||||
ok = mirror.push_vocals_guide(
|
||||
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac",
|
||||
"NOMAD-1500 - Rush - The Spirit of Radio.flac",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
bucket.blob.assert_called_once_with(
|
||||
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac"
|
||||
)
|
||||
blob.upload_from_filename.assert_called_once_with(
|
||||
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac"
|
||||
)
|
||||
|
||||
|
||||
def test_push_vocals_guide_is_non_fatal_on_error():
|
||||
mirror, _bucket, blob = _mirror_with_mock()
|
||||
blob.upload_from_filename.side_effect = RuntimeError("boom")
|
||||
assert mirror.push_vocals_guide("/tmp/x.flac", "NOMAD-1 - A - B.flac") is False
|
||||
|
||||
|
||||
def test_delete_vocals_guides_by_brand_deletes_all_matching_by_prefix():
|
||||
mirror, bucket, blobs = _mirror_with_blobs([
|
||||
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - Spirit of Radio.flac",
|
||||
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac",
|
||||
])
|
||||
n = mirror.delete_vocals_guides_by_brand("NOMAD-1500")
|
||||
assert n == 2
|
||||
bucket.list_blobs.assert_called_once_with(
|
||||
prefix="files/Nomad Karaoke/vocals-padded/NOMAD-1500 - "
|
||||
)
|
||||
for b in blobs:
|
||||
b.delete.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
|
||||
def test_delete_vocals_guides_by_brand_refuses_non_nomad_or_bare(brand):
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
assert mirror.delete_vocals_guides_by_brand(brand) == 0
|
||||
bucket.list_blobs.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_vocals_guides_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_vocals_guides_by_brand("NOMAD-1500") == 0
|
||||
|
||||
|
||||
def test_cleanup_nomad_masters_delegates_for_nomad(monkeypatch):
|
||||
from backend.services import nomad_master_mirror as mod
|
||||
|
||||
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")
|
||||
# Brand recycle must also clear the release's original-vocals guide(s).
|
||||
inst.delete_vocals_guides_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,112 @@
|
||||
"""Unit tests for the padded original-vocals guide builder."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.original_vocals_guide import (
|
||||
build_original_vocals_guide,
|
||||
probe_duration,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None,
|
||||
reason="ffmpeg/ffprobe not available",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tone(tmp_path):
|
||||
"""A 4-second 440Hz tone standing in for the mixed-vocals stem."""
|
||||
src = tmp_path / "vocals.flac"
|
||||
subprocess.run(
|
||||
["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
|
||||
"-i", "sine=frequency=440:duration=4", "-c:a", "flac", str(src)],
|
||||
check=True,
|
||||
)
|
||||
return str(src)
|
||||
|
||||
|
||||
def _first_sound_onset(path):
|
||||
"""Seconds until audio first exceeds the silence threshold (leading-silence length)."""
|
||||
out = subprocess.run(
|
||||
["ffmpeg", "-hide_banner", "-i", path, "-af",
|
||||
"silencedetect=noise=-50dB:d=0.1", "-f", "null", "-"],
|
||||
capture_output=True, text=True,
|
||||
).stderr
|
||||
# A guide with N seconds of leading silence reports "silence_end: N".
|
||||
for line in out.splitlines():
|
||||
if "silence_end:" in line:
|
||||
return float(line.split("silence_end:")[1].split("|")[0].strip())
|
||||
return 0.0
|
||||
|
||||
|
||||
def test_prepends_intro_silence_and_reports_expected_duration(tmp_path, tone):
|
||||
dest = str(tmp_path / "NOMAD-1500 - A - B.flac")
|
||||
out = build_original_vocals_guide(tone, intro_seconds=5, dest_path=dest)
|
||||
|
||||
assert out == dest
|
||||
assert os.path.isfile(dest)
|
||||
# silence[5] + 4s tone ≈ 9s total, with the tone starting ~5s in.
|
||||
total = probe_duration(dest)
|
||||
assert total == pytest.approx(9.0, abs=0.3)
|
||||
assert _first_sound_onset(dest) == pytest.approx(5.0, abs=0.3)
|
||||
|
||||
|
||||
def test_respects_non_default_intro(tmp_path, tone):
|
||||
dest = str(tmp_path / "guide.flac")
|
||||
build_original_vocals_guide(tone, intro_seconds=10, dest_path=dest)
|
||||
# Proves we honour the job's actual intro, not a hardcoded 5s.
|
||||
assert _first_sound_onset(dest) == pytest.approx(10.0, abs=0.3)
|
||||
|
||||
|
||||
def test_caps_to_master_duration(tmp_path, tone):
|
||||
dest = str(tmp_path / "guide.flac")
|
||||
# silence[5] + 4s tone would be 9s; cap to 7s.
|
||||
build_original_vocals_guide(tone, intro_seconds=5, dest_path=dest, master_duration=7.0)
|
||||
assert probe_duration(dest) == pytest.approx(7.0, abs=0.3)
|
||||
|
||||
|
||||
def test_output_is_valid_flac(tmp_path, tone):
|
||||
dest = str(tmp_path / "guide.flac")
|
||||
build_original_vocals_guide(tone, intro_seconds=1, dest_path=dest)
|
||||
codec = subprocess.run(
|
||||
["ffprobe", "-v", "error", "-select_streams", "a:0",
|
||||
"-show_entries", "stream=codec_name", "-of",
|
||||
"default=noprint_wrappers=1:nokey=1", dest],
|
||||
capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
assert codec == "flac"
|
||||
|
||||
|
||||
def test_no_part_file_left_behind(tmp_path, tone):
|
||||
dest = str(tmp_path / "guide.flac")
|
||||
build_original_vocals_guide(tone, intro_seconds=1, dest_path=dest)
|
||||
assert not os.path.exists(dest + ".part")
|
||||
|
||||
|
||||
def test_missing_input_returns_none(tmp_path):
|
||||
out = build_original_vocals_guide(
|
||||
str(tmp_path / "nope.flac"), intro_seconds=5, dest_path=str(tmp_path / "g.flac")
|
||||
)
|
||||
assert out is None
|
||||
assert not os.path.exists(tmp_path / "g.flac")
|
||||
|
||||
|
||||
def test_negative_intro_returns_none(tmp_path, tone):
|
||||
assert build_original_vocals_guide(tone, intro_seconds=-1, dest_path=str(tmp_path / "g.flac")) is None
|
||||
|
||||
|
||||
def test_ffmpeg_failure_is_non_fatal(tmp_path, tone):
|
||||
# A bogus ffmpeg binary must not raise; just returns None.
|
||||
out = build_original_vocals_guide(
|
||||
tone, intro_seconds=5, dest_path=str(tmp_path / "g.flac"),
|
||||
ffmpeg_path="/nonexistent/ffmpeg",
|
||||
)
|
||||
assert out is None
|
||||
assert not os.path.exists(str(tmp_path / "g.flac") + ".part")
|
||||
|
||||
|
||||
def test_probe_duration_missing_file_returns_none(tmp_path):
|
||||
assert probe_duration(str(tmp_path / "nope.flac")) 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)
|
||||
@@ -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:
|
||||
|
||||
@@ -2049,3 +2049,86 @@ class TestStageOriginalAudio:
|
||||
# Must not raise
|
||||
orch._stage_original_audio_for_upload()
|
||||
assert any("Original audio" in w for w in orch.result.distribution_warnings)
|
||||
|
||||
|
||||
class TestOriginalVocalsGuideEmit:
|
||||
"""The write-path emit of the padded original-vocals guide at finalize."""
|
||||
|
||||
def _orch(self, brand="NOMAD-1500", video_720p=None, job_manager=None):
|
||||
config = OrchestratorConfig(
|
||||
job_id="job-1", artist="A", title="B",
|
||||
title_video_path="/t.mov", karaoke_video_path="/k.mov",
|
||||
instrumental_audio_path="/a.flac",
|
||||
)
|
||||
orch = VideoWorkerOrchestrator(config, job_manager=job_manager, storage=MagicMock())
|
||||
orch.result.brand_code = brand
|
||||
orch.result.final_video_720p = video_720p
|
||||
return orch
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_skips_non_nomad(self, tmp_path):
|
||||
v = tmp_path / "v.mp4"; v.write_bytes(b"x")
|
||||
orch = self._orch(brand="VOCALSTAR-1", video_720p=str(v))
|
||||
assert await orch._emit_original_vocals_guide("VOCALSTAR-1") is None
|
||||
orch.storage.download_file.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_none_when_no_720p(self):
|
||||
orch = self._orch(brand="NOMAD-1500", video_720p=None)
|
||||
assert await orch._emit_original_vocals_guide("NOMAD-1500") is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_builds_guide_for_nomad(self, tmp_path):
|
||||
v = tmp_path / "v.mp4"; v.write_bytes(b"video")
|
||||
orch = self._orch(brand="NOMAD-1500", video_720p=str(v), job_manager=None)
|
||||
with patch("backend.services.original_vocals_guide.build_original_vocals_guide",
|
||||
return_value="/tmp/guide.flac") as mb, \
|
||||
patch("backend.services.original_vocals_guide.probe_duration", return_value=200.0):
|
||||
out = await orch._emit_original_vocals_guide("NOMAD-1500")
|
||||
assert out == "/tmp/guide.flac"
|
||||
# The mixed-vocals stem is pulled from the job's GCS stems path.
|
||||
assert orch.storage.download_file.call_args[0][0] == "jobs/job-1/stems/vocals_clean.flac"
|
||||
# Built with the resolved intro (5s fallback, no job_manager) capped to master dur.
|
||||
assert mb.call_args[0][1] == 5.0
|
||||
assert mb.call_args.kwargs.get("master_duration") == 200.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_emit_none_when_stem_download_fails(self, tmp_path):
|
||||
v = tmp_path / "v.mp4"; v.write_bytes(b"video")
|
||||
orch = self._orch(brand="NOMAD-1500", video_720p=str(v))
|
||||
orch.storage.download_file.side_effect = RuntimeError("gone")
|
||||
assert await orch._emit_original_vocals_guide("NOMAD-1500") is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_intro_seconds_defaults_to_5_without_job_manager(self):
|
||||
orch = self._orch(job_manager=None)
|
||||
assert await orch._resolve_intro_seconds() == 5.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_intro_seconds_preserves_explicit_zero(self):
|
||||
# A style with no title card (video_duration=0) must NOT collapse to the 5s
|
||||
# default — that would push the guide's vocals 5s late.
|
||||
orch = self._orch(job_manager=MagicMock())
|
||||
orch.job_manager.get_job.return_value = MagicMock()
|
||||
fake_style = MagicMock()
|
||||
fake_style.get_intro_format.return_value = {"video_duration": 0}
|
||||
|
||||
async def fake_load(*a, **k):
|
||||
return fake_style
|
||||
|
||||
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
|
||||
assert await orch._resolve_intro_seconds() == 0.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_intro_seconds_honors_long_intro_style(self):
|
||||
# A long-intro style (e.g. 8s) must be read, not assumed to be 5s.
|
||||
orch = self._orch(job_manager=MagicMock())
|
||||
orch.job_manager.get_job.return_value = MagicMock()
|
||||
fake_style = MagicMock()
|
||||
fake_style.get_intro_format.return_value = {"video_duration": 8}
|
||||
|
||||
async def fake_load(*a, **k):
|
||||
return fake_style
|
||||
|
||||
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
|
||||
assert await orch._resolve_intro_seconds() == 8.0
|
||||
@@ -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",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "خطأ في تحديد الصوت للمهمة {job_id}: {error}",
|
||||
"searchAudioError": "خطأ في البحث عن الصوت: {error}",
|
||||
"searchCreatedSuccessfully": "تم إنشاء المهمة. جاري البحث عن الصوت...",
|
||||
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل..."
|
||||
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل...",
|
||||
"drmUrlUnsupported": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. حاول تنزيل الصوت باستخدام أداة خارجية أولاً، ثم قم برفع ملف الصوت هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية.",
|
||||
"drmUrlUnsupportedWithLink": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. يمكنك تنزيل المقطع الصوتي باستخدام أداة مثل {downloader} ثم رفع الملف الصوتي هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية.",
|
||||
"drmUrlUnsupportedSearch": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. ابحث في الويب عن \"أداة تنزيل {platform}\" للحصول على الصوت — على سبيل المثال {searchUrl} — ثم قم برفع ملف الصوت هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Error en seleccionar l'àudio per a la tasca {job_id}: {error}",
|
||||
"searchAudioError": "Error en cercar l'àudio: {error}",
|
||||
"searchCreatedSuccessfully": "Tasca creada. Cercant àudio...",
|
||||
"autoDownloadStarted": "Millor resultat seleccionat automàticament. Iniciant la descàrrega..."
|
||||
"autoDownloadStarted": "Millor resultat seleccionat automàticament. Iniciant la descàrrega...",
|
||||
"drmUrlUnsupported": "Els enllaços de {platform} estan protegits contra còpia, així que no els podem descarregar directament. Prova de descarregar l'àudio amb una eina de tercers primer i, a continuació, puja el fitxer d'àudio aquí. També pots enganxar un enllaç de YouTube o utilitzar la Cerca d'àudio per trobar aquesta cançó.",
|
||||
"drmUrlUnsupportedWithLink": "Els enllaços de {platform} estan protegits contra còpia, de manera que no els podem descarregar directament. Pots descarregar la pista utilitzant una eina com {downloader} i després pujar el fitxer d'àudio aquí. També pots enganxar un enllaç de YouTube o utilitzar la Cerca d'àudio per trobar aquesta cançó.",
|
||||
"drmUrlUnsupportedSearch": "Els enllaços de {platform} estan protegits contra còpia, així que no els podem descarregar directament. Cerca a la web un \"{platform} downloader\" per obtenir l'àudio — per exemple {searchUrl} — i després puja el fitxer d'àudio aquí. També pots enganxar un enllaç de YouTube, o utilitzar la Cerca d'àudio per trobar aquesta cançó."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Chyba při výběru zvuku pro úlohu {job_id}: {error}",
|
||||
"searchAudioError": "Chyba při vyhledávání zvuku: {error}",
|
||||
"searchCreatedSuccessfully": "Úloha vytvořena. Vyhledávám zvuk...",
|
||||
"autoDownloadStarted": "Nejlepší výsledek byl vybrán automaticky. Začíná stahování..."
|
||||
"autoDownloadStarted": "Nejlepší výsledek byl vybrán automaticky. Začíná stahování...",
|
||||
"drmUrlUnsupported": "Odkazy z {platform} jsou chráněny proti kopírování, takže je nemůžeme stáhnout přímo. Zkus nejprve stáhnout zvuk pomocí nástroje třetí strany a poté sem nahraj zvukový soubor. Můžeš také vložit odkaz na YouTube nebo použít Audio Search k vyhledání této písně.",
|
||||
"drmUrlUnsupportedWithLink": "Odkazy z {platform} jsou chráněny proti kopírování, takže je nemůžeme stáhnout přímo. Skladbu si můžeš stáhnout pomocí nástroje jako {downloader} a poté sem nahrát zvukový soubor. Můžeš také vložit odkaz na YouTube, nebo k nalezení této písně použít Vyhledávání zvuku.",
|
||||
"drmUrlUnsupportedSearch": "Odkazy z {platform} jsou chráněny proti kopírování, takže je nemůžeme stáhnout přímo. Vyhledej na webu „{platform} downloader“ pro získání zvuku — například {searchUrl} — a poté sem nahraj zvukový soubor. Můžeš také vložit odkaz na YouTube nebo použít vyhledávání zvuku k nalezení této písničky."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Fejl ved valg af lyd for job {job_id}: {error}",
|
||||
"searchAudioError": "Fejl ved søgning efter lyd: {error}",
|
||||
"searchCreatedSuccessfully": "Jobbet er oprettet. Søger efter lyd...",
|
||||
"autoDownloadStarted": "Det bedste resultat blev valgt automatisk. Download starter..."
|
||||
"autoDownloadStarted": "Det bedste resultat blev valgt automatisk. Download starter...",
|
||||
"drmUrlUnsupported": "{platform}-links er kopibeskyttede, så vi kan ikke downloade dem direkte. Prøv at downloade lyden med et tredjepartsværktøj først, og upload derefter lydfilen her. Du kan også indsætte et YouTube-link eller bruge Audio Search til at finde denne sang.",
|
||||
"drmUrlUnsupportedWithLink": "{platform}-links er kopibeskyttede, så vi kan ikke downloade dem direkte. Du kan downloade nummeret ved hjælp af et værktøj som {downloader} og derefter uploade lydfilen her. Du kan også indsætte et YouTube-link eller bruge Lydsøgning til at finde denne sang.",
|
||||
"drmUrlUnsupportedSearch": "{platform}-links er kopibeskyttede, så vi kan ikke downloade dem direkte. Søg på nettet efter en \"{platform} downloader\" for at hente lyden — for eksempel {searchUrl} — og upload derefter lydfilen her. Du kan også indsætte et YouTube-link eller bruge Lydsøgning til at finde denne sang."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
|
||||
"searchAudioError": "Fehler bei der Audiosuche: {error}",
|
||||
"searchCreatedSuccessfully": "Auftrag erstellt. Suche nach Audio...",
|
||||
"autoDownloadStarted": "Bestes Ergebnis automatisch ausgewählt. Download startet..."
|
||||
"autoDownloadStarted": "Bestes Ergebnis automatisch ausgewählt. Download startet...",
|
||||
"drmUrlUnsupported": "{platform}-Links sind kopiergeschützt, daher können wir sie nicht direkt herunterladen. Versuche zuerst, das Audio mit einem Drittanbieter-Tool herunterzuladen, und lade die Audiodatei dann hier hoch. Du kannst auch einen YouTube-Link einfügen oder die Audiosuche verwenden, um diesen Song zu finden.",
|
||||
"drmUrlUnsupportedWithLink": "{platform}-Links sind kopiergeschützt, daher können wir sie nicht direkt herunterladen. Du kannst den Titel mit einem Tool wie {downloader} herunterladen und die Audiodatei dann hier hochladen. Du kannst auch einen YouTube-Link einfügen oder die Audiosuche verwenden, um diesen Song zu finden.",
|
||||
"drmUrlUnsupportedSearch": "{platform}-Links sind kopiergeschützt, daher können wir sie nicht direkt herunterladen. Suche im Internet nach einem \"{platform} Downloader\", um das Audio zu erhalten — zum Beispiel {searchUrl} — und lade die Audiodatei dann hier hoch. Du kannst auch einen YouTube-Link einfügen oder die Audio-Suche verwenden, um diesen Song zu finden."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
|
||||
"searchAudioError": "Σφάλμα κατά την αναζήτηση ήχου: {error}",
|
||||
"searchCreatedSuccessfully": "Η εργασία δημιουργήθηκε. Αναζήτηση για ήχο...",
|
||||
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά..."
|
||||
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά...",
|
||||
"drmUrlUnsupported": "Οι σύνδεσμοι του {platform} προστατεύονται από αντιγραφή, οπότε δεν μπορούμε να τους κατεβάσουμε απευθείας. Δοκίμασε να κατεβάσεις τον ήχο με ένα εργαλείο τρίτου πρώτα, και μετά ανέβασε το αρχείο ήχου εδώ. Μπορείς επίσης να επικολλήσεις έναν σύνδεσμο YouTube, ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι.",
|
||||
"drmUrlUnsupportedWithLink": "Οι σύνδεσμοι {platform} προστατεύονται από αντιγραφή, επομένως δεν μπορούμε να τους κατεβάσουμε απευθείας. Μπορείς να κατεβάσεις το κομμάτι χρησιμοποιώντας ένα εργαλείο όπως το {downloader} και μετά να ανεβάσεις το αρχείο ήχου εδώ. Μπορείς επίσης να κάνεις επικόλληση έναν σύνδεσμο YouTube ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι.",
|
||||
"drmUrlUnsupportedSearch": "Οι σύνδεσμοι του {platform} έχουν προστασία αντιγραφής, οπότε δεν μπορούμε να τους κατεβάσουμε απευθείας. Ψάξε στο διαδίκτυο για ένα \"{platform} downloader\" για να κατεβάσεις τον ήχο — για παράδειγμα {searchUrl} — και μετά ανέβασε το αρχείο ήχου εδώ. Μπορείς επίσης να επικολλήσεις έναν σύνδεσμο YouTube ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Error al seleccionar el audio para el trabajo {job_id}: {error}",
|
||||
"searchAudioError": "Error al buscar audio: {error}",
|
||||
"searchCreatedSuccessfully": "Trabajo creado. Buscando audio...",
|
||||
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga..."
|
||||
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga...",
|
||||
"drmUrlUnsupported": "Los enlaces de {platform} están protegidos contra copia, así que no podemos descargarlos directamente. Intenta descargar el audio con una herramienta de terceros primero, y luego sube el archivo de audio aquí. También puedes pegar un enlace de YouTube, o usar la Búsqueda de Audio para encontrar esta canción.",
|
||||
"drmUrlUnsupportedWithLink": "Los enlaces de {platform} están protegidos contra copia, por lo que no podemos descargarlos directamente. Puedes descargar la pista usando una herramienta como {downloader} y luego subir el archivo de audio aquí. También puedes pegar un enlace de YouTube, o usar la Búsqueda de Audio para encontrar esta canción.",
|
||||
"drmUrlUnsupportedSearch": "Los enlaces de {platform} están protegidos por derechos de autor, así que no podemos descargarlos directamente. Busca en la web un \"descargador de {platform}\" para obtener el audio — por ejemplo {searchUrl} — y luego sube el archivo de audio aquí. También puedes pegar un enlace de YouTube, o usar la Búsqueda de Audio para encontrar esta canción."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Virhe valittaessa ääntä työlle {job_id}: {error}",
|
||||
"searchAudioError": "Virhe haettaessa ääntä: {error}",
|
||||
"searchCreatedSuccessfully": "Työ luotu. Etsitään ääntä...",
|
||||
"autoDownloadStarted": "Paras tulos valittu automaattisesti. Lataus alkaa..."
|
||||
"autoDownloadStarted": "Paras tulos valittu automaattisesti. Lataus alkaa...",
|
||||
"drmUrlUnsupported": "{platform}-linkit ovat kopiosuojattuja, joten emme voi ladata niitä suoraan. Kokeile ladata ääni ensin kolmannen osapuolen työkalulla ja lataa äänitiedosto sitten tänne. Voit myös liittää YouTube-linkin tai etsiä tämän kappaleen Äänihaun avulla.",
|
||||
"drmUrlUnsupportedWithLink": "{platform}-linkit ovat kopiosuojattuja, joten emme voi ladata niitä suoraan. Voit ladata kappaleen esimerkiksi {downloader}-työkalulla ja ladata äänitiedoston sitten tänne. Voit myös liittää YouTube-linkin tai etsiä kappaleen Äänihaun avulla.",
|
||||
"drmUrlUnsupportedSearch": "{platform}-linkit ovat kopiosuojattuja, joten emme voi ladata niitä suoraan. Etsi netistä \"{platform} downloader\" saadaksesi äänen — esimerkiksi {searchUrl} — ja lataa äänitiedosto sitten tänne. Voit myös liittää YouTube-linkin tai käyttää äänihakua löytääksesi tämän kappaleen."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Erreur lors de la sélection de l'audio pour la tâche {job_id} : {error}",
|
||||
"searchAudioError": "Erreur lors de la recherche audio : {error}",
|
||||
"searchCreatedSuccessfully": "Tâche créée. Recherche de l'audio en cours...",
|
||||
"autoDownloadStarted": "Meilleur résultat sélectionné automatiquement. Le téléchargement commence..."
|
||||
"autoDownloadStarted": "Meilleur résultat sélectionné automatiquement. Le téléchargement commence...",
|
||||
"drmUrlUnsupported": "Les liens {platform} sont protégés par le droit d'auteur, nous ne pouvons donc pas les télécharger directement. Essaie d'abord de télécharger l'audio avec un outil tiers, puis téléverse le fichier audio ici. Tu peux aussi coller un lien YouTube, ou utiliser la Recherche Audio pour trouver cette chanson.",
|
||||
"drmUrlUnsupportedWithLink": "Les liens {platform} sont protégés contre la copie, nous ne pouvons donc pas les télécharger directement. Tu peux télécharger le morceau en utilisant un outil comme {downloader}, puis importer le fichier audio ici. Tu peux également coller un lien YouTube, ou utiliser la recherche audio pour trouver cette chanson.",
|
||||
"drmUrlUnsupportedSearch": "Les liens {platform} sont protégés contre la copie, nous ne pouvons donc pas les télécharger directement. Cherche sur le web un « {platform} downloader » pour récupérer l'audio — par exemple {searchUrl} — puis importe le fichier audio ici. Tu peux aussi coller un lien YouTube, ou utiliser la Recherche Audio pour trouver cette chanson."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "שגיאה בבחירת אודיו עבור המשימה {job_id}: {error}",
|
||||
"searchAudioError": "שגיאה בחיפוש אודיו: {error}",
|
||||
"searchCreatedSuccessfully": "המשימה נוצרה. מחפש אודיו...",
|
||||
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה..."
|
||||
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה...",
|
||||
"drmUrlUnsupported": "הקישורים של {platform} מוגנים מפני העתקה, ולכן איננו יכולים להוריד אותם ישירות. נסו להוריד את האודיו בעזרת כלי צד שלישי תחילה, ואז העלו את קובץ האודיו לכאן. תוכלו גם להדביק קישור ל-YouTube, או להשתמש בחיפוש אודיו כדי למצוא את השיר הזה.",
|
||||
"drmUrlUnsupportedWithLink": "קישורים מ-{platform} מוגנים מפני העתקה, ולכן איננו יכולים להוריד אותם ישירות. ניתן להוריד את השיר באמצעות כלי כמו {downloader} ולאחר מכן להעלות את קובץ השמע לכאן. אפשר גם להדביק קישור של YouTube, או להשתמש בחיפוש שמע כדי למצוא את השיר הזה.",
|
||||
"drmUrlUnsupportedSearch": "קישורים של {platform} מוגנים בזכויות יוצרים, ולכן איננו יכולים להוריד אותם ישירות. חפשו ברשת \"{platform} downloader\" כדי להשיג את קובץ השמע — לדוגמה {searchUrl} — ואז העלו את קובץ השמע לכאן. אפשר גם להדביק קישור של YouTube, או להשתמש בחיפוש שמע כדי למצוא את השיר הזה."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "जॉब {job_id} के लिए ऑडियो चुनने में त्रुटि: {error}",
|
||||
"searchAudioError": "ऑडियो खोजने में त्रुटि: {error}",
|
||||
"searchCreatedSuccessfully": "जॉब बन गई। ऑडियो खोजा जा रहा है...",
|
||||
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है..."
|
||||
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है...",
|
||||
"drmUrlUnsupported": "{platform} लिंक्स कॉपी-प्रोटेक्टेड हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। पहले किसी थर्ड-पार्टी टूल से ऑडियो डाउनलोड करने की कोशिश करो, फिर ऑडियो फ़ाइल को यहाँ अपलोड करो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।",
|
||||
"drmUrlUnsupportedWithLink": "{platform} लिंक कॉपी-प्रोटेक्टेड होते हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। तुम {downloader} जैसे टूल का उपयोग करके ट्रैक डाउनलोड कर सकते हो और फिर ऑडियो फ़ाइल को यहाँ अपलोड कर सकते हो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।",
|
||||
"drmUrlUnsupportedSearch": "{platform} लिंक्स कॉपी-प्रोटेक्टेड होते हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। ऑडियो पाने के लिए वेब पर \"{platform} downloader\" सर्च करो — उदाहरण के लिए {searchUrl} — फिर ऑडियो फ़ाइल को यहाँ अपलोड करो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।"
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Pogreška pri odabiru zvuka za zadatak {job_id}: {error}",
|
||||
"searchAudioError": "Pogreška pri pretraživanju zvuka: {error}",
|
||||
"searchCreatedSuccessfully": "Zadatak je kreiran. Pretražujem zvuk...",
|
||||
"autoDownloadStarted": "Najbolji rezultat je automatski odabran. Preuzimanje započinje..."
|
||||
"autoDownloadStarted": "Najbolji rezultat je automatski odabran. Preuzimanje započinje...",
|
||||
"drmUrlUnsupported": "{platform} poveznice su zaštićene od kopiranja, pa ih ne možemo izravno preuzeti. Pokušaj prvo preuzeti zvuk pomoću alata treće strane, a zatim ovdje prenesi audio datoteku. Također možeš zalijepiti YouTube poveznicu ili koristiti pretraživanje zvuka da pronađeš ovu pjesmu.",
|
||||
"drmUrlUnsupportedWithLink": "{platform} poveznice su zaštićene od kopiranja, pa ih ne možemo izravno preuzeti. Pjesmu možeš preuzeti pomoću alata kao što je {downloader} i zatim ovdje učitati audio datoteku. Također možeš zalijepiti YouTube poveznicu ili upotrijebiti Audio pretraživanje da pronađeš ovu pjesmu.",
|
||||
"drmUrlUnsupportedSearch": "{platform} poveznice su zaštićene od kopiranja, pa ih ne možemo izravno preuzeti. Potraži na webu \"{platform} downloader\" kako bi preuzeo/la audio — na primjer {searchUrl} — a zatim ovdje prenesi audio datoteku. Također možeš zalijepiti YouTube poveznicu ili koristiti Pretraživanje zvuka da pronađeš ovu pjesmu."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Hiba a hang kiválasztásakor a(z) {job_id} feladatnál: {error}",
|
||||
"searchAudioError": "Hiba a hang keresésekor: {error}",
|
||||
"searchCreatedSuccessfully": "Feladat létrehozva. Hang keresése...",
|
||||
"autoDownloadStarted": "A legjobb eredmény automatikusan kiválasztva. Letöltés indítása..."
|
||||
"autoDownloadStarted": "A legjobb eredmény automatikusan kiválasztva. Letöltés indítása...",
|
||||
"drmUrlUnsupported": "A(z) {platform} linkek másolásvédettek, így nem tudjuk őket közvetlenül letölteni. Próbáld meg először letölteni a hanganyagot egy külső eszközzel, majd töltsd fel ide a hangfájlt. Beilleszthetsz egy YouTube linket is, vagy használd az Audio Search funkciót a dal megtalálásához.",
|
||||
"drmUrlUnsupportedWithLink": "A(z) {platform} linkek másolásvédettek, ezért nem tudjuk őket közvetlenül letölteni. A számot letöltheted egy olyan eszközzel, mint a(z) {downloader}, majd feltöltheted ide a hangfájlt. Beilleszthetsz egy YouTube linket is, vagy használhatod a Hangkeresést a dal megtalálásához.",
|
||||
"drmUrlUnsupportedSearch": "A(z) {platform} linkek másolásvédettek, így nem tudjuk őket közvetlenül letölteni. Keress rá a weben egy „{platform} downloader” kifejezésre a hanganyag letöltéséhez — például: {searchUrl} —, majd töltsd fel ide az audiofájlt. Beilleszthetsz egy YouTube linket is, vagy használd a Hangkeresőt a dal megtalálásához."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Kesalahan saat memilih audio untuk tugas {job_id}: {error}",
|
||||
"searchAudioError": "Kesalahan saat mencari audio: {error}",
|
||||
"searchCreatedSuccessfully": "Tugas dibuat. Mencari audio...",
|
||||
"autoDownloadStarted": "Hasil terbaik dipilih secara otomatis. Unduhan dimulai..."
|
||||
"autoDownloadStarted": "Hasil terbaik dipilih secara otomatis. Unduhan dimulai...",
|
||||
"drmUrlUnsupported": "Tautan {platform} dilindungi hak cipta, jadi kami tidak dapat mengunduhnya secara langsung. Coba unduh audionya dengan alat pihak ketiga terlebih dahulu, lalu unggah file audionya di sini. Anda juga dapat menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini.",
|
||||
"drmUrlUnsupportedWithLink": "Tautan {platform} dilindungi hak cipta, sehingga kami tidak dapat mengunduhnya secara langsung. Anda dapat mengunduh lagu tersebut menggunakan alat seperti {downloader} lalu mengunggah file audionya di sini. Anda juga dapat menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini.",
|
||||
"drmUrlUnsupportedSearch": "Tautan {platform} dilindungi hak cipta, jadi kami tidak bisa mengunduhnya secara langsung. Cari \"downloader {platform}\" di internet untuk mendapatkan audionya — misalnya {searchUrl} — lalu unggah file audio di sini. Anda juga bisa menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Errore durante la selezione dell'audio per il lavoro {job_id}: {error}",
|
||||
"searchAudioError": "Errore durante la ricerca dell'audio: {error}",
|
||||
"searchCreatedSuccessfully": "Lavoro creato. Ricerca dell'audio in corso...",
|
||||
"autoDownloadStarted": "Miglior risultato selezionato automaticamente. Avvio del download..."
|
||||
"autoDownloadStarted": "Miglior risultato selezionato automaticamente. Avvio del download...",
|
||||
"drmUrlUnsupported": "I link di {platform} sono protetti da copyright, quindi non possiamo scaricarli direttamente. Prova prima a scaricare l'audio con uno strumento di terze parti, poi carica il file audio qui. Puoi anche incollare un link di YouTube, oppure usare la Ricerca Audio per trovare questa canzone.",
|
||||
"drmUrlUnsupportedWithLink": "I link di {platform} sono protetti da copyright, quindi non possiamo scaricarli direttamente. Puoi scaricare il brano usando uno strumento come {downloader} e poi caricare il file audio qui. Puoi anche incollare un link di YouTube, oppure usare la Ricerca Audio per trovare questa canzone.",
|
||||
"drmUrlUnsupportedSearch": "I link di {platform} sono protetti da copyright, quindi non possiamo scaricarli direttamente. Cerca sul web un \"{platform} downloader\" per ottenere l'audio — ad esempio {searchUrl} — poi carica il file audio qui. Puoi anche incollare un link di YouTube, oppure usare la Ricerca Audio per trovare questa canzone."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
|
||||
"searchAudioError": "オーディオの検索中にエラーが発生しました: {error}",
|
||||
"searchCreatedSuccessfully": "ジョブが作成されました。オーディオを検索しています...",
|
||||
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します..."
|
||||
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します...",
|
||||
"drmUrlUnsupported": "{platform}のリンクはコピー保護されているため、直接ダウンロードできません。サードパーティのツールでオーディオをダウンロードしてから、ここにアップロードしてみてください。または、YouTubeのリンクを貼り付けるか、オーディオ検索を使ってこの曲を探すこともできます。",
|
||||
"drmUrlUnsupportedWithLink": "{platform}のリンクはコピーガードで保護されているため、直接ダウンロードすることはできません。{downloader}のようなツールを使用してトラックをダウンロードし、その音声ファイルをここにアップロードしてください。また、YouTubeのリンクを貼り付けるか、オーディオ検索を使用してこの曲を見つけることもできます。",
|
||||
"drmUrlUnsupportedSearch": "{platform}のリンクはコピープロテクトされているため、直接ダウンロードすることはできません。音声を取得するには、ウェブで「{platform} downloader」を検索し(例:{searchUrl})、その音声ファイルをここにアップロードしてください。また、YouTubeのリンクを貼り付けるか、オーディオ検索を使用してこの曲を見つけることもできます。"
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "使い捨てメールアドレスは許可されていません",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
|
||||
"searchAudioError": "오디오 검색 중 오류 발생: {error}",
|
||||
"searchCreatedSuccessfully": "작업이 생성되었습니다. 오디오를 검색하는 중...",
|
||||
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다..."
|
||||
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다...",
|
||||
"drmUrlUnsupported": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. 먼저 타사 도구를 사용하여 오디오를 다운로드한 다음, 여기에 오디오 파일을 업로드해 보세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용하여 이 노래를 찾을 수도 있습니다.",
|
||||
"drmUrlUnsupportedWithLink": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. {downloader} 같은 도구를 사용해 음원을 다운로드한 후, 여기에 오디오 파일을 업로드해 주세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용해 이 노래를 찾을 수도 있습니다.",
|
||||
"drmUrlUnsupportedSearch": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. 오디오를 추출하려면 웹에서 '{platform} 다운로더'를 검색한 후(예: {searchUrl}) 여기에 오디오 파일을 업로드해 주세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용하여 이 노래를 찾을 수도 있습니다."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Ralat memilih audio untuk tugasan {job_id}: {error}",
|
||||
"searchAudioError": "Ralat mencari audio: {error}",
|
||||
"searchCreatedSuccessfully": "Tugasan dicipta. Sedang mencari audio...",
|
||||
"autoDownloadStarted": "Hasil terbaik dipilih secara automatik. Muat turun bermula..."
|
||||
"autoDownloadStarted": "Hasil terbaik dipilih secara automatik. Muat turun bermula...",
|
||||
"drmUrlUnsupported": "Pautan {platform} dilindungi hak cipta, jadi kami tidak dapat memuat turunnya secara terus. Cuba muat turun audio menggunakan alat pihak ketiga terlebih dahulu, kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau menggunakan Carian Audio untuk mencari lagu ini.",
|
||||
"drmUrlUnsupportedWithLink": "Pautan {platform} dilindungi hak cipta, jadi kami tidak dapat memuat turunnya secara terus. Anda boleh memuat turun trek tersebut menggunakan alat seperti {downloader} dan kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau menggunakan Carian Audio untuk mencari lagu ini.",
|
||||
"drmUrlUnsupportedSearch": "Pautan {platform} dilindungi hak cipta, jadi kami tidak dapat memuat turunnya secara terus. Cari di web untuk \"{platform} downloader\" untuk mendapatkan audio — contohnya {searchUrl} — kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau guna Carian Audio untuk mencari lagu ini."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Feil ved valg av lyd for jobb {job_id}: {error}",
|
||||
"searchAudioError": "Feil ved søk etter lyd: {error}",
|
||||
"searchCreatedSuccessfully": "Jobb opprettet. Søker etter lyd...",
|
||||
"autoDownloadStarted": "Beste resultat valgt automatisk. Nedlasting starter..."
|
||||
"autoDownloadStarted": "Beste resultat valgt automatisk. Nedlasting starter...",
|
||||
"drmUrlUnsupported": "{platform}-lenker er kopibeskyttet, så vi kan ikke laste dem ned direkte. Prøv å laste ned lyden med et tredjepartsverktøy først, og last deretter opp lydfilen her. Du kan også lime inn en YouTube-lenke, eller bruke Lydsøk for å finne denne sangen.",
|
||||
"drmUrlUnsupportedWithLink": "{platform}-lenker er kopibeskyttet, så vi kan ikke laste dem ned direkte. Du kan laste ned sporet ved å bruke et verktøy som {downloader} og deretter laste opp lydfilen her. Du kan også lime inn en YouTube-lenke, eller bruke Lydsøk for å finne denne sangen.",
|
||||
"drmUrlUnsupportedSearch": "{platform}-lenker er kopibeskyttet, så vi kan ikke laste dem ned direkte. Søk på nettet etter en \"{platform} downloader\" for å hente lyden — for eksempel {searchUrl} — og last deretter opp lydfilen her. Du kan også lime inn en YouTube-lenke, eller bruke Lydsøk for å finne denne sangen."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Fout bij het selecteren van audio voor taak {job_id}: {error}",
|
||||
"searchAudioError": "Fout bij het zoeken naar audio: {error}",
|
||||
"searchCreatedSuccessfully": "Taak aangemaakt. Zoeken naar audio...",
|
||||
"autoDownloadStarted": "Beste resultaat automatisch geselecteerd. Downloaden wordt gestart..."
|
||||
"autoDownloadStarted": "Beste resultaat automatisch geselecteerd. Downloaden wordt gestart...",
|
||||
"drmUrlUnsupported": "{platform}-links zijn kopieerbeveiligd, dus we kunnen ze niet direct downloaden. Probeer de audio eerst te downloaden met een externe tool en upload het audiobestand vervolgens hier. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden.",
|
||||
"drmUrlUnsupportedWithLink": "{platform}-links zijn kopieerbeveiligd, dus we kunnen ze niet direct downloaden. Je kunt het nummer downloaden met een tool zoals {downloader} en vervolgens het audiobestand hier uploaden. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden.",
|
||||
"drmUrlUnsupportedSearch": "{platform}-links zijn kopieerbeveiligd, dus we kunnen ze niet direct downloaden. Zoek op het web naar een \"{platform} downloader\" om de audio te verkrijgen — bijvoorbeeld {searchUrl} — en upload het audiobestand vervolgens hier. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Błąd podczas wybierania audio dla zadania {job_id}: {error}",
|
||||
"searchAudioError": "Błąd podczas wyszukiwania audio: {error}",
|
||||
"searchCreatedSuccessfully": "Zadanie utworzone. Wyszukiwanie audio...",
|
||||
"autoDownloadStarted": "Najlepszy wynik wybrany automatycznie. Rozpoczynanie pobierania..."
|
||||
"autoDownloadStarted": "Najlepszy wynik wybrany automatycznie. Rozpoczynanie pobierania...",
|
||||
"drmUrlUnsupported": "Linki z {platform} są chronione przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Spróbuj najpierw pobrać dźwięk za pomocą zewnętrznego narzędzia, a następnie prześlij plik audio tutaj. Możesz też wkleić link do YouTube lub użyć wyszukiwania audio, aby znaleźć tę piosenkę.",
|
||||
"drmUrlUnsupportedWithLink": "Linki z {platform} są zabezpieczone przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Możesz pobrać utwór za pomocą narzędzia takiego jak {downloader}, a następnie przesłać plik audio tutaj. Możesz również wkleić link do YouTube lub użyć Wyszukiwania Audio, aby znaleźć tę piosenkę.",
|
||||
"drmUrlUnsupportedSearch": "Linki z {platform} są zabezpieczone przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Wyszukaj w sieci „{platform} downloader”, aby pobrać plik audio — na przykład {searchUrl} — a następnie prześlij plik audio tutaj. Możesz również wkleić link do YouTube lub użyć Wyszukiwania Audio, aby znaleźć tę piosenkę."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Erro ao selecionar áudio para o job {job_id}: {error}",
|
||||
"searchAudioError": "Erro ao pesquisar áudio: {error}",
|
||||
"searchCreatedSuccessfully": "Job criado. Pesquisando áudio...",
|
||||
"autoDownloadStarted": "Melhor resultado selecionado automaticamente. Iniciando download..."
|
||||
"autoDownloadStarted": "Melhor resultado selecionado automaticamente. Iniciando download...",
|
||||
"drmUrlUnsupported": "Os links do {platform} são protegidos contra cópia, então não podemos baixá-los diretamente. Tente baixar o áudio com uma ferramenta de terceiros primeiro e depois faça o upload do arquivo de áudio aqui. Você também pode colar um link do YouTube ou usar a Pesquisa de Áudio para encontrar esta música.",
|
||||
"drmUrlUnsupportedWithLink": "Os links do {platform} são protegidos contra cópia, então não podemos baixá-los diretamente. Você pode baixar a faixa usando uma ferramenta como o {downloader} e depois fazer o upload do arquivo de áudio aqui. Você também pode colar um link do YouTube ou usar a Pesquisa de Áudio para encontrar esta música.",
|
||||
"drmUrlUnsupportedSearch": "Os links do {platform} são protegidos contra cópia, então não podemos baixá-los diretamente. Pesquise na web por um \"{platform} downloader\" para obter o áudio — por exemplo, {searchUrl} — e depois faça o upload do arquivo de áudio aqui. Você também pode colar um link do YouTube ou usar a Pesquisa de Áudio para encontrar esta música."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Eroare la selectarea fișierului audio pentru jobul {job_id}: {error}",
|
||||
"searchAudioError": "Eroare la căutarea audio: {error}",
|
||||
"searchCreatedSuccessfully": "Job creat. Se caută fișierul audio...",
|
||||
"autoDownloadStarted": "Cel mai bun rezultat a fost selectat automat. Descărcarea începe..."
|
||||
"autoDownloadStarted": "Cel mai bun rezultat a fost selectat automat. Descărcarea începe...",
|
||||
"drmUrlUnsupported": "Linkurile {platform} sunt protejate la copiere, așa că nu le putem descărca direct. Încearcă să descarci mai întâi conținutul audio cu un instrument terț, apoi încarcă fișierul audio aici. De asemenea, poți lipi un link YouTube sau poți folosi Căutare Audio pentru a găsi această melodie.",
|
||||
"drmUrlUnsupportedWithLink": "Linkurile {platform} sunt protejate la copiere, așa că nu le putem descărca direct. Poți descărca piesa folosind un instrument precum {downloader} și apoi poți încărca fișierul audio aici. De asemenea, poți lipi un link YouTube sau poți folosi Căutarea Audio pentru a găsi această melodie.",
|
||||
"drmUrlUnsupportedSearch": "Linkurile {platform} sunt protejate la copiere, așa că nu le putem descărca direct. Caută pe web un „{platform} downloader” pentru a obține fișierul audio — de exemplu {searchUrl} — apoi încarcă fișierul audio aici. De asemenea, poți lipi un link YouTube sau poți folosi Căutarea Audio pentru a găsi această piesă."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Ошибка при выборе аудио для задачи {job_id}: {error}",
|
||||
"searchAudioError": "Ошибка при поиске аудио: {error}",
|
||||
"searchCreatedSuccessfully": "Задача создана. Ищем аудио...",
|
||||
"autoDownloadStarted": "Лучший результат выбран автоматически. Начинается скачивание..."
|
||||
"autoDownloadStarted": "Лучший результат выбран автоматически. Начинается скачивание...",
|
||||
"drmUrlUnsupported": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Попробуй сначала скачать аудио с помощью стороннего инструмента, а затем загрузи аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать Поиск аудио, чтобы найти эту песню.",
|
||||
"drmUrlUnsupportedWithLink": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Ты можешь скачать трек с помощью такого инструмента, как {downloader}, а затем загрузить аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать поиск аудио, чтобы найти эту песню.",
|
||||
"drmUrlUnsupportedSearch": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Поищи в интернете «{platform} downloader», чтобы получить аудио — например, {searchUrl} — а затем загрузи аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать Поиск аудио, чтобы найти эту песню."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Chyba pri výbere zvuku pre úlohu {job_id}: {error}",
|
||||
"searchAudioError": "Chyba pri vyhľadávaní zvuku: {error}",
|
||||
"searchCreatedSuccessfully": "Úloha bola vytvorená. Vyhľadáva sa zvuk...",
|
||||
"autoDownloadStarted": "Najlepší výsledok bol vybraný automaticky. Sťahovanie sa začína..."
|
||||
"autoDownloadStarted": "Najlepší výsledok bol vybraný automaticky. Sťahovanie sa začína...",
|
||||
"drmUrlUnsupported": "Odkazy {platform} sú chránené proti kopírovaniu, takže ich nemôžeme stiahnuť priamo. Skús najprv stiahnuť zvuk pomocou nástroja tretej strany a potom sem nahraj zvukový súbor. Môžeš tiež vložiť odkaz na YouTube alebo použiť vyhľadávanie zvuku na nájdenie tejto piesne.",
|
||||
"drmUrlUnsupportedWithLink": "Odkazy {platform} sú chránené proti kopírovaniu, takže ich nemôžeme stiahnuť priamo. Skladbu si môžeš stiahnuť pomocou nástroja ako {downloader} a potom sem nahrať zvukový súbor. Môžeš tiež vložiť odkaz na YouTube, alebo použiť Vyhľadávanie zvuku na nájdenie tejto piesne.",
|
||||
"drmUrlUnsupportedSearch": "Odkazy z {platform} sú chránené proti kopírovaniu, takže ich nemôžeme stiahnuť priamo. Vyhľadaj na webe „{platform} downloader“, aby si získal zvuk — napríklad {searchUrl} — a potom sem nahraj zvukový súbor. Môžeš tiež vložiť odkaz na YouTube alebo použiť vyhľadávanie zvuku na nájdenie tejto piesne."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Fel vid val av ljud för jobb {job_id}: {error}",
|
||||
"searchAudioError": "Fel vid sökning efter ljud: {error}",
|
||||
"searchCreatedSuccessfully": "Jobbet har skapats. Söker efter ljud...",
|
||||
"autoDownloadStarted": "Bästa resultatet valdes automatiskt. Nedladdningen startar..."
|
||||
"autoDownloadStarted": "Bästa resultatet valdes automatiskt. Nedladdningen startar...",
|
||||
"drmUrlUnsupported": "{platform}-länkar är kopieringsskyddade, så vi kan inte ladda ner dem direkt. Försök att ladda ner ljudet med ett tredjepartsverktyg först och ladda sedan upp ljudfilen här. Du kan också klistra in en YouTube-länk eller använda Ljudsökning för att hitta den här låten.",
|
||||
"drmUrlUnsupportedWithLink": "{platform}-länkar är kopieringsskyddade, så vi kan inte ladda ner dem direkt. Du kan ladda ner låten med ett verktyg som {downloader} och sedan ladda upp ljudfilen här. Du kan också klistra in en YouTube-länk, eller använda Audio Search för att hitta den här låten.",
|
||||
"drmUrlUnsupportedSearch": "{platform}-länkar är kopieringsskyddade, så vi kan inte ladda ner dem direkt. Sök på nätet efter en \"{platform} downloader\" för att hämta ljudet — till exempel {searchUrl} — och ladda sedan upp ljudfilen här. Du kan också klistra in en YouTube-länk, eller använda Audio Search för att hitta den här låten."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "เกิดข้อผิดพลาดในการเลือกเสียงสำหรับงาน {job_id}: {error}",
|
||||
"searchAudioError": "เกิดข้อผิดพลาดในการค้นหาเสียง: {error}",
|
||||
"searchCreatedSuccessfully": "สร้างงานแล้ว กำลังค้นหาเสียง...",
|
||||
"autoDownloadStarted": "เลือกผลลัพธ์ที่ดีที่สุดโดยอัตโนมัติ กำลังเริ่มดาวน์โหลด..."
|
||||
"autoDownloadStarted": "เลือกผลลัพธ์ที่ดีที่สุดโดยอัตโนมัติ กำลังเริ่มดาวน์โหลด...",
|
||||
"drmUrlUnsupported": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง ลองดาวน์โหลดเสียงด้วยเครื่องมือของบุคคลที่สามก่อน แล้วจึงอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้อีกด้วย",
|
||||
"drmUrlUnsupportedWithLink": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง คุณสามารถดาวน์โหลดเพลงโดยใช้เครื่องมืออย่าง {downloader} แล้วอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้เช่นกัน",
|
||||
"drmUrlUnsupportedSearch": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง ลองค้นหาบนเว็บด้วยคำว่า \"{platform} downloader\" เพื่อรับไฟล์เสียง — ตัวอย่างเช่น {searchUrl} — จากนั้นอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้อีกด้วย"
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Error sa pagpili ng audio para sa job {job_id}: {error}",
|
||||
"searchAudioError": "Error sa paghahanap ng audio: {error}",
|
||||
"searchCreatedSuccessfully": "Nagawa na ang job. Naghahanap ng audio...",
|
||||
"autoDownloadStarted": "Awtomatikong napili ang pinakamagandang resulta. Nagsisimula na ang pag-download..."
|
||||
"autoDownloadStarted": "Awtomatikong napili ang pinakamagandang resulta. Nagsisimula na ang pag-download...",
|
||||
"drmUrlUnsupported": "Ang mga link ng {platform} ay copy-protected, kaya hindi namin ito direktang ma-download. Subukan munang i-download ang audio gamit ang isang third-party na tool, pagkatapos ay i-upload ang audio file dito. Maaari ka ring mag-paste ng YouTube link, o gamitin ang Audio Search para hanapin ang kantang ito.",
|
||||
"drmUrlUnsupportedWithLink": "Ang mga {platform} link ay copy-protected, kaya hindi namin ito direktang ma-download. Maaari mong i-download ang track gamit ang tool tulad ng {downloader} at i-upload ang audio file dito. Maaari ka ring mag-paste ng YouTube link, o gumamit ng Audio Search para hanapin ang kantang ito.",
|
||||
"drmUrlUnsupportedSearch": "Ang mga {platform} link ay copy-protected, kaya hindi namin ito direktang ma-download. Maghanap sa web ng \"{platform} downloader\" para makuha ang audio — halimbawa {searchUrl} — pagkatapos ay i-upload ang audio file dito. Maaari ka ring mag-paste ng YouTube link, o gumamit ng Audio Search para hanapin ang kantang ito."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "{job_id} işi için ses seçme hatası: {error}",
|
||||
"searchAudioError": "Ses arama hatası: {error}",
|
||||
"searchCreatedSuccessfully": "İş oluşturuldu. Ses aranıyor...",
|
||||
"autoDownloadStarted": "En iyi sonuç otomatik olarak seçildi. İndirme başlıyor..."
|
||||
"autoDownloadStarted": "En iyi sonuç otomatik olarak seçildi. İndirme başlıyor...",
|
||||
"drmUrlUnsupported": "{platform} bağlantıları kopya korumalı olduğu için onları doğrudan indiremiyoruz. Sesi önce üçüncü taraf bir araçla indirmeyi dene, ardından ses dosyasını buraya yükle. Ayrıca bir YouTube bağlantısı yapıştırabilir veya bu şarkıyı bulmak için Ses Arama'yı kullanabilirsin.",
|
||||
"drmUrlUnsupportedWithLink": "{platform} bağlantıları kopyalamaya karşı korumalı, bu yüzden onları doğrudan indiremiyoruz. Parçayı {downloader} gibi bir araç kullanarak indirebilir ve ardından ses dosyasını buraya yükleyebilirsin. Ayrıca bir YouTube bağlantısı yapıştırabilir veya bu şarkıyı bulmak için Ses Araması'nı kullanabilirsin.",
|
||||
"drmUrlUnsupportedSearch": "{platform} bağlantıları kopya korumalı olduğu için onları doğrudan indiremiyoruz. Sesi elde etmek için internette bir \"{platform} downloader\" ara — örneğin {searchUrl} — ardından ses dosyasını buraya yükle. Ayrıca bir YouTube bağlantısı yapıştırabilir veya bu şarkıyı bulmak için Ses Arama'yı kullanabilirsin."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Помилка вибору аудіо для завдання {job_id}: {error}",
|
||||
"searchAudioError": "Помилка пошуку аудіо: {error}",
|
||||
"searchCreatedSuccessfully": "Завдання створено. Шукаємо аудіо...",
|
||||
"autoDownloadStarted": "Найкращий результат вибрано автоматично. Починається завантаження..."
|
||||
"autoDownloadStarted": "Найкращий результат вибрано автоматично. Починається завантаження...",
|
||||
"drmUrlUnsupported": "Посилання {platform} захищені від копіювання, тому ми не можемо завантажити їх безпосередньо. Спробуй спочатку завантажити аудіо за допомогою стороннього інструменту, а потім завантаж аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню.",
|
||||
"drmUrlUnsupportedWithLink": "Посилання з {platform} захищені від копіювання, тому ми не можемо завантажити їх напряму. Ти можеш завантажити трек за допомогою такого інструменту, як {downloader}, а потім завантажити аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню.",
|
||||
"drmUrlUnsupportedSearch": "Посилання {platform} захищені від копіювання, тому ми не можемо завантажити їх безпосередньо. Знайди в інтернеті \"{platform} downloader\", щоб отримати аудіо — наприклад, {searchUrl} — а потім завантаж аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "Lỗi khi chọn âm thanh cho công việc {job_id}: {error}",
|
||||
"searchAudioError": "Lỗi khi tìm kiếm âm thanh: {error}",
|
||||
"searchCreatedSuccessfully": "Đã tạo công việc. Đang tìm kiếm âm thanh...",
|
||||
"autoDownloadStarted": "Kết quả tốt nhất được chọn tự động. Đang bắt đầu tải xuống..."
|
||||
"autoDownloadStarted": "Kết quả tốt nhất được chọn tự động. Đang bắt đầu tải xuống...",
|
||||
"drmUrlUnsupported": "Các liên kết {platform} được bảo vệ bản quyền, vì vậy chúng tôi không thể tải chúng xuống trực tiếp. Hãy thử tải âm thanh bằng công cụ của bên thứ ba trước, sau đó tải tệp âm thanh lên đây. Bạn cũng có thể dán liên kết YouTube hoặc sử dụng Tìm kiếm Âm thanh để tìm bài hát này.",
|
||||
"drmUrlUnsupportedWithLink": "Các liên kết {platform} được bảo vệ bản quyền, nên chúng tôi không thể tải xuống trực tiếp. Bạn có thể tải bài hát bằng công cụ như {downloader} rồi tải tệp âm thanh lên đây. Bạn cũng có thể dán liên kết YouTube, hoặc dùng Tìm kiếm Âm thanh để tìm bài hát này.",
|
||||
"drmUrlUnsupportedSearch": "Các liên kết {platform} được bảo vệ bản quyền, nên chúng tôi không thể tải xuống trực tiếp. Hãy tìm kiếm trên mạng công cụ \"{platform} downloader\" để lấy tệp âm thanh — ví dụ {searchUrl} — sau đó tải tệp âm thanh lên đây. Bạn cũng có thể dán liên kết YouTube, hoặc dùng tính năng Tìm kiếm Âm thanh để tìm bài hát này."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
|
||||
@@ -92,7 +92,10 @@
|
||||
"selectAudioError": "为任务 {job_id} 选择音频时出错:{error}",
|
||||
"searchAudioError": "搜索音频时出错:{error}",
|
||||
"searchCreatedSuccessfully": "任务已创建。正在搜索音频...",
|
||||
"autoDownloadStarted": "已自动选择最佳结果。开始下载..."
|
||||
"autoDownloadStarted": "已自动选择最佳结果。开始下载...",
|
||||
"drmUrlUnsupported": "{platform} 链接受版权保护,因此我们无法直接下载。请先尝试使用第三方工具下载音频,然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或者使用音频搜索来查找这首歌。",
|
||||
"drmUrlUnsupportedWithLink": "{platform} 链接受版权保护,因此我们无法直接下载。您可以使用 {downloader} 等工具下载该曲目,然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或使用“音频搜索”来查找这首歌。",
|
||||
"drmUrlUnsupportedSearch": "{platform} 链接受防复制保护,因此我们无法直接下载。请在网上搜索“{platform} downloader”来获取音频——例如 {searchUrl} ——然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或者使用音频搜索来查找这首歌。"
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "不允许使用一次性邮箱",
|
||||
|
||||
@@ -80,6 +80,15 @@ DOWNLOAD_ALREADY_DONE_STATUSES = frozenset({
|
||||
JobStatus.CANCELLED,
|
||||
})
|
||||
|
||||
# How long to wait for a flacfetch download before giving up. This MUST stay
|
||||
# strictly below the Cloud Run task `timeout` for audio-download-job (see
|
||||
# infrastructure/modules/cloud_run.py::create_audio_download_job). If they are
|
||||
# equal, Cloud Run SIGKILLs the task before this timeout can fire, so the
|
||||
# worker never records retry-pending or fails gracefully — leaving an in-flight
|
||||
# auto-retry that races manual retries (job 1cd29294). The headroom below the
|
||||
# task timeout covers the final GCS upload + state transition.
|
||||
DOWNLOAD_WAIT_TIMEOUT_SECONDS = 1080 # task timeout is 1200s
|
||||
|
||||
|
||||
def _current_task_attempt() -> int:
|
||||
"""Read CLOUD_RUN_TASK_ATTEMPT env var injected by Cloud Run Jobs.
|
||||
@@ -227,6 +236,22 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
storage_service=storage_service,
|
||||
)
|
||||
|
||||
# Concurrency guard: a second download run may have completed while we
|
||||
# were downloading — e.g. a manual /retry racing this task's Cloud Run
|
||||
# auto-retry. Re-read status now (it was read once at entry, before a
|
||||
# potentially minutes-long download). If another run already advanced
|
||||
# the job, treat this as an idempotent success: don't re-write the input
|
||||
# path, don't re-transition (that would be an invalid
|
||||
# downloading -> downloading), and don't re-trigger downstream workers.
|
||||
# The winning run owns all of that.
|
||||
latest = job_manager.get_job(job_id)
|
||||
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Another run already advanced the job "
|
||||
f"(status={latest.status}); skipping duplicate transition/triggers"
|
||||
)
|
||||
return True
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
@@ -241,13 +266,32 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
# previous error so the UI stops showing a resolved failure.
|
||||
_clear_retry_pending_and_error(job_manager, job_id)
|
||||
|
||||
# Transition from DOWNLOADING_AUDIO to DOWNLOADING
|
||||
job_manager.transition_to_state(
|
||||
# Transition from DOWNLOADING_AUDIO (or FAILED, on recovery) to
|
||||
# DOWNLOADING. Use raise_on_invalid=False so a tight race that slipped
|
||||
# past the guard above (another run advancing the job between our
|
||||
# re-read and here) does NOT raise into the generic except and fail_job
|
||||
# a job another run already succeeded on.
|
||||
transitioned = job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
message="Audio downloaded, starting processing",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
if not transitioned:
|
||||
latest = job_manager.get_job(job_id)
|
||||
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Concurrent run advanced job during transition "
|
||||
f"(status={latest.status}); treating as idempotent success"
|
||||
)
|
||||
return True
|
||||
# Genuinely unexpected state (not a concurrency case) — surface it
|
||||
# through the normal failure path so retry-pending is recorded.
|
||||
raise DownloadError(
|
||||
f"Could not transition to DOWNLOADING "
|
||||
f"(status={latest.status if latest else 'missing'})"
|
||||
)
|
||||
|
||||
# Check if audio editing was requested — enter blocking state instead of processing
|
||||
job = job_manager.get_job(job_id)
|
||||
@@ -423,7 +467,7 @@ async def _download_torrent(
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
@@ -461,7 +505,7 @@ async def _download_spotify(
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
|
||||
@@ -57,6 +57,10 @@ RENDER_WORKER_SHUTDOWN_CODE = "WORKER_SHUTDOWN"
|
||||
# Import from lyrics_transcriber (submodule)
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.output.timing_validation import (
|
||||
LyricsTimingError,
|
||||
validate_segment_timing,
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
@@ -362,6 +366,19 @@ async def process_render_video(job_id: str) -> bool:
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# 4b. Reject untimed lyrics BEFORE any expensive work or encoder
|
||||
# dispatch. Custom/replaced lyrics that were never tap-synced carry
|
||||
# None start/end times and otherwise crash the encoder with a cryptic
|
||||
# "'<' not supported between instances of 'NoneType' and 'float'".
|
||||
# Failing here gives the user an actionable message and never sends a
|
||||
# broken job to the GCE encoder (which runs its own pinned wheel).
|
||||
try:
|
||||
validate_segment_timing(correction_result.corrected_segments)
|
||||
except LyricsTimingError as timing_err:
|
||||
job_log.error(f"Render rejected — lyrics not synchronized: {timing_err}")
|
||||
logger.error(f"Job {job_id}: Render rejected — lyrics not synchronized: {timing_err}")
|
||||
raise ValueError(str(timing_err)) from timing_err
|
||||
|
||||
# 5. Download audio file
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
|
||||
@@ -1123,6 +1123,7 @@ async def _handle_native_distribution(
|
||||
brand_code=upload_brand_code,
|
||||
base_name=base_name,
|
||||
output_files=output_files,
|
||||
warnings=result.setdefault('distribution_warnings', []),
|
||||
)
|
||||
|
||||
result['gdrive_files'] = uploaded
|
||||
|
||||
@@ -871,11 +871,19 @@ class VideoWorkerOrchestrator:
|
||||
'final_karaoke_cdg_zip': self.result.final_karaoke_cdg_zip,
|
||||
}
|
||||
|
||||
# Emit the padded original-vocals guide for public NOMAD releases so kjbox can
|
||||
# layer it under the master at the "Original Vocals" slider. Best-effort: a
|
||||
# failure just omits the guide (the upload layer pushes it if present).
|
||||
guide_path = await self._emit_original_vocals_guide(brand_code)
|
||||
if guide_path:
|
||||
output_files['original_vocals_guide'] = guide_path
|
||||
|
||||
uploaded = gdrive.upload_to_public_share(
|
||||
root_folder_id=self.config.gdrive_folder_id,
|
||||
brand_code=brand_code,
|
||||
base_name=base_name,
|
||||
output_files=output_files,
|
||||
warnings=self.result.distribution_warnings,
|
||||
)
|
||||
|
||||
self.result.gdrive_files = uploaded
|
||||
@@ -886,6 +894,78 @@ class VideoWorkerOrchestrator:
|
||||
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the pipeline - GDrive is optional
|
||||
|
||||
async def _emit_original_vocals_guide(self, brand_code) -> Optional[str]:
|
||||
"""Build the padded original-vocals guide (silence[intro] + mixed_vocals, capped to
|
||||
the master's duration) for a public NOMAD release, and return its local path.
|
||||
|
||||
The mixed-vocals stem is a byproduct of the karaoke separation (uploaded to
|
||||
``jobs/{job_id}/stems/vocals_clean.flac``) and the intro offset is the job's own
|
||||
style ``intro_video_duration`` — so no correlation/review is needed. Best-effort:
|
||||
returns ``None`` (and never raises) for non-NOMAD brands, a missing stem, or any
|
||||
build failure — the guide simply won't be distributed.
|
||||
"""
|
||||
try:
|
||||
from backend.services.nomad_master_mirror import is_nomad_public_brand
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return None
|
||||
master_720p = self.result.final_video_720p
|
||||
if not master_720p or not os.path.exists(master_720p):
|
||||
return None
|
||||
if not self.storage:
|
||||
return None
|
||||
|
||||
import tempfile
|
||||
from backend.services.original_vocals_guide import (
|
||||
build_original_vocals_guide,
|
||||
probe_duration,
|
||||
)
|
||||
|
||||
work_dir = tempfile.mkdtemp(prefix="vocals_guide_")
|
||||
stem_gcs = f"jobs/{self.config.job_id}/stems/vocals_clean.flac"
|
||||
local_stem = os.path.join(work_dir, "vocals_clean.flac")
|
||||
try:
|
||||
self.storage.download_file(stem_gcs, local_stem)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.job_log.warning(
|
||||
f"Original-vocals guide: mixed-vocals stem unavailable ({stem_gcs}): {e}"
|
||||
)
|
||||
return None
|
||||
|
||||
intro_seconds = await self._resolve_intro_seconds()
|
||||
master_duration = probe_duration(master_720p)
|
||||
dest = os.path.join(work_dir, "original_vocals_guide.flac")
|
||||
guide = build_original_vocals_guide(
|
||||
local_stem, intro_seconds, dest, master_duration=master_duration
|
||||
)
|
||||
if guide:
|
||||
self.job_log.info(
|
||||
f"Built original-vocals guide for {brand_code} (intro={intro_seconds}s)"
|
||||
)
|
||||
return guide
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
self.job_log.warning(f"Original-vocals guide emit skipped: {e}")
|
||||
return None
|
||||
|
||||
async def _resolve_intro_seconds(self) -> float:
|
||||
"""The master's silent title-card length = the job's style intro ``video_duration``
|
||||
(default 5s). Read the *actual* value — long-intro styles exist. Falls back to 5s
|
||||
(``get_intro_format`` raises when no theme is loaded — that's the fallback path)."""
|
||||
try:
|
||||
from backend.workers.style_helper import load_style_config
|
||||
import tempfile
|
||||
|
||||
job = self.job_manager.get_job(self.config.job_id) if self.job_manager else None
|
||||
if job is None:
|
||||
return 5.0
|
||||
style = await load_style_config(job, self.storage, tempfile.mkdtemp(prefix="style_"))
|
||||
# Preserve an intentional 0 (a style with no title card); only None/absent
|
||||
# falls back to the 5s default. A truthiness check would misalign the guide.
|
||||
intro = style.get_intro_format().get("video_duration", 5)
|
||||
return float(intro) if intro is not None else 5.0
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.job_log.warning(f"Original-vocals guide: intro-duration lookup fell back to 5s: {e}")
|
||||
return 5.0
|
||||
|
||||
async def _run_notifications(self):
|
||||
"""Run the notifications stage (Discord)."""
|
||||
self.job_log.info("Starting notifications stage")
|
||||
|
||||
+12
-3
@@ -2,6 +2,13 @@
|
||||
|
||||
Base URL: `https://api.nomadkaraoke.com` (production) or `http://localhost:8000` (local)
|
||||
|
||||
> **Edge:** production traffic must go through `https://api.nomadkaraoke.com`
|
||||
> (proxied by Cloudflare — WAF + rate limiting). The Cloud Run origin is
|
||||
> **origin-locked**: requests hitting the raw `*.run.app` URL directly are
|
||||
> rejected with `403` unless they carry the Cloudflare-injected `X-Edge-Auth`
|
||||
> header (`/` and `/api/health*` are exempt for probes). See
|
||||
> [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare).
|
||||
|
||||
## Authentication
|
||||
|
||||
All endpoints except `/health` and `/api/themes` require authentication.
|
||||
@@ -630,7 +637,9 @@ best-effort — storage failures degrade to a normal uncached run.
|
||||
|
||||
`op` is `replace` | `delete` | `insert_after` (for `insert_after`, `word_ids`
|
||||
holds the anchor word). Errors: `422` when no reference lyrics are available,
|
||||
`400` for invalid settings, `502` when the model call fails or returns
|
||||
`400` for invalid settings, `429` when the model provider is temporarily
|
||||
rate-limited (transient — retryable; the service already retries with backoff
|
||||
before surfacing this), `502` when the model call otherwise fails or returns
|
||||
malformed output. Design/eval background:
|
||||
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`.
|
||||
|
||||
@@ -2279,11 +2288,11 @@ routes require auth.
|
||||
|
||||
- `GET /api/bulk/album/artists?q=<name>` → `[{mbid,name,disambiguation,type,country}]`
|
||||
- `GET /api/bulk/album/albums?artist_mbid=<mbid>` → `[{release_group_mbid,title,primary_type,secondary_types,first_release_date,is_studio}]` (studio albums first)
|
||||
- `GET /api/bulk/album/tracklist?artist=<name>&release_group_mbid=<mbid>` (or `&release_mbid=<mbid>` for a specific edition) → `{release_mbid,canonical_release_mbid,title,date,tracks:[{position,title,recording_mbid,length_ms,is_extra,extra_reason,available,brands}],editions:[{release_mbid,title,status,date,country,track_count}]}`. Each track is enriched with KaraokeNerds community-version availability (`available`/`brands`); enrichment is best-effort and never fatal.
|
||||
- `GET /api/bulk/album/tracklist?artist=<name>&release_group_mbid=<mbid>` (or `&release_mbid=<mbid>` for a specific edition; optional `&locale=<code>` biases representative-pressing choice) → `{release_mbid,canonical_release_mbid,selected_variant_mbid,title,date,tracks:[{position,title,recording_mbid,length_ms,is_extra,extra_reason,available,brands,versions:[{brand,url}]}],editions:[{release_mbid,title,status,date,country,track_count}],variants:[{representative_release_mbid,label,track_count,year,pressing_count,delta_vs_original}]}`. `variants` collapses the release-group's country pressings into distinct tracklists grouped by track count (label `Original`/`Reissue`, `Original` = earliest); load one via its `representative_release_mbid` as `release_mbid`. Each track is enriched with KaraokeNerds community-version availability — `available`/`brands` plus `versions` (per-version `{brand,url}` YouTube links for clickable preview); enrichment is best-effort and never fatal.
|
||||
|
||||
### Availability (text mode)
|
||||
|
||||
- `POST /api/bulk/availability` body `{tracks:[{artist,title}]}` (≤100) → `{results:[{artist,title,available,brands,brand_count}]}`. Backed by the existing KaraokeNerds community-version scraper (1h cache, bounded concurrency).
|
||||
- `POST /api/bulk/availability` body `{tracks:[{artist,title}]}` (≤100) → `{results:[{artist,title,available,brands,brand_count,versions:[{brand,url}]}]}`. Backed by the existing KaraokeNerds community-version scraper (1h cache, bounded concurrency). `versions` carries per-version YouTube links for clickable preview.
|
||||
|
||||
### Submit
|
||||
|
||||
|
||||
+40
-1
@@ -11,9 +11,17 @@
|
||||
│ HTTPS
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Cloudflare edge (api.nomadkaraoke.com proxied — orange-cloud) │
|
||||
│ WAF (exploit-path block) + rate limit + injects X-Edge-Auth │
|
||||
│ header. See § Edge Security (Cloudflare). │
|
||||
└───────────────────────────┬─────────────────────────────────────┘
|
||||
│ HTTPS (SSL "full")
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Backend API (Cloud Run) │
|
||||
│ FastAPI + Python 3.12 │
|
||||
│ https://api.nomadkaraoke.com │
|
||||
│ https://api.nomadkaraoke.com (origin lock: rejects direct- │
|
||||
│ to-origin requests lacking X-Edge-Auth, health/root exempt) │
|
||||
│ │
|
||||
│ Workers: │
|
||||
│ • Audio Worker - Stem separation via Cloud Run GPU (L4) │
|
||||
@@ -61,6 +69,37 @@ Discord-alerting pipeline. `ChunkLoadError` after deploy triggers an automatic
|
||||
hard reload; the `CrashReport` card also checks `/version.json` and shows an
|
||||
"Update now" CTA when the running bundle is stale.
|
||||
|
||||
## Edge Security (Cloudflare)
|
||||
|
||||
`api.nomadkaraoke.com` is proxied through Cloudflare (orange-cloud) — the same
|
||||
zone that already fronts the marketing site, `gen`, `decide`, and the tenant
|
||||
portals. Cut over 2026-07-20 after a vuln-scanner hammered the previously
|
||||
directly-exposed Cloud Run origin. Managed as IaC in
|
||||
`infrastructure/modules/edge_security.py` (`pulumi_cloudflare`).
|
||||
|
||||
**Request path:** client → Cloudflare edge → Cloud Run. At the edge:
|
||||
- **WAF** (`http_request_firewall_custom`) blocks exploit/secret-exposure paths
|
||||
(`/.env`, `/.git/`, `/.ssh/`, `wp-config`, `/etc/passwd`, …) — uses the
|
||||
`contains` operator (regex `matches` needs a Business plan; zone is Free).
|
||||
- **Rate limiting** (`http_ratelimit`) — per-IP flood control (Free-plan limits:
|
||||
`period=10s`, characteristics must include `cf.colo.id`). Excludes
|
||||
`/api/internal/*` (scheduler/Cloud-Tasks cron).
|
||||
- **Origin lock** — a Transform Rule injects a secret `X-Edge-Auth` header
|
||||
(`http_request_late_transform`); the backend's `EdgeAuthMiddleware`
|
||||
(`backend/middleware/edge_auth.py`, `EDGE_AUTH_MODE=enforce`) rejects public
|
||||
requests lacking it, so hitting the raw `*.run.app` origin directly is blocked
|
||||
(health/root exempt for Cloud Run probes). Internal callers reach the backend
|
||||
via `api.nomadkaraoke.com` (Cloud Tasks use `CLOUD_RUN_SERVICE_URL`), so they
|
||||
traverse the edge and carry the header.
|
||||
|
||||
**SSL:** zone TLS mode is **"full"** (not strict). The Cloud Run domain-mapping
|
||||
managed cert cannot provision behind Cloudflare (ACME challenge not visible), but
|
||||
"full" mode doesn't validate the origin cert, so the edge works and is
|
||||
**renewal-safe** — no run.app Origin Rule or load balancer needed. **Never switch
|
||||
the zone to "full (strict)".** Full rationale + cutover runbook:
|
||||
`docs/archive/2026-07-20-edge-security-hardening-plan.md` and
|
||||
`docs/archive/2026-07-20-edge-security-cutover-runbook.md`.
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
```text
|
||||
|
||||
@@ -216,7 +216,7 @@ re-deploy).
|
||||
|
||||
## Image families
|
||||
|
||||
Three GCE image families are maintained by
|
||||
Four GCE image families are maintained by
|
||||
[`.github/workflows/build-runner-images.yml`](../.github/workflows/build-runner-images.yml):
|
||||
|
||||
| Family | Base | Bakes | Built on |
|
||||
@@ -224,6 +224,20 @@ Three GCE image families are maintained by
|
||||
| `gha-runner-general` | Debian 12 | Docker, gcloud, runner v2.332, Python 3.13 (pyenv), Node 20, Java 21, FFmpeg, Poetry | n2-standard-8, 50GB pd-balanced |
|
||||
| `gha-runner-build` | Debian 12 | Same as general + pre-pulled `karaoke-backend-base`/`:latest` + `fake-gcs-server` | n2-standard-8, 50GB pd-balanced |
|
||||
| `gha-runner-gpu` | Debian 12 | NVIDIA driver + CUDA 12.4, Python 3.13 (compiled), FFmpeg+libsamplerate, audio-separator models (~14GB at `/opt/audio-separator-models`) | n1-standard-4 + T4, 200GB pd-balanced |
|
||||
| `gha-runner-gpu-windows` | Windows Server 2022 | NVIDIA **GRID** driver (WDDM — required for DirectML; datacenter driver = TCC = no DirectX), Python 3.12, Git, FFmpeg, Poetry, runner (win-x64), DirectML test models at `C:\audio-separator-models` | n1-standard-4 + T4, 100GB pd-balanced |
|
||||
|
||||
The Windows variant is provisioned by
|
||||
[`runner-image-provision.ps1`](../infrastructure/scripts/runner-image-provision.ps1)
|
||||
delivered via the `windows-startup-script-ps1` metadata key (Windows ignores
|
||||
`startup-script`). It exists for python-audio-separator's `windows-directml`
|
||||
integration tests (RoFormer-on-Windows, issue #292 there).
|
||||
|
||||
**Label routing**: every runner advertises `self-hosted, <os>, x64, gcp`.
|
||||
Families additionally advertise `large-disk` (general/build), `docker-build`
|
||||
(build), or `gpu` (GPU families). The dispatcher resolves families with
|
||||
precedence windows → gpu → build → general, so jobs MUST include an OS label
|
||||
in `runs-on` (`[self-hosted, linux, gpu]` / `[self-hosted, windows, gpu]`) —
|
||||
GitHub schedules onto any runner whose labels are a superset of the job's.
|
||||
|
||||
Each image is tagged `gha-runner-<variant>-<YYYYMMDD-HHMMSS>` and joined to the
|
||||
matching image family. The dispatcher always selects from the family, so the
|
||||
@@ -235,7 +249,7 @@ Build cadence: monthly cron (`0 2 1 * *` UTC) + `workflow_dispatch`. Manual:
|
||||
```bash
|
||||
gh workflow run build-runner-images.yml -f variants=general,build
|
||||
gh workflow run build-runner-images.yml -f variants=gpu
|
||||
gh workflow run build-runner-images.yml # all three
|
||||
gh workflow run build-runner-images.yml # all variants
|
||||
```
|
||||
|
||||
Pulumi does **not** manage images — they're produced by the GHA workflow. The
|
||||
|
||||
@@ -6,6 +6,61 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## Cloudflare edge in front of Cloud Run — the SSL "dragon" (Jul 2026)
|
||||
|
||||
Putting `api.nomadkaraoke.com` behind Cloudflare (WAF/rate-limit/origin-lock)
|
||||
surfaced several non-obvious gotchas. See `infrastructure/modules/edge_security.py`
|
||||
and `docs/archive/2026-07-20-edge-security-*.md`.
|
||||
|
||||
- **Cloud Run domain-mapping managed certs cannot provision behind Cloudflare.**
|
||||
Even with a correct grey-cloud CNAME → `ghs.googlehosted.com` (right DNS,
|
||||
propagated, no CAA), Google's ACME challenge is "not visible through the public
|
||||
internet" and the cert stays `pending` forever. Recreating the mapping doesn't
|
||||
help. **This does not matter** because the zone SSL mode is **"full" (not
|
||||
strict)**: Cloudflare encrypts to the origin but doesn't validate its cert, so
|
||||
the edge works regardless and is **renewal-safe** (a never-provisioning /
|
||||
never-renewing cert can't cause a 525 when the cert isn't checked). **Rule:
|
||||
keep the zone on "full", never "full (strict)".** The much-feared run.app
|
||||
SNI-override Origin Rule and a GCP load balancer are both unnecessary — and the
|
||||
Origin Rule is blocked anyway by the zone's singleton `http_request_origin`
|
||||
entrypoint (already holds a flacfetch prod rule).
|
||||
- **A proxied (orange) record blocks cert issuance** (DNS points at Cloudflare,
|
||||
not `ghs`) — so if you ever DO need the managed cert, create grey → provision →
|
||||
flip orange. For the prod cutover this was moot: `api`'s cert already existed
|
||||
and "full" mode tolerates it, so the cutover was just the grey→orange flip.
|
||||
- **Cloudflare Free-plan WAF/rate-limit constraints (fail at apply time):** the
|
||||
regex `matches` operator needs Business+ (use `contains`); rate-limit `period`
|
||||
must be `10`s and `characteristics` MUST include `cf.colo.id` (per-colo
|
||||
counting); managed OWASP ruleset is Pro+ only.
|
||||
- **Origin lock without breaking internal callers:** all internal traffic (Cloud
|
||||
Tasks via `CLOUD_RUN_SERVICE_URL`, schedulers, frontend) reaches the backend
|
||||
through `api.nomadkaraoke.com`, so it traverses Cloudflare and carries the
|
||||
injected `X-Edge-Auth` header. Validated by running the prod E2E in `warn` mode
|
||||
first and confirming **zero** missing-header warnings before flipping to
|
||||
`enforce`. Health/root paths are exempt (Cloud Run probes hit the origin
|
||||
directly).
|
||||
- **Applying from a worktree:** the prod Pulumi stack shows benign cross-worktree
|
||||
Cloud Function source-archive drift (last applied from a different worktree) —
|
||||
apply edge changes with `pulumi up --target <urn>` to avoid touching it. CI
|
||||
does NOT auto-run `pulumi up` (apply locally before merge).
|
||||
|
||||
## Magic-link auth vs. email link-scanners (Jul 2026)
|
||||
|
||||
- **Never auto-consume a single-use token on page render.** `/auth/verify` used to
|
||||
call `verifyMagicLink(token)` from a `useEffect` on mount (no user gesture) against
|
||||
the state-mutating `GET /api/users/auth/verify`. Any agent that renders the page and
|
||||
runs its JS — Gmail/Safe-Browsing scanners, corporate security proxies — burns the
|
||||
token and creates a throwaway session, so the real user then sees "This link has
|
||||
already been used." Diagnosed for one user whose links were consumed within ~60s by
|
||||
Google LLC IPs (`2607:f8b0…`), his own click losing a sub-second race in Cloud Run logs.
|
||||
- **Fix pattern:** gate verification behind an explicit "Complete Sign-In" click
|
||||
(`frontend/app/[locale]/auth/verify/page.tsx`). Scanners render but don't click, so
|
||||
the token survives. Switching GET→POST alone does NOT help — a JS-executing scanner
|
||||
runs the fetch regardless of method; the user-gesture gate is the robust mitigation.
|
||||
- **Still latent:** the admin one-click login path (`/app?admin_token=…`,
|
||||
`frontend/app/[locale]/app/page.tsx`) auto-verifies the same way. Admin-only/low-volume,
|
||||
so not yet gated — apply the same pattern if it ever bites.
|
||||
|
||||
## Bulk Mode (Jun 2026)
|
||||
|
||||
- **Auto-pick "tier 1" rule is duplicated** between `frontend/lib/audio-search-utils.ts`
|
||||
@@ -1351,3 +1406,34 @@ can recover via the review UI's "Search All Providers" control with
|
||||
`force_sources=["spotify"]` (registered at
|
||||
`/api/review/{job_id}/search-lyrics`); no code change to the filter is
|
||||
warranted.
|
||||
|
||||
## CJK Lyrics: Line-Splitting Must Use Display Width, Not Character Count (Jul 2026)
|
||||
|
||||
**Symptom:** A Japanese karaoke video (job `4dcca2d6`) rendered with lyric
|
||||
lines overlapping and running off both screen edges.
|
||||
|
||||
**Root cause:** `SegmentResizer` gated/split lines on raw character count
|
||||
(`len(text) <= max_line_length`, budget calibrated for Latin at 4K). East-Asian
|
||||
*Wide/Fullwidth* glyphs render ~2.5× a Latin character, and CJK has no
|
||||
inter-word spaces, so a Japanese line well under the *character* budget was ~2×
|
||||
too wide for the frame. The karaoke ASS sets **no `WrapStyle`**, so libass
|
||||
smart-wraps (style 0) a too-wide line onto a second physical row — which lands
|
||||
on the next slot's fixed `y = first_pos + i*line_height` position and overlaps it.
|
||||
|
||||
**Fix:** Measure an **East-Asian display width** (`unicodedata.east_asian_width`
|
||||
W/F → `WIDE_RATIO=2.7` units, else 1). For pure ASCII/Latin `display_width == len`,
|
||||
so Latin/European output is byte-for-byte unchanged. Only the oversize *gate* uses
|
||||
display width; wide-script segments are then split by **word-token packing**
|
||||
(`_pack_words_into_lines`), which is boundary-safe (never cuts inside a multi-char
|
||||
CJK token like `立ち向かう`) and counts the inter-token space the renderer emits.
|
||||
|
||||
**Gotchas for next time:**
|
||||
- libass renders at ~0.70× the nominal ASS `Fontsize` — calibrate widths against
|
||||
that effective size (`lyrics_line.ASS_FONT_SCALE`), not the nominal 250px.
|
||||
- The renderer emits a space after **every** word token (`lyrics_line.py`
|
||||
`transformed_text + " "`), which both inflates CJK width ~25% and is why CJK
|
||||
text looks oddly spaced-out. Dropping inter-CJK spaces is a separate improvement.
|
||||
- A wordless oversized segment must be **preserved**, not split — the word-matching
|
||||
splitters map zero words and would return `[]`, silently dropping lyrics.
|
||||
- The CJK font is a **system fallback** (Noto Sans CJK); the configured karaoke
|
||||
font (Montserrat/Avenir) has no CJK glyphs. See `video_generator._find_cjk_font`.
|
||||
@@ -43,6 +43,7 @@
|
||||
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
|
||||
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
|
||||
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
|
||||
| **Edge security (Cloudflare)** | Working (api.nomadkaraoke.com proxied — WAF + rate limit + origin lock enforced; 2026-07-20) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -54,6 +55,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Cloudflare Edge Security for the Backend API** (2026-07-20): `api.nomadkaraoke.com` is now proxied through Cloudflare (WAF + rate limiting + origin lock), after a vuln-scanner hammered the previously directly-exposed Cloud Run origin. WAF blocks exploit/secret-exposure paths (`contains` operator — regex needs a Business plan); per-IP rate limiting excludes `/api/internal/*`; a Transform Rule injects a secret `X-Edge-Auth` header that the backend's `EdgeAuthMiddleware` (`EDGE_AUTH_MODE=enforce`) requires, blocking direct-to-`*.run.app` bypass (health/root exempt). Key finding: the Cloud Run managed cert can't provision behind Cloudflare, but zone SSL mode "full" (not strict) doesn't validate the origin cert, so it works and is renewal-safe — **never switch the zone to "full (strict)".** Managed as IaC in `infrastructure/modules/edge_security.py`. Also retuned the "High Error Rate" alert to 5xx-only (scanner 404s no longer page). See [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare), [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloudflare-edge-in-front-of-cloud-run--the-ssl-dragon-jul-2026), and [archive/2026-07-20-edge-security-cutover-runbook.md](archive/2026-07-20-edge-security-cutover-runbook.md).
|
||||
|
||||
- **AI Auto-Correct Suggestions** (2026-06-11): Opt-in AI correction suggestions in the lyrics review UI — the third attempt at lyrics auto-correction, redesigned around the failures that led to disabling it in PR #321 (Jan 2026). One whole-song LLM call (default Gemini 3.1 Pro via Vertex, `AUTO_CORRECT_MODEL` env) compares the working transcription against reference lyrics and returns word-id-keyed suggestions; nothing is applied until the reviewer accepts each one (or accept-all) in a dedicated panel with per-row undo. New `POST /api/review/{job_id}/auto-correct` endpoint + `backend/services/auto_correct/`; frontend `useAutoCorrect` hook, `AutoCorrectModal` (knobs: adlib removal, insertions, confidence filter), `AutoCorrectPanel`. Accept/reject decisions land in the EditLog (`ai_suggestion_*` ops) to measure real accept rates. 5-model offline eval over 30 real jobs with human ground truth picked the default (Fable 5 ≈ Gemini 3.1 Pro ≫ GPT-5.2, which made lyrics worse). See [archive/2026-06-10-lyrics-auto-correction-reeval-plan.md](archive/2026-06-10-lyrics-auto-correction-reeval-plan.md).
|
||||
|
||||
- **Syllable-Aware Custom Lyrics** (2026-05-02): Enhanced the Custom Lyrics LLM mode with syllable-count validation and a per-line repair loop. Backend computes per-line target/candidate syllable counts via the existing `SyllablesMatchHandler` engine and re-prompts Gemini up to 3 times until lines fit budget (Δ ≤ 2 default, configurable via Verbatim/Loose/Balanced/Tight/Strict strictness). New `GenerationSettings` (`allow_reword`, `allow_omit`, `fixed_line_count`, `strictness`) exposed in the modal as a collapsible settings panel. New `CustomLyricsPreview` component shows per-line syllable annotations (target / actual / Δ) with severity badges and stop-reason banners. Variable-line-count mode (when `fixed_line_count=false`) re-times segments proportionally. Eval harness with disk-backed Gemini cache, per-line + per-fixture + corpus scorers, and 4 fixtures (1 from production, 3 handcrafted public-domain). v1-ships criteria validation (Year 5 ≥75% pass@2, macro corpus ≥70% pass@2) deferred to post-merge. See [archive/2026-05-02-custom-lyrics-syllable-aware-design.md](archive/2026-05-02-custom-lyrics-syllable-aware-design.md) and [archive/2026-05-02-custom-lyrics-syllable-aware-plan.md](archive/2026-05-02-custom-lyrics-syllable-aware-plan.md).
|
||||
|
||||
@@ -230,7 +230,9 @@ done
|
||||
|
||||
**Configuration knobs:** `MAX_PER_TICK = 1` and `MAX_WAIT_SECONDS = 24*3600` constants in `backend/api/routes/internal.py::retry_pending_render_jobs`.
|
||||
|
||||
**Not an incident:** a *primary* warmup hitting `503 SERVICE_UNAVAILABLE` / capacity exhaustion is self-healing — the encoding flow's `ensure_any_running()` falls back to an alternate-zone worker and the job completes. As of 0.174.12 the `/internal/encoding-worker/warmup` endpoint logs this at **WARNING** (`"Primary encoding worker warmup failed (...); encoding will fall back..."`), specifically so it stays below the error monitor's `severity>=ERROR` filter and does **not** page Discord. Only a genuine, unexpected warmup failure (non-`EncodingWorkerStartError`) logs at ERROR. If you see the WARNING in logs with a job that still completed, no action is needed.
|
||||
**Not an incident:** a *primary* warmup hitting `503 SERVICE_UNAVAILABLE` / capacity exhaustion is self-healing — the encoding flow's `ensure_any_running()` falls back to an alternate-zone worker and the job completes. As of 0.174.12 the `/internal/encoding-worker/warmup/{job_id}` endpoint logs this at **WARNING** (`"Primary encoding worker warmup failed (...); encoding will fall back..."`), specifically so it stays below the error monitor's `severity>=ERROR` filter and does **not** page Discord. Only a genuine, unexpected warmup failure (non-`EncodingWorkerStartError`) logs at ERROR. If you see the WARNING in logs with a job that still completed, no action is needed.
|
||||
|
||||
**403 on `/internal/encoding-worker/warmup` or `/heartbeat`:** as of 0.188.9 these endpoints are `{job_id}`-scoped and gated on `require_review_auth` (not `require_admin`). The lyrics-review page calls them on load / while editing so the encoding VM is warm by the time the reviewer previews a render. If you see 403s in the browser console, the caller lacks review access to that job — before 0.188.9 they required admin, so **every non-admin customer 403'd and the JIT pre-warm never fired** (renders paid the full cold-boot latency).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# Lyrics Review: Auto-Applied Corrections UX
|
||||
|
||||
**Date:** 2026-06-18
|
||||
**Status:** Shipped (iterated live against prod backend)
|
||||
**Worktree:** `karaoke-gen-lyrics-autocorrect-ux` · branch `feat/sess-20260618-0022-lyrics-autocorrect-ux`
|
||||
|
||||
## Final shipped scope (beyond the original design below)
|
||||
|
||||
The design below captured the initial auto-correct-display work. The shipped PR
|
||||
also includes, from live iteration:
|
||||
|
||||
- **Toolbar consolidation:** the applied-corrections row was removed; the toolbar
|
||||
button reads **"Auto-corrected · N"** and opens the details panel on demand
|
||||
(per-item undo, **Re-run**, and **Revert all** auto-corrections).
|
||||
- **Long-word duration badge** moved *inside* the word pill, right-aligned.
|
||||
- **Timeline view replaced:** the old Text/Timeline + Simple/Advanced toggles are
|
||||
now a single **Simple / Advanced** toggle (`DurationTimelineView` deleted).
|
||||
Inline **>2s word / >2s gap** warnings show in both modes. **Advanced** mode
|
||||
stretches each word pill by its duration (flex-grow) so a segment fills the
|
||||
full width as a readable timeline, with gap **spacers** you can click to play
|
||||
from that point (hover shows a play icon).
|
||||
- **Auto-corrections are the review baseline:** the on-load apply rebases history
|
||||
(not an undoable edit), so no session/restore prompt appears unless there are
|
||||
genuine manual edits.
|
||||
- **Unified session restore:** removed the ad-hoc `window.confirm` localStorage
|
||||
path; the same `SessionRestoreDialog` is used everywhere — server-backed in
|
||||
cloud mode, localStorage-backed (`localSessionStore`) when running locally.
|
||||
- **Crash-reporter localhost guard:** local dev errors no longer POST to the prod
|
||||
error monitor.
|
||||
|
||||
## Problem
|
||||
|
||||
Since the AI auto-correct suggestions feature shipped (PR #809+, v0.177.0), the
|
||||
suggestions are good enough that the operator always clicks **Accept All**. The
|
||||
manual review of a separate suggestions panel (Image #1) is pure friction. We
|
||||
want the corrections applied automatically, and the *review* effort redirected
|
||||
to where it's actually needed: **re-checking word timing on the segments the AI
|
||||
touched** — especially where timing was estimated.
|
||||
|
||||
## Goals (operator's 5 points)
|
||||
|
||||
1. Remove the always-visible suggestions panel; collapse it behind a
|
||||
**"Show auto-corrections (N)"** toggle (details on demand).
|
||||
2. **Auto-apply** all suggestions on load — exactly today's *Accept All*
|
||||
semantics (apply all pending, conflict-group winners by consensus then
|
||||
confidence, default run settings).
|
||||
3. **Distinct colour** for AI-corrected words (purple) vs human-edited (green).
|
||||
4. **Compact, always-visible annotation** of what changed: a small bubble above
|
||||
each corrected span showing the *original transcription text* (Image #2),
|
||||
with extra vertical line spacing to fit.
|
||||
5. **Guidance + scrutiny**: tell operators to play and re-check sync on every
|
||||
edited/auto-corrected segment, and **visually flag words whose timing was
|
||||
estimated** (one word split into N evenly-spaced words) — those almost always
|
||||
need a timing nudge. A 1:1 word replacement keeps the original word's real
|
||||
timing and needs less scrutiny.
|
||||
|
||||
## Current architecture (what we build on)
|
||||
|
||||
- `useAutoCorrect` already **auto-runs one pass on load** (`autoRunOnLoad`);
|
||||
backend pre-generates + caches, so it's normally an instant cache hit.
|
||||
Suggestions land as a **pending layer** in `AutoCorrectPanel` (Image #1).
|
||||
- `acceptAll()` applies pending suggestions via `applySuggestion`, choosing
|
||||
conflict-group winners. Applied words are **new `Word`s** with
|
||||
`created_during_correction: true`.
|
||||
- `editedWordIds` (in `LyricsAnalyzer`) is a **diff of current data vs
|
||||
`history[0]`** (initial state). New AI word IDs fall into this set → they
|
||||
render with the same green/lime "edited" highlight as human edits. *This is
|
||||
why there's no visual distinction today.*
|
||||
- `autoCorrectApply.ts:distributeTimings` is the **estimated-timing signal**:
|
||||
for a replace, it spreads the removed span's `[start,end]` evenly across the
|
||||
new words. `newTexts.length > 1` ⇒ estimated. A 1:1 replace (or N→1 merge)
|
||||
inherits a real range ⇒ trustworthy. `insert_after` words are always synthetic
|
||||
⇒ estimated.
|
||||
- Re-applying a suggestion is **naturally idempotent**: `isSuggestionStale`
|
||||
checks the original word IDs still exist; once replaced they don't, so a
|
||||
re-run on reload applies nothing. This de-risks auto-apply-on-load against
|
||||
reloads and restored sessions.
|
||||
|
||||
## Data model
|
||||
|
||||
Stamp new fields on AI-applied `Word`s at apply time (`autoCorrectApply.ts`):
|
||||
|
||||
| Field | Meaning | Where set |
|
||||
|-------|---------|-----------|
|
||||
| `ai_corrected?: boolean` | This word came from an AI correction → purple + bubble | every new word in a replace/insert |
|
||||
| `original_text?: string` | The original transcription text for the whole span → bubble content | the **first** new word of the span only |
|
||||
| `timing_estimated?: boolean` | Timing was guessed by even-split / insert → scrutiny marker | per new word (`true` when `newTexts.length > 1` or `insert_after`) |
|
||||
| `correction_span_id?: string` | Groups the new words of one suggestion (= suggestion id) → one bubble per span, inline-undo lookup | every new word in the span |
|
||||
|
||||
`validation.ts` (zod) gains the same optional fields so saved/restored data
|
||||
round-trips.
|
||||
|
||||
**Purple vs green rule:** purple = `ai_corrected === true`. `editedWordIds`
|
||||
(green) excludes `ai_corrected` words. If an operator later hand-edits an AI
|
||||
word, it stays purple — the bubble (original transcription) and estimated marker
|
||||
remain accurate; this is an acceptable v1 simplification (rare, not harmful).
|
||||
|
||||
## Auto-apply flow
|
||||
|
||||
- Add an `autoApplyOnLoad` behaviour to `useAutoCorrect`: after the initial
|
||||
auto-run reaches `reviewing`, immediately run `acceptAll()` once (guarded by a
|
||||
ref), then leave the panel collapsed.
|
||||
- On reload of an already-corrected job: the stamped words are present (purple
|
||||
renders from the stamps, independent of the history diff); the re-run is stale
|
||||
⇒ `acceptAll` applies 0 ⇒ no spurious history entry. Idempotent.
|
||||
- **EditLog** still records `ai_suggestion_accept` per applied suggestion (now
|
||||
automatic). The meaningful negative signal becomes `ai_suggestion_undo`.
|
||||
|
||||
## Details panel + undo
|
||||
|
||||
- `AutoCorrectPanel` starts **collapsed**; header becomes
|
||||
*"Show auto-corrections (N)"*. Expanded: the existing list, each row with
|
||||
**Undo** (the accept/reject buttons are gone from the main flow).
|
||||
- **Inline undo:** clicking a purple word looks up its `correction_span_id` →
|
||||
`undoAccept(suggestionId)`. Works within the active review session (where the
|
||||
hook holds `undoInfos`). On a fresh reload the corrections are "baked"; the
|
||||
panel still lists them, and undo falls back to normal manual editing if no
|
||||
in-memory undo info exists. (v1 limitation — operators review in one sitting.)
|
||||
|
||||
## Rendering
|
||||
|
||||
**Text view only for v1** (`TranscriptionView` → `HighlightedText` →
|
||||
`WordComponent`). Thread the AI word data down:
|
||||
|
||||
- **Purple highlight** for `ai_corrected` words (new constant, e.g.
|
||||
`bg-purple-500/30`), visually distinct from green (`bg-green-500/25`) and
|
||||
user-edited lime (`bg-lime-400/40`).
|
||||
- **Bubble** above the first word of each span: tiny muted text = `original_text`
|
||||
with a small connector. `TranscriptionView` row gets extra top padding when a
|
||||
segment contains AI corrections (point 4: "more space between lines").
|
||||
- **Estimated-timing marker** on `timing_estimated` words: a distinct treatment
|
||||
(e.g. dashed amber underline/ring) vs the solid purple of trustworthy 1:1
|
||||
replacements. *Exact styling tuned live in the browser.*
|
||||
|
||||
The Duration/Timeline view keeps its current rendering for v1 (timing is already
|
||||
visible there); colour-only follow-up if wanted.
|
||||
|
||||
## Guidance (`GuidancePanel`)
|
||||
|
||||
- Add **purple → "AI-corrected"** to the colour legend.
|
||||
- Rewrite the workflow tips: instruct operators to **play each edited/AI-corrected
|
||||
segment and confirm the words still line up**, calling out that
|
||||
**[estimated]-marked words had their timing guessed and usually need a nudge**,
|
||||
while 1:1 replacements keep the original timing.
|
||||
- Optional summary line: *"N words auto-corrected · X with estimated timing —
|
||||
check these."*
|
||||
|
||||
## i18n
|
||||
|
||||
All new user-facing strings go in `frontend/messages/en.json` and are translated
|
||||
to all 33 locales via `python scripts/translate.py --messages-dir ./messages
|
||||
--target all` (CI enforces completeness).
|
||||
|
||||
## Testing
|
||||
|
||||
- **Unit (`autoCorrectApply`)**: stamping correctness for replace 1:1 (not
|
||||
estimated, original_text on first), replace 1→N (estimated), `insert_after`
|
||||
(estimated), `delete` (no new words), N→1 merge (not estimated).
|
||||
- **Unit (`editedWordIds`)**: excludes `ai_corrected` words; includes a
|
||||
hand-edited AI word if/where we decide it flips (v1: stays purple).
|
||||
- **Unit (auto-apply)**: applies all winners on load; idempotent when stale.
|
||||
- **Component**: `WordComponent` renders purple + bubble + estimated marker;
|
||||
`AutoCorrectPanel` collapsed by default, toggle reveals list with undo.
|
||||
- **Prod E2E** (`frontend/e2e/production/`): load a job with references, assert
|
||||
purple words + bubbles render and the panel is collapsed.
|
||||
|
||||
## Files
|
||||
|
||||
types.ts · validation.ts · utils/autoCorrectApply.ts · hooks/useAutoCorrect.ts ·
|
||||
LyricsAnalyzer.tsx · AutoCorrectPanel.tsx · TranscriptionView.tsx ·
|
||||
shared/HighlightedText.tsx · shared/Word.tsx · constants.ts · GuidancePanel.tsx ·
|
||||
messages/en.json (+ locales) · tests.
|
||||
|
||||
## Out of scope (v1)
|
||||
|
||||
Backend changes (auto-apply is frontend-only); purple/bubble in the Timeline
|
||||
view; durable cross-reload inline-undo of baked corrections.
|
||||
@@ -0,0 +1,221 @@
|
||||
# Bulk Mode — Edition Collapse + Community-Versions Redesign (Design)
|
||||
|
||||
**Date:** 2026-06-22
|
||||
**Branch:** `feat/sess-20260622-0041-bulk-release-selection`
|
||||
**Scope:** karaoke-gen Bulk Mode "By album" + "By text" flows, against **live MusicBrainz** (no
|
||||
mirror dependency).
|
||||
|
||||
## Context
|
||||
|
||||
Bulk Mode lets a user submit up to 100 karaoke jobs at once. The "By album" flow searches
|
||||
MusicBrainz, picks a release, and shows a tracklist with checkboxes + community-version badges.
|
||||
Two UX problems, both visible in production:
|
||||
|
||||
1. **The edition dropdown is noise.** For ABBA *Arrival* it showed ~17 editions, most of which were
|
||||
the *same* 1976 10-track album pressed in different countries (US/AU/SE/NL/DE…). The selection's
|
||||
only job is to produce a list of **track names** for submission — the country of pressing is
|
||||
irrelevant to that.
|
||||
2. **The community-version badge is wide and inert.** It renders
|
||||
`Community version: SNDL Karaoke, Nomad Karaoke, Reekies Karaoke` inline, which grows
|
||||
horizontally with the number of brands and is not clickable — the user can't preview a version to
|
||||
decide whether it's good enough or whether to remake it.
|
||||
|
||||
This is the **near-term, live-MB** improvement. The larger mirror-backed upgrade (exact
|
||||
tracklist-signature grouping + popularity ranking) is captured separately in
|
||||
`../../../docs/archive/2026-06-18-musicbrainz-mirror-and-album-ux-handoff.md` (Part 3a, Option 2)
|
||||
and is **out of scope here**.
|
||||
|
||||
## Goals
|
||||
|
||||
- Collapse the edition list into a handful of distinct **tracklist variants**, not country pressings.
|
||||
- Make the common case a single confident default; hide the choice behind "Change".
|
||||
- Show **track numbers**.
|
||||
- Replace the community-version badge with a **vertical, clickable** list of versions, each linking
|
||||
to its YouTube video so the user can preview it.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- The MusicBrainz mirror (decide) and anything that depends on it (exact signature grouping,
|
||||
popularity-based auto-select). Tracked in the handoff doc.
|
||||
- Changing how jobs are submitted, credited, or processed downstream.
|
||||
- Fetching per-edition tracklists to compare them (would trip MB's egress rate limiter — explicitly
|
||||
avoided; see Option 1 rationale).
|
||||
|
||||
---
|
||||
|
||||
## Feature 1 — Edition selection: collapse to tracklist variants (A + C)
|
||||
|
||||
### Model
|
||||
- **A — collapse to variants.** Group the release-group's official editions into distinct tracklist
|
||||
variants. Present only meaningfully-different tracklists. Country is no longer the headline.
|
||||
- **C — single default, choice hidden.** Show one line; reveal the variant list only on *Change*; if
|
||||
there's a single variant, no Change affordance at all.
|
||||
|
||||
### Grouping key — Option 1 (track count)
|
||||
Group official editions by `track_count`. Within a single release-group, same track count ≈ same
|
||||
songs (reissues *add* tracks ⇒ a different count), so this is ~95% correct with **zero extra MB API
|
||||
calls** (`_list_editions()` already returns `track_count` per edition). Known, accepted gap: a rare
|
||||
reissue that swaps one track 1-for-1 (same count, different song) would merge incorrectly — the user
|
||||
still sees the full tracklist before submitting. Tracklists stay **lazy-fetched** only for the
|
||||
selected variant, exactly as today.
|
||||
|
||||
> Rationale for not fetching every edition's tracklist: MusicBrainz rate-limits hard from Cloud Run
|
||||
> egress (we've hit 503s and added retry/backoff). Comparing 17 editions = 17 extra calls per album,
|
||||
> in a flow where users look up many albums. The exact-signature approach waits for the mirror.
|
||||
|
||||
### Backend (`backend/services/musicbrainz_service.py`, `backend/api/routes/bulk.py`)
|
||||
|
||||
`get_album_tracklist(release_group_mbid)` already runs `_list_editions()` →
|
||||
`pick_canonical_edition()` → `get_release_tracklist(canonical)`. Add a variant-building step after
|
||||
`_list_editions()`:
|
||||
|
||||
1. Filter to `status == "Official"` (mirrors `pick_canonical_edition`).
|
||||
2. Group by `track_count`.
|
||||
3. For each group, choose a **representative release** using the existing canonical heuristic scoped
|
||||
to the group: earliest date, then locale-preferred country (see Locale), then a stable fallback.
|
||||
4. Compute each group's earliest year (for display) and `pressing_count` (how many editions
|
||||
collapsed in).
|
||||
5. **Label** variants:
|
||||
- The group with the overall-earliest date → `label = "Original"`.
|
||||
- Other groups → labeled by track-count delta vs the Original: more tracks ⇒ `"+N tracks"`
|
||||
(rendered as e.g. "Reissue · +2 tracks"); fewer ⇒ `"-N tracks"`. Year disambiguates.
|
||||
6. Sort variants: Original first, then by year ascending.
|
||||
|
||||
The **default** tracklist remains the canonical release = the Original variant's representative
|
||||
(no behavior change to the default load). Switching variants on the frontend reuses the **existing**
|
||||
`GET /album/tracklist?release_mbid=<representative_release_mbid>` path — no new endpoint.
|
||||
|
||||
New response field on `BulkTracklistResponse`:
|
||||
|
||||
```python
|
||||
class BulkEditionVariant(BaseModel):
|
||||
representative_release_mbid: str
|
||||
label: str # "Original" | "Reissue" | derived
|
||||
track_count: int
|
||||
year: str = "" # earliest year in the group, e.g. "1976"
|
||||
pressing_count: int = 0
|
||||
delta_vs_original: int = 0 # track_count - original.track_count
|
||||
|
||||
class BulkTracklistResponse(BaseModel):
|
||||
...
|
||||
variants: list[BulkEditionVariant] = []
|
||||
selected_variant_mbid: Optional[str] = None # which variant the returned tracklist belongs to
|
||||
```
|
||||
|
||||
`editions[]` may stay for back-compat but is no longer the primary UI input. `selected_variant_mbid`
|
||||
lets the frontend highlight the active variant after a switch.
|
||||
|
||||
### Locale
|
||||
The frontend passes the active locale (`useLocale()` from next-intl) to `/album/tracklist`
|
||||
(e.g. `?locale=en`). Backend maps locale → ordered country-preference list used in the
|
||||
representative pick, falling back to today's `[XW, XE, US, GB]`:
|
||||
|
||||
| locale prefix | preferred countries |
|
||||
|---|---|
|
||||
| en | GB, US, AU, CA, IE, NZ |
|
||||
| ja | JP |
|
||||
| de | DE, AT, CH |
|
||||
| ko | KR |
|
||||
| es | ES, MX, AR |
|
||||
| fr | FR, CA, BE |
|
||||
| (other / unknown) | XW, XE, US, GB |
|
||||
|
||||
Under Option 1 this mostly affects *which pressing backs a variant*, not which variant is default
|
||||
(Original/earliest is always default). It wires the hook the mirror era will lean on.
|
||||
|
||||
### Frontend (`frontend/components/job/bulk/BulkAlbumMode.tsx`, `lib/api.ts`, `bulk/types.ts`)
|
||||
- Replace the raw editions `<Select>` with the **C** pattern:
|
||||
- One summary line: *"Using the {label} {year} release · {N} tracks"* + a **Change** button.
|
||||
- **Change** opens the variant list (reuse `<Select>` / a small popover) showing each variant's
|
||||
label, year, track count, and (subtly) pressing_count. Selecting one calls the existing
|
||||
`release_mbid` fetch.
|
||||
- If `variants.length <= 1`, render the summary line **without** a Change affordance.
|
||||
- **Track numbers:** prefix each track row with `position` (e.g. `1.`). Data already present on
|
||||
`BulkTrack.position`; currently unrendered. Hide if `position` is null.
|
||||
|
||||
---
|
||||
|
||||
## Feature 2 — Community versions: vertical, clickable list
|
||||
|
||||
### Data — stop discarding `youtube_url`
|
||||
`_parse_single_track()` in `karaokenerds_service.py` already captures
|
||||
`{brand_name, brand_code, youtube_url, is_community}`. `check_community_versions_batch()` flattens it
|
||||
to `brands: [str]`, dropping the URL. Enrich it to also return per-version objects:
|
||||
|
||||
```python
|
||||
# per result, in addition to existing available/brands/brand_count:
|
||||
"versions": [{"brand": brand_name, "url": youtube_url}, ...]
|
||||
```
|
||||
|
||||
Dedup by `brand` (first community `youtube_url` per brand). `brands`/`brand_count` retained for
|
||||
back-compat (existing tests, any other consumers).
|
||||
|
||||
### Backend plumbing (`backend/api/routes/bulk.py`)
|
||||
- `BulkTrack`: add `versions: list[CommunityVersion] = []` where
|
||||
`CommunityVersion = {brand: str, url: str}`.
|
||||
- `AvailabilityResult`: add `versions: list[CommunityVersion] = []`.
|
||||
- `/album/tracklist`: set `t["versions"] = a["versions"]` in the enrichment loop.
|
||||
- `/availability` (text mode): pass `versions` through.
|
||||
|
||||
### Frontend (`frontend/components/job/bulk/AvailabilityBadge.tsx` → versions list)
|
||||
Replace the single wide badge with a vertical block when `available && versions.length`:
|
||||
|
||||
```
|
||||
Existing versions:
|
||||
▶ SNDL Karaoke (anchor → version.url, target=_blank rel="noopener noreferrer")
|
||||
▶ Nomad Karaoke
|
||||
▶ Reekies Karaoke
|
||||
```
|
||||
|
||||
- lucide `Youtube` icon per row.
|
||||
- **Show all versions, always** (no cap/expander) — multiple community versions of one song is rare;
|
||||
vertical layout already solves the original width problem.
|
||||
- Each row is a link opening the YouTube video in a new tab; clicking it must **not** toggle the
|
||||
track checkbox.
|
||||
- Fallback: if `available` but `versions` is empty (shouldn't happen — a community track always has a
|
||||
URL), render the existing plain "Community version exists" text.
|
||||
- Shared by album and text modes (both render this component).
|
||||
|
||||
Track-selection default logic is unchanged: tracks with `is_extra` or `available` start **unticked**
|
||||
(`shouldSelectTrack` in `types.ts`).
|
||||
|
||||
---
|
||||
|
||||
## i18n
|
||||
Per workspace policy, any `messages/en.json` change ships with all 33 locales.
|
||||
- New/changed keys (bulk namespace): `existingVersions` ("Existing versions:"),
|
||||
`usingRelease` ("Using the {label} {year} release · {count} tracks"), `changeEdition` ("Change"),
|
||||
`variantOriginal` ("Original"), `variantReissue` ("Reissue"), `variantTrackDelta` ("+{n} tracks").
|
||||
- Remove now-unused `communityExistsWithBrands` only if no other consumer references it.
|
||||
- Run `python scripts/translate.py --messages-dir ./messages --target all` before the PR.
|
||||
|
||||
## Testing
|
||||
- **Backend unit (`musicbrainz_service`):** variant grouping — multiple same-track-count editions
|
||||
collapse to one variant; differing counts → separate variants; Original = earliest; representative
|
||||
pick honors locale country preference then falls back; single-edition album → one variant.
|
||||
- **Backend unit (`karaokenerds_service`):** `check_community_versions_batch` returns `versions` with
|
||||
brand+url, deduped by brand; still returns `brands`/`brand_count`; failed lookup → empty, never
|
||||
raises. Parser test: a `<li class="track">` with a YouTube href yields `youtube_url`.
|
||||
- **Backend API (`bulk.py`):** `/album/tracklist` response includes `variants` and per-track
|
||||
`versions`; `/availability` includes `versions`. Add a regression test that `variants` and the new
|
||||
fields survive the Pydantic round-trip.
|
||||
- **Frontend:** AvailabilityBadge renders one anchor per version with correct href + `target=_blank`;
|
||||
clicking a version link does not toggle the checkbox; edition summary line + Change toggle; track
|
||||
numbers rendered from `position`; single-variant hides Change.
|
||||
|
||||
## Risk / rollback
|
||||
- Pure additive backend fields + frontend rendering swap; no job-submission or money-path changes.
|
||||
- Option 1's merge edge case (1-for-1 track swap) is visible to the user before submit — acceptable.
|
||||
- If MB shape surprises us, variant building degrades to "one variant = canonical" (current behavior).
|
||||
|
||||
## Files touched (anticipated)
|
||||
- `backend/services/musicbrainz_service.py` — variant grouping, locale country pref.
|
||||
- `backend/services/karaokenerds_service.py` — `versions` in batch result.
|
||||
- `backend/api/routes/bulk.py` — models (`BulkEditionVariant`, `CommunityVersion`, `versions`
|
||||
fields), tracklist/availability plumbing, accept `locale`.
|
||||
- `frontend/lib/api.ts` — types for variants + versions.
|
||||
- `frontend/components/job/bulk/types.ts` — `BulkTrack.versions`, variant types.
|
||||
- `frontend/components/job/bulk/BulkAlbumMode.tsx` — C-pattern edition picker, track numbers, pass locale.
|
||||
- `frontend/components/job/bulk/AvailabilityBadge.tsx` — vertical clickable versions list.
|
||||
- `frontend/messages/en.json` (+ 32 locales via translate.py).
|
||||
- Tests alongside each.
|
||||
@@ -0,0 +1,199 @@
|
||||
# PyPI 10 GB Storage-Limit Fix (karaoke-gen)
|
||||
|
||||
**Date:** 2026-06-22
|
||||
**Repo:** `karaoke-gen`
|
||||
**Status:** ✅ Resolved & verified in production
|
||||
**Shipped in:** PR #851 (v0.187.5) + a one-time PyPI release deletion
|
||||
**Related earlier prompt:** `nomadkaraoke/docs/archive/2026-06-18-pypi-storage-limit-fix-prompt.md` (the task spec this session executed; now superseded by this doc)
|
||||
|
||||
---
|
||||
|
||||
## TL;DR
|
||||
|
||||
The PyPI project `karaoke-gen` hit PyPI's **10 GB total-size cap**, so every
|
||||
`poetry publish` on merge to `main` failed with HTTP 400. We fixed it two ways:
|
||||
|
||||
1. **One-time deletion** of 42 old bloated releases (`0.172.1`–`0.182.2`),
|
||||
freeing ~4.35 GB → project down to **~6.36 GB** (3.64 GB headroom).
|
||||
2. **Wheel-only publish** going forward (`poetry build --format wheel`), which
|
||||
halves per-release cost (**104 MB → 54 MB**) by no longer publishing the
|
||||
redundant source distribution.
|
||||
|
||||
Both were needed: deletion unblocks *now*; wheel-only slows *recurrence*.
|
||||
|
||||
---
|
||||
|
||||
## Symptom
|
||||
|
||||
`Deploy - Publish to PyPI` job in `.github/workflows/ci.yml` failed on every
|
||||
push to `main`:
|
||||
|
||||
```
|
||||
HTTP Error 400: Bad Request
|
||||
Project size too large. Limit project 'karaoke-gen' total size 10 GB.
|
||||
See https://docs.pypi.org/project-management/storage-limits
|
||||
```
|
||||
|
||||
The **build** succeeded; only the **upload** was rejected (a project-wide cap,
|
||||
not a per-file or version-conflict error). Backend (Cloud Run), frontend
|
||||
(Cloudflare Pages), and the GCE encoding worker were all unaffected — only the
|
||||
public `pip install karaoke-gen` / `karaoke-gen-remote` path was blocked.
|
||||
|
||||
---
|
||||
|
||||
## Diagnosis (measured, not assumed)
|
||||
|
||||
Pulled the PyPI JSON API and summed file sizes per release:
|
||||
|
||||
- **10.711 GB across 444 releases** (over the 10 GB cap).
|
||||
- Size distribution was bimodal: **387 small releases** (~11 MB median, all
|
||||
`≤0.171.x`) and **57 fat releases** (~104 MB each = 53.7 MB wheel + 50.2 MB
|
||||
sdist) — the fat ones alone were >5.8 GB.
|
||||
- Chronological inflection: the wheel jumped **18 MB → 102 MB on 2026-04-23 at
|
||||
v0.172.1** and stayed fat for every release after.
|
||||
|
||||
### Root cause: the i18n initiative
|
||||
|
||||
The wheel/sdist bundle the Next.js static export
|
||||
(`karaoke_gen/nextjs_frontend/out/**`). When i18n shipped (Apr 2026),
|
||||
`next build` began pre-rendering the **entire app into 33 locale directories**
|
||||
(`hi/`, `th/`, `el/`, `uk/`, `ru/`, `ar/`, `ja/`, …), each ~3.4 MB of HTML.
|
||||
That's ~112 MB uncompressed — a 33× duplication of the page HTML. The shared JS
|
||||
(`out/_next`) is only 4.5 MB; the locale HTML is the bloat. Bundling this in
|
||||
**both** the wheel and the sdist, multiplied across ~57 releases, blew past the cap.
|
||||
|
||||
It was *not* "too many patch versions" — the 387 pre-i18n releases together were
|
||||
under half the total.
|
||||
|
||||
### Why the frontend can't simply be dropped from the wheel
|
||||
|
||||
The **CLI local-review server reads `out/` at runtime**
|
||||
(`karaoke_gen/lyrics_transcriber/review/server.py` → `_mount_frontend` /
|
||||
`_discover_locales`). It serves locale-prefixed routes (`/{locale}/app/jobs/local/review`)
|
||||
because the `LocaleRedirect` client component bounces the browser to
|
||||
`/{locale}/...` by browser preference, and it 404s on any locale not present on
|
||||
disk. So the wheel must keep the full `out/` tree. (The sdist, however, never
|
||||
needs it — see the fix.)
|
||||
|
||||
### Blast radius (why deletion was safe)
|
||||
|
||||
- Nothing in the workspace pins `karaoke-gen==x.y.z` (checked all
|
||||
`*.txt/*.toml/*.cfg/Dockerfile/*.sh`).
|
||||
- The GCE encoding worker pulls the wheel from **GCS**
|
||||
(`gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl`), not PyPI.
|
||||
- Backend/frontend deploys are independent of PyPI.
|
||||
- So PyPI exists only for public `pip install`. Deleting old patch versions has
|
||||
essentially zero internal blast radius.
|
||||
|
||||
---
|
||||
|
||||
## Decisions (Andrew's calls)
|
||||
|
||||
1. **Packaging:** chose wheel-only publish over trying to trim only the frontend
|
||||
out of the sdist (see "Gotcha" below — the trim wasn't a config tweak).
|
||||
2. **Deletion:** approved a **surgical** delete of the *older* fat releases,
|
||||
keeping the 15 most recent fat releases and all small historical ones —
|
||||
rather than a blunt "keep latest N" that would drop old historical versions.
|
||||
|
||||
---
|
||||
|
||||
## What we did
|
||||
|
||||
### Part 1 — Delete 42 old fat releases (irreversible; web UI)
|
||||
|
||||
**Kept:** the 15 most recent fat releases (`0.183.0`–`0.187.2`) + all 387 small
|
||||
releases (`≤0.171.x`).
|
||||
**Deleted:** the 42 fat releases `0.172.1`–`0.182.2`.
|
||||
**Result:** 10.711 GB → ~6.36 GB.
|
||||
|
||||
**How (there is no PyPI deletion API — tokens are upload-only):** drive the
|
||||
logged-in PyPI web UI via browser automation. For each version:
|
||||
|
||||
- Whole-release delete is a POST to
|
||||
`/manage/project/karaoke-gen/release/<version>/` from the modal
|
||||
`#delete_version-modal`, with two fields: a session-wide `csrf_token` (hidden)
|
||||
and `confirm_delete_version` set to the **version string** (not the project name).
|
||||
- We GET each release's manage page, scrape its `csrf_token`, verify the form
|
||||
action matches the exact version, then POST with `credentials: 'include'`,
|
||||
~400 ms apart. A hardcoded keep-list guard ensured the 15 kept versions were
|
||||
never touched. Success = the POST redirects to `/releases/`.
|
||||
|
||||
**Verification gotcha:** the aggregate `pypi.org/pypi/karaoke-gen/json` endpoint
|
||||
is Fastly-cached and lagged for minutes (still showed 444 releases after
|
||||
deletion). Verify instead via the **logged-in manage page** (live: showed
|
||||
exactly 402 releases, all deleted versions absent, all kept versions present) or
|
||||
the **per-version** endpoint `pypi.org/pypi/karaoke-gen/<v>/json` (404s
|
||||
immediately on delete).
|
||||
|
||||
### Part 2 — Wheel-only publish (PR #851, v0.187.5)
|
||||
|
||||
The sdist is dead weight: we ship a universal `py3-none-any` wheel, pip always
|
||||
installs from it, and nothing builds karaoke-gen from source. So we stopped
|
||||
building/publishing the sdist:
|
||||
|
||||
- `poetry build --format wheel` in **both** the `Package - Build & Install (Test)`
|
||||
job and the publish-feeding `Package - Build` job in `.github/workflows/ci.yml`.
|
||||
- Removed `dist/*.tar.gz` from the GitHub release attachments (it no longer exists).
|
||||
- Bumped `0.187.4 → 0.187.5`.
|
||||
|
||||
The wheel is **unchanged** — still bundles the full `out/` the CLI review server
|
||||
needs (verified: built wheel contained all 3575 `out/` entries + the 3 console
|
||||
entry points). Per-release PyPI cost: **104 MB → 54 MB**.
|
||||
|
||||
#### Gotcha: why we did NOT just trim `out/` from the sdist
|
||||
|
||||
The "obvious" fix — keep a small sdist without the frontend — does **not** work
|
||||
with a config tweak, because:
|
||||
|
||||
- `out/` is **git-tracked** under the `karaoke_gen` package, so Poetry pulls it
|
||||
into the sdist as package data.
|
||||
- **Poetry's `exclude` does not remove VCS-tracked files**, even when scoped with
|
||||
`format = "sdist"`. We tried `exclude = [{ path = ".../out/**/*", format = "sdist" }]`
|
||||
and rebuilt — the sdist still contained all 3575 `out/` entries.
|
||||
- `include` takes precedence over `exclude`, so a wheel-scoped `include` for the
|
||||
same path also kept it force-included.
|
||||
|
||||
Trimming the sdist *properly* would have required **untracking `out/` from git**
|
||||
(`git rm --cached`, gitignore it), adding a wheel-only `include`, and adding a
|
||||
frontend build+copy step (`make build-frontend`: `npm run build` →
|
||||
`cp -r frontend/out/* karaoke_gen/nextjs_frontend/out/`) to the `package-build`
|
||||
CI job — which currently has no frontend build and relies on the committed
|
||||
`out/`. That's a bigger, riskier change (CI builds the frontend in the publish
|
||||
path, large git diff, local `poetry build` would need a frontend build first).
|
||||
Wheel-only achieves the same storage win with one-line changes and saves more.
|
||||
|
||||
---
|
||||
|
||||
## Verification (production)
|
||||
|
||||
- `Deploy - Publish to PyPI` job **succeeded** on the post-merge run (no 400).
|
||||
- **0.187.5 is live on PyPI as wheel-only** — one file: the 53.7 MB
|
||||
`karaoke_gen-0.187.5-py3-none-any.whl`, no `.tar.gz`.
|
||||
- Project size ~6.36 GB (3.64 GB headroom).
|
||||
- Encoding worker VM was auto-stopped (idle, normal cost-saving). It is
|
||||
unaffected — the wheel content and the GCS wheel-upload step are unchanged; it
|
||||
pulls `karaoke_gen-current.whl` from GCS as usual on its next boot.
|
||||
|
||||
---
|
||||
|
||||
## If this recurs (runbook)
|
||||
|
||||
**Headroom math:** at 54 MB/release with ~3.64 GB headroom, that's ~65 more
|
||||
releases before the cap bites again — months at current cadence.
|
||||
|
||||
When the publish starts 400ing again:
|
||||
|
||||
1. **Measure:** sum per-release sizes from `pypi.org/pypi/karaoke-gen/json`
|
||||
(use a file + `python3`, not piped curl — output filters can mangle it).
|
||||
Identify the fat band and a safe keep-set (latest N + anything still referenced).
|
||||
2. **Delete surgically** via the browser web-UI technique in Part 1 (no API).
|
||||
Verify via the logged-in manage page / per-version JSON, NOT the cached
|
||||
aggregate JSON.
|
||||
3. **Confirm** the wheel itself hasn't re-bloated. If the frontend grew, the next
|
||||
lever (more involved) is to stop committing `out/` and host/download it instead
|
||||
of bundling — see the "Gotcha" above for the shape of that change.
|
||||
4. PyPI also accepts storage-limit-increase requests (free, slow, days–weeks) as
|
||||
a fallback if deletion isn't enough.
|
||||
|
||||
**Do not** rely on `exclude` to slim the sdist while `out/` is git-tracked — it
|
||||
won't work.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Apple Music URL → cascading download-failure alerts (2026-06-27)
|
||||
|
||||
## Incident
|
||||
|
||||
Four "New Error Pattern" alerts fired simultaneously (first seen `2026-06-27T20:32:01Z`):
|
||||
|
||||
1. `karaoke-backend` — `URL download failed: ... Unsupported URL: https://music.apple.com/...` (×2)
|
||||
2. `karaoke-backend` — `Job <ID> failed: Download failed: ... Unsupported URL: https://music.apple.com/...` (×2)
|
||||
3. `audio-separation-job` — `Exception: Failed to download audio file` (×6)
|
||||
4. `lyrics-transcription-job` — `Exception: Failed to download audio file` (×6)
|
||||
|
||||
All four were **one incident**: a single user tried to make a karaoke track from an
|
||||
Apple Music link (Hailey Whitters – "Gone Country"), submitted it twice (jobs
|
||||
`7f36304a` + `cb145971`), and clicked **Retry** once.
|
||||
|
||||
### Confirmed timeline (job `7f36304a`)
|
||||
|
||||
| Time (UTC) | Event |
|
||||
|---|---|
|
||||
| 20:23:02 | Job created from `https://music.apple.com/...` |
|
||||
| 20:23:07 | flacfetch → `Unsupported URL` → job **failed**, HTTP 500 to user |
|
||||
| 20:23:20 | User resubmits same URL → job `cb145971`, fails identically |
|
||||
| 20:23:31 | User clicks **Retry** → `POST /api/jobs/7f36304a/retry` → *"Has input audio, restarting from beginning"* |
|
||||
| 20:23:32 | Retry triggers **audio-separation-job + lyrics-transcription-job** (NOT a re-download) |
|
||||
| 20:24–20:28 | Workers find no audio in GCS → "Failed to download audio file" → Cloud Run retries each task several times → the ×6/×6 counts |
|
||||
|
||||
## Root causes (two bugs)
|
||||
|
||||
### Bug A — DRM streaming URLs accepted, then fail deep with a cryptic error
|
||||
`_validate_url` (`backend/api/routes/file_upload.py`) has a supported-domain allowlist
|
||||
but falls through to `return True` for everything else ("let yt-dlp try"). Apple Music
|
||||
/ Spotify / Tidal / Amazon Music / Deezer / Pandora are DRM-protected and can *never* be
|
||||
downloaded, so a job got created and died at the download stage with an HTTP 500 +
|
||||
"Unsupported URL".
|
||||
|
||||
### Bug B — retrying a URL job that failed *before download* fires the wrong workers
|
||||
`backend/api/routes/jobs.py` retry path used
|
||||
`elif job.input_media_gcs_path or job.url:` to "restart from beginning". A URL job whose
|
||||
download never succeeded still has `job.url` set (but **no** audio in GCS), so Retry
|
||||
jumped straight to the audio/lyrics workers. They can't find audio → "Failed to download
|
||||
audio file" → Cloud Run retries them → wasted GPU + noisy alerts. Latent for *any*
|
||||
URL-download failure (private/geo YouTube, transient flacfetch errors), not just Apple Music.
|
||||
|
||||
## Fixes
|
||||
|
||||
- **Bug A:** new `_unsupported_url_platform(url)` helper + a known-DRM-host map; the
|
||||
`create-from-url` endpoint now returns **400** with a friendly i18n message
|
||||
(`audioSearch.drmUrlUnsupported`, translated to all 33 locales) before a job is created.
|
||||
YouTube Music (`music.youtube.com`) is deliberately *not* blocked (it's downloadable).
|
||||
- The message suggests downloading the audio with a third-party tool and then
|
||||
uploading the file. For platforms with a verified downloader
|
||||
(`_DRM_DOWNLOADER_SUGGESTIONS`) it links to it — Apple Music →
|
||||
`https://am-dl.pages.dev` — via the `drmUrlUnsupportedWithLink` variant.
|
||||
- URLs in submit-error messages are now clickable via a new
|
||||
`LinkifiedText` component (`frontend/components/ui/linkified-text.tsx`), wired
|
||||
into the guided flow and the URL-tab submit error.
|
||||
- **v0.188.3:** `_DRM_DOWNLOADER_SUGGESTIONS` now maps each platform to a *list*
|
||||
of downloader links (Apple Music → `am-dl.pages.dev`, `aplmate.com`; Spotify →
|
||||
`spotdown.org`, `spotmate.online`). Platforms without a known tool (Tidal,
|
||||
Amazon Music, Deezer, Pandora) fall back to a Google search link for
|
||||
"`<platform> downloader`" via the new `drmUrlUnsupportedSearch` message. The
|
||||
`_drm_unsupported_detail(locale, platform)` helper builds the right message;
|
||||
`LinkifiedText` renders the multiple URLs as clickable links (no frontend
|
||||
change needed).
|
||||
- **v0.188.3 (early validation):** the guided flow previously only surfaced the
|
||||
DRM rejection at *final submit* — after the user walked the whole flow. Added
|
||||
a lightweight `POST /api/jobs/validate-url` endpoint (reuses
|
||||
`_unsupported_url_platform` + `_drm_unsupported_detail`, single source of
|
||||
truth) that `AudioSourceStep`'s "Use this URL" button now calls, showing the
|
||||
guidance immediately (with a "Checking…" spinner) and blocking advancement.
|
||||
Fails open on network error — the final submit still validates server-side.
|
||||
- **Bug B:** the retry "restart from beginning" branch is now gated on
|
||||
`job.input_media_gcs_path` only. URL jobs without downloaded audio fall through to the
|
||||
existing clean **"resubmit"** 400 instead of firing doomed workers — matching the
|
||||
endpoint's documented intent ("re-runs from beginning if input audio exists").
|
||||
|
||||
## Tests
|
||||
|
||||
- `TestUnsupportedDrmUrl` (`test_file_upload.py`) — detection across Apple Music / Spotify
|
||||
/ Tidal / Amazon Music / Deezer / Pandora (+ subdomains); YouTube/YouTube Music/Vimeo/
|
||||
SoundCloud/generic/None not flagged.
|
||||
- `TestRetryUrlJobWithoutDownload` (`test_routes_jobs.py`) — URL job without audio → 400
|
||||
resubmit + **no** workers scheduled; URL job *with* audio in GCS → restarts + workers
|
||||
scheduled.
|
||||
|
||||
## Not done (deliberately out of scope)
|
||||
|
||||
- **Re-download on retry for URL jobs.** There is no worker that re-downloads a *generic*
|
||||
`job.url` (the download is inline in `create-from-url`; `audio_download_worker` only
|
||||
handles audio-search sources: YouTube/RED/OPS/Spotify-by-id). For transient URL failures
|
||||
the user must resubmit. A future enhancement could extract the inline download into a
|
||||
reusable worker so Retry can re-fetch.
|
||||
- **Worker-side hard exit.** `audio_worker.py` detects the bad state but logs
|
||||
"Continue anyway"; fixing the retry trigger (Bug B) removes the amplification at its
|
||||
source, so the worker guard was left as-is to contain risk.
|
||||
@@ -0,0 +1,255 @@
|
||||
# Divebar Index Filename-Parsing Fix — Plan
|
||||
|
||||
_Worktree: `karaoke-gen-divebar-index-parsing` · branch `feat/sess-20260628-0511-divebar-index-parsing`_
|
||||
_Picks up: HANDOFF-divebar-mirror-parsing.md (kjbox side shipped v0.41.1; this is the upstream index fix)_
|
||||
|
||||
## Problem (refined by live data, not just the handoff examples)
|
||||
|
||||
The Divebar Drive→BigQuery indexer (`infrastructure/functions/divebar_mirror/filename_parser.py`,
|
||||
Cloud Function `divebar-mirror`) mis-parses community-brand filenames. kjbox cross-references
|
||||
mirror files on `(normalized artist, normalized title)` + brand, so bad parses → mirror files
|
||||
never surface in the rotation selector even though the file is in GCS.
|
||||
|
||||
### Measured state (BigQuery `karaoke_decide.divebar_catalog`, 50,046 rows)
|
||||
|
||||
| Signal | Count | Meaning |
|
||||
|---|---|---|
|
||||
| null `artist` | 164 (0.3%) | rare |
|
||||
| null `title` | 0 | — |
|
||||
| **null `brand_code`** | **18,437 (37%)** | biggest visible gap |
|
||||
| `artist` is 2–6 all-caps/digits | 1,908 | brand-code-as-artist mis-split (e.g. `CKK`, `EBK`) |
|
||||
| `artist` starts with `(` | 3,051 | `(SDK) Artist` prefix (Sandell) |
|
||||
| `title` contains ` - ` | 5,947 | unstripped ` - Brand` suffix / disc-id-in-title |
|
||||
| `title` ends in `[..]`/`(..)` | 2,583 | `[DJ Sauly Karaoke]`, `[Karaoke]`, etc. |
|
||||
|
||||
Current xref coverage: 90,719 matches, 17,261 KN songs, **23,318 / 50,046 divebar files matched (47%)**.
|
||||
|
||||
> Reframe vs handoff: `artist`/`title` are rarely *null*, but **mis-splits + polluted titles**
|
||||
> are common and silently defeat the EXACT xref (`LOWER(TRIM(kn.Title)) = db.title_normalized`).
|
||||
> Every polluted title misses the join. That + missing `brand_code` is the real lever.
|
||||
|
||||
### Root cause: parser has only 3 rigid patterns and never uses the folder brand to clean
|
||||
|
||||
`parse_filename(name, brand_folder)`:
|
||||
1. `^CODE-### - Artist - Title` (disc-id prefix) — works.
|
||||
2. `... (BrandTag)$` — strips ANY trailing paren (so it also eats `(KARAOKE)`, `(Live)`,
|
||||
`(Banda Remix)` → clobbers `brand_name`), and never sets `brand_code`.
|
||||
3. `Artist - Title` fallback split on ` - `.
|
||||
|
||||
It ignores `[...]` brackets, ` - Brand` dash-suffixes, disc-id *suffixes*, `(CODE) ` prefixes,
|
||||
and `CODE - ` (no-number) prefixes. The folder name (reliable brand) is passed in but only used as
|
||||
a fallback `brand_name` — **never to strip the brand token before splitting artist/title**.
|
||||
`_KARAOKE_SUFFIXES` is applied only to the normalized fields, never the display `title`.
|
||||
|
||||
Note: `build_rows` writes `brand` = folder (always, reliable) and only consumes `brand_code` from
|
||||
the parser (not `brand_name`) — so Pattern-2's `brand_name` clobbering is harmless. The fields that
|
||||
matter from the parser are **artist, title, brand_code, disc_id**.
|
||||
|
||||
## Real-world conventions (gold fixtures, observed live)
|
||||
|
||||
| Convention | Example filename | Brand (folder) | Correct artist / title |
|
||||
|---|---|---|---|
|
||||
| disc-id prefix (OK today) | `FATBIRD-163 - Incubus - I Miss You.zip` | Fatbird | Incubus / I Miss You |
|
||||
| code prefix, no number | `CKK - Buoys, The - Timothy.zip` | Cereal Killer Karaoke | Buoys, The / Timothy |
|
||||
| `(CODE)` paren prefix | `(SDK) (G)I-DLE - Queencard.cdg` | Sandell Karaoke | (G)I-DLE / Queencard |
|
||||
| `(Brand)` paren suffix (OK today) | `10 Years - Fix Me (BellySings).mp4` | BellySings | 10 Years / Fix Me |
|
||||
| `[Brand]` bracket suffix | `3rd Bass - Green Eggs And Swine [DJ Sauly Karaoke].zip` | DJ Sauly Collection | 3rd Bass / Green Eggs And Swine |
|
||||
| ` - Brand` dash suffix | `100 Gecs - Last Train To Awesometown - Rock Solid Karaoke.zip` | Rock Solid Karaoke | 100 Gecs / Last Train To Awesometown |
|
||||
| ` - CODE` dash suffix | `Akon - Right Now (Na Na Na) - EBK.avi` | ForteKaraoke Discord | Akon / Right Now (Na Na Na) |
|
||||
| disc-id *suffix* | `Against Me - Wagon Wheel - SOKC-0306 - (KARAOKE).zip` | Steve-O Karaoke Cult | Against Me / Wagon Wheel |
|
||||
| disc-id suffix no dash | `Angelcorpse - Wolflust - ATG0014.zip` | ATG Karaoke | Angelcorpse / Wolflust |
|
||||
| `[Karaoke]` generic tag | `Bill Murray - Star Wars [Karaoke].mp4` | Mobile Karaoke Unit | Bill Murray / Star Wars |
|
||||
| mixed-case brand prefix | `Lopenash-002 - Dexter's Laboratory - Breathe in The Sunshine.mp4` | Lopenash | Dexter's Laboratory / Breathe in The Sunshine |
|
||||
| clean (only brand_code missing) | `A Tribe Called Quest - Lyrics To Go.avi` | WIZZYOKE | A Tribe Called Quest / Lyrics To Go |
|
||||
|
||||
**Guard cases (must NOT over-strip):** `(G)I-DLE`, `R.E.M.`, artist `311`; titles `(Live)`,
|
||||
`(Banda Remix)`, `(Single Version 2 WBV)`, `(99X Live)`, `[Acoustic]` must survive.
|
||||
|
||||
## Design — folder-brand-aware parser
|
||||
|
||||
Core principle (per handoff): **the top-level folder reliably names the brand; use it to recognise
|
||||
and strip the brand token wherever it sits, then split the remainder into artist/title.**
|
||||
|
||||
`parse_filename(name, brand_folder)` rewrite, in order:
|
||||
|
||||
1. **Strip generic karaoke tags** from the display name: trailing `(karaoke|instrumental|backing
|
||||
track|no vocals|kj version|with vocals|demo)` in either `()` or `[]` (reuse `_KARAOKE_SUFFIXES`,
|
||||
now applied to display too).
|
||||
2. **Build brand matchers from `brand_folder`**: normalized full name, and name with trailing
|
||||
descriptors removed (`karaoke`, `collection`, `cdg files`, `discord`, `videos`, `mp4`,
|
||||
`zipped mp3+g`, etc.); plus an acronym of significant words (Cereal Killer Karaoke→CKK,
|
||||
Steve-O Karaoke Cult→SOKC, ATG Karaoke→ATG).
|
||||
3. **Strip the brand token from whichever position it occupies — each gated so we only remove a
|
||||
*known* brand, never song text:**
|
||||
- disc-id **prefix** `^CODE[-\s]?### - ` → `brand_code`, `disc_id`. (existing)
|
||||
- disc-id **suffix** ` - CODE-### ` / ` CODE#### ` at end, gated on `CODE` ≈ folder acronym/known → `brand_code`,`disc_id`.
|
||||
- `[Brand]`/`(Brand)` **bracket/paren suffix** where content ≈ folder brand → strip; `brand_code` from folder map.
|
||||
- ` - Brand` **dash suffix** where the last ` - ` segment ≈ folder brand → strip.
|
||||
- `(CODE) ` **paren prefix** (≤6 chars, alnum) with content after → strip; `brand_code`=CODE.
|
||||
- `CODE - ` / `Folder-### - ` **prefix** where token ≈ folder acronym/name → strip; `brand_code`.
|
||||
4. **Split remainder** on ` - ` → artist = parts[0], title = join(parts[1:]); strip any leftover
|
||||
generic karaoke tag from title.
|
||||
5. **brand_code resolution order:** captured-during-strip → small curated **folder→code map** →
|
||||
null. `brand` always = folder (unchanged in `build_rows`).
|
||||
|
||||
### Brand registry decision (diverges from handoff)
|
||||
|
||||
Handoff suggested importing kjbox `version_priority.py` `COMMUNITY_BRANDS`. **Rejected** because:
|
||||
(a) cross-repo import isn't viable inside a GCP Cloud Function, (b) that registry is **incomplete**
|
||||
vs the 63 real Divebar folder brands (no Cereal Killer/DJ Sauly/Rock Solid/Sandell), and (c) it
|
||||
**conflicts** — registry maps `SDK`→SNDL but Sandell's folder uses `(SDK)`. Instead: derive
|
||||
`brand_code` from the in-filename token / folder, and keep a **small curated `folder→KN-code` map**
|
||||
seeded from the actual KN community codes that intersect Divebar folders (FBK, BELLY, DJS, C11K,
|
||||
PLAY, REEKIES, HALJAM, NOMAD, FAKEY, CC, …). kjbox's read-time `canonical_brand_for_match` already
|
||||
folds codes/names, so the index doesn't need canonical output — just resolvable.
|
||||
|
||||
## Refined design from full 63-brand data (read-only export)
|
||||
|
||||
Exported all 50,046 rows + per-brand samples + KN community codes to scratchpad. Key refinement:
|
||||
**artist is wrong-but-rarely-null; the measurable gaps are polluted titles + null brand_code.**
|
||||
Brands needing a fix fall into these convention buckets (✅ already-correct buckets only need the
|
||||
brand_code map):
|
||||
|
||||
| Bucket | Brands (examples) | Fix |
|
||||
|---|---|---|
|
||||
| disc-id PREFIX `CODE-### - A - T` | Nomad, Imperfekt, Play, Gnome, Fakey, C11K, Reekies, Fatbird, … | works today — **preserve** |
|
||||
| disc-id PREFIX space-sep `CODE-#### Artist - T` | Potos (`RABZ-0001 The Seatbelts - …`) | allow space (not just ` - `) after disc-id |
|
||||
| disc-id PREFIX mixed-case/digit-lead `Tok-### - …` | Lopenash (`Lopenash-002 -`), 7uLpA (`7uLpA-0003 -`) | match when prefix token ≈ folder name |
|
||||
| leading track-no after disc-id `CODE-### - NN - A - T` | Mix Tape (`MIX001 - 02 - …`) | drop leading pure-numeric segment |
|
||||
| disc-id SUFFIX `A - T - CODE-####` | It Might Be (IMBK), Steve-O (SOKC), ATG (ATG####) | **strip trailing disc-id (unconditional), set brand_code/disc_id** |
|
||||
| `(CODE)` paren PREFIX | Sandell (`(SDK) A - T`) | strip leading `(short-alnum) ` |
|
||||
| `CODE - ` PREFIX no number | Cereal Killer (`CKK - A - T`), Nerdy (`TNSK -`), Crossfire (`Crossfire - A - T`) | strip when token ≈ folder acronym/name |
|
||||
| `[Brand]` bracket SUFFIX | DJ Sauly (`… [DJ Sauly Karaoke]`) | strip bracket suffix gated on folder-name match |
|
||||
| `(Brand)` paren SUFFIX | BellySings (`… (BellySings)`), Popeoke (`(popeoke)`/`[popeoke]`) | already strips paren; add bracket + folder-gate |
|
||||
| ` - Brand` dash SUFFIX | Rock Solid (`… - Rock Solid Karaoke`), Forte (`… - EBK`) | strip last ` - ` segment gated on folder-name match (Forte EBK via per-folder token) |
|
||||
| generic karaoke tag `[Karaoke]`/`(Karaoke HD)` | Mobile, Funbox, Matt Joy, Steve-O | strip generic tag from **display** title (currently only normalized), tolerate trailing words |
|
||||
| clean `Artist - Title`, only brand_code missing | Funbox, WIZZYOKE, Brilliant Trash, Monster Tracks, KaddaOK, April's Choice | **curated folder→code map only** |
|
||||
|
||||
### Parser algorithm (folder-brand-aware), ordered
|
||||
|
||||
1. strip extension; `format = detect_format`.
|
||||
2. strip generic karaoke tags from display name (both `()`/`[]`, token optionally followed by words).
|
||||
3. brand-token strip, first match wins, each sets `brand_code`/`disc_id` and removes the token:
|
||||
(a) disc-id PREFIX `^CODE[-\s]?NUM` followed by ` - ` **or** whitespace; CODE all-caps **or** ≈ folder token (covers Lopenash/7uLpA/Potos);
|
||||
(b) disc-id SUFFIX `[-\s]\s*CODE-?NUM$` — **unconditional** (trailing `ABCD-0123` is a strong signal);
|
||||
(c) `[Brand]`/`(Brand)` SUFFIX gated on `norm(content) ≈ norm(folder)`;
|
||||
(d) ` - Brand` dash SUFFIX gated on `norm(last segment) ≈ norm(folder)` (or per-folder token);
|
||||
(e) `(CODE)` paren PREFIX (≤6 alnum) with content after;
|
||||
(f) `CODE - ` PREFIX (no number) gated on `CODE ≈ folder acronym/name`.
|
||||
4. split remainder on ` - ` → artist=parts[0], title=join(rest); drop a leading pure-numeric segment;
|
||||
1 part → title only.
|
||||
5. strip any leftover generic karaoke tag from title.
|
||||
6. `brand_code` = captured → **curated folder→code map** → null. `brand` always = folder (in `build_rows`).
|
||||
|
||||
**Guards (must survive):** `(G)I-DLE`, `R.E.M.`, artist `311`, titles `(Live)`, `(Banda Remix)`,
|
||||
`(Single Version 2 WBV)`, `(99X Live)`, `[Acoustic]`. Folder-gating + "disc-id has digits" +
|
||||
"prefix code ≈ folder" are what prevent eating these.
|
||||
|
||||
### Curated folder→KN-code map (minimal, high-confidence only)
|
||||
|
||||
Aligned to actual KN community `Brand` codes (so the secondary brand_match xref can also fire);
|
||||
brands with no confident KN code are left null (artist/title fix already surfaces them via the
|
||||
primary 0.95 exact xref):
|
||||
|
||||
```
|
||||
Funbox Karaoke→FBK · Sandell Karaoke→SDK · BellySings Karaoke→BELLY · DJ Sauly Collection→DJS
|
||||
PlayKaraoke→PLAY · Reekies Karaoke→REEKIES · Cereal Killer Karaoke→CKK · WIZZYOKE→WIZZY
|
||||
Brilliant Trash Karaoke→BTRASH · Lopenash→LOPE · Monster Tracks→MTRAX · Popeoke→POPE
|
||||
KaddaOK→KADDA · Potos Power Plant Productions→PPPP · April's Choice Karaoke→APRIL
|
||||
The Nerdy Singer Karaoke→TNS · Mobile Karaoke Unit→MKU · ATG Karaoke - Zipped MP3+G→ATG
|
||||
It Might Be Karaoke→IMBK
|
||||
```
|
||||
(Map *overrides* a prefix-derived code where they differ, e.g. Play `PLK`→`PLAY`, Reekies
|
||||
`REEK`→`REEKIES`; `disc_id` keeps the literal prefix.) Skipped (no confident code): Rock Solid,
|
||||
Steve-O (uses SOKC, not a KN code — set from disc-id suffix anyway), ForteKaraoke (EBK≠KN), Gnome,
|
||||
7uLpA, Crossfire, Monster… handled where a code exists.
|
||||
|
||||
## Work breakdown
|
||||
|
||||
**Phase 1 — Parser rewrite (TDD, primary deliverable).** New `tests/unit/test_divebar_filename_parser.py`
|
||||
with all gold fixtures + guard cases (add function dir to `sys.path`; parser deps are stdlib only).
|
||||
Rewrite `filename_parser.py` to the design above. Keep `normalize_for_search`, `detect_format`,
|
||||
`should_index_file` behaviour. Keep existing `test_divebar_index_builder.py` green.
|
||||
|
||||
**Phase 2 — brand_code coverage.** Curated `folder→code` map + disc-id-suffix / leading-token
|
||||
capture. Target: cut null `brand_code` well below 37% on the offline harness.
|
||||
|
||||
**Phase 3 — Deploy enablement (infra papercut).** The module points the function at a *static*
|
||||
source object (`divebar-mirror-source.zip`) with no content hash, so overwriting it won't make
|
||||
`pulumi up` redeploy. Switch `modules/divebar_mirror.py` to `pulumi.FileArchive` + `BucketObject`
|
||||
(the proven pattern in `modules/runner_manager.py`) so new code deploys on `pulumi up`. (Optional
|
||||
but needed for the fix to ship cleanly; Andrew runs the apply.)
|
||||
|
||||
**Phase 4 — Offline validation harness + prod verify.**
|
||||
- Export distinct `(filename, brand)` from BQ (read-only) → run NEW parser locally over all 50k →
|
||||
report before/after: % null brand_code, % artist-looks-like-code, % title-has-dash, % title-ends-bracket,
|
||||
plus a spot-check sample. **Proves improvement with zero prod writes** (fits read-only ADC).
|
||||
- After Andrew deploys + triggers `divebar-mirror-daily` then `divebar-xref-rebuild-daily`
|
||||
(MERGE preserves `gcs_path`; no Drive→GCS re-sync needed): re-measure xref `db_files` matched
|
||||
(baseline 23,318/50,046) and the live `incubus admiration` repro.
|
||||
|
||||
## Constraints / notes
|
||||
|
||||
- **My ADC is read-only** (workspace memory `feedback_claude_readonly_adc`): I can read BQ and run
|
||||
the offline harness, but **cannot** `pulumi up`, upload source, or run scheduler jobs. Andrew
|
||||
deploys + re-indexes; I validate offline first and via BQ reads after.
|
||||
- Re-index re-parses ALL files (full Drive listing → MERGE by `file_id`), so existing rows are
|
||||
corrected in place; `gcs_path` is preserved.
|
||||
- Version bump `pyproject.toml`; this is infra/function code (no i18n, no frontend).
|
||||
- Tests: `make test` (or targeted `pytest tests/unit/test_divebar_filename_parser.py`).
|
||||
|
||||
## Results (offline harness over all 50,046 live rows)
|
||||
|
||||
| metric | before | after | delta |
|
||||
|---|---|---|---|
|
||||
| null brand_code | 18,437 (37%) | 1,619 (3%) | **−16,818** |
|
||||
| title contains ` - ` | 5,947 | 2,523 | −3,424 (residual mostly legit multi-part titles) |
|
||||
| artist looks like a code | 1,908 | 1,400 | −508 (residual are real bands: ACDC, KISS, ABBA, U2…) |
|
||||
| null artist | 164 | 179 | +15 (medleys / single-field — acceptable) |
|
||||
| rows with changed artist/title | — | 13,348 (26.7%) | — |
|
||||
|
||||
Per-brand `brand_code` null% collapsed to ~0% for every broken brand (Sandell, BellySings,
|
||||
DJ Sauly, Cereal Killer, Steve-O, WIZZYOKE, Lopenash, ForteKaraoke, ATG, Mobile, 7uLpA, …);
|
||||
Rock Solid stays null by design (no confident KN code).
|
||||
|
||||
**Xref lift (replaying the live `_rebuild_xref` EXACT join):** Divebar files that match a KN
|
||||
song **20,802 → 23,394 (+2,592, +12.5%)** — i.e. that many more mirror files now surface in kjbox.
|
||||
|
||||
### BUNDLED: the xref SQL normalization asymmetry (fixed in this PR)
|
||||
|
||||
`_rebuild_xref` joined `LOWER(TRIM(kn.Artist)) = db.artist_normalized`, but `db.artist_normalized`
|
||||
is produced by `normalize_for_search` (strips diacritics, a leading "the ", and all punctuation)
|
||||
while the KN side got only `LOWER(TRIM(...))` — so most rows could never match. **Fix:** a new
|
||||
`_norm_sql(col)` helper routes **both** sides through one identical BigQuery expression
|
||||
replicating `normalize_for_search` (NFD + drop `\p{Mn}`, lower/trim, strip trailing karaoke tag,
|
||||
strip leading "the ", drop non-`\p{L}\p{N}_\s`, collapse whitespace). Applied to the exact join,
|
||||
the brand_match join, and the NOT EXISTS de-dup.
|
||||
|
||||
**Validated read-only against live BigQuery** (the real `_norm_sql`): the SQL normalization
|
||||
reproduces the Python `normalize_for_search` baseline exactly (32,496 on current data), and the
|
||||
**full new union already matches 33,449 distinct Divebar files on current (old-parse) data vs
|
||||
production's 23,318 — +10,131 from symmetry alone**, before any re-index. After the parser
|
||||
re-index the exact portion lifts toward ~37,910, compounding further. Residual misses after the parser fix are tiny and documented: `(WTF Karaone)` typo
|
||||
(~6), `SOKC-O104` letter-O typo (~21), `GGZ007-02,2` comma in disc-id (~16), `RVZ-033.d` (~5).
|
||||
|
||||
## Status: IMPLEMENTED
|
||||
|
||||
- `filename_parser.py` rewritten folder-brand-aware; `tests/unit/test_divebar_filename_parser.py`
|
||||
added (48 cases, green); existing `test_divebar_index_builder.py` still green.
|
||||
- `divebar_lookup/main.py` `_rebuild_xref` rewritten to normalize both sides via `_norm_sql`;
|
||||
3 guard tests added to `test_divebar_lookup` (`test_main.py`). All 64 divebar tests green.
|
||||
- `modules/divebar_mirror.py` switched to `pulumi.FileArchive` + `BucketObject` with
|
||||
generation-pinning so `pulumi up` actually redeploys new function code; `deploy.sh` note updated.
|
||||
- Version bumped 0.188.3 → 0.188.4.
|
||||
- **Deploy (Andrew, read-only ADC blocks me):** `cd infrastructure && pulumi up` (redeploys both
|
||||
`divebar-mirror` and `divebar-lookup`), then trigger scheduler jobs `divebar-mirror-daily`
|
||||
(re-parse → MERGE, preserves `gcs_path`) then `divebar-xref-rebuild-daily`. Then re-measure xref
|
||||
`db_files` and the live `incubus admiration` repro. (Order matters: re-index before xref rebuild.)
|
||||
|
||||
## Open questions for Andrew
|
||||
|
||||
1. **Include Phase 3** (FileArchive deploy fix) in this PR, or keep PR parser-only and handle deploy
|
||||
mechanics separately?
|
||||
2. **brand_code map scope** — minimal (only folders that clearly map to a KN community code) vs
|
||||
broader best-effort? Minimal is safer (no mismaps); recommend minimal.
|
||||
3. Confirm **you'll run the `pulumi up` + scheduler re-index** after merge (I can't with read-only ADC).
|
||||
@@ -0,0 +1,81 @@
|
||||
# Prod Error Triage & Fix — 2026-07-01
|
||||
|
||||
Batch of Discord error alerts, grouped, root-caused, and fixed.
|
||||
|
||||
## Group A (PRIMARY — job-breaking, today): render/preview crash on untimed lyrics
|
||||
|
||||
### Symptoms (all job `231806a4`, "Nelly Furtado - Maneater")
|
||||
- `Failed to generate outputs: unsupported format string passed to NoneType.__format__` (×4)
|
||||
- `Job 231806a4: Failed to generate preview video: unsupported format string passed to NoneType.__format__` (×2)
|
||||
- `Video render failed: Encoding job 231806a4 failed: '<' not supported between instances of 'NoneType' and 'float'` (×3, retried 3× then job failed)
|
||||
|
||||
### Root cause
|
||||
The saved corrections JSON (`gs://.../jobs/231806a4/lyrics/corrections_updated.json`) had
|
||||
**all 50 segments and all 364 words with `start_time`/`end_time` = `null`.**
|
||||
|
||||
The lyrics were Danish custom parody lyrics ("Vor's veninde er blevet gift") replacing the
|
||||
original Maneater transcription. Segment IDs (`segment-N-<epoch>`) trace to the **LyricsSynchronizer's
|
||||
"Edit Lyrics" sub-modal** (`LyricsSynchronizer.tsx:334 handleSaveEditedLyrics`), which creates
|
||||
segments/words with `start_time: null, end_time: null` — an *expected intermediate state* that the
|
||||
user must resolve by tap-syncing. The user saved + triggered preview/render **without synchronizing**,
|
||||
so every timing was null.
|
||||
|
||||
The pipeline then crashes cryptically instead of rejecting cleanly. Both paths funnel through
|
||||
`OutputGenerator.generate_outputs → SegmentResizer.resize_segments → ASS generation`, which has
|
||||
**many** None-unsafe timing operations:
|
||||
- `segment_resizer.py:540/550` — `f"time={segment.start_time:.2f}..."` → format crash (preview, newer Cloud Run wheel dies here first, at a *debug log line*).
|
||||
- `segment_resizer.py:149` — `segment.end_time >= seg_start` (segment-level None not handled; only word-level is).
|
||||
- `ass/lyrics_line.py:70/97` — `segment.start_time - previous_end_time >= threshold`.
|
||||
- `ass/lyrics_screen.py:245/250` — `min/max(... .start_time/.end_time ...)`.
|
||||
- `ass/section_detector.py:36` — `segments[0].start_time >= gap_threshold`.
|
||||
- `_is_in_instrumental_section` — `segment.start_time < inst_end` → **exact `'<' NoneType vs float`** the GCE encoder hits (encoder runs its own pinned wheel and gets deeper before crashing).
|
||||
|
||||
Per-site None-guarding is whack-a-mole. The correct fix is a **validation gate** at the shared choke
|
||||
points that rejects untimed lyrics with a clear, actionable message — untimed custom/replaced lyrics
|
||||
*cannot* produce a correct karaoke video (auto-distribution would be meaningless against different
|
||||
vocals), so blocking-with-guidance is the right product behavior.
|
||||
|
||||
### Fix
|
||||
1. **Shared validator** `karaoke_gen/lyrics_transcriber/output/timing_validation.py` — new
|
||||
`validate_segment_timing(segments) -> None` raising `LyricsTimingError` (with count + first
|
||||
offending line) when any segment/word has `None` start/end. Called at the top of
|
||||
`OutputGenerator.generate_outputs()`. Covers preview (Cloud Run) + local render + encoder (once its
|
||||
wheel updates).
|
||||
2. **Backend render gate** — call the validator in `render_video_worker.py` right after the
|
||||
`correction_result` is loaded (~line 363), *before* any render/encoder dispatch. This stops the
|
||||
encoder from ever being sent an untimed job **now**, without waiting for an encoder-wheel redeploy.
|
||||
Fail the job with a clear user-facing message.
|
||||
3. **Preview endpoint** `review.py generate_preview_video` — map `LyricsTimingError` to a clean
|
||||
422 with a "synchronize your lyrics first" message (instead of the current cryptic 500).
|
||||
4. **Defense-in-depth** — make `_log_input_segments`/`_log_output_segments` None-safe (a debug log
|
||||
must never crash a job); make `_sanitize_segment_timings` tolerate None segment timing.
|
||||
5. **Frontend guard (prevention/UX)** — in the review UI, block "Generate preview" and
|
||||
"Complete/Submit" when untimed words exist, with a message pointing the user to synchronize.
|
||||
|
||||
## Group B (cheap robustness win): GDrive brand_code cleanup incomplete
|
||||
|
||||
- `Error cleaning up Google Drive for job 94ee69f3: GDrive brand_code search incomplete: 2/3 subfolder(s) failed`
|
||||
- Underlying per-subfolder errors: `[SSL: UNEXPECTED_EOF_WHILE_READING]`, `[Errno 32] Broken pipe`
|
||||
— transient Drive API connection drops.
|
||||
- `gdrive_service.py:462` correctly refuses to declare "clean" on partial results (prevents brand-code
|
||||
recycling) — behavior is right, but transient drops shouldn't reach that raise.
|
||||
|
||||
### Fix
|
||||
Wrap the per-subfolder `files().list().execute()` (`gdrive_service.py:438`) in a small
|
||||
retry-with-backoff for transient connection errors, so single SSL/broken-pipe blips self-heal.
|
||||
|
||||
## Group C (transient — document only, no code change)
|
||||
|
||||
- **`request_audit_error` + "Exception in ASGI application"** (same event): Firestore
|
||||
`The referenced transaction has expired or is no longer valid` on
|
||||
`/api/admin/rate-limits/blocklists/allowlisted-domains` (`email_validation_service.py:754`).
|
||||
Count 1, admin-only, transient (likely a cold/paused instance mid-transaction). Admin can retry.
|
||||
Not worth added complexity.
|
||||
- **`Default STARTUP TCP probe failed ... DEADLINE_EXCEEDED`**: single slow cold start at 12:07:30;
|
||||
**retry succeeded** at 12:10. Pure Cloud Run infra noise, no code issue.
|
||||
|
||||
## Testing
|
||||
- Unit: `validate_segment_timing` raises on None segment/word timing, passes on valid; `_log_input_segments`
|
||||
no longer crashes on None; gdrive retry recovers from transient then succeeds / raises after exhaustion.
|
||||
- Frontend: Jest test that preview/complete is blocked when untimed words present.
|
||||
- Regression fixture built from the real 231806a4 corrections shape (all-null timings).
|
||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user