mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
Compare commits
No files matched your search
+111
-5
@@ -959,6 +959,11 @@ jobs:
|
||||
REPOSITORY: karaoke-repo
|
||||
BASE_IMAGE_NAME: karaoke-backend-base
|
||||
APP_IMAGE_NAME: karaoke-backend
|
||||
# GPU image for audio worker (L4 in us-east4)
|
||||
GPU_REGISTRY: us-east4-docker.pkg.dev
|
||||
GPU_REPOSITORY: karaoke-backend-gpu
|
||||
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
|
||||
GPU_APP_IMAGE_NAME: karaoke-backend
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
run: |
|
||||
@@ -1146,6 +1151,7 @@ jobs:
|
||||
|
||||
- name: Wait for service health
|
||||
id: health
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
@@ -1174,6 +1180,7 @@ jobs:
|
||||
- name: Deep health check - real encode test
|
||||
if: steps.health.outputs.healthy == 'true'
|
||||
id: encode-test
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
@@ -1225,7 +1232,7 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
if: failure()
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
@@ -1317,7 +1324,9 @@ jobs:
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
run: |
|
||||
gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
|
||||
|
||||
# ============================================
|
||||
# Docker Build with BuildKit + Registry Cache
|
||||
@@ -1436,6 +1445,88 @@ jobs:
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# Same pattern as base image: hash check → rebuild if needed
|
||||
# GPU image lives in us-east4 (co-located with GPU instances)
|
||||
# ============================================
|
||||
|
||||
- name: Calculate GPU base image hash
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
|
||||
# Using poetry.lock instead of pyproject.toml so that version-only bumps
|
||||
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
EXISTING_HASH=""
|
||||
|
||||
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
|
||||
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
|
||||
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
|
||||
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
|
||||
TOKEN=$(gcloud auth print-access-token)
|
||||
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
|
||||
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
|
||||
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
|
||||
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
|
||||
else
|
||||
echo "⚠️ No existing GPU base image found in registry - will build"
|
||||
fi
|
||||
|
||||
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
|
||||
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build and push GPU base image (if needed)
|
||||
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 45
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.gpu-base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
|
||||
provenance: false
|
||||
|
||||
- name: Build and push GPU app image
|
||||
timeout-minutes: 10
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
build-args: |
|
||||
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
@@ -1465,22 +1556,37 @@ jobs:
|
||||
--min-instances 4 \
|
||||
--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,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,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" \
|
||||
--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" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key: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,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
|
||||
echo "📦 Updating Cloud Run Jobs..."
|
||||
|
||||
# Video encoding job - runs video worker to completion, immune to service deployments
|
||||
# Video encoding job (CPU, us-central1)
|
||||
gcloud run jobs update video-encoding-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
# Audio separation job (GPU, us-east4) — uses GPU image
|
||||
gcloud run jobs update audio-separation-job \
|
||||
--image "$GPU_IMAGE" \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
echo "✅ Cloud Run Jobs updated"
|
||||
|
||||
- name: Verify deployment and version
|
||||
|
||||
@@ -67,6 +67,16 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
# testmail.app is used for E2E testing but gets flagged as disposable
|
||||
# by external APIs. Ensure it's in the allowlist before the test runs.
|
||||
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: failed to allowlist domain (may already exist)"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
|
||||
@@ -232,3 +232,4 @@ flacfetch
|
||||
|
||||
# Test output directories
|
||||
Rick Astley*/
|
||||
.superpowers/
|
||||
+9
-1
@@ -26,7 +26,15 @@ COPY backend /app/backend
|
||||
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
RUN pip install --no-cache-dir -e .
|
||||
# GPU images (MODEL_DIR set in base): use --no-deps to preserve pinned torch cu126
|
||||
# and audio-separator[gpu]. Without this, pip upgrades torch to cu130 (breaks CUDA
|
||||
# on Cloud Run L4 drivers) and reinstalls audio-separator[cpu] (breaks GPU ONNX).
|
||||
# CPU images: normal install resolves all deps from pyproject.toml.
|
||||
RUN if [ -n "$MODEL_DIR" ]; then \
|
||||
pip install --no-cache-dir --no-deps -e .; \
|
||||
else \
|
||||
pip install --no-cache-dir -e .; \
|
||||
fi
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models
|
||||
# This image is rebuilt only when deps or models change (infrequently).
|
||||
#
|
||||
# Build with: gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
|
||||
# Or manually: docker build -f backend/Dockerfile.gpu-base -t karaoke-backend-gpu-base .
|
||||
#
|
||||
# Layer caching strategy:
|
||||
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
|
||||
# 2. CUDA library path configuration
|
||||
# 3. pyproject.toml + package stubs (changes with dep updates)
|
||||
# 4. pip install karaoke-gen deps + audio-separator[gpu] (slow, cached unless pyproject.toml changes)
|
||||
# 5. Source code copy (changes every rebuild, but AFTER deps are installed)
|
||||
# 6. spaCy model download (cached unless pip install layer changes)
|
||||
# 7. Pre-downloaded ensemble preset models (~1-1.5 GB, cached unless pip layer changes)
|
||||
|
||||
FROM nvidia/cuda:12.6.3-runtime-ubuntu22.04
|
||||
|
||||
# Prevent interactive prompts during package installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Install Python 3.11 from deadsnakes PPA and system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
software-properties-common \
|
||||
&& add-apt-repository -y ppa:deadsnakes/ppa \
|
||||
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||
# Python 3.11
|
||||
python3.11 \
|
||||
python3.11-dev \
|
||||
python3.11-venv \
|
||||
# Audio libraries
|
||||
libsndfile1 \
|
||||
libsox-dev \
|
||||
sox \
|
||||
# Build tools
|
||||
build-essential \
|
||||
# Utilities
|
||||
curl \
|
||||
xz-utils \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& python3.11 --version
|
||||
|
||||
# Install comprehensive font support for international lyrics and symbols
|
||||
# Noto fonts provide full Unicode coverage including:
|
||||
# - Latin, Greek, Cyrillic (core)
|
||||
# - CJK: Chinese, Japanese, Korean (~150MB)
|
||||
# - Arabic, Hebrew, Thai, Hindi, and other scripts (extra)
|
||||
# - Color emoji (limited support in libass, but available)
|
||||
# - Musical symbols (♪ ♫ etc.)
|
||||
# Note: This adds ~200-300MB to the image but ensures all languages render correctly
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fonts-noto-extra \
|
||||
fonts-noto-color-emoji \
|
||||
fontconfig \
|
||||
&& fc-cache -f \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install FFmpeg from Ubuntu package
|
||||
# The audio worker only uses FFmpeg for format conversion and padding, not
|
||||
# encoding-intensive tasks, so the Debian package is sufficient. The static
|
||||
# build from johnvansickle.com is used for the encoding worker instead.
|
||||
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set Python 3.11 as default and install pip
|
||||
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
|
||||
&& update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 \
|
||||
&& curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11 \
|
||||
&& python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel
|
||||
|
||||
# Set up CUDA library paths so GPU-accelerated packages can find CUDA libs at runtime
|
||||
RUN echo '/usr/local/cuda/lib64' >> /etc/ld.so.conf.d/cuda.conf && ldconfig
|
||||
|
||||
# Environment configuration for CUDA and Python
|
||||
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \
|
||||
PATH=/usr/local/cuda/bin:$PATH \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MODEL_DIR=/models
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy ONLY dependency specification files first (changes less often than source code)
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
|
||||
# Create minimal package stubs so pip can resolve the editable install
|
||||
# pip install -e . needs package directories to exist but doesn't validate content
|
||||
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
|
||||
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
|
||||
|
||||
# Install all karaoke-gen Python dependencies (the slow part)
|
||||
# BuildKit cache mount preserves downloaded wheels across builds
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install --upgrade pip && \
|
||||
pip install -e .
|
||||
|
||||
# Install audio-separator with GPU support (PyTorch + CUDA + onnxruntime-gpu)
|
||||
# This is separate from pip install -e . to keep layer caching granular
|
||||
#
|
||||
# IMPORTANT: Install PyTorch cu126 FIRST, then audio-separator[gpu].
|
||||
# The default audio-separator[gpu] pulls PyTorch cu130, but Cloud Run L4 GPUs
|
||||
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
|
||||
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
|
||||
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
|
||||
pip install "audio-separator[gpu]"
|
||||
|
||||
# Now copy actual source code (AFTER deps installed, so code changes don't
|
||||
# invalidate the expensive pip install layer in registry cache)
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
|
||||
COPY backend /app/backend
|
||||
|
||||
# Download spaCy language model for lyrics transcription
|
||||
# Must be done at build time, not runtime (Cloud Run network restrictions)
|
||||
RUN python -m spacy download en_core_web_sm
|
||||
|
||||
# Create models directory and pre-download ensemble preset models
|
||||
# Baking models into the image eliminates cold-start model download latency.
|
||||
# Total model size: ~1-1.5 GB for instrumental_clean + karaoke presets.
|
||||
RUN mkdir -p /models
|
||||
COPY backend/scripts/download_models.py /tmp/download_models.py
|
||||
RUN python /tmp/download_models.py /models && \
|
||||
rm /tmp/download_models.py && \
|
||||
ls -lh /models/
|
||||
|
||||
# Label with build info
|
||||
ARG BUILD_DATE
|
||||
ARG BUILD_ID
|
||||
ARG BASE_CONTENT_HASH
|
||||
LABEL org.opencontainers.image.created="${BUILD_DATE}"
|
||||
LABEL org.opencontainers.image.revision="${BUILD_ID}"
|
||||
LABEL org.opencontainers.image.title="karaoke-backend-gpu-base"
|
||||
LABEL org.opencontainers.image.description="GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models for karaoke-backend audio worker"
|
||||
LABEL base.content.hash="${BASE_CONTENT_HASH}"
|
||||
@@ -1693,11 +1693,14 @@ async def retry_job(
|
||||
"retry_stage": "video_generation"
|
||||
}
|
||||
|
||||
# If we have corrections and screens but no video, retry render
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
|
||||
# If we have corrections, screens, AND review was completed, retry render
|
||||
# Review completion is proven by instrumental_selection in state_data
|
||||
# (set only when user submits the review endpoint)
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title') and
|
||||
state_data.get('instrumental_selection')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
|
||||
|
||||
# Clear error state and reset worker progress for idempotency
|
||||
job_manager.update_job(job_id, {
|
||||
@@ -1717,16 +1720,48 @@ async def retry_job(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
|
||||
# Trigger render video worker
|
||||
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
|
||||
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "review_complete",
|
||||
"message": "Job retry started from render stage",
|
||||
"retry_stage": "render_video"
|
||||
}
|
||||
|
||||
# If we have corrections and screens but review was NOT completed,
|
||||
# return to awaiting_review so the user can review lyrics
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
|
||||
|
||||
# Clear error state
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
})
|
||||
|
||||
# Transition to AWAITING_REVIEW so user can review lyrics
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message=f"Ready for review. Please review lyrics and select your instrumental."
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "awaiting_review",
|
||||
"message": "Job retry: returning to lyrics review (review was not completed before failure)",
|
||||
"retry_stage": "awaiting_review"
|
||||
}
|
||||
|
||||
# If we have stems and corrections, retry from screens generation
|
||||
elif (file_urls.get('stems', {}).get('instrumental_clean') and
|
||||
|
||||
@@ -19,7 +19,7 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Set, Tuple
|
||||
from typing import Dict, Any, List, Optional, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends
|
||||
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
@@ -427,8 +427,10 @@ async def add_lyrics(
|
||||
|
||||
source = data.get("source", "").strip()
|
||||
lyrics_text = data.get("lyrics", "").strip()
|
||||
|
||||
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters")
|
||||
raw_force = data.get("force", False)
|
||||
force = raw_force if isinstance(raw_force, bool) else str(raw_force).lower() == "true"
|
||||
|
||||
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters (force={force})")
|
||||
|
||||
# Use tracing and job_log_context for full observability
|
||||
with create_span("add-lyrics", {"job_id": job_id, "source": source, "lyrics_length": len(lyrics_text)}) as span:
|
||||
@@ -465,7 +467,8 @@ async def add_lyrics(
|
||||
source=source,
|
||||
lyrics_text=lyrics_text,
|
||||
cache_dir=cache_dir,
|
||||
logger=logger
|
||||
logger=logger,
|
||||
force=force,
|
||||
)
|
||||
add_span_event("correction_complete", {
|
||||
"new_segments": len(updated_result.corrected_segments) if updated_result.corrected_segments else 0,
|
||||
@@ -501,6 +504,151 @@ async def add_lyrics(
|
||||
raise HTTPException(status_code=500, detail=f"Failed to add lyrics: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/search-lyrics")
|
||||
async def search_lyrics(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Search for lyrics using an alternate artist/title and rerun correction.
|
||||
|
||||
Queries all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB)
|
||||
with the supplied artist and title, then runs the correction pipeline (which
|
||||
includes the relevance filter). Sources that pass the filter are added to the
|
||||
job's corrections.json and returned to the frontend.
|
||||
|
||||
Request body:
|
||||
artist (str): Artist name to search.
|
||||
title (str): Song title to search.
|
||||
force_sources (list[str], optional): Provider names whose results should
|
||||
bypass the relevance filter.
|
||||
|
||||
Response:
|
||||
200 {"status": "success", "data": {...CorrectionData...}, "sources_added": [...],
|
||||
"sources_rejected": {...}, "sources_not_found": [...]}
|
||||
200 {"status": "no_results", "message": "...", "sources_rejected": {...},
|
||||
"sources_not_found": [...]}
|
||||
400 on invalid request / wrong job state
|
||||
500 on internal error
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
)
|
||||
|
||||
artist = (data.get("artist") or "").strip()
|
||||
title = (data.get("title") or "").strip()
|
||||
force_sources: List[str] = data.get("force_sources") or []
|
||||
|
||||
if not artist or not title:
|
||||
raise HTTPException(status_code=400, detail="artist and title are required")
|
||||
|
||||
logger.info(f"Job {job_id}: Searching lyrics for '{artist}' - '{title}' (force={force_sources})")
|
||||
|
||||
with create_span("search-lyrics", {"job_id": job_id, "artist": artist, "title": title}) as span:
|
||||
with job_log_context(job_id, worker="search-lyrics"):
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download current corrections.json
|
||||
with create_span("download-corrections") as download_span:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
corrections_path = os.path.join(temp_dir, "corrections.json")
|
||||
storage.download_file(corrections_gcs, corrections_path)
|
||||
download_span.set_attribute("gcs_path", corrections_gcs)
|
||||
|
||||
with open(corrections_path, "r", encoding="utf-8") as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
add_span_event("corrections_loaded", {
|
||||
"segments": len(correction_result.corrected_segments) if correction_result.corrected_segments else 0,
|
||||
"reference_sources": len(correction_result.reference_lyrics) if correction_result.reference_lyrics else 0,
|
||||
})
|
||||
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
with create_span("correction-operations-search-lyrics") as correction_span:
|
||||
correction_span.set_attribute("artist", artist)
|
||||
correction_span.set_attribute("title", title)
|
||||
search_result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist=artist,
|
||||
title=title,
|
||||
cache_dir=cache_dir,
|
||||
force_sources=force_sources,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
sources_added = search_result["sources_added"]
|
||||
sources_rejected = search_result["sources_rejected"]
|
||||
sources_not_found = search_result["sources_not_found"]
|
||||
updated_result = search_result["updated_result"]
|
||||
|
||||
if not sources_added or updated_result is None:
|
||||
logger.info(
|
||||
f"Job {job_id}: No valid lyrics found via search "
|
||||
f"(rejected={list(sources_rejected.keys())}, not_found={sources_not_found})"
|
||||
)
|
||||
span.set_attribute("success", False)
|
||||
return {
|
||||
"status": "no_results",
|
||||
"message": "No matching lyrics found from any provider",
|
||||
"sources_added": [],
|
||||
"sources_rejected": sources_rejected,
|
||||
"sources_not_found": sources_not_found,
|
||||
}
|
||||
|
||||
# Add audio hash / job metadata for the frontend
|
||||
audio_hash = _get_audio_hash(job_id)
|
||||
if not updated_result.metadata:
|
||||
updated_result.metadata = {}
|
||||
updated_result.metadata["audio_hash"] = audio_hash
|
||||
updated_result.metadata["artist"] = job.artist
|
||||
updated_result.metadata["title"] = job.title
|
||||
|
||||
# Upload updated corrections back to GCS
|
||||
with create_span("upload-corrections") as upload_span:
|
||||
updated_data = updated_result.to_dict()
|
||||
storage.upload_json(corrections_gcs, updated_data)
|
||||
upload_span.set_attribute("gcs_path", corrections_gcs)
|
||||
|
||||
logger.info(
|
||||
f"Job {job_id}: Search complete — added={sources_added}, "
|
||||
f"rejected={list(sources_rejected.keys())}, not_found={sources_not_found}"
|
||||
)
|
||||
span.set_attribute("success", True)
|
||||
span.set_attribute("sources_added", len(sources_added))
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"data": updated_data,
|
||||
"sources_added": sources_added,
|
||||
"sources_rejected": sources_rejected,
|
||||
"sources_not_found": sources_not_found,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except ValueError as e:
|
||||
logger.warning(f"Job {job_id}: Invalid search lyrics request: {e}")
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to search lyrics: {e}", exc_info=True)
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(status_code=500, detail=f"Failed to search lyrics: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/preview-video")
|
||||
async def generate_preview_video(
|
||||
job_id: str,
|
||||
|
||||
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
@@ -132,6 +133,32 @@ class LogoutResponse(BaseModel):
|
||||
# Magic Link Authentication
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def _precompute_credit_eval(token: str, email: str) -> None:
|
||||
"""Run credit evaluation in background and store result on magic link doc.
|
||||
|
||||
Called in a background thread after sending a magic link for new users.
|
||||
If the user clicks the link before this finishes, verify_magic_link falls
|
||||
back to inline evaluation (same as before this optimization).
|
||||
"""
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
from backend.services.user_service import get_user_service, MAGIC_LINKS_COLLECTION
|
||||
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
user_service = get_user_service()
|
||||
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
"credit_eval_decision": evaluation.decision,
|
||||
"credit_eval_reasoning": evaluation.reasoning,
|
||||
"credit_eval_error": evaluation.error,
|
||||
})
|
||||
logger.info(f"Pre-computed credit eval for {_mask_email(email)}: {evaluation.decision}")
|
||||
except Exception:
|
||||
logger.exception(f"Background credit eval failed for {_mask_email(email)} — verify will compute inline")
|
||||
|
||||
|
||||
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
|
||||
async def send_magic_link(
|
||||
request: SendMagicLinkRequest,
|
||||
@@ -250,6 +277,17 @@ async def send_magic_link(
|
||||
# Don't reveal failure to prevent email enumeration
|
||||
# Still return success
|
||||
|
||||
# Pre-compute credit evaluation in background for new users.
|
||||
# By the time they check their email and click the link, the decision
|
||||
# will be ready and verification will be instant.
|
||||
if existing_user is None:
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, email),
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
@@ -298,9 +336,20 @@ async def verify_magic_link(
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
# Grant welcome credits on first verification (with AI abuse evaluation)
|
||||
# Use pre-computed evaluation from magic link if available (computed at send time)
|
||||
precomputed_eval = None
|
||||
if magic_link_doc.exists:
|
||||
precomputed_eval = {
|
||||
k: magic_link_data.get(k)
|
||||
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
|
||||
if magic_link_data.get(k) is not None
|
||||
} or None
|
||||
|
||||
credits_granted = 0
|
||||
credit_status = "not_applicable" # returning user, not first login
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(user.email)
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
if granted:
|
||||
credits_granted = user_service.NEW_USER_FREE_CREDITS
|
||||
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Cloud Build config for GPU base image
|
||||
#
|
||||
# Builds the CUDA + PyTorch + models base image used by the audio worker.
|
||||
# This image is large (~10GB) so builds take 15-30 minutes.
|
||||
#
|
||||
# Trigger manually:
|
||||
# gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
|
||||
#
|
||||
# The app-layer Dockerfile uses this as its BASE_IMAGE for audio worker deploys.
|
||||
|
||||
steps:
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args:
|
||||
- 'build'
|
||||
- '-f'
|
||||
- 'backend/Dockerfile.gpu-base'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- '--build-arg'
|
||||
- 'BUILD_DATE=$_BUILD_DATE'
|
||||
- '--build-arg'
|
||||
- 'BUILD_ID=$BUILD_ID'
|
||||
- '.'
|
||||
|
||||
images:
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
|
||||
timeout: '3600s'
|
||||
|
||||
options:
|
||||
machineType: 'E2_HIGHCPU_32'
|
||||
diskSizeGb: 100
|
||||
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
|
||||
|
||||
# Authentication
|
||||
admin_tokens: Optional[str] = os.getenv("ADMIN_TOKENS") # Comma-separated list
|
||||
scheduler_service_account: str = os.getenv(
|
||||
"SCHEDULER_SERVICE_ACCOUNT",
|
||||
"karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
|
||||
)
|
||||
|
||||
# Application
|
||||
environment: str = os.getenv("ENVIRONMENT", "development")
|
||||
|
||||
@@ -129,6 +129,11 @@ class MagicLinkToken(BaseModel):
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
tenant_id: Optional[str] = None
|
||||
|
||||
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
|
||||
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
|
||||
credit_eval_reasoning: Optional[str] = None
|
||||
credit_eval_error: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Download ensemble preset models at Docker build time.
|
||||
|
||||
Bakes models into the image so they're available immediately at runtime,
|
||||
avoiding cold-start model download latency in Cloud Run Jobs.
|
||||
|
||||
Usage: python backend/scripts/download_models.py /models
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import logging
|
||||
import importlib.resources as resources
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Presets to bake into the GPU image
|
||||
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
|
||||
|
||||
|
||||
def download_preset_models(model_dir: str) -> None:
|
||||
"""Download all models for the configured presets individually.
|
||||
|
||||
Ensemble presets resolve to multiple model filenames. We must download
|
||||
each model individually via load_model(model_filename) — calling
|
||||
load_model() with no args on an ensemble preset doesn't trigger downloads.
|
||||
"""
|
||||
with resources.open_text("audio_separator", "ensemble_presets.json") as f:
|
||||
presets = json.load(f)["presets"]
|
||||
|
||||
models_to_download = set()
|
||||
for preset_name in PRESETS_TO_DOWNLOAD:
|
||||
models_to_download.update(presets[preset_name]["models"])
|
||||
|
||||
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
|
||||
for model in sorted(models_to_download):
|
||||
logger.info(f" Downloading: {model}")
|
||||
sep = Separator(model_file_dir=model_dir)
|
||||
sep.load_model(model)
|
||||
logger.info(f" Done: {model}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model_dir = sys.argv[1] if len(sys.argv) > 1 else "/models"
|
||||
download_preset_models(model_dir)
|
||||
logger.info(f"All preset models downloaded to {model_dir}")
|
||||
@@ -3,6 +3,7 @@ Authentication service for karaoke backend.
|
||||
|
||||
Provides token-based authentication with support for:
|
||||
- Admin tokens (hardcoded in environment)
|
||||
- Google OIDC tokens (from Cloud Scheduler / Cloud Tasks service accounts)
|
||||
- Admin by email domain (@nomadkaraoke.com)
|
||||
- User tokens (stored in Firestore auth_tokens collection)
|
||||
- Session tokens (stored in Firestore sessions collection, from magic link auth)
|
||||
@@ -19,6 +20,9 @@ from enum import Enum
|
||||
from typing import Optional, Tuple, Dict, Any, List
|
||||
from datetime import datetime
|
||||
|
||||
from google.auth.transport import requests as google_auth_requests
|
||||
from google.oauth2 import id_token as google_id_token
|
||||
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.config import get_settings
|
||||
from backend.models.user import UserRole
|
||||
@@ -72,6 +76,7 @@ class AuthService:
|
||||
self.firestore = FirestoreService()
|
||||
self.settings = get_settings()
|
||||
self._init_admin_tokens()
|
||||
self._scheduler_service_account = self.settings.scheduler_service_account
|
||||
|
||||
def _init_admin_tokens(self):
|
||||
"""Load admin tokens from environment variables."""
|
||||
@@ -83,6 +88,56 @@ class AuthService:
|
||||
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
|
||||
else:
|
||||
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
|
||||
|
||||
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
|
||||
"""
|
||||
Validate a Google OIDC token (from Cloud Scheduler or Cloud Tasks).
|
||||
|
||||
Returns AuthResult if token is a valid Google OIDC JWT from an allowed
|
||||
service account, None if the token is not a JWT or validation fails.
|
||||
"""
|
||||
# Quick check: JWTs have 3 dot-separated parts
|
||||
if token.count('.') != 2:
|
||||
return None
|
||||
|
||||
try:
|
||||
# Verify the token signature and claims with Google
|
||||
# audience=None skips audience check — Cloud Scheduler sets audience
|
||||
# to the endpoint URL, which varies per endpoint
|
||||
claims = google_id_token.verify_oauth2_token(
|
||||
token,
|
||||
google_auth_requests.Request(),
|
||||
audience=None,
|
||||
)
|
||||
|
||||
token_email = claims.get("email", "")
|
||||
|
||||
# Only accept tokens from the configured service account
|
||||
if token_email != self._scheduler_service_account:
|
||||
logger.warning(
|
||||
f"OIDC token from unexpected service account: {token_email} "
|
||||
f"(expected {self._scheduler_service_account})"
|
||||
)
|
||||
return None
|
||||
|
||||
logger.info(f"OIDC token validated for service account: {token_email}")
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=-1,
|
||||
message="OIDC service account access granted",
|
||||
user_email=token_email,
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
# verify_oauth2_token raises ValueError for invalid/expired tokens
|
||||
logger.debug(f"OIDC token validation failed: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
# Network errors fetching Google certs, etc.
|
||||
logger.warning(f"OIDC token verification error: {e}")
|
||||
return None
|
||||
|
||||
def validate_token(self, token: str) -> Tuple[bool, UserType, int, str]:
|
||||
"""
|
||||
@@ -213,6 +268,12 @@ class AuthService:
|
||||
is_admin=True
|
||||
)
|
||||
|
||||
# Check for Google OIDC tokens (Cloud Scheduler / Cloud Tasks)
|
||||
# Done before Firestore lookup to avoid wasting a read on JWT strings
|
||||
oidc_result = self._validate_oidc_token(token)
|
||||
if oidc_result is not None:
|
||||
return oidc_result
|
||||
|
||||
# Check stored tokens in Firestore (auth_tokens collection)
|
||||
token_data = self.firestore.get_token(token)
|
||||
|
||||
|
||||
@@ -297,7 +297,7 @@ class CreditEvaluationService:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location=self.settings.gcp_region,
|
||||
location="global",
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.credit_eval_model,
|
||||
|
||||
@@ -212,9 +212,11 @@ class EmailValidationService:
|
||||
effective_domains = (external | manual) - allowlisted
|
||||
else:
|
||||
# Old data model (pre-migration): use disposable_domains + defaults
|
||||
allowlisted = set()
|
||||
effective_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
|
||||
config = {
|
||||
"disposable_domains": effective_domains,
|
||||
"allowlisted_domains": allowlisted,
|
||||
"blocked_emails": set(data.get("blocked_emails", [])),
|
||||
"blocked_ips": set(data.get("blocked_ips", [])),
|
||||
"verified_clean_domains": data.get("verified_clean_domains", {}),
|
||||
@@ -222,6 +224,7 @@ class EmailValidationService:
|
||||
else:
|
||||
config = {
|
||||
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
|
||||
"allowlisted_domains": set(),
|
||||
"blocked_emails": set(),
|
||||
"blocked_ips": set(),
|
||||
"verified_clean_domains": {},
|
||||
@@ -267,6 +270,12 @@ class EmailValidationService:
|
||||
if domain in config["disposable_domains"]:
|
||||
return True
|
||||
|
||||
# Tier 1.5: Explicitly allowlisted domains skip external API checks.
|
||||
# Without this, external APIs can override admin allowlist decisions
|
||||
# (e.g. inbox.testmail.app is a legitimate testing domain we allow).
|
||||
if domain in config.get("allowlisted_domains", set()):
|
||||
return False
|
||||
|
||||
# Tier 2: Recently verified clean? Skip API calls
|
||||
if self._is_domain_verified_clean(domain, config):
|
||||
return False
|
||||
|
||||
@@ -115,6 +115,28 @@ class EncodingService:
|
||||
"""Check if GCE preview encoding is enabled and configured."""
|
||||
return self.settings.use_gce_preview_encoding and self.is_configured
|
||||
|
||||
def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
|
||||
"""Safety net: try to start the encoding worker VM on first connection failure.
|
||||
|
||||
If the worker_manager is available, calls ensure_primary_running() so the VM
|
||||
starts booting during the retry window. If worker_manager is not set (e.g. dev
|
||||
mode with static URL), this is a no-op.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return
|
||||
try:
|
||||
result = self._worker_manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
|
||||
|
||||
async def _request_with_retry(
|
||||
self,
|
||||
method: str,
|
||||
@@ -176,6 +198,8 @@ class EncodingService:
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if attempt == 0:
|
||||
self._warmup_encoding_worker_fallback(job_id)
|
||||
if attempt < MAX_RETRIES:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
|
||||
|
||||
@@ -213,8 +213,10 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
|
||||
"video_worker": [
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.GENERATING_VIDEO,
|
||||
# Note: RENDERING_VIDEO and GENERATING_VIDEO are intentionally excluded.
|
||||
# If the job is already in those states, another worker is actively processing it.
|
||||
# Including them caused a race condition where Cloud Run Job retries + manual retries
|
||||
# could launch concurrent workers that corrupt each other's state transitions.
|
||||
],
|
||||
"render_video_worker": [
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
|
||||
@@ -370,7 +370,11 @@ class UserService:
|
||||
logger.exception("Error verifying magic link")
|
||||
return False, None, "An error occurred during verification"
|
||||
|
||||
def grant_welcome_credits_if_eligible(self, email: str) -> Tuple[bool, str]:
|
||||
def grant_welcome_credits_if_eligible(
|
||||
self,
|
||||
email: str,
|
||||
precomputed_eval: Optional[dict] = None,
|
||||
) -> Tuple[bool, str]:
|
||||
"""
|
||||
Grant welcome credits on first magic link verification.
|
||||
|
||||
@@ -381,6 +385,12 @@ class UserService:
|
||||
check (survives credit_transactions list trimming). Falls back to
|
||||
checking for welcome_credit transaction as secondary defense.
|
||||
|
||||
Args:
|
||||
email: User's email address.
|
||||
precomputed_eval: Optional pre-computed evaluation from magic link doc.
|
||||
Keys: credit_eval_decision, credit_eval_reasoning, credit_eval_error.
|
||||
If provided and has a decision, skips the AI call.
|
||||
|
||||
Returns:
|
||||
Tuple of (credits_granted: bool, status: str).
|
||||
status is one of: "granted", "denied", "already_granted", "not_found", "error"
|
||||
@@ -401,10 +411,24 @@ class UserService:
|
||||
return False, "already_granted"
|
||||
|
||||
# AI evaluation: check for abuse signals before granting
|
||||
# Use pre-computed result from magic link if available
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
from backend.services.credit_evaluation_service import (
|
||||
get_credit_evaluation_service,
|
||||
CreditEvaluation,
|
||||
)
|
||||
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
|
||||
if precomputed_decision:
|
||||
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
|
||||
evaluation = CreditEvaluation(
|
||||
decision=precomputed_decision,
|
||||
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
|
||||
confidence=1.0,
|
||||
error=(precomputed_eval or {}).get("credit_eval_error"),
|
||||
)
|
||||
else:
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
if evaluation.decision == "deny":
|
||||
# Mark as evaluated but not granted so we don't re-evaluate
|
||||
|
||||
@@ -383,14 +383,13 @@ class WorkerService:
|
||||
"""
|
||||
Trigger audio separation worker.
|
||||
|
||||
Always uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
|
||||
instances mid-processing when no HTTP requests were active.
|
||||
Uses Cloud Run Jobs with L4 GPU in us-east4 for direct audio separation.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-separation-job",
|
||||
worker_module="audio_worker",
|
||||
location="us-east4", # GPU job runs in us-east4 (L4 quota)
|
||||
)
|
||||
|
||||
async def trigger_lyrics_worker(self, job_id: str) -> bool:
|
||||
@@ -412,14 +411,40 @@ class WorkerService:
|
||||
"""Trigger screen generation worker."""
|
||||
return await self.trigger_worker("screens", job_id)
|
||||
|
||||
def _warmup_encoding_worker(self, job_id: str) -> None:
|
||||
"""Fire-and-forget warmup of the encoding worker VM.
|
||||
|
||||
Called before dispatching video/render workers so the GCE encoding
|
||||
VM starts booting while the worker downloads files and prepares.
|
||||
Failures are logged but never block worker dispatch.
|
||||
"""
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
db = firestore.Client(project=self.settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=self.settings.google_cloud_project,
|
||||
)
|
||||
result = manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.info(f"[job:{job_id}] Encoding worker warmup: started VM {result['vm_name']}")
|
||||
else:
|
||||
logger.info(f"[job:{job_id}] Encoding worker warmup: VM {result['vm_name']} already running")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Encoding worker warmup failed (non-fatal): {e}")
|
||||
|
||||
async def trigger_video_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger video generation worker.
|
||||
|
||||
|
||||
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
|
||||
uses Cloud Run Jobs for execution (supports >30 min encoding).
|
||||
Otherwise, uses Cloud Tasks or direct HTTP.
|
||||
"""
|
||||
self._warmup_encoding_worker(job_id)
|
||||
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
|
||||
return await self._trigger_cloud_run_job(job_id)
|
||||
return await self.trigger_worker("video", job_id)
|
||||
@@ -448,6 +473,7 @@ class WorkerService:
|
||||
job_id: str,
|
||||
cloud_run_job_name: str,
|
||||
worker_module: str,
|
||||
location: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Trigger a worker as a Cloud Run Job.
|
||||
@@ -460,6 +486,7 @@ class WorkerService:
|
||||
job_id: Job ID to process
|
||||
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
|
||||
worker_module: Worker module name (e.g., "lyrics_worker")
|
||||
location: GCP region for the job (defaults to settings.gcp_region)
|
||||
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
@@ -472,7 +499,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = location or self.settings.gcp_region
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
|
||||
|
||||
# Create Cloud Run Jobs client
|
||||
@@ -510,6 +537,7 @@ class WorkerService:
|
||||
|
||||
async def trigger_render_video_worker(self, job_id: str) -> bool:
|
||||
"""Trigger render video worker (post-review)."""
|
||||
self._warmup_encoding_worker(job_id)
|
||||
return await self.trigger_worker("render-video", job_id)
|
||||
|
||||
async def schedule_idle_reminder(
|
||||
|
||||
@@ -130,6 +130,36 @@ class TestGrantWelcomeCredits:
|
||||
assert update_args['credits'] == 1
|
||||
assert update_args['welcome_credits_granted'] is True
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_uses_precomputed_eval_when_provided(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible uses pre-computed eval and skips AI call."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@example.com", credits=0, credit_transactions=[])
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
granted, status = service.grant_welcome_credits_if_eligible(
|
||||
"new@example.com",
|
||||
precomputed_eval={
|
||||
"credit_eval_decision": "grant",
|
||||
"credit_eval_reasoning": "Pre-computed: clean user",
|
||||
},
|
||||
)
|
||||
# AI evaluation should NOT have been called
|
||||
mock_eval.return_value.evaluate.assert_not_called()
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_if_flag_already_set(self, mock_fs, mock_settings):
|
||||
@@ -565,6 +595,49 @@ class TestVerifyGrantsCredits:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_passes_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes pre-computed eval from magic link doc."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
# Add pre-computed eval to the magic link doc
|
||||
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
|
||||
mock_ml_doc.to_dict.return_value = {
|
||||
'email': user.email,
|
||||
'tenant_id': None,
|
||||
'credit_eval_decision': 'grant',
|
||||
'credit_eval_reasoning': 'Clean user',
|
||||
}
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify precomputed_eval was passed through
|
||||
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
|
||||
assert call_kwargs[1]['precomputed_eval'] == {
|
||||
'credit_eval_decision': 'grant',
|
||||
'credit_eval_reasoning': 'Clean user',
|
||||
}
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_falls_back_without_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes None when no pre-computed eval exists."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
|
||||
assert call_kwargs[1]['precomputed_eval'] is None
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_returns_zero_credits_for_returning_user(self, mock_user_svc):
|
||||
"""Returning user gets credits_granted=0."""
|
||||
user = User(
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""
|
||||
Tests for Google OIDC token validation in AuthService.
|
||||
|
||||
Cloud Scheduler and Cloud Tasks send OIDC JWTs signed by Google.
|
||||
The auth service must validate these and grant admin access for
|
||||
requests from the configured service account.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from backend.services.auth_service import AuthService, AuthResult, UserType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_service():
|
||||
"""Create an AuthService instance with mocked Firestore."""
|
||||
with patch("backend.services.auth_service.FirestoreService"):
|
||||
service = AuthService()
|
||||
service._scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
|
||||
return service
|
||||
|
||||
|
||||
# A fake JWT-shaped token (3 dot-separated parts)
|
||||
FAKE_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifQ.signature"
|
||||
|
||||
|
||||
class TestOidcTokenValidation:
|
||||
"""Tests for _validate_oidc_token."""
|
||||
|
||||
def test_non_jwt_returns_none(self, auth_service):
|
||||
"""Non-JWT tokens (no dots) should return None immediately."""
|
||||
result = auth_service._validate_oidc_token("simple-token-no-dots")
|
||||
assert result is None
|
||||
|
||||
def test_two_dots_not_three_parts_returns_none(self, auth_service):
|
||||
"""Tokens with wrong number of dots should return None."""
|
||||
result = auth_service._validate_oidc_token("only.one.dot-but-not-jwt")
|
||||
# This has 2 dots = 3 parts, so it will attempt OIDC validation
|
||||
# but fail signature verification. That's fine — it returns None.
|
||||
# A token with 1 dot should be skipped entirely.
|
||||
result_one_dot = auth_service._validate_oidc_token("one.dot")
|
||||
assert result_one_dot is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_valid_oidc_from_allowed_sa(self, mock_verify, auth_service):
|
||||
"""Valid OIDC token from the configured service account grants admin."""
|
||||
mock_verify.return_value = {
|
||||
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
|
||||
"email_verified": True,
|
||||
"iss": "https://accounts.google.com",
|
||||
"aud": "https://api.nomadkaraoke.com/api/internal/process-stale-reviews",
|
||||
}
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is not None
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.user_type == UserType.ADMIN
|
||||
assert result.remaining_uses == -1
|
||||
assert result.user_email == "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_oidc_from_wrong_sa_returns_none(self, mock_verify, auth_service):
|
||||
"""OIDC token from a different service account is rejected."""
|
||||
mock_verify.return_value = {
|
||||
"email": "attacker@evil-project.iam.gserviceaccount.com",
|
||||
"email_verified": True,
|
||||
"iss": "https://accounts.google.com",
|
||||
}
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_expired_oidc_token_returns_none(self, mock_verify, auth_service):
|
||||
"""Expired OIDC token raises ValueError and returns None."""
|
||||
mock_verify.side_effect = ValueError("Token expired")
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_invalid_signature_returns_none(self, mock_verify, auth_service):
|
||||
"""Token with invalid signature raises ValueError and returns None."""
|
||||
mock_verify.side_effect = ValueError("Could not verify token signature")
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_network_error_returns_none(self, mock_verify, auth_service):
|
||||
"""Network error fetching Google certs returns None gracefully."""
|
||||
mock_verify.side_effect = Exception("Connection timeout")
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestValidateTokenFullOidc:
|
||||
"""Tests that OIDC validation is properly integrated into validate_token_full."""
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_oidc_token_grants_admin_via_validate_token_full(self, mock_verify, auth_service):
|
||||
"""OIDC token flows through validate_token_full and grants admin."""
|
||||
mock_verify.return_value = {
|
||||
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
|
||||
"email_verified": True,
|
||||
}
|
||||
|
||||
# Mock Firestore to not interfere
|
||||
auth_service.firestore.get_token = MagicMock(return_value=None)
|
||||
|
||||
result = auth_service.validate_token_full(FAKE_JWT)
|
||||
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.user_type == UserType.ADMIN
|
||||
|
||||
def test_admin_token_still_works(self, auth_service):
|
||||
"""Admin tokens from env var still take priority over OIDC."""
|
||||
auth_service.admin_tokens = ["test-admin-token"]
|
||||
|
||||
result = auth_service.validate_token_full("test-admin-token")
|
||||
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.message == "Admin access granted"
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_failed_oidc_falls_through_to_firestore(self, mock_verify, auth_service):
|
||||
"""If OIDC validation fails, token is still checked against Firestore."""
|
||||
mock_verify.side_effect = ValueError("Invalid token")
|
||||
|
||||
# Firestore has a valid token
|
||||
auth_service.firestore.get_token = MagicMock(return_value={
|
||||
"type": "unlimited",
|
||||
"active": True,
|
||||
"max_uses": -1,
|
||||
"user_email": "user@example.com",
|
||||
})
|
||||
|
||||
result = auth_service.validate_token_full(FAKE_JWT)
|
||||
|
||||
assert result.is_valid is True
|
||||
assert result.user_type == UserType.UNLIMITED
|
||||
@@ -542,6 +542,41 @@ class TestExternalAPIChecks:
|
||||
# No HTTP calls should have been made
|
||||
mock_client.return_value.get.assert_not_called()
|
||||
|
||||
# =========================================================================
|
||||
# Allowlisted domain bypass (Tier 1.5)
|
||||
# =========================================================================
|
||||
|
||||
def test_allowlisted_domain_skips_external_api_checks(self, mock_db):
|
||||
"""Allowlisted domains should skip external API checks entirely.
|
||||
|
||||
Regression test: inbox.testmail.app was getting flagged by DeBounce
|
||||
even though it was in the allowlist, because external API calls ran
|
||||
after the static blocklist check but before checking the allowlist.
|
||||
"""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["yopmail.com"],
|
||||
"manual_domains": ["inbox.testmail.app"], # auto-learned by DeBounce
|
||||
"allowlisted_domains": ["inbox.testmail.app"], # but also allowlisted
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
service = EmailValidationService(db=mock_db)
|
||||
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client:
|
||||
result = service.is_disposable_domain("user@inbox.testmail.app")
|
||||
assert result is False
|
||||
# No HTTP calls should have been made — allowlist bypasses external APIs
|
||||
mock_client.return_value.get.assert_not_called()
|
||||
|
||||
# =========================================================================
|
||||
# DeBounce API
|
||||
# =========================================================================
|
||||
|
||||
@@ -239,6 +239,37 @@ class TestRequestWithRetry:
|
||||
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
|
||||
class TestWarmupFallback:
|
||||
"""Tests for _warmup_encoding_worker_fallback() in the retry loop."""
|
||||
|
||||
def test_warmup_fallback_called_on_first_connection_failure(self, encoding_service):
|
||||
"""Warmup fallback is called when the first connection attempt fails."""
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.ensure_primary_running.return_value = {
|
||||
"started": True, "vm_name": "encoding-worker-b", "primary_url": "http://1.2.3.4:8080"
|
||||
}
|
||||
encoding_service._worker_manager = mock_manager
|
||||
|
||||
encoding_service._warmup_encoding_worker_fallback("test-job")
|
||||
|
||||
mock_manager.ensure_primary_running.assert_called_once()
|
||||
|
||||
def test_warmup_fallback_noop_without_worker_manager(self, encoding_service):
|
||||
"""Warmup fallback is a no-op when worker_manager is not set (dev mode)."""
|
||||
encoding_service._worker_manager = None
|
||||
# Should not raise
|
||||
encoding_service._warmup_encoding_worker_fallback("test-job")
|
||||
|
||||
def test_warmup_fallback_swallows_exceptions(self, encoding_service):
|
||||
"""Warmup fallback never raises — failures are logged but non-fatal."""
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.ensure_primary_running.side_effect = Exception("Compute API down")
|
||||
encoding_service._worker_manager = mock_manager
|
||||
|
||||
# Should not raise
|
||||
encoding_service._warmup_encoding_worker_fallback("test-job")
|
||||
|
||||
|
||||
class TestWaitForCompletionPollTolerance:
|
||||
"""Tests for wait_for_completion() transient failure tolerance."""
|
||||
|
||||
|
||||
@@ -285,6 +285,13 @@ class TestValidateWorkerCanRun:
|
||||
assert error is not None
|
||||
assert "video_worker called but job status is pending" in error
|
||||
|
||||
def test_video_worker_invalid_with_generating_video_status(self):
|
||||
"""Test video worker rejects GENERATING_VIDEO to prevent concurrent worker races."""
|
||||
job = create_test_job(status=JobStatus.GENERATING_VIDEO)
|
||||
error = validate_worker_can_run("video_worker", job)
|
||||
assert error is not None
|
||||
assert "video_worker called but job status is generating_video" in error
|
||||
|
||||
def test_render_video_worker_valid_with_review_complete_status(self):
|
||||
"""Test render video worker is valid with REVIEW_COMPLETE status."""
|
||||
job = create_test_job(status=JobStatus.REVIEW_COMPLETE)
|
||||
|
||||
@@ -387,3 +387,128 @@ class TestScreensWorkerPrerequisites:
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
|
||||
# ==================== GCS URI Passthrough ====================
|
||||
|
||||
class TestGCSURIPassthrough:
|
||||
"""
|
||||
Test that Stage 1 uses gcs_uri when input_gcs_uri is set on the processor.
|
||||
Fixes 413 Request Entity Too Large for large FLAC files.
|
||||
"""
|
||||
|
||||
def test_stage1_uses_gcs_uri_when_set(self):
|
||||
"""When input_gcs_uri is set, Stage 1 passes gcs_uri instead of file_path."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "gcs-test-001"
|
||||
processor.input_gcs_uri = "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["gcs-test-001_mixed_vocals.flac", "gcs-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify gcs_uri was passed instead of file_path
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert call_kwargs["gcs_uri"] == "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
# Verify file_path was NOT passed as a positional arg
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert len(call_args) == 0
|
||||
|
||||
def test_stage1_uses_file_upload_when_no_gcs_uri(self):
|
||||
"""When input_gcs_uri is not set, Stage 1 uses file upload as before."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "file-test-001"
|
||||
# No input_gcs_uri set
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["file-test-001_mixed_vocals.flac", "file-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "file-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "file-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify file_path was passed as positional arg (old behavior)
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert call_args[0] == input_file
|
||||
# Verify gcs_uri was NOT in kwargs
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert "gcs_uri" not in call_kwargs
|
||||
@@ -224,7 +224,38 @@ class TestRetryEndpoint:
|
||||
assert has_video and has_instrumental_selection
|
||||
|
||||
def test_retry_checkpoint_detection_render_stage(self):
|
||||
"""Test retry detects render stage checkpoint."""
|
||||
"""Test retry detects render stage checkpoint when review was completed."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
},
|
||||
state_data={
|
||||
'instrumental_selection': 'clean'
|
||||
}
|
||||
)
|
||||
|
||||
# This job has corrections, screens, AND completed review - should retry from render
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
has_review = (job.state_data or {}).get('instrumental_selection')
|
||||
assert has_corrections and has_screens and not has_video and has_review
|
||||
|
||||
def test_retry_checkpoint_returns_to_review_when_not_completed(self):
|
||||
"""Test retry returns to awaiting_review when corrections and screens exist
|
||||
but user never completed the review (no instrumental_selection).
|
||||
|
||||
Regression test: previously, retry would skip to REVIEW_COMPLETE based solely
|
||||
on corrections.json + title.mov existing, but these are auto-generated artifacts
|
||||
that exist BEFORE the user reviews anything.
|
||||
"""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
@@ -236,13 +267,15 @@ class TestRetryEndpoint:
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
}
|
||||
# No state_data.instrumental_selection — review was never completed
|
||||
)
|
||||
|
||||
# This job has corrections and screens - should retry from render
|
||||
# Has corrections and screens but NO review completion
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
assert has_corrections and has_screens and not has_video
|
||||
has_review = (job.state_data or {}).get('instrumental_selection')
|
||||
# Should match the "awaiting_review" checkpoint, NOT "render"
|
||||
assert has_corrections and has_screens and not has_review
|
||||
|
||||
def test_retry_checkpoint_detection_from_beginning(self):
|
||||
"""Test retry detects need to restart from beginning."""
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
"""
|
||||
Tests for the search-lyrics operation and API endpoint.
|
||||
|
||||
Covers:
|
||||
- create_lyrics_providers() factory function
|
||||
- CorrectionOperations.search_lyrics_sources() static method
|
||||
- CorrectionOperations.add_lyrics_source() force parameter
|
||||
- POST /{job_id}/search-lyrics API endpoint
|
||||
"""
|
||||
import pytest
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
from typing import Dict, Any, List
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers / fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_lyrics_data(source: str = "TestSource", text: str = "Hello world\nTest line") -> "LyricsData":
|
||||
"""Create a minimal LyricsData object for testing."""
|
||||
from karaoke_gen.lyrics_transcriber.types import LyricsData, LyricsSegment, LyricsMetadata, Word
|
||||
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
|
||||
|
||||
segments = []
|
||||
for line in text.strip().splitlines():
|
||||
words = [
|
||||
Word(id=WordUtils.generate_id(), text=w, start_time=None, end_time=None)
|
||||
for w in line.split()
|
||||
]
|
||||
segments.append(
|
||||
LyricsSegment(
|
||||
id=WordUtils.generate_id(),
|
||||
text=line,
|
||||
words=words,
|
||||
start_time=None,
|
||||
end_time=None,
|
||||
)
|
||||
)
|
||||
return LyricsData(source=source, segments=segments, metadata=LyricsMetadata(source=source, track_name="Test Track", artist_names="Test Artist"))
|
||||
|
||||
|
||||
def _make_correction_result(
|
||||
reference_lyrics: Dict = None,
|
||||
metadata: Dict = None,
|
||||
) -> "CorrectionResult":
|
||||
"""Create a minimal CorrectionResult for testing."""
|
||||
from karaoke_gen.lyrics_transcriber.types import (
|
||||
CorrectionResult, LyricsSegment, Word, LyricsData, LyricsMetadata
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
|
||||
|
||||
# A single transcription segment
|
||||
word = Word(id=WordUtils.generate_id(), text="hello", start_time=0.0, end_time=0.5)
|
||||
segment = LyricsSegment(id=WordUtils.generate_id(), text="hello", words=[word], start_time=0.0, end_time=0.5)
|
||||
|
||||
return CorrectionResult(
|
||||
original_segments=[segment],
|
||||
corrected_segments=[segment],
|
||||
corrections=[],
|
||||
corrections_made=0,
|
||||
confidence=1.0,
|
||||
reference_lyrics=reference_lyrics or {},
|
||||
anchor_sequences=[],
|
||||
gap_sequences=[],
|
||||
resized_segments=None,
|
||||
metadata=metadata or {"audio_hash": "testhash"},
|
||||
correction_steps=[],
|
||||
word_id_map={},
|
||||
segment_id_map={},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: create_lyrics_providers factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestCreateLyricsProviders:
|
||||
"""Tests for the create_lyrics_providers() module-level factory."""
|
||||
|
||||
def test_returns_list(self):
|
||||
"""Factory always returns a list."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {}, clear=False):
|
||||
# Remove API keys so only LRCLIB is created
|
||||
env_override = {
|
||||
k: "" for k in ["GENIUS_API_KEY", "RAPIDAPI_KEY", "SPOTIFY_COOKIE_SP_DC"]
|
||||
}
|
||||
with patch.dict(os.environ, env_override):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
assert isinstance(providers, list)
|
||||
|
||||
def test_lrclib_always_included(self):
|
||||
"""LRCLIBProvider is always included regardless of env vars."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "LRCLIB" in provider_names
|
||||
|
||||
def test_genius_included_when_genius_key_set(self):
|
||||
"""GeniusProvider is included when GENIUS_API_KEY is set."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {"GENIUS_API_KEY": "fake-key", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "Genius" in provider_names
|
||||
|
||||
def test_genius_included_when_rapidapi_key_set(self):
|
||||
"""GeniusProvider is included when RAPIDAPI_KEY is set (uses RapidAPI path)."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "Genius" in provider_names
|
||||
|
||||
def test_spotify_included_when_cookie_set(self):
|
||||
"""SpotifyProvider is included when SPOTIFY_COOKIE_SP_DC is set."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": "fake-cookie"}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "Spotify" in provider_names
|
||||
|
||||
def test_musixmatch_included_when_rapidapi_key_set(self):
|
||||
"""MusixmatchProvider is included when RAPIDAPI_KEY is set."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "Musixmatch" in provider_names
|
||||
|
||||
def test_genius_not_included_without_keys(self):
|
||||
"""GeniusProvider is excluded when neither key is set."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "Genius" not in provider_names
|
||||
|
||||
def test_all_providers_when_all_keys_set(self):
|
||||
"""All four providers are returned when all credentials are set."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
|
||||
with patch.dict(os.environ, {
|
||||
"GENIUS_API_KEY": "gk",
|
||||
"RAPIDAPI_KEY": "rk",
|
||||
"SPOTIFY_COOKIE_SP_DC": "sc",
|
||||
}):
|
||||
providers = create_lyrics_providers(cache_dir="/tmp")
|
||||
provider_names = [p.get_name() for p in providers]
|
||||
assert "Genius" in provider_names
|
||||
assert "Spotify" in provider_names
|
||||
assert "Musixmatch" in provider_names
|
||||
assert "LRCLIB" in provider_names
|
||||
assert len(providers) == 4
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: CorrectionOperations.search_lyrics_sources
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSearchLyricsSources:
|
||||
"""Tests for CorrectionOperations.search_lyrics_sources()."""
|
||||
|
||||
def _mock_provider(self, name: str, lyrics_data=None):
|
||||
"""Build a mock BaseLyricsProvider that returns lyrics_data."""
|
||||
mock = MagicMock()
|
||||
mock.get_name.return_value = name
|
||||
mock.fetch_lyrics.return_value = lyrics_data
|
||||
return mock
|
||||
|
||||
def test_returns_dict_with_expected_keys(self):
|
||||
"""Return value always contains all four expected keys."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
|
||||
mock_factory.return_value = [] # No providers — simulates empty env
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
assert "updated_result" in result
|
||||
assert "sources_added" in result
|
||||
assert "sources_rejected" in result
|
||||
assert "sources_not_found" in result
|
||||
|
||||
def test_no_providers_returns_no_results(self):
|
||||
"""When no providers are available, returns no results."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
|
||||
mock_factory.return_value = []
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
assert result["updated_result"] is None
|
||||
assert result["sources_added"] == []
|
||||
|
||||
def test_provider_not_found_appended_to_not_found(self):
|
||||
"""Provider returning None is recorded in sources_not_found."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
mock_provider = self._mock_provider("LRCLIB", lyrics_data=None)
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
|
||||
mock_factory.return_value = [mock_provider]
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
assert "LRCLIB" in result["sources_not_found"]
|
||||
assert result["updated_result"] is None
|
||||
|
||||
def test_provider_exception_appended_to_not_found(self):
|
||||
"""Provider raising an exception is recorded in sources_not_found."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
mock_provider = self._mock_provider("Genius")
|
||||
mock_provider.fetch_lyrics.side_effect = RuntimeError("network error")
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
|
||||
mock_factory.return_value = [mock_provider]
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
assert "Genius" in result["sources_not_found"]
|
||||
|
||||
def test_existing_source_skipped(self):
|
||||
"""Provider whose name is already in reference_lyrics is skipped."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
existing_lyrics = {"Genius": _make_lyrics_data("Genius")}
|
||||
correction_result = _make_correction_result(reference_lyrics=existing_lyrics)
|
||||
mock_provider = self._mock_provider("Genius", lyrics_data=_make_lyrics_data("Genius"))
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
|
||||
mock_factory.return_value = [mock_provider]
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
# fetch_lyrics should NOT have been called
|
||||
mock_provider.fetch_lyrics.assert_not_called()
|
||||
assert result["updated_result"] is None # Nothing new to add
|
||||
|
||||
def test_lyrics_found_runs_corrector(self):
|
||||
"""When lyrics are found, LyricsCorrector.run is called."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
lyrics_data = _make_lyrics_data("LRCLIB")
|
||||
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
|
||||
|
||||
mock_corrector = MagicMock()
|
||||
mock_corrector.all_handlers = []
|
||||
mock_corrector.handlers = []
|
||||
mock_updated = _make_correction_result(metadata={"audio_hash": "testhash"})
|
||||
mock_corrector.run.return_value = mock_updated
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
|
||||
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
|
||||
mock_factory.return_value = [mock_provider]
|
||||
MockCorrector.return_value = mock_corrector
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
assert mock_corrector.run.called
|
||||
|
||||
def test_force_sources_bypass_rejection(self):
|
||||
"""Sources in force_sources are added even if the corrector rejects them."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
lyrics_data = _make_lyrics_data("Genius")
|
||||
mock_provider = self._mock_provider("Genius", lyrics_data=lyrics_data)
|
||||
|
||||
# Corrector result that puts "Genius" in rejected_sources
|
||||
mock_corrector = MagicMock()
|
||||
mock_corrector.all_handlers = []
|
||||
mock_corrector.handlers = []
|
||||
mock_updated = _make_correction_result(
|
||||
reference_lyrics={}, # Corrector filtered it out
|
||||
metadata={
|
||||
"audio_hash": "testhash",
|
||||
"rejected_sources": {
|
||||
"Genius": {"relevance": 0.0, "matched_words": 0, "total_words": 10,
|
||||
"track_name": "", "artist_names": ""},
|
||||
},
|
||||
}
|
||||
)
|
||||
mock_corrector.run.return_value = mock_updated
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
|
||||
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
|
||||
mock_factory.return_value = [mock_provider]
|
||||
MockCorrector.return_value = mock_corrector
|
||||
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
force_sources=["Genius"],
|
||||
)
|
||||
|
||||
# The forced source should be in sources_added, not rejected
|
||||
assert "Genius" in result["sources_added"]
|
||||
assert "Genius" not in result["sources_rejected"]
|
||||
# And it should have been re-added to reference_lyrics
|
||||
assert "Genius" in result["updated_result"].reference_lyrics
|
||||
|
||||
def test_audio_hash_preserved(self):
|
||||
"""The audio_hash from the original correction_result is preserved."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
original_hash = "original-audio-hash-abc"
|
||||
correction_result = _make_correction_result(metadata={"audio_hash": original_hash})
|
||||
lyrics_data = _make_lyrics_data("LRCLIB")
|
||||
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
|
||||
|
||||
mock_corrector = MagicMock()
|
||||
mock_corrector.all_handlers = []
|
||||
mock_corrector.handlers = []
|
||||
mock_updated = _make_correction_result(metadata={}) # metadata without audio_hash
|
||||
mock_corrector.run.return_value = mock_updated
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
|
||||
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
|
||||
mock_factory.return_value = [mock_provider]
|
||||
MockCorrector.return_value = mock_corrector
|
||||
result = CorrectionOperations.search_lyrics_sources(
|
||||
correction_result=correction_result,
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
cache_dir="/tmp",
|
||||
)
|
||||
|
||||
if result["updated_result"] is not None:
|
||||
assert result["updated_result"].metadata.get("audio_hash") == original_hash
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: CorrectionOperations.add_lyrics_source force parameter
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAddLyricsSourceForce:
|
||||
"""Tests for the force parameter added to add_lyrics_source."""
|
||||
|
||||
def test_force_false_does_not_override_rejection(self):
|
||||
"""With force=False (default), rejected sources remain rejected."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
|
||||
mock_corrector = MagicMock()
|
||||
mock_corrector.all_handlers = []
|
||||
mock_corrector.handlers = []
|
||||
mock_updated = _make_correction_result(
|
||||
reference_lyrics={}, # source was filtered out
|
||||
metadata={
|
||||
"audio_hash": "testhash",
|
||||
"rejected_sources": {
|
||||
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
|
||||
"track_name": "", "artist_names": ""},
|
||||
},
|
||||
}
|
||||
)
|
||||
mock_corrector.run.return_value = mock_updated
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
|
||||
MockCorrector.return_value = mock_corrector
|
||||
result = CorrectionOperations.add_lyrics_source(
|
||||
correction_result=correction_result,
|
||||
source="custom",
|
||||
lyrics_text="Hello world\nTest line",
|
||||
cache_dir="/tmp",
|
||||
force=False,
|
||||
)
|
||||
|
||||
# Source should NOT be in reference_lyrics when force=False
|
||||
assert "custom" not in result.reference_lyrics
|
||||
|
||||
def test_force_true_adds_source_even_if_rejected(self):
|
||||
"""With force=True, source is added back even if the corrector rejected it."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
|
||||
mock_corrector = MagicMock()
|
||||
mock_corrector.all_handlers = []
|
||||
mock_corrector.handlers = []
|
||||
mock_updated = _make_correction_result(
|
||||
reference_lyrics={}, # source was filtered out
|
||||
metadata={
|
||||
"audio_hash": "testhash",
|
||||
"rejected_sources": {
|
||||
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
|
||||
"track_name": "", "artist_names": ""},
|
||||
},
|
||||
}
|
||||
)
|
||||
mock_corrector.run.return_value = mock_updated
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
|
||||
MockCorrector.return_value = mock_corrector
|
||||
result = CorrectionOperations.add_lyrics_source(
|
||||
correction_result=correction_result,
|
||||
source="custom",
|
||||
lyrics_text="Hello world\nTest line",
|
||||
cache_dir="/tmp",
|
||||
force=True,
|
||||
)
|
||||
|
||||
# Source SHOULD be in reference_lyrics when force=True
|
||||
assert "custom" in result.reference_lyrics
|
||||
|
||||
def test_force_true_no_op_when_source_not_rejected(self):
|
||||
"""With force=True but source wasn't rejected, nothing extra happens."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
correction_result = _make_correction_result()
|
||||
|
||||
mock_corrector = MagicMock()
|
||||
mock_corrector.all_handlers = []
|
||||
mock_corrector.handlers = []
|
||||
# Source is accepted (not in rejected_sources)
|
||||
mock_updated = _make_correction_result(
|
||||
reference_lyrics={"custom": _make_lyrics_data("custom")},
|
||||
metadata={"audio_hash": "testhash"},
|
||||
)
|
||||
mock_corrector.run.return_value = mock_updated
|
||||
|
||||
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
|
||||
MockCorrector.return_value = mock_corrector
|
||||
result = CorrectionOperations.add_lyrics_source(
|
||||
correction_result=correction_result,
|
||||
source="custom",
|
||||
lyrics_text="Hello world\nTest line",
|
||||
cache_dir="/tmp",
|
||||
force=True,
|
||||
)
|
||||
|
||||
# Source remains in reference_lyrics normally
|
||||
assert "custom" in result.reference_lyrics
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: POST /{job_id}/search-lyrics API endpoint
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSearchLyricsEndpoint:
|
||||
"""Tests for the POST /{job_id}/search-lyrics API endpoint."""
|
||||
|
||||
def test_endpoint_exists(self):
|
||||
"""Verify the search-lyrics endpoint is registered in the router."""
|
||||
from backend.api.routes.review import router
|
||||
paths = [route.path for route in router.routes]
|
||||
assert any("search-lyrics" in p for p in paths), f"search-lyrics not found in: {paths}"
|
||||
|
||||
def test_search_lyrics_requires_artist_and_title(self):
|
||||
"""Document that the endpoint requires artist and title fields."""
|
||||
valid_payload = {
|
||||
"artist": "The Beatles",
|
||||
"title": "Hey Jude",
|
||||
}
|
||||
assert "artist" in valid_payload
|
||||
assert "title" in valid_payload
|
||||
assert valid_payload["artist"].strip()
|
||||
assert valid_payload["title"].strip()
|
||||
|
||||
def test_search_lyrics_accepts_force_sources(self):
|
||||
"""Document that force_sources is an optional list of provider names."""
|
||||
payload_with_force = {
|
||||
"artist": "The Beatles",
|
||||
"title": "Hey Jude",
|
||||
"force_sources": ["Genius", "LRCLIB"],
|
||||
}
|
||||
assert isinstance(payload_with_force["force_sources"], list)
|
||||
|
||||
def test_success_response_format(self):
|
||||
"""Document the expected success response format."""
|
||||
example_success_response = {
|
||||
"status": "success",
|
||||
"data": {}, # CorrectionData dict
|
||||
"sources_added": ["LRCLIB"],
|
||||
"sources_rejected": {"Genius": {"relevance": 0.1}},
|
||||
"sources_not_found": ["Spotify"],
|
||||
}
|
||||
assert example_success_response["status"] == "success"
|
||||
assert "data" in example_success_response
|
||||
assert "sources_added" in example_success_response
|
||||
assert "sources_rejected" in example_success_response
|
||||
assert "sources_not_found" in example_success_response
|
||||
|
||||
def test_no_results_response_format(self):
|
||||
"""Document the expected no_results response format."""
|
||||
example_no_results_response = {
|
||||
"status": "no_results",
|
||||
"message": "No matching lyrics found from any provider",
|
||||
"sources_rejected": {},
|
||||
"sources_not_found": ["Genius", "LRCLIB"],
|
||||
}
|
||||
assert example_no_results_response["status"] == "no_results"
|
||||
assert "message" in example_no_results_response
|
||||
assert "sources_rejected" in example_no_results_response
|
||||
assert "sources_not_found" in example_no_results_response
|
||||
|
||||
def test_search_lyrics_uses_correction_operations(self):
|
||||
"""Verify CorrectionOperations.search_lyrics_sources exists and is callable."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
assert hasattr(CorrectionOperations, "search_lyrics_sources")
|
||||
method = getattr(CorrectionOperations, "search_lyrics_sources")
|
||||
assert callable(method)
|
||||
|
||||
def test_add_lyrics_source_has_force_parameter(self):
|
||||
"""Verify add_lyrics_source now accepts a force parameter."""
|
||||
import inspect
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
sig = inspect.signature(CorrectionOperations.add_lyrics_source)
|
||||
assert "force" in sig.parameters
|
||||
# Default should be False
|
||||
assert sig.parameters["force"].default is False
|
||||
@@ -336,9 +336,54 @@ class TestWorkerService:
|
||||
assert "test123" in str(override_args)
|
||||
|
||||
|
||||
class TestWorkerServiceWarmup:
|
||||
"""Test encoding worker warmup in trigger methods."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_video_worker_calls_warmup(self):
|
||||
"""trigger_video_worker calls _warmup_encoding_worker before dispatching."""
|
||||
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
worker_service = get_worker_service()
|
||||
|
||||
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
|
||||
await worker_service.trigger_video_worker("test-job")
|
||||
mock_warmup.assert_called_once_with("test-job")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_render_video_worker_calls_warmup(self):
|
||||
"""trigger_render_video_worker calls _warmup_encoding_worker before dispatching."""
|
||||
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
worker_service = get_worker_service()
|
||||
|
||||
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
|
||||
await worker_service.trigger_render_video_worker("test-job")
|
||||
mock_warmup.assert_called_once_with("test-job")
|
||||
|
||||
def test_warmup_swallows_exceptions(self):
|
||||
"""Warmup failures are logged but never block worker dispatch."""
|
||||
worker_service = get_worker_service()
|
||||
|
||||
with patch('backend.services.encoding_worker_manager.EncodingWorkerManager.ensure_primary_running',
|
||||
side_effect=Exception("Compute API down")):
|
||||
# Should not raise
|
||||
worker_service._warmup_encoding_worker("test-job")
|
||||
|
||||
|
||||
class TestWorkerServiceCloudTasks:
|
||||
"""Test WorkerService Cloud Tasks integration."""
|
||||
|
||||
|
||||
def test_should_use_cloud_tasks_default_false(self):
|
||||
"""Test that Cloud Tasks is disabled by default."""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
|
||||
@@ -179,48 +179,48 @@ class TestLyricsWorker:
|
||||
return storage
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_requires_job(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results correctly fetches job for artist/title.
|
||||
|
||||
This test would have caught the UnboundLocalError bug where job was used
|
||||
before being defined.
|
||||
async def test_upload_lyrics_results_finds_corrections_by_scan(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results finds corrections JSON by scanning the directory.
|
||||
|
||||
The function scans for files ending in '(Lyrics Corrections).json' rather than
|
||||
reconstructing filenames from job.artist/title, since those may change mid-processing
|
||||
(e.g. admin updates artist name while lyrics worker is running).
|
||||
"""
|
||||
with patch('backend.workers.lyrics_worker.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.workers.lyrics_worker.StorageService', return_value=mock_storage):
|
||||
|
||||
|
||||
from backend.workers.lyrics_worker import upload_lyrics_results
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Create mock lyrics directory and files
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
os.makedirs(lyrics_dir)
|
||||
|
||||
# Create test LRC file
|
||||
|
||||
lrc_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Karaoke).lrc")
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write("[00:00.00]Test lyrics\n")
|
||||
|
||||
# Create corrections JSON
|
||||
corrections_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Lyrics Corrections).json")
|
||||
|
||||
# Use a different artist than what's in the job to simulate mid-run rename
|
||||
corrections_path = os.path.join(lyrics_dir, "OldArtist - Waterloo (Lyrics Corrections).json")
|
||||
with open(corrections_path, 'w') as f:
|
||||
json.dump({"lines": [], "corrections": []}, f)
|
||||
|
||||
|
||||
transcription_result = {
|
||||
"lrc_filepath": lrc_path,
|
||||
"corrections_filepath": corrections_path
|
||||
}
|
||||
|
||||
# This should NOT raise UnboundLocalError
|
||||
|
||||
await upload_lyrics_results(
|
||||
"test123",
|
||||
temp_dir,
|
||||
transcription_result,
|
||||
mock_storage,
|
||||
"test123",
|
||||
temp_dir,
|
||||
transcription_result,
|
||||
mock_storage,
|
||||
mock_job_manager
|
||||
)
|
||||
|
||||
# Verify job was fetched
|
||||
mock_job_manager.get_job.assert_called_with("test123")
|
||||
|
||||
# Verify corrections file was found and uploaded as corrections.json
|
||||
upload_calls = mock_storage.upload_file.call_args_list
|
||||
corrections_uploads = [c for c in upload_calls if 'corrections.json' in str(c)]
|
||||
assert len(corrections_uploads) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_uploads_lrc_file(self, mock_job_manager, mock_storage, mock_job):
|
||||
@@ -281,53 +281,68 @@ class TestLyricsWorker:
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_uses_artist_title_from_job(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results correctly uses job.artist and job.title.
|
||||
|
||||
This test specifically validates the bug fix where job was not defined
|
||||
when accessing job.artist and job.title for reference file lookups.
|
||||
"""
|
||||
async def test_upload_lyrics_results_raises_when_no_corrections(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results raises when no corrections file exists at all."""
|
||||
from backend.workers.lyrics_worker import upload_lyrics_results
|
||||
import json
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
os.makedirs(lyrics_dir)
|
||||
|
||||
# Create LRC file
|
||||
|
||||
lrc_path = os.path.join(lyrics_dir, "test.lrc")
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write("[00:00.00]Test\n")
|
||||
|
||||
# Create required corrections.json file
|
||||
corrections_path = os.path.join(lyrics_dir, "corrections.json")
|
||||
|
||||
# No corrections file at all
|
||||
transcription_result = {"lrc_filepath": lrc_path}
|
||||
|
||||
with pytest.raises(Exception, match="No corrections JSON found"):
|
||||
await upload_lyrics_results(
|
||||
"test123", temp_dir, transcription_result,
|
||||
mock_storage, mock_job_manager
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_lyrics_results_finds_reference_and_uncorrected_by_scan(self, mock_job_manager, mock_storage, mock_job):
|
||||
"""Test that upload_lyrics_results finds reference and uncorrected files by scanning.
|
||||
|
||||
Files are found by suffix pattern, not by reconstructing from job.artist/title,
|
||||
so mid-processing artist name changes don't break the upload.
|
||||
"""
|
||||
from backend.workers.lyrics_worker import upload_lyrics_results
|
||||
import json
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
os.makedirs(lyrics_dir)
|
||||
|
||||
lrc_path = os.path.join(lyrics_dir, "test.lrc")
|
||||
with open(lrc_path, 'w') as f:
|
||||
f.write("[00:00.00]Test\n")
|
||||
|
||||
corrections_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Corrections).json")
|
||||
with open(corrections_path, 'w') as f:
|
||||
json.dump({"corrected_segments": []}, f)
|
||||
|
||||
# Create a reference lyrics file using the job's artist/title
|
||||
ref_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Genius).txt")
|
||||
|
||||
# Reference and uncorrected files with arbitrary artist name
|
||||
ref_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Genius).txt")
|
||||
with open(ref_path, 'w') as f:
|
||||
f.write("Reference lyrics content\n")
|
||||
|
||||
# Create uncorrected transcription file using job's artist/title
|
||||
uncorrected_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Uncorrected).txt")
|
||||
|
||||
uncorrected_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Uncorrected).txt")
|
||||
with open(uncorrected_path, 'w') as f:
|
||||
f.write("Uncorrected transcription\n")
|
||||
|
||||
|
||||
transcription_result = {"lrc_filepath": lrc_path}
|
||||
|
||||
# This should NOT raise UnboundLocalError for 'job'
|
||||
|
||||
await upload_lyrics_results(
|
||||
"test123", temp_dir, transcription_result,
|
||||
mock_storage, mock_job_manager
|
||||
)
|
||||
|
||||
# Verify job was fetched to get artist/title
|
||||
mock_job_manager.get_job.assert_called_with("test123")
|
||||
|
||||
# Verify files were uploaded (the reference and uncorrected files exist)
|
||||
|
||||
# Verify files were uploaded: LRC + corrections + genius ref + uncorrected = 4
|
||||
upload_calls = mock_storage.upload_file.call_args_list
|
||||
assert len(upload_calls) >= 2 # LRC + at least one reference or uncorrected
|
||||
assert len(upload_calls) == 4
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_lyrics_transcription_marks_failed_on_error(self, mock_job_manager, mock_storage):
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
Audio separation worker.
|
||||
|
||||
Handles the audio processing track of parallel processing:
|
||||
1. Stage 1: Clean instrumental separation (Modal API, 3-5 min)
|
||||
2. Stage 2: Backing vocals separation (Modal API, 2-3 min)
|
||||
1. Stage 1: Clean instrumental separation (GPU, 3-5 min)
|
||||
2. Stage 2: Backing vocals separation (GPU, 2-3 min)
|
||||
3. Post-processing: Combine instrumentals, normalize
|
||||
|
||||
Re-uses karaoke_gen.audio_processor.AudioProcessor for remote GPU separation.
|
||||
Supports two modes:
|
||||
- Local GPU: Runs Separator directly with L4 GPU (MODEL_DIR env var)
|
||||
- Remote API: Calls audio-separator Cloud Run Service (AUDIO_SEPARATOR_API_URL env var)
|
||||
|
||||
Observability:
|
||||
- All operations wrapped in tracing spans for Cloud Trace visibility
|
||||
@@ -200,6 +202,7 @@ async def download_from_url(url: str, temp_dir: str, artist: str, title: str, jo
|
||||
|
||||
def create_audio_processor(
|
||||
temp_dir: str,
|
||||
model_file_dir: Optional[str] = None,
|
||||
clean_instrumental_model: Optional[str] = None,
|
||||
backing_vocals_models: Optional[list] = None,
|
||||
other_stems_models: Optional[list] = None,
|
||||
@@ -207,15 +210,24 @@ def create_audio_processor(
|
||||
karaoke_preset: Optional[str] = None,
|
||||
) -> AudioProcessor:
|
||||
"""
|
||||
Create an AudioProcessor instance configured for remote API processing.
|
||||
Create an AudioProcessor instance configured for audio processing.
|
||||
|
||||
Supports two modes:
|
||||
- Local GPU mode: When model_file_dir is set, uses the local Separator class
|
||||
with GPU models loaded from that directory. No remote API calls.
|
||||
- Remote API mode (default): When model_file_dir is None, delegates separation
|
||||
to a remote audio-separator API server.
|
||||
|
||||
Within each mode, separation can be configured via:
|
||||
- Preset mode (default): Uses ensemble presets for higher quality separation.
|
||||
Presets are resolved by the audio-separator API server.
|
||||
Presets are resolved by the audio-separator API server (remote) or local
|
||||
preset definitions (local GPU).
|
||||
- Model mode (legacy): Uses explicit model filenames for per-job overrides.
|
||||
|
||||
Args:
|
||||
temp_dir: Temporary directory for processing
|
||||
model_file_dir: Directory containing local model files for GPU separation.
|
||||
When set, enables local GPU mode. When None (default), uses remote API.
|
||||
clean_instrumental_model: Model for clean instrumental (legacy, overrides preset)
|
||||
backing_vocals_models: Models for backing vocals (legacy, overrides preset)
|
||||
other_stems_models: Models for other stems (legacy, default empty)
|
||||
@@ -241,7 +253,7 @@ def create_audio_processor(
|
||||
logger=audio_logger,
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None, # No local models, using remote API
|
||||
model_file_dir=model_file_dir,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model=effective_clean_model,
|
||||
backing_vocals_models=effective_backing_models,
|
||||
@@ -249,7 +261,7 @@ def create_audio_processor(
|
||||
ffmpeg_base_command=ffmpeg_base_command,
|
||||
)
|
||||
|
||||
# Set preset configuration (used by _process_audio_separation_remote)
|
||||
# Set preset configuration (used by both remote and local paths)
|
||||
processor.instrumental_preset = instrumental_preset or DEFAULT_INSTRUMENTAL_PRESET
|
||||
processor.karaoke_preset = karaoke_preset or DEFAULT_KARAOKE_PRESET
|
||||
|
||||
@@ -265,8 +277,8 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
|
||||
Workflow:
|
||||
1. Download audio from GCS
|
||||
2. Stage 1: Separate with clean instrumental + other stems models (Modal API)
|
||||
3. Stage 2: Separate vocals for backing vocals (Modal API)
|
||||
2. Stage 1: Separate with clean instrumental + other stems models (GPU)
|
||||
3. Stage 2: Separate vocals for backing vocals (GPU)
|
||||
4. Post-process: Combine instrumentals, normalize audio
|
||||
5. Upload all stems to GCS
|
||||
6. Mark job as AUDIO_COMPLETE
|
||||
@@ -326,13 +338,22 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
job_log.info(f"Starting audio separation for {job.artist} - {job.title}")
|
||||
logger.info(f"[job:{job_id}] Starting audio separation for {job.artist} - {job.title}")
|
||||
|
||||
# Ensure AUDIO_SEPARATOR_API_URL is set
|
||||
# Determine separation mode: local GPU or remote API
|
||||
api_url = os.environ.get("AUDIO_SEPARATOR_API_URL")
|
||||
if not api_url:
|
||||
raise Exception("AUDIO_SEPARATOR_API_URL environment variable not set. "
|
||||
"Cannot perform audio separation without remote API access.")
|
||||
job_log.info(f"Audio separator API: {api_url}")
|
||||
add_span_attribute("audio_separator_api", api_url)
|
||||
model_dir = os.environ.get("MODEL_DIR")
|
||||
if api_url:
|
||||
job_log.info(f"Audio separator mode: remote API at {api_url}")
|
||||
add_span_attribute("audio_separator_mode", "remote")
|
||||
add_span_attribute("audio_separator_api", api_url)
|
||||
elif model_dir:
|
||||
job_log.info(f"Audio separator mode: local GPU (models at {model_dir})")
|
||||
add_span_attribute("audio_separator_mode", "local_gpu")
|
||||
add_span_attribute("model_dir", model_dir)
|
||||
else:
|
||||
raise Exception(
|
||||
"Audio separation not configured. Set either AUDIO_SEPARATOR_API_URL "
|
||||
"(remote API) or MODEL_DIR (local GPU with baked-in models)."
|
||||
)
|
||||
|
||||
# Download audio file from GCS or URL
|
||||
with job_span("download-audio", job_id) as download_span:
|
||||
@@ -371,9 +392,15 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
clean_instrumental_model=job.clean_instrumental_model,
|
||||
backing_vocals_models=job.backing_vocals_models,
|
||||
other_stems_models=job.other_stems_models,
|
||||
model_file_dir=model_dir,
|
||||
)
|
||||
audio_processor.job_id = job_id # Used as filename prefix (avoids artist/title encoding issues)
|
||||
|
||||
# Pass GCS URI so the separator can fetch directly from GCS (avoids 413 for large files)
|
||||
if job.input_media_gcs_path:
|
||||
audio_processor.input_gcs_uri = f"gs://{settings.gcs_bucket_name}/{job.input_media_gcs_path}"
|
||||
job_log.info(f" GCS URI for separator: {audio_processor.input_gcs_uri}")
|
||||
|
||||
# Store effective model names in state_data for video_worker to use in file naming
|
||||
# This ensures output filenames match local CLI behavior (e.g., "Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt")
|
||||
effective_model_names = {
|
||||
@@ -392,15 +419,15 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
artist_title = f"{safe_artist} - {safe_title}"
|
||||
|
||||
# Run audio separation (calls Modal API internally)
|
||||
# Run audio separation (local GPU or remote API)
|
||||
# This returns a dict with paths to all separated stems
|
||||
with job_span("modal-separation", job_id) as sep_span:
|
||||
with job_span("audio-separation", job_id) as sep_span:
|
||||
sep_start = time.time()
|
||||
job_log.info("Starting audio separation (this may take 5-10 minutes)...")
|
||||
job_log.info(" Stage 1: Clean instrumental separation (MDX models)")
|
||||
job_log.info(" Stage 2: Backing vocals separation (Demucs model)")
|
||||
add_span_event("separation_started")
|
||||
logger.info(f"[job:{job_id}] Calling Modal API for audio separation")
|
||||
logger.info(f"[job:{job_id}] Starting audio separation")
|
||||
|
||||
# Retry with exponential backoff. The audio-separator GPU service
|
||||
# may be busy processing other jobs for 5-10+ minutes each, so we
|
||||
@@ -408,7 +435,7 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
max_retries = 5
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
with metrics.time_external_api("modal", job_id):
|
||||
with metrics.time_external_api("audio_separation", job_id):
|
||||
separation_result = audio_processor.process_audio_separation(
|
||||
audio_file=audio_path,
|
||||
artist_title=artist_title,
|
||||
@@ -455,7 +482,7 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
# Store processing metadata for separation provenance
|
||||
duration = time.time() - start_time
|
||||
job_manager.update_processing_metadata(job_id, "separation", {
|
||||
"provider": "modal",
|
||||
"provider": "local_gpu" if model_dir else "remote_api",
|
||||
"clean_model": effective_model_names['clean_instrumental_model'],
|
||||
"backing_models": effective_model_names['backing_vocals_models'],
|
||||
"other_models": effective_model_names['other_stems_models'],
|
||||
@@ -796,7 +823,7 @@ def main():
|
||||
Environment Variables:
|
||||
GOOGLE_CLOUD_PROJECT: GCP project ID (required)
|
||||
GCS_BUCKET_NAME: Storage bucket name (required)
|
||||
AUDIO_SEPARATOR_API_URL: Modal API URL (required)
|
||||
AUDIO_SEPARATOR_API_URL: Remote API URL (or MODEL_DIR for local GPU)
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
|
||||
@@ -29,7 +29,6 @@ from typing import Optional, Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
@@ -599,10 +598,7 @@ async def upload_lyrics_results(
|
||||
job_log: Optional JobLogger for remote debugging
|
||||
"""
|
||||
logger.info(f"Job {job_id}: Uploading lyrics results to GCS")
|
||||
|
||||
# Get job object for artist/title
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
|
||||
lyrics_dir = os.path.join(temp_dir, "lyrics")
|
||||
|
||||
# Upload LRC file (timed lyrics)
|
||||
@@ -614,17 +610,21 @@ async def upload_lyrics_results(
|
||||
|
||||
# Upload corrections JSON (for review interface)
|
||||
# LyricsProcessor saves it as "{artist} - {title} (Lyrics Corrections).json"
|
||||
# Sanitize artist/title to prevent path injection and match LyricsProcessor's sanitization
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
corrections_filename = f"{safe_artist} - {safe_title} (Lyrics Corrections).json"
|
||||
corrections_file = os.path.join(lyrics_dir, corrections_filename)
|
||||
# Scan the directory instead of reconstructing the filename, because the artist/title
|
||||
# in Firestore may have been updated (e.g. by admin) after LyricsProcessor generated the file.
|
||||
corrections_file = None
|
||||
if os.path.isdir(lyrics_dir):
|
||||
for fname in os.listdir(lyrics_dir):
|
||||
if fname.endswith("(Lyrics Corrections).json"):
|
||||
corrections_file = os.path.join(lyrics_dir, fname)
|
||||
break
|
||||
# Fallback: check for generic corrections.json
|
||||
if not corrections_file:
|
||||
fallback = os.path.join(lyrics_dir, "corrections.json")
|
||||
if os.path.exists(fallback):
|
||||
corrections_file = fallback
|
||||
|
||||
# Also check for generic corrections.json (fallback)
|
||||
if not os.path.exists(corrections_file):
|
||||
corrections_file = os.path.join(lyrics_dir, "corrections.json")
|
||||
|
||||
if os.path.exists(corrections_file):
|
||||
if corrections_file and os.path.exists(corrections_file):
|
||||
# Always upload as corrections.json for consistent access
|
||||
gcs_path = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
url = storage.upload_file(corrections_file, gcs_path)
|
||||
@@ -660,33 +660,29 @@ async def upload_lyrics_results(
|
||||
else:
|
||||
# CRITICAL: corrections.json is required for the review UI
|
||||
# If it's missing, the job cannot proceed to review
|
||||
error_msg = f"No corrections JSON found at {corrections_file}. Transcription may have produced no lyrics."
|
||||
error_msg = f"No corrections JSON found in {lyrics_dir}. Transcription may have produced no lyrics."
|
||||
logger.error(f"Job {job_id}: {error_msg}")
|
||||
raise Exception(error_msg)
|
||||
|
||||
# Upload ALL reference lyrics files (not just first) so they're available for distribution
|
||||
# Note: Source names use .title() so "lrclib" -> "Lrclib", "genius" -> "Genius"
|
||||
# Use sanitized artist/title to match LyricsProcessor's file naming
|
||||
reference_files = [
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Genius).txt", "genius"),
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Spotify).txt", "spotify"),
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Musixmatch).txt", "musixmatch"),
|
||||
(f"{safe_artist} - {safe_title} (Lyrics Lrclib).txt", "lrclib"),
|
||||
]
|
||||
# Scan directory for reference files instead of reconstructing filenames,
|
||||
# since artist/title may have changed in Firestore after file generation.
|
||||
source_keys = {"Genius": "genius", "Spotify": "spotify", "Musixmatch": "musixmatch", "Lrclib": "lrclib"}
|
||||
|
||||
found_references = []
|
||||
for ref_filename, source_key in reference_files:
|
||||
ref_path = os.path.join(lyrics_dir, ref_filename)
|
||||
if os.path.exists(ref_path):
|
||||
# Upload with original filename to preserve proper naming
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{ref_filename}"
|
||||
url = storage.upload_file(ref_path, gcs_path)
|
||||
# Track in job.files so video_worker can download for distribution
|
||||
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
|
||||
if job_log:
|
||||
job_log.info(f"Found reference lyrics from {source_key}")
|
||||
logger.info(f"Job {job_id}: Uploaded reference lyrics: {ref_filename}")
|
||||
found_references.append(source_key)
|
||||
if os.path.isdir(lyrics_dir):
|
||||
for fname in os.listdir(lyrics_dir):
|
||||
for source_label, source_key in source_keys.items():
|
||||
if fname.endswith(f"(Lyrics {source_label}).txt"):
|
||||
ref_path = os.path.join(lyrics_dir, fname)
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
|
||||
url = storage.upload_file(ref_path, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
|
||||
if job_log:
|
||||
job_log.info(f"Found reference lyrics from {source_key}")
|
||||
logger.info(f"Job {job_id}: Uploaded reference lyrics: {fname}")
|
||||
found_references.append(source_key)
|
||||
break
|
||||
|
||||
if not found_references:
|
||||
if job_log:
|
||||
@@ -695,14 +691,17 @@ async def upload_lyrics_results(
|
||||
else:
|
||||
logger.info(f"Job {job_id}: Found {len(found_references)} reference lyrics sources: {found_references}")
|
||||
|
||||
# Upload uncorrected transcription if available (preserve original filename for distribution)
|
||||
uncorrected_filename = f"{safe_artist} - {safe_title} (Lyrics Uncorrected).txt"
|
||||
uncorrected_file = os.path.join(lyrics_dir, uncorrected_filename)
|
||||
if os.path.exists(uncorrected_file):
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{uncorrected_filename}"
|
||||
url = storage.upload_file(uncorrected_file, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
|
||||
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {uncorrected_filename}")
|
||||
# Upload uncorrected transcription if available
|
||||
# Scan directory instead of reconstructing filename (artist/title may have changed)
|
||||
if os.path.isdir(lyrics_dir):
|
||||
for fname in os.listdir(lyrics_dir):
|
||||
if fname.endswith("(Lyrics Uncorrected).txt"):
|
||||
uncorrected_file = os.path.join(lyrics_dir, fname)
|
||||
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
|
||||
url = storage.upload_file(uncorrected_file, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
|
||||
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {fname}")
|
||||
break
|
||||
|
||||
logger.info(f"Job {job_id}: All lyrics results uploaded successfully")
|
||||
|
||||
|
||||
@@ -1219,7 +1219,7 @@ def _validate_prerequisites(job) -> bool:
|
||||
status_error = validate_worker_can_run("video_worker", job)
|
||||
if status_error:
|
||||
logger.warning(f"Job {job.job_id}: {status_error}")
|
||||
# Continue anyway - this is a safety net warning, not a hard failure
|
||||
return False
|
||||
|
||||
# Check instrumental selection
|
||||
instrumental_selection = job.state_data.get('instrumental_selection')
|
||||
|
||||
+55
@@ -441,6 +441,61 @@ Content-Type: application/json
|
||||
|
||||
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
|
||||
|
||||
#### Add Reference Lyrics (Paste)
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/add-lyrics
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"source": "manual",
|
||||
"lyrics": "Full lyrics text...",
|
||||
"force": false
|
||||
}
|
||||
```
|
||||
|
||||
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
|
||||
|
||||
Returns `{ "status": "success", "data": <CorrectionData> }`.
|
||||
|
||||
#### Search Reference Lyrics
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/search-lyrics
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Billie Eilish",
|
||||
"title": "What Was I Made For",
|
||||
"force_sources": []
|
||||
}
|
||||
```
|
||||
|
||||
Searches all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB) with the given artist/title. Results are filtered through the relevance threshold (30% word match minimum) — sources below are rejected as likely wrong-song matches. Sources in `force_sources` bypass the threshold.
|
||||
|
||||
**Success response** (at least one source passed):
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"data": { "...CorrectionData..." },
|
||||
"sources_added": ["genius", "lrclib"],
|
||||
"sources_rejected": {
|
||||
"spotify": { "relevance": 0.12, "matched_words": 18, "total_words": 150, "track_name": "...", "artist_names": "..." }
|
||||
},
|
||||
"sources_not_found": ["musixmatch"]
|
||||
}
|
||||
```
|
||||
|
||||
**No results response** (all filtered or nothing found):
|
||||
```json
|
||||
{
|
||||
"status": "no_results",
|
||||
"message": "No matching lyrics found from any provider",
|
||||
"sources_rejected": { "genius": { "relevance": 0.05, "..." } },
|
||||
"sources_not_found": ["lrclib", "musixmatch"]
|
||||
}
|
||||
```
|
||||
|
||||
#### Review Sessions
|
||||
|
||||
Server-side backup/restore of lyrics review editing sessions. Correction data is stored in GCS; metadata in Firestore subcollection `jobs/{job_id}/review_sessions/{session_id}`.
|
||||
|
||||
+28
-2
@@ -161,7 +161,7 @@ LyricsTranscriber LyricsTranscriber
|
||||
|
||||
| Service | Purpose | Required |
|
||||
|---------|---------|----------|
|
||||
| Cloud Run GPU (L4) | Audio stem separation (us-east4) | Yes |
|
||||
| Cloud Run GPU Job (L4, us-east4) | Audio stem separation — `Separator` runs directly in the audio worker Job (no HTTP hop) | Yes |
|
||||
| AudioShake | Lyrics transcription | Yes |
|
||||
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
|
||||
| Genius | Reference lyrics | Yes |
|
||||
@@ -369,7 +369,7 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
|
||||
│ │
|
||||
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
|
||||
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
|
||||
│ audio-separation-job - 10-20 min (Cloud Run GPU) │
|
||||
│ audio-separation-job - 10-20 min (L4 GPU, us-east4, direct) │
|
||||
│ video-encoding-job - up to 60 min (optional) │
|
||||
│ │
|
||||
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
|
||||
@@ -406,6 +406,32 @@ Screens and render workers run via internal HTTP endpoints with BackgroundTasks,
|
||||
- If workers active, calls `wait_for_completion(timeout=600)` (10 min max)
|
||||
- Logs which workers are still running for debugging
|
||||
|
||||
## Audio Separation Architecture
|
||||
|
||||
Audio stem separation runs **directly inside the audio worker Cloud Run Job** — the `Separator` class from `audio-separator` is imported and called in-process. There is no separate GPU microservice.
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ audio-separation-job (Cloud Run Job, L4 GPU, us-east4) │
|
||||
│ │
|
||||
│ AudioWorker │
|
||||
│ ├── download audio from GCS │
|
||||
│ ├── create_audio_processor() ← Separator(model_file_dir=...) │
|
||||
│ ├── Stage 1: instrumental_clean preset │
|
||||
│ │ └── produces: vocals.flac, instrumental_clean.flac │
|
||||
│ ├── Stage 2: karaoke preset │
|
||||
│ │ └── produces: instrumental_with_backing.flac │
|
||||
│ └── upload stems to GCS │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Key decisions:**
|
||||
- **Direct GPU** — No HTTP hop to a separate service. Jobs can run up to 24h; no timeout concerns.
|
||||
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
|
||||
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
|
||||
|
||||
**Rollback**: The old audio-separator Cloud Run Service (HTTP endpoint) is kept for rollback but no longer receives traffic. It will be removed in a future phase.
|
||||
|
||||
## Multitenancy
|
||||
|
||||
The platform supports white-label B2B portals where business customers get their own branded karaoke generation experience.
|
||||
|
||||
@@ -170,7 +170,6 @@ The frontend's `detectTenantFromUrl()` checks for the `tenant` query param on lo
|
||||
# Required
|
||||
AUDIOSHAKE_API_TOKEN=...
|
||||
GENIUS_ACCESS_TOKEN=...
|
||||
AUDIO_SEPARATOR_API_URL=... # Modal API endpoint
|
||||
|
||||
# GCP (auto-configured in Cloud Run)
|
||||
GOOGLE_CLOUD_PROJECT=...
|
||||
|
||||
@@ -8,6 +8,9 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
## UX Patterns
|
||||
|
||||
### Don't Conflate "No Results" with "Not Yet Searched" (Mar 2026)
|
||||
When a search component initializes `results = []`, any rendering condition like `results.length === 0 && !error` will match both "search returned empty" and "haven't searched yet" (or "search failed silently"). Use an explicit state machine with phases (`searching | succeeded | failed`) so that "no results" UI only appears after a confirmed successful search. This prevents misleading users when the real problem was a timeout, network error, or silent exception.
|
||||
|
||||
### Fixture-Driven UI Verification
|
||||
For UI that renders differently based on data (e.g., audio search result tiers), fetch real production data as fixtures and build a Playwright review tool. The `npm run fixtures:review-ui` pattern (41 fixtures, console-based `next()` advancement) was far more effective than manual testing or screenshots — caught edge cases with non-Latin filenames, single-character filenames, and underscore-separated names that unit tests alone would have missed.
|
||||
|
||||
@@ -25,6 +28,7 @@ Three patterns from investigating production job failures where errors cascaded
|
||||
1. **Validate every stage's outputs, not just some** — stage 1 of audio separation had validation for expected stems, stage 2 didn't. The missing validation let a transient Modal API failure propagate through 3 more functions before crashing with a confusing NoneType error.
|
||||
2. **Block impossible downstream work early** — AudioShake returning 0 lyrics segments was treated as "success", letting the user submit an empty review that only failed at CDG generation. Validate at the boundary: if transcription returns 0 segments, fail with a user-friendly error, not 4 steps later.
|
||||
3. **File handles in retry loops** — when wrapping HTTP calls with retry (e.g. tenacity), ensure file handles are re-opened on each attempt. A `with open()` wrapping a retried `requests.post(files=...)` exhausts the file handle on the first attempt; subsequent retries send empty data.
|
||||
4. **Text normalization changes word counts** — `clean_text()` (strip punctuation, normalize whitespace) then `split()` can produce a different word count than the original Word objects list. In anchor sequence correction, `ref_texts_clean` had 599 words for Spotify but `ref_words` only had 528 Word objects. Anchor positions computed against the cleaned list were used to index the Word list, causing IndexError. Always bounds-check when indexing a different data structure than the one used to compute positions.
|
||||
|
||||
---
|
||||
|
||||
@@ -49,6 +53,38 @@ When a metadata key is missing, don't set it to "now" and skip the action — th
|
||||
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
|
||||
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
|
||||
|
||||
### Cloud Run GPU: Let the Platform Scale, Not Your Code (Mar 2026)
|
||||
|
||||
**Don't use fire-and-forget + semaphore on Cloud Run.** We tried making the `/separate` endpoint return immediately (fire-and-forget background thread) with a `threading.Semaphore(1)` to serialize GPU work. Cloud Run couldn't see background threads as "busy", so it routed ALL requests to one instance where they queued behind the semaphore — causing 30-minute timeouts in production.
|
||||
|
||||
**Fix: synchronous endpoint + `concurrency=1`.** Keep the HTTP request active during processing. Cloud Run sees the request as occupying the instance and scales to new GPU instances for concurrent jobs. This matches Modal's `.spawn()` pattern where each job gets its own container. The client POST timeout must match Cloud Run's request timeout (1800s).
|
||||
|
||||
**Rule of thumb**: If you need the platform's autoscaler to work for you, the request must stay active. Background threads are invisible to the platform.
|
||||
|
||||
### Direct GPU in Cloud Run Jobs > HTTP Microservice
|
||||
|
||||
When a Cloud Run Job needs GPU processing, attach the GPU directly to the Job instead of calling a separate GPU service over HTTP. Benefits:
|
||||
- No HTTP timeout concerns (Jobs can run up to 24h)
|
||||
- No connection management, retry logic, or polling
|
||||
- Simpler architecture (1 hop instead of 3)
|
||||
- Platform handles scaling naturally (each Job execution gets its own GPU)
|
||||
|
||||
The audio separator started as a separate Cloud Run Service called via HTTP from the audio worker Job. This required 1800s HTTP timeouts, complex retry logic, and caused a production outage when the fire-and-forget pattern interacted badly with Cloud Run's autoscaler. Moving the GPU work directly into the Job eliminated all of this complexity.
|
||||
|
||||
### GPU Docker Images: Pin CUDA-Specific Package Versions (Mar 2026)
|
||||
|
||||
**`pip install audio-separator[gpu]` pulls the latest PyTorch, which may require a newer CUDA than your runtime provides.** Cloud Run L4 GPUs have NVIDIA driver 570 (CUDA 12.8 max), but the default torch install gets `cu130` (requires CUDA 13.0), which fails silently — PyTorch reports "NVIDIA driver is too old" and falls back to CPU, then ONNX models fail to load.
|
||||
|
||||
**Fix:** Pin torch to a CUDA version your driver supports (`torch==2.6.0+cu126` from `--index-url https://download.pytorch.org/whl/cu126`), install it BEFORE `audio-separator[gpu]`, and protect it from being overwritten by later `pip install` commands (use `--no-deps` in the app layer).
|
||||
|
||||
**Validate with the actual Docker image, not just packages.** We proved the package combo worked interactively on a VM but missed that the app Dockerfile's `pip install -e .` (with `torch>=2.7` in pyproject.toml) upgraded torch back to cu130. The fastest debugging loop: spin up a GCE L4 VM (~$1/hr), build the Docker image locally, run separation inside the container with `--gpus all`, tear down.
|
||||
|
||||
### audio-separator Ensemble Presets Require Explicit load_model() (Mar 2026)
|
||||
|
||||
**Always call `separator.load_model()` before `separator.separate()`, even when using ensemble presets.** The Separator constructor with `ensemble_preset=` resolves the preset to model names but does NOT load them into memory. Calling `separate()` without `load_model()` fails with "Initialization failed or model not loaded."
|
||||
|
||||
Similarly, **baking models into Docker images requires downloading each model individually** — `Separator(ensemble_preset=...).load_model()` with no args doesn't trigger downloads. Use `sep.load_model(model_filename)` for each model file in the preset.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
@@ -843,6 +879,12 @@ Add defensive type checking for all external service responses. Lists vs dicts,
|
||||
### Thread All Encoding Outputs Through OrchestratorResult (Mar 2026)
|
||||
The encoding pipeline (`LocalEncodingService`) created a `(With Vocals).mp4` file (3.4x smaller than the raw MKV), but `OrchestratorResult` had no field for it so it was silently dropped. Users got the 134MB raw MKV instead of the 39MB encoded MP4. **Pattern**: When adding output files to encoding, verify the full chain: `EncodingOutput` → `OrchestratorResult` → `_upload_results()` file_mappings → Firestore `file_urls`. Also beware of hardcoded file extensions — the temp directory saved `.mkv` files as `.mov`, causing Dropbox to receive mislabeled files.
|
||||
|
||||
### Cloud Run Job Retries Race With Manual Retries (Mar 2026)
|
||||
Job 13b8adcf failed because Cloud Run Job `max_retries: 2` and a manual `/retry` call launched concurrent video workers. Worker A transitioned to `generating_video`, Worker B saw `generating_video` as valid (it was in the `validate_worker_can_run` allowlist), tried the same transition, failed, and marked the job `failed` — then Worker A tried `failed → encoding` and also failed. **Fix**: Remove in-progress states (`generating_video`, `rendering_video`) from the video_worker startup validation — if a job is already in those states, another worker is processing it. Also make `_validate_prerequisites` a hard failure, not just a warning.
|
||||
|
||||
### Encoding Worker Warmup Must Cover All Paths (Mar 2026)
|
||||
The JIT startup design (frontend calls warmup on lyrics review page, VM boots during editing) only covered the happy path. Five of ten paths to encoding (retries, admin resets, pipeline chains, visibility changes) had no warmup — the encoding service retried blindly for ~90s against a TERMINATED VM. **Fix**: Call `ensure_primary_running()` at two layers: (1) in `trigger_video_worker`/`trigger_render_video_worker` for early start, and (2) as a fallback in `EncodingService._request_with_retry` on first connection failure. Defense in depth: frontend warmup → worker dispatch warmup → encoding retry warmup.
|
||||
|
||||
### Brand Code Allocation Must Be Atomic (Feb 2026)
|
||||
Two concurrent jobs both got brand code `NOMADNP-0012` because `get_next_brand_code()` scanned Dropbox folders to find the next number — a classic TOCTOU race condition. Jobs processed 0.86s apart both saw the same state. **Fix**: `brand_code_service.py` uses Firestore transactions to atomically allocate codes. Counter doc per prefix (`NOMAD`, `NOMADNP`) with `next_number` and `recycled` pool. E2E cleanup recycles numbers via `recycle_brand_code()`.
|
||||
|
||||
@@ -987,3 +1029,29 @@ For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_d
|
||||
|
||||
**Key insight:** For abuse prevention, static lists give you a floor but not a ceiling. Real-time API verification services maintain much larger and more current databases. The tiered approach (free service first, paid service only for edge cases) keeps costs minimal while dramatically improving detection. In our test of 60 recent signups, the free DeBounce API caught 6 disposable accounts and verifymail.io caught 4 more that DeBounce missed.
|
||||
|
||||
### Lyrics Upload Race Condition: Admin Edits During Processing (Mar 2026)
|
||||
|
||||
**Problem:** When an admin updated a job's artist name while the lyrics worker was running, `upload_lyrics_results` reconstructed filenames from the updated Firestore values (`job.artist`, `job.title`), which no longer matched the files on disk generated with the original values. This caused "No corrections JSON found" errors even though the files existed.
|
||||
|
||||
**Fix:** Scan the lyrics directory for files by suffix pattern (e.g., `*(Lyrics Corrections).json`, `*(Lyrics Genius).txt`) instead of reconstructing filenames from Firestore job metadata. This decouples the upload from the current state of mutable job fields.
|
||||
|
||||
**Key insight:** Long-running workers should avoid re-reading mutable metadata to reconstruct local file paths. If a file was created earlier in the same pipeline, find it by pattern rather than reconstructing its name from state that may have changed. This is a variant of TOCTOU — the "check" (reading artist/title) and "use" (looking for the file) happen at different times, and the underlying data can change between them.
|
||||
|
||||
### Reference Lyrics Relevance Filtering: Data-Driven Thresholds (Mar 2026)
|
||||
|
||||
**Problem:** Lyrics providers often return wrong-song results for tracks with remixes, "feat." artists, or unusual naming. These irrelevant references pollute anchor/gap statistics and confuse correction tooling.
|
||||
|
||||
**Solution:** Added relevance filtering in `LyricsCorrector` — after anchor sequences are found, compute `(reference words in anchors) / (total reference words)` per source. Sources below 30% are rejected. The threshold was determined empirically by analyzing 168 source pairs across 81 production jobs: wrong-song sources maxed at 3.5%, correct-song sources started at 26.8%.
|
||||
|
||||
**Key insight:** Don't guess thresholds — measure them. A visual review tool showing side-by-side lyrics with match highlighting made it trivial to classify 168 pairs in minutes. The massive gap between wrong (0-3.5%) and correct (26.8%+) meant any threshold from 5-25% would work, but 30% provides safety margin. Always include a force-add override for edge cases where the transcription is bad (not the reference).
|
||||
|
||||
### Cloud Scheduler OIDC Tokens ≠ Admin Tokens (Mar 2026)
|
||||
|
||||
**Problem:** All 4 Cloud Scheduler → backend jobs (stale review processor, stuck job recovery, YouTube queue, disposable domain sync) were silently returning 401 since deployment. The auth system only validated admin tokens, Firestore tokens, and session tokens — it had no OIDC JWT validation. Cloud Scheduler sends a Google-signed OIDC JWT in the `Authorization: Bearer` header, which the auth service didn't recognize.
|
||||
|
||||
**Root cause:** A plan document incorrectly stated "The existing `require_admin` dependency handles OIDC via the Authorization header flow, so this works without changes." This was never verified, and the 401s went unnoticed because scheduler endpoints run in the background with no user-visible feedback.
|
||||
|
||||
**Fix:** Added OIDC token validation to `validate_token_full()` using `google.oauth2.id_token.verify_oauth2_token()`. Verifies the token is Google-signed and the `email` claim matches the configured backend service account.
|
||||
|
||||
**Key insight:** Background cron jobs need monitoring for auth failures — a 401 from a scheduler is silent by default. When adding new Cloud Scheduler endpoints, verify the auth flow end-to-end (check Cloud Logging for 200s after deployment). Don't assume OIDC "just works" with custom auth middleware — Cloud Tasks uses `X-Admin-Token` (custom header) for a reason, while Cloud Scheduler only sends OIDC.
|
||||
|
||||
@@ -45,7 +45,7 @@ Input (audio + metadata)
|
||||
v v
|
||||
┌───────────────────┐ ┌───────────────────┐
|
||||
│ Audio Separation │ │ Lyrics Processing │
|
||||
│ (Modal GPU) │ │ (AudioShake API) │
|
||||
│ (Cloud Run GPU L4)│ │ (AudioShake API) │
|
||||
│ │ │ │
|
||||
│ • Clean vocal │ │ • Fetch reference │
|
||||
│ removal │ │ lyrics │
|
||||
@@ -98,7 +98,7 @@ All code is open source (MIT license) because:
|
||||
However, reliable fully-automated generation requires:
|
||||
- **AudioShake API**: ~$0.50-1.00 per track for high-quality transcription
|
||||
- **LLM tokens**: ~$0.50-1.00 for agentic correction workflow
|
||||
- **GPU compute**: ~$0.20-0.50 for audio separation on Modal
|
||||
- **GPU compute**: ~$0.10-0.30 for audio separation on Cloud Run GPU (L4)
|
||||
- **Infrastructure**: Cloud Run, Firestore, GCS, etc.
|
||||
|
||||
**Cost per track: ~$2-3** for fully-automated processing, making a paid service necessary to sustain development.
|
||||
@@ -130,7 +130,7 @@ Commercial producers pay for API access or custom integration to generate tracks
|
||||
## Current State (December 2025)
|
||||
|
||||
### What Works
|
||||
- Audio upload and separation (Modal API)
|
||||
- Audio upload and separation (Cloud Run GPU)
|
||||
- Lyrics transcription (AudioShake API)
|
||||
- Agentic AI correction (Gemini 3 Flash via Vertex AI)
|
||||
- Human lyrics review (React UI)
|
||||
@@ -188,7 +188,7 @@ Commercial producers pay for API access or custom integration to generate tracks
|
||||
- **Database**: Firestore
|
||||
- **Storage**: Google Cloud Storage
|
||||
- **Secrets**: Google Secret Manager
|
||||
- **Audio Separation**: Modal (GPU compute)
|
||||
- **Audio Separation**: Cloud Run GPU (L4, us-east4)
|
||||
- **Lyrics Transcription**: AudioShake API
|
||||
- **AI Correction**: Vertex AI (Gemini 3 Flash)
|
||||
- **Payments**: Stripe
|
||||
|
||||
+1
-1
@@ -237,7 +237,7 @@
|
||||
```
|
||||
Upload Audio → Parallel Processing → Human Review → Video Generation → Download
|
||||
│ │
|
||||
(Modal + AudioShake) (LyricsTranscriber UI)
|
||||
(Cloud Run GPU + AudioShake) (LyricsTranscriber UI)
|
||||
```
|
||||
|
||||
## For AI Agents
|
||||
|
||||
@@ -252,3 +252,114 @@ doc = firestore.Client(project='nomadkaraoke').collection('config').document('en
|
||||
print('primary:', doc.to_dict().get('primary'))
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Surgical job repair: re-run audio separation without losing lyrics/review
|
||||
|
||||
**When to use:** Jobs where audio separation failed or produced incomplete stems, but the user has already completed lyrics review. The admin `/restart` endpoint clears ALL state including lyrics — use direct Firestore updates instead.
|
||||
|
||||
**Approach:** Clear only audio-related state, trigger the Cloud Run GPU audio job, then advance the job to the correct next step.
|
||||
|
||||
```python
|
||||
import os
|
||||
os.environ["GOOGLE_CLOUD_PROJECT"] = "nomadkaraoke"
|
||||
from google.cloud import firestore, run_v2
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
from datetime import datetime, timezone
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
job_id = "YOUR_JOB_ID"
|
||||
|
||||
# Step 1: Clear audio state only (preserves lyrics, review, instrumental selection)
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
job_ref.update({
|
||||
"status": "downloading", # Required: idempotency checks reject terminal states
|
||||
"state_data.audio_progress": DELETE_FIELD,
|
||||
"state_data.audio_complete": False,
|
||||
"state_data.instrumental_options": DELETE_FIELD,
|
||||
"state_data.backing_vocals_analysis": DELETE_FIELD,
|
||||
"file_urls.stems": DELETE_FIELD,
|
||||
"error_message": DELETE_FIELD,
|
||||
"error_details": DELETE_FIELD,
|
||||
"progress": 15,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "downloading",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": "Admin repair: re-running audio separation",
|
||||
}]),
|
||||
})
|
||||
|
||||
# Step 2: Trigger Cloud Run GPU audio job directly
|
||||
# (bypasses internal HTTP endpoint which has idempotency checks)
|
||||
client = run_v2.JobsClient()
|
||||
client.run_job(request=run_v2.RunJobRequest(
|
||||
name="projects/nomadkaraoke/locations/us-east4/jobs/audio-separation-job",
|
||||
overrides=run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=["python", "-m", "backend.workers.audio_worker", "--job-id", job_id],
|
||||
)]
|
||||
)
|
||||
))
|
||||
|
||||
# Step 3: After audio completes, advance the job based on its previous state:
|
||||
# - If job was "failed" with lyrics: trigger screens worker → awaiting_review
|
||||
# - If job was "instrumental_selected": set status back, trigger video worker
|
||||
```
|
||||
|
||||
**Key gotchas:**
|
||||
- Must set `status` to a non-terminal state (`"downloading"`) before triggering workers
|
||||
- `mark_audio_complete()` only sets a flag — it does NOT trigger the next pipeline step
|
||||
- After audio completes, you must manually trigger screens (for review path) or video (for post-review path)
|
||||
- The admin `/restart` endpoint with `preserve_audio_stems=false` is the simpler option when lyrics don't need preserving
|
||||
|
||||
---
|
||||
|
||||
## Triggering Cloud Run Jobs directly (bypassing internal API)
|
||||
|
||||
**When to use:** The internal worker endpoints (`/api/internal/workers/audio`, etc.) have idempotency checks that reject jobs in terminal states (`failed`, `complete`, etc.). When repairing jobs, trigger Cloud Run Jobs directly via the API.
|
||||
|
||||
```python
|
||||
from google.cloud import run_v2
|
||||
|
||||
client = run_v2.JobsClient()
|
||||
client.run_job(request=run_v2.RunJobRequest(
|
||||
name="projects/nomadkaraoke/locations/{REGION}/jobs/{JOB_NAME}",
|
||||
overrides=run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=["python", "-m", "backend.workers.{MODULE}", "--job-id", "{JOB_ID}"],
|
||||
)]
|
||||
)
|
||||
))
|
||||
```
|
||||
|
||||
**Available Cloud Run Jobs:**
|
||||
|
||||
| Job Name | Region | Module | GPU |
|
||||
|----------|--------|--------|-----|
|
||||
| `audio-separation-job` | `us-east4` | `audio_worker` | L4 |
|
||||
| `lyrics-transcription-job` | `us-central1` | `lyrics_worker` | No |
|
||||
| `video-encoding-job` | `us-central1` | `video_worker` | No |
|
||||
|
||||
---
|
||||
|
||||
## CI does not update `lyrics-transcription-job` image
|
||||
|
||||
**Symptoms:** Deployed code fixes don't take effect for lyrics processing. The backend service shows the new version, but lyrics jobs still crash with the old bug.
|
||||
|
||||
**Cause:** The CI workflow (`.github/workflows/ci.yml`) updates `audio-separation-job` and `video-encoding-job` after deploy, but does NOT update `lyrics-transcription-job`. The job uses the `:latest` tag, but Cloud Run Jobs resolve the tag to a digest at update time — pushing a new `:latest` image doesn't automatically update running jobs.
|
||||
|
||||
**Manual fix after deploy:**
|
||||
```bash
|
||||
# Pin to the specific version tag (preferred)
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:vX.Y.Z \
|
||||
--region us-central1 --project nomadkaraoke
|
||||
|
||||
# Or force re-resolve :latest
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:latest \
|
||||
--region us-central1 --project nomadkaraoke
|
||||
```
|
||||
|
||||
**Permanent fix:** Add `lyrics-transcription-job` update to CI deploy step in `.github/workflows/ci.yml` alongside the existing `video-encoding-job` and `audio-separation-job` updates (~line 1568).
|
||||
@@ -0,0 +1,70 @@
|
||||
# Audio Separator Cloud Run GPU Architecture
|
||||
|
||||
**Date:** 2026-03-25 (updated 2026-03-26)
|
||||
**Status:** Implemented and deployed
|
||||
**Repos:** python-audio-separator, karaoke-gen (infrastructure)
|
||||
|
||||
## Problem
|
||||
|
||||
The audio separator service had two issues:
|
||||
1. **Client timeout**: The POST timeout (300s) was too short for ensemble presets on large WAV files (>5 min processing)
|
||||
2. **No multi-instance scaling**: In-memory job status store and no concurrency protection prevented scaling
|
||||
|
||||
## Solution: Synchronous + Cloud Run Autoscaling (Modal Pattern)
|
||||
|
||||
The architecture mirrors how Modal handled this: **each separation request occupies one GPU instance** for its full duration, and the platform (Cloud Run) handles scaling to multiple instances for concurrent jobs.
|
||||
|
||||
### How it works
|
||||
|
||||
1. Client POSTs to `/separate` with `timeout=1800s`
|
||||
2. Server downloads audio (from GCS URI or upload), runs separation synchronously
|
||||
3. Server uploads output files to GCS, updates Firestore with status
|
||||
4. Server returns completed result to client
|
||||
5. Cloud Run sees the request as "active" for 3-5 minutes, so with `concurrency=1`, it scales to new instances for new requests
|
||||
6. Up to 5 GPU instances run in parallel (Cloud Run GPU limit)
|
||||
|
||||
### Key infrastructure
|
||||
|
||||
| Component | Detail |
|
||||
|-----------|--------|
|
||||
| **Cloud Run GPU** | L4, us-east4, concurrency=1, max_instances=5 |
|
||||
| **Firestore** | `audio_separation_jobs` collection — job status for observability |
|
||||
| **GCS** | `nomadkaraoke-audio-separator-outputs` bucket — output files (1-day lifecycle) |
|
||||
| **Client timeout** | 1800s POST timeout (matches Cloud Run request timeout) |
|
||||
|
||||
### Why synchronous, not fire-and-forget
|
||||
|
||||
We initially tried fire-and-forget (background threads + polling), but Cloud Run can't see background threads as "busy". With `concurrency=50` and fire-and-forget, all requests routed to one instance and queued behind a GPU semaphore — defeating the purpose of multi-instance scaling. Making the endpoint synchronous lets Cloud Run's autoscaler work naturally.
|
||||
|
||||
### Why no GPU semaphore
|
||||
|
||||
With `concurrency=1`, Cloud Run guarantees only one active request per instance. Each instance has its own GPU. No application-level serialization needed.
|
||||
|
||||
## Cross-repo changes
|
||||
|
||||
### python-audio-separator
|
||||
- `deploy_cloudrun.py` — synchronous endpoint, Firestore status, GCS output upload
|
||||
- `api_client.py` — 1800s POST timeout
|
||||
- `job_store.py` — Firestore-backed job status store
|
||||
- `output_store.py` — GCS output file management
|
||||
- `Dockerfile.cloudrun` — google-cloud-firestore dependency
|
||||
|
||||
### karaoke-gen (infrastructure)
|
||||
- `audio_separator_service.py` — concurrency=1, GCS bucket, Firestore IAM, env vars
|
||||
- `database.py` — Firestore composite index for cleanup queries
|
||||
|
||||
## Phase 2: Migrate to Cloud Run Jobs
|
||||
|
||||
The current synchronous-service approach works but is not the ideal architecture. Cloud Run Jobs would be a natural fit — karaoke-gen already uses them for the audio worker itself. Benefits:
|
||||
- No HTTP timeout concern (Jobs run up to 24h, no client connection needed)
|
||||
- Native scaling (each execution gets its own container/GPU)
|
||||
- Fire-and-forget + poll pattern (submit job, poll Firestore, download from GCS)
|
||||
- Eliminates the `concurrency=1` workaround for autoscaling
|
||||
|
||||
The Firestore job store and GCS output store built in this session are the right foundations — they'd be reused directly by the Jobs-based approach.
|
||||
|
||||
## Lessons learned
|
||||
|
||||
1. **Cloud Run can't track background threads** — fire-and-forget makes the instance look idle, so the autoscaler doesn't scale. If you need the platform to scale for you, keep the request active.
|
||||
2. **Match the platform's scaling model** — Modal's `.spawn()` gave each job its own container. Cloud Run's `concurrency=1` with synchronous processing achieves the same effect.
|
||||
3. **The GPU semaphore was the wrong abstraction** — it serialized work on one instance instead of distributing across instances. Let the platform handle concurrency.
|
||||
@@ -0,0 +1,123 @@
|
||||
# Plan: Fix 413 Audio Separation Error via GCS Path Passthrough
|
||||
|
||||
**Created:** 2026-03-25
|
||||
**Branch:** feat/sess-20260325-1130-fix-413-audio-sep
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Audio separation fails with `413 Request Entity Too Large` when FLAC files exceed Cloud Run's 32MB request body limit. The current architecture uploads the entire audio file as a multipart POST body to the separator API. Since the file is **already in GCS** by the time the audio worker runs, we should pass the GCS path and let the separator download directly from GCS.
|
||||
|
||||
**Root cause:** `api_client.py:77,136` sends the file as `files={"file": (filename, open(file_path, "rb"))}` in a POST to `/separate`. Cloud Run rejects bodies > 32MB.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Audio separation works for files of any size (no HTTP body limit)
|
||||
- [ ] Backward compatible — file upload still works for non-GCS callers (CLI, tests)
|
||||
- [ ] No data duplication — separator reads from the same GCS bucket, doesn't copy
|
||||
- [ ] Stage 2 (backing vocals) still works — uses Stage 1 output which is local on the separator
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Change:** Add a `gcs_uri` parameter to the `/separate` endpoint. When provided, the separator downloads from GCS instead of expecting a file upload. The API client gains a new parameter for this.
|
||||
|
||||
Both services are in the same GCP project (`nomadkaraoke`), so the separator's service account just needs `roles/storage.objectViewer` on the `karaoke-gen-storage` bucket.
|
||||
|
||||
### Flow: Before
|
||||
```
|
||||
audio_worker → download from GCS → local file → HTTP POST (file bytes) → separator
|
||||
```
|
||||
|
||||
### Flow: After
|
||||
```
|
||||
audio_worker → pass GCS path → separator downloads from GCS directly
|
||||
```
|
||||
|
||||
Stage 2 (backing vocals) still uploads the local mixed_vocals file since it's a Stage 1 output that only exists on the separator's local disk. But Stage 2 files are small (vocals only), so no 413 risk.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Repo 1: python-audio-separator (separate worktree)
|
||||
|
||||
1. [ ] **Server: Add `gcs_uri` parameter to `/separate` endpoint** (`audio_separator/remote/deploy_cloudrun.py`)
|
||||
- Add `gcs_uri: Optional[str] = Form(None)` parameter
|
||||
- When provided, download from GCS instead of reading `file` upload
|
||||
- Make `file` parameter optional (required only when `gcs_uri` not provided)
|
||||
- Validate: exactly one of `file` or `gcs_uri` must be provided
|
||||
|
||||
2. [ ] **Server: Add GCS download helper** (`audio_separator/remote/deploy_cloudrun.py`)
|
||||
- `download_from_gcs(gcs_uri: str, output_dir: str) -> tuple[bytes, str]`
|
||||
- Parse `gs://bucket/path` or just `bucket/path` format
|
||||
- Use `google-cloud-storage` (already a dependency for model download)
|
||||
- Return `(audio_bytes, filename)`
|
||||
|
||||
3. [ ] **Client: Add `gcs_uri` parameter** (`audio_separator/remote/api_client.py`)
|
||||
- Add `gcs_uri` param to `separate_audio()` and `separate_audio_and_wait()`
|
||||
- When `gcs_uri` is provided, send it as form data instead of file upload
|
||||
- When `gcs_uri` is provided, `file_path` becomes optional (not opened/sent)
|
||||
|
||||
4. [ ] **Tests: Add unit tests for GCS passthrough**
|
||||
- Test server accepts `gcs_uri` parameter
|
||||
- Test client sends `gcs_uri` instead of file when provided
|
||||
- Test validation (can't provide both `file` and `gcs_uri`, must provide one)
|
||||
|
||||
5. [ ] **Bump version, push, publish**
|
||||
|
||||
### Repo 2: karaoke-gen (this worktree)
|
||||
|
||||
6. [ ] **Infrastructure: Grant GCS read access to separator SA** (`infrastructure/modules/audio_separator_service.py`)
|
||||
- Add `roles/storage.objectViewer` on `karaoke-gen-storage` bucket to the `audio-separator` service account
|
||||
|
||||
7. [ ] **Audio worker: Pass GCS path to separator** (`karaoke_gen/audio_processor.py`)
|
||||
- In `_process_audio_separation_remote()`, pass `gcs_uri` for Stage 1
|
||||
- Construct URI: `gs://karaoke-gen-storage/{job.input_media_gcs_path}`
|
||||
- Stage 2 continues using local file upload (the mixed_vocals file is on separator's disk, not in GCS)
|
||||
|
||||
8. [ ] **Update audio-separator dependency** (`pyproject.toml`)
|
||||
- `poetry update audio-separator` after the new version is published
|
||||
|
||||
9. [ ] **Tests**
|
||||
- Update existing audio processor tests to verify `gcs_uri` is passed
|
||||
- Test that Stage 1 uses GCS path, Stage 2 uses file upload
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### python-audio-separator
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `audio_separator/remote/deploy_cloudrun.py` | Modify | Add `gcs_uri` param to `/separate`, add GCS download helper |
|
||||
| `audio_separator/remote/api_client.py` | Modify | Add `gcs_uri` param to client methods |
|
||||
| `tests/unit/test_remote_api_client.py` | Modify | Add tests for GCS passthrough |
|
||||
| `pyproject.toml` | Modify | Bump version |
|
||||
|
||||
### karaoke-gen
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `infrastructure/modules/audio_separator_service.py` | Modify | Add GCS read permission |
|
||||
| `karaoke_gen/audio_processor.py` | Modify | Pass `gcs_uri` in Stage 1 |
|
||||
| `backend/workers/audio_worker.py` | Modify | Pass GCS path to audio processor |
|
||||
| `pyproject.toml` | Modify | Update audio-separator dependency |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Mock GCS client in separator, verify download_from_gcs works
|
||||
- **Unit tests:** Verify API client sends gcs_uri param correctly
|
||||
- **Integration test:** Deploy separator locally, test with a real GCS file
|
||||
- **Production test:** Re-run failed job `45f9bbc0` after deployment
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we also upload Stage 2 input (mixed_vocals) to GCS and use gcs_uri? Not needed now — vocals-only files are small — but would be more consistent.
|
||||
- [ ] Should the `gcs_uri` format be `gs://bucket/path` or just the blob path with a separate bucket param? Suggest `gs://` URI for clarity and flexibility.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Revert to file upload by not passing `gcs_uri` — the parameter is optional
|
||||
- The separator still accepts file uploads as before (backward compatible)
|
||||
- No infrastructure changes needed for rollback (extra IAM permission is harmless)
|
||||
|
||||
## Execution Order
|
||||
|
||||
1. Start with python-audio-separator (steps 1-5) — this is the dependency
|
||||
2. Apply infra change (step 6) — can be done in parallel
|
||||
3. Update karaoke-gen (steps 7-9) — depends on step 5
|
||||
@@ -0,0 +1,53 @@
|
||||
# Plan: Pre-compute Credit Evaluation at Magic Link Send Time
|
||||
|
||||
**Created:** 2026-03-25
|
||||
**Branch:** feat/sess-20260324-2308-welcome-credit-abuse
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Move the AI credit evaluation from verify-magic-link time to send-magic-link time. By the time the user clicks the link in their email (typically 10-20+ seconds later), the decision is already made and verification is instant. If they click very fast, fall back to computing inline (same experience as today).
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Run credit evaluation asynchronously after sending the magic link email
|
||||
- [ ] Store the evaluation result on the magic link document in Firestore
|
||||
- [ ] At verify time, read pre-computed result if available
|
||||
- [ ] Fall back to inline evaluation if result isn't ready yet (preserves "preparing" UX)
|
||||
- [ ] Only evaluate new users (existing users skip evaluation already)
|
||||
- [ ] No change to the user-facing experience — just faster
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Key insight:** `send_magic_link` already has all the signals needed (email, IP, fingerprint) and already creates the user via `get_or_create_user()`. We just need to run the evaluation after sending the email and store the result.
|
||||
|
||||
**Threading:** Use `threading.Thread` to run evaluation in background so the magic link response returns immediately. FastAPI's async doesn't help here since the evaluation is sync (Firestore + Gemini calls).
|
||||
|
||||
**Storage:** Add `credit_eval_decision`, `credit_eval_reasoning`, and `credit_eval_error` fields to the magic link Firestore document. The verify endpoint already reads this document.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] Add evaluation result fields to magic link document schema
|
||||
2. [ ] Create helper function that runs evaluation and writes result to magic link doc
|
||||
3. [ ] Call helper in background thread from `send_magic_link` (new users only)
|
||||
4. [ ] Update `verify_magic_link` to check for pre-computed result before calling evaluation
|
||||
5. [ ] Update tests
|
||||
6. [ ] Bump version
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/users.py` | Modify | Trigger background eval in send_magic_link; read pre-computed result in verify_magic_link |
|
||||
| `backend/services/user_service.py` | Modify | Add method to store eval result on magic link doc |
|
||||
| `backend/models/user.py` | Modify | Add optional eval fields to MagicLinkToken model |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Update existing anti-abuse tests to verify pre-computation flow
|
||||
- Test fallback path (no pre-computed result → inline evaluation)
|
||||
- Test that send_magic_link still returns quickly (doesn't block on eval)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
The fallback path IS the current behavior. If pre-computation breaks, verify just runs evaluation inline as before.
|
||||
@@ -0,0 +1,158 @@
|
||||
# Direct GPU Audio Separation in Audio Worker
|
||||
|
||||
**Date:** 2026-03-26
|
||||
**Status:** Approved, ready for implementation
|
||||
**Repos:** karaoke-gen (primary), python-audio-separator (read-only reference)
|
||||
**Branch:** feat/sess-20260326-1339-audio-sep-direct-gpu
|
||||
|
||||
## Problem
|
||||
|
||||
The audio worker Cloud Run Job calls a separate Cloud Run Service (audio-separator) over HTTP for GPU-accelerated stem separation. This architecture has proven fragile:
|
||||
|
||||
- 1800s HTTP timeout is the max Cloud Run allows; large files can exceed it
|
||||
- Holding connections open for 5-10 minutes wastes resources
|
||||
- `concurrency=1` forces a new $1/hr GPU instance per request
|
||||
- Cold start delays add to the client's wait time
|
||||
- A recent production outage (2026-03-25) was caused by the fire-and-forget/semaphore interaction with Cloud Run's autoscaler
|
||||
|
||||
## Solution
|
||||
|
||||
Run the `Separator` class directly inside the audio worker Cloud Run Job with an L4 GPU attached. This eliminates the HTTP hop entirely.
|
||||
|
||||
### Architecture Change
|
||||
|
||||
```
|
||||
Current (3 hops):
|
||||
karaoke-gen backend → Cloud Run Job (audio worker, CPU, us-central1)
|
||||
→ HTTP POST → Cloud Run Service (separator, GPU, us-east4)
|
||||
|
||||
New (1 hop):
|
||||
karaoke-gen backend → Cloud Run Job (audio worker, GPU, us-east4)
|
||||
→ Separator class runs locally
|
||||
```
|
||||
|
||||
## Decisions
|
||||
|
||||
| Decision | Choice | Rationale |
|
||||
|----------|--------|-----------|
|
||||
| Docker image | Separate `karaoke-backend-gpu` image | Keeps regular backend lean; audio worker gets exactly what it needs |
|
||||
| GPU region | us-east4 | L4 GPU quota already exists there; batch job tolerates cross-region latency |
|
||||
| Model loading | Bake into image | Faster cold starts; model set rarely changes |
|
||||
| Rollback strategy | Keep old service running | Phase 1 adds new path; old service removed in phase 2 |
|
||||
| Code path | Reuse existing local Separator path | Already works; minimizes code changes and risk |
|
||||
|
||||
## Components
|
||||
|
||||
### 1. New Docker image: `karaoke-backend-gpu`
|
||||
|
||||
A GPU-capable base image for the audio worker. Based on `nvidia/cuda:12.6.3-runtime-ubuntu22.04`, includes everything from `karaoke-backend-base` plus GPU-specific dependencies.
|
||||
|
||||
**GPU dependencies (from audio-separator's Dockerfile.cloudrun):**
|
||||
- PyTorch with CUDA support
|
||||
- ONNX Runtime GPU (`onnxruntime-gpu`)
|
||||
- `audio-separator[gpu]` package
|
||||
- CUDA runtime libraries (already in base NVIDIA image)
|
||||
|
||||
**Baked-in models (~1.5GB total):**
|
||||
- `instrumental_clean` preset models (Fv7z + Resurrection)
|
||||
- `karaoke` preset models (3 karaoke models)
|
||||
- Downloaded at build time via `scripts/download_preset_models.py` pattern from python-audio-separator
|
||||
|
||||
**Shared with karaoke-backend-base:**
|
||||
- Python 3.11 (note: audio-separator uses 3.12; need to verify compatibility or align)
|
||||
- FFmpeg (static build), sox, libsndfile
|
||||
- Noto fonts (CJK, emoji, etc.)
|
||||
- spaCy `en_core_web_sm` model
|
||||
- All pip dependencies from karaoke-gen's pyproject.toml
|
||||
|
||||
**New files:**
|
||||
- `backend/Dockerfile.gpu-base` — GPU base image definition
|
||||
- `backend/cloudbuild-gpu-base.yaml` — Cloud Build config
|
||||
- `backend/scripts/download_models.py` — Model download script for build time
|
||||
|
||||
**Artifact Registry:**
|
||||
- New repo `karaoke-backend-gpu` in `us-east4` (co-located with GPU instances)
|
||||
|
||||
### 2. Infrastructure changes
|
||||
|
||||
All in `infrastructure/modules/cloud_run.py`:
|
||||
|
||||
**Audio worker Cloud Run Job modifications:**
|
||||
- Move from `us-central1` to `us-east4` (GPU quota)
|
||||
- Add L4 GPU: `nvidia.com/gpu: "1"`
|
||||
- Increase resources: CPU 2→4, memory 4Gi→16Gi
|
||||
- Change image to `us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend:latest`
|
||||
- Remove `AUDIO_SEPARATOR_API_URL` env var (absence triggers local Separator path)
|
||||
- Add `MODEL_DIR=/models` env var (tells Separator where baked-in models live)
|
||||
|
||||
**New resources in `infrastructure/`:**
|
||||
- Artifact Registry repo for `karaoke-backend-gpu` in us-east4
|
||||
- IAM for the existing audio-separator service account to pull from the new repo
|
||||
|
||||
### 3. Code changes
|
||||
|
||||
**`backend/workers/audio_worker.py`:**
|
||||
- Remove the hard error when `AUDIO_SEPARATOR_API_URL` is not set (lines ~330-333)
|
||||
- When `AUDIO_SEPARATOR_API_URL` is absent, configure `create_audio_processor()` with `model_file_dir` pointing to the baked-in models directory
|
||||
|
||||
**`backend/workers/audio_worker.py` — `create_audio_processor()`:**
|
||||
- Accept optional `model_file_dir` parameter
|
||||
- Pass `instrumental_preset` and `karaoke_preset` through to the processor (currently only used in remote path; the local path needs to use them too)
|
||||
- When `model_file_dir` is set, the processor uses local `Separator`; when not set, it errors
|
||||
|
||||
**`karaoke_gen/audio_processor.py`:**
|
||||
- In the local code path (lines ~200+), support `ensemble_preset` on the `Separator` constructor instead of only using explicit model lists
|
||||
- The existing local path currently uses `self.clean_instrumental_model` / `self.backing_vocals_models` to call individual separation methods. With presets, we pass `ensemble_preset` to `Separator()` and call `separator.separate()` once — the preset handles model selection internally.
|
||||
- Keep the file-lock mechanism (harmless in Cloud Run Jobs; one container = no contention)
|
||||
|
||||
### 4. What stays unchanged (phase 1)
|
||||
|
||||
- Audio-separator Cloud Run Service (kept for rollback)
|
||||
- Firestore `audio_separation_jobs` collection and GCS output bucket
|
||||
- Remote API code path in `audio_processor.py` (`_process_audio_separation_remote`)
|
||||
- CI/CD for the existing `karaoke-backend` image
|
||||
- All other Cloud Run Jobs (lyrics, video workers)
|
||||
|
||||
### 5. CI/CD
|
||||
|
||||
- Add a Cloud Build trigger for the GPU base image (triggered by changes to `backend/Dockerfile.gpu-base` or `pyproject.toml`)
|
||||
- The existing app-layer build (`backend/Dockerfile`) works unchanged — just needs `BASE_IMAGE` build arg set to the GPU base for audio worker deploys
|
||||
- GitHub Actions workflow addition: build and push the GPU image on merge to main
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
**Unit tests:**
|
||||
- Verify `create_audio_processor()` configures correctly with and without `AUDIO_SEPARATOR_API_URL`
|
||||
- Verify `model_file_dir` is passed through when set
|
||||
- Verify preset parameters reach the `Separator` constructor
|
||||
|
||||
**Local integration:**
|
||||
- Build the GPU image locally (requires NVIDIA Docker runtime)
|
||||
- Run a test separation with a sample audio file
|
||||
|
||||
**Production verification:**
|
||||
- Submit a test job after deploy
|
||||
- Verify all stems are generated: clean instrumental, vocals, lead vocals, backing vocals, combined instrumentals
|
||||
- Compare output quality with a job processed through the old HTTP path
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If issues arise after deployment:
|
||||
1. Add `AUDIO_SEPARATOR_API_URL` back to the audio worker job env vars
|
||||
2. The code falls through to the remote API path
|
||||
3. The old audio-separator service is still running (scale-to-zero, no cost)
|
||||
|
||||
No code changes needed for rollback — just an infra env var change via Pulumi.
|
||||
|
||||
## Phase 2 (follow-up PR)
|
||||
|
||||
After the direct GPU path is verified in production:
|
||||
- Remove the audio-separator Cloud Run Service infrastructure
|
||||
- Remove `AUDIO_SEPARATOR_API_URL` references from code
|
||||
- Remove `_process_audio_separation_remote()` method
|
||||
- Remove `AudioSeparatorAPIClient` import
|
||||
- Clean up Firestore job store / GCS output bucket if no longer needed for observability
|
||||
|
||||
## Python Version
|
||||
|
||||
The audio-separator package requires Python >= 3.10. The GPU base image will use Python 3.11 (same as the existing karaoke-gen base) for consistency. The audio-separator's Dockerfile.cloudrun uses 3.12, but that's not a requirement — it was just the version chosen for that image.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,86 @@
|
||||
# Audio Search Robustness — Design Spec
|
||||
|
||||
**Date:** 2026-03-27
|
||||
**Status:** Approved
|
||||
**Scope:** Frontend only — `AudioSourceStep.tsx`
|
||||
|
||||
## Problem
|
||||
|
||||
When an audio search fails silently (timeout, network error, edge case), the UI shows "No audio sources found" — implying the search succeeded with zero results. This misleads users into thinking the song isn't available when it actually is.
|
||||
|
||||
**Root cause:** The component uses `results.length === 0 && !error` to decide whether to show the "no results" message. But `results` initializes as `[]`, so any failure path that doesn't explicitly set the `error` string will render "No audio sources found."
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Search State Machine
|
||||
|
||||
Replace `isSearching` (boolean), `error` (string), and `isCreditError` (boolean) with a single discriminated union:
|
||||
|
||||
```ts
|
||||
type SearchStatus =
|
||||
| { phase: 'idle' }
|
||||
| { phase: 'searching'; attempt: number }
|
||||
| { phase: 'succeeded' }
|
||||
| { phase: 'failed'; reason: string; isCreditError: boolean; attempt: number }
|
||||
```
|
||||
|
||||
Initial state: `{ phase: 'searching', attempt: 1 }` (search fires on mount).
|
||||
|
||||
**Rendering rules:**
|
||||
|
||||
| Condition | UI |
|
||||
|---|---|
|
||||
| `phase === 'searching'` | Spinner (with retry indicator if attempt > 1) |
|
||||
| `phase === 'succeeded' && results.length > 0` | Tier-based result cards |
|
||||
| `phase === 'succeeded' && results.length === 0` | NoResultsSection |
|
||||
| `phase === 'failed' && isCreditError` | Credit error + Buy Credits button |
|
||||
| `phase === 'failed' && !isCreditError` | Error banner + Retry button |
|
||||
|
||||
**Key guarantee:** `NoResultsSection` only renders when `phase === 'succeeded'` AND `results.length === 0`. No other path can reach it.
|
||||
|
||||
### 2. Retry Logic
|
||||
|
||||
Up to 3 automatic attempts (1 initial + 2 retries) with delays:
|
||||
|
||||
- Attempt 1: immediate
|
||||
- Attempt 2: after 2s delay
|
||||
- Attempt 3: after 4s delay
|
||||
|
||||
Only retry on transient failures:
|
||||
- Network errors (TypeError from fetch, connection refused)
|
||||
- Timeouts (AbortError from 45s timeout)
|
||||
- Server errors (5xx status codes)
|
||||
|
||||
Do NOT retry on:
|
||||
- 4xx errors (auth, credits, bad request)
|
||||
|
||||
Spinner shows retry progress: "Searching for audio sources... (retry 2 of 3)"
|
||||
|
||||
### 3. Error Classification
|
||||
|
||||
| Error Type | Detection | Message |
|
||||
|---|---|---|
|
||||
| Credit (402) | `ApiError` with status 402 | "You're out of credits..." + Buy Credits |
|
||||
| Auth (401/403) | `ApiError` with status 401 or 403 | "Authentication required" |
|
||||
| Server (5xx) | `ApiError` with status >= 500 | Auto-retry → "Our search service is temporarily unavailable. Please try again." |
|
||||
| Timeout | `AbortError` or `err.name === 'AbortError'` | Auto-retry → "Search timed out. Please try again." |
|
||||
| Network | Non-`ApiError` (TypeError, etc.) | Auto-retry → "Network error — check your connection and try again." |
|
||||
|
||||
All classified errors land in `{ phase: 'failed' }` — never a silent empty state.
|
||||
|
||||
### 4. Files Changed
|
||||
|
||||
Only `frontend/components/job/steps/AudioSourceStep.tsx`:
|
||||
|
||||
- Replace `isSearching`, `error`, `isCreditError` state variables with `searchStatus` state
|
||||
- Rewrite `doSearch` to use state machine + retry with backoff
|
||||
- Update all rendering conditionals to use `searchStatus.phase`
|
||||
- Update spinner to show retry attempt count
|
||||
|
||||
No changes to: API client, backend, `NoResultsSection` component, result rendering, tier logic, fuzzy matching, catalog search.
|
||||
|
||||
### 5. Compatibility
|
||||
|
||||
- The `handleFuzzyAccept` function resets state and re-triggers search — will reset to `{ phase: 'searching', attempt: 1 }`
|
||||
- Retry button in error banner resets to `{ phase: 'searching', attempt: 1 }` and calls `doSearch`
|
||||
- External consumers (`onSearchCompleted`, `onSearchResultChosen`) are unaffected — they fire from the same success paths
|
||||
@@ -0,0 +1,434 @@
|
||||
# Audio Search Robustness Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Prevent the "No audio sources found" message from appearing when a search actually failed, by replacing scattered boolean/string state with an explicit state machine and adding automatic retries.
|
||||
|
||||
**Architecture:** Replace `isSearching` (boolean), `error` (string), and `isCreditError` (boolean) in `AudioSourceStep` with a single `searchStatus` discriminated union. Update `doSearch` to classify errors and auto-retry transient failures (up to 3 attempts with backoff). Update all rendering conditionals to key off `searchStatus.phase`.
|
||||
|
||||
**Tech Stack:** React (existing component), TypeScript
|
||||
|
||||
**Spec:** `docs/archive/2026-03-27-audio-search-robustness-design.md`
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add SearchStatus Type and Replace State Variables
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:110-114`
|
||||
|
||||
- [ ] **Step 1: Define the SearchStatus type**
|
||||
|
||||
Add immediately above the `AudioSourceStep` function (after the `PendingChoice` type around line 36):
|
||||
|
||||
```ts
|
||||
type SearchStatus =
|
||||
| { phase: 'idle' }
|
||||
| { phase: 'searching'; attempt: number }
|
||||
| { phase: 'succeeded' }
|
||||
| { phase: 'failed'; reason: string; isCreditError: boolean; attempt: number }
|
||||
|
||||
const MAX_SEARCH_ATTEMPTS = 3
|
||||
const RETRY_DELAYS = [0, 2000, 4000] // ms delay before each attempt
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace the three state variables**
|
||||
|
||||
Replace lines 110-114:
|
||||
|
||||
```ts
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [isSearching, setIsSearching] = useState(true)
|
||||
const [error, setError] = useState("")
|
||||
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
|
||||
const [isCreditError, setIsCreditError] = useState(false)
|
||||
```
|
||||
|
||||
With:
|
||||
|
||||
```ts
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [searchStatus, setSearchStatus] = useState<SearchStatus>({ phase: 'searching', attempt: 1 })
|
||||
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add derived booleans for convenience**
|
||||
|
||||
Add after the `searchStatus` state declaration (these keep the rest of the file readable and limit the blast radius):
|
||||
|
||||
```ts
|
||||
// Derived from searchStatus for rendering convenience
|
||||
const isSearching = searchStatus.phase === 'searching'
|
||||
const error = searchStatus.phase === 'failed' ? searchStatus.reason : ''
|
||||
const isCreditError = searchStatus.phase === 'failed' && searchStatus.isCreditError
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify the file compiles**
|
||||
|
||||
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
|
||||
|
||||
This should succeed because the derived booleans preserve the same interface that the rendering code expects. If there are type errors, fix them before proceeding.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "refactor: replace search booleans with SearchStatus state machine type"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Rewrite doSearch with State Machine and Retry Logic
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:140-165`
|
||||
|
||||
- [ ] **Step 1: Add a helper to classify whether an error is retryable**
|
||||
|
||||
Add immediately after the `RETRY_DELAYS` constant:
|
||||
|
||||
```ts
|
||||
/** Returns true for transient errors that should be auto-retried */
|
||||
function isRetryableError(err: unknown): boolean {
|
||||
// Network errors (TypeError: Failed to fetch, connection refused, CORS)
|
||||
if (!(err instanceof ApiError)) return true
|
||||
// Server errors (5xx) are retryable
|
||||
if (err.status >= 500) return true
|
||||
// Everything else (4xx) is not
|
||||
return false
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace the doSearch function**
|
||||
|
||||
Replace lines 140-165 (the entire `doSearch` useCallback) with:
|
||||
|
||||
```ts
|
||||
// Search with automatic retry for transient failures
|
||||
const doSearch = useCallback(async (attempt = 1): Promise<void> => {
|
||||
setSearchStatus({ phase: 'searching', attempt })
|
||||
|
||||
// Delay before retry attempts
|
||||
if (attempt > 1) {
|
||||
await new Promise(r => setTimeout(r, RETRY_DELAYS[attempt - 1] ?? RETRY_DELAYS[RETRY_DELAYS.length - 1]))
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.searchStandalone(artist, title)
|
||||
onSearchCompleted(response.search_session_id)
|
||||
setResults(response.results as ExtendedAudioSearchResult[])
|
||||
setSearchStatus({ phase: 'succeeded' })
|
||||
} catch (err) {
|
||||
// Credit errors — never retry
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setSearchStatus({
|
||||
phase: 'failed',
|
||||
reason: "You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
isCreditError: true,
|
||||
attempt,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Retryable errors — try again if attempts remain
|
||||
if (isRetryableError(err) && attempt < MAX_SEARCH_ATTEMPTS) {
|
||||
return doSearch(attempt + 1)
|
||||
}
|
||||
|
||||
// All retries exhausted or non-retryable error — show failure
|
||||
let reason: string
|
||||
if (err instanceof ApiError) {
|
||||
reason = err.message
|
||||
} else if (err instanceof DOMException && err.name === 'AbortError') {
|
||||
reason = "Search timed out. Please try again."
|
||||
} else {
|
||||
reason = "Search failed due to a network error. Please try again."
|
||||
}
|
||||
|
||||
setSearchStatus({ phase: 'failed', reason, isCreditError: false, attempt })
|
||||
}
|
||||
}, [artist, title, onSearchCompleted])
|
||||
```
|
||||
|
||||
Note: the `finally { setIsSearching(false) }` is gone — the state machine handles it. Every path through `doSearch` now explicitly sets `searchStatus` to either `succeeded` or `failed`.
|
||||
|
||||
- [ ] **Step 3: Verify the file compiles**
|
||||
|
||||
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "feat: rewrite doSearch with state machine and auto-retry (up to 3 attempts)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Update handleFuzzyAccept to Use State Machine
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:225-265` (the `handleFuzzyAccept` function)
|
||||
|
||||
The fuzzy accept has its own inline search call that bypasses `doSearch`. It needs to use the state machine too.
|
||||
|
||||
- [ ] **Step 1: Update handleFuzzyAccept state resets**
|
||||
|
||||
In the `handleFuzzyAccept` function, replace the state reset block (lines ~230-243):
|
||||
|
||||
```ts
|
||||
setFuzzySuggestion(null)
|
||||
setFuzzyAlternatives([])
|
||||
setFuzzyDismissed(true)
|
||||
setResults([])
|
||||
setIsSearching(true)
|
||||
setError("")
|
||||
setCatalogResults([])
|
||||
setCatalogDismissed(false)
|
||||
setCommunityData(null)
|
||||
setCommunityDismissed(false)
|
||||
setShowOtherOptions(false)
|
||||
searchTriggered.current = false
|
||||
fuzzyTriggered.current = false
|
||||
```
|
||||
|
||||
With:
|
||||
|
||||
```ts
|
||||
setFuzzySuggestion(null)
|
||||
setFuzzyAlternatives([])
|
||||
setFuzzyDismissed(true)
|
||||
setResults([])
|
||||
setSearchStatus({ phase: 'searching', attempt: 1 })
|
||||
setCatalogResults([])
|
||||
setCatalogDismissed(false)
|
||||
setCommunityData(null)
|
||||
setCommunityDismissed(false)
|
||||
setShowOtherOptions(false)
|
||||
searchTriggered.current = false
|
||||
fuzzyTriggered.current = false
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update the inline search call's catch/finally**
|
||||
|
||||
In the same function, replace the `.catch` and `.finally` in the microtask (lines ~254-258):
|
||||
|
||||
```ts
|
||||
.catch((err) => {
|
||||
if (err instanceof ApiError) setError(err.message)
|
||||
else setError("Search failed. Please try again.")
|
||||
})
|
||||
.finally(() => setIsSearching(false))
|
||||
```
|
||||
|
||||
With:
|
||||
|
||||
```ts
|
||||
.then(() => {
|
||||
setSearchStatus({ phase: 'succeeded' })
|
||||
})
|
||||
.catch((err) => {
|
||||
const reason = err instanceof ApiError
|
||||
? err.message
|
||||
: "Search failed. Please try again."
|
||||
setSearchStatus({ phase: 'failed', reason, isCreditError: false, attempt: 1 })
|
||||
})
|
||||
```
|
||||
|
||||
Note: remove the `.finally(() => setIsSearching(false))` — the state machine handles it in both `.then` and `.catch`.
|
||||
|
||||
- [ ] **Step 3: Verify the file compiles**
|
||||
|
||||
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "refactor: update handleFuzzyAccept to use SearchStatus state machine"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Update the No-Results Guard and Retry Button
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:439-455` (error display), `529-531` (no-results)
|
||||
|
||||
- [ ] **Step 1: Update the no-results conditional**
|
||||
|
||||
The current line 529:
|
||||
|
||||
```tsx
|
||||
{!isSearching && results.length === 0 && !error && (
|
||||
<NoResultsSection />
|
||||
)}
|
||||
```
|
||||
|
||||
Replace with:
|
||||
|
||||
```tsx
|
||||
{searchStatus.phase === 'succeeded' && results.length === 0 && (
|
||||
<NoResultsSection />
|
||||
)}
|
||||
```
|
||||
|
||||
This is the **key safety change** — `NoResultsSection` now requires an explicit `succeeded` phase, not just the absence of an error string.
|
||||
|
||||
- [ ] **Step 2: Update the retry button in the error display**
|
||||
|
||||
In the error display section (around line 448), the retry button currently does:
|
||||
|
||||
```tsx
|
||||
<button onClick={() => { searchTriggered.current = false; doSearch() }} ...>Retry</button>
|
||||
```
|
||||
|
||||
This still works because `doSearch()` defaults to `attempt = 1`. No change needed here — the derived `error` and `isCreditError` booleans keep the error display working.
|
||||
|
||||
- [ ] **Step 3: Verify the file compiles**
|
||||
|
||||
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "fix: only show NoResultsSection when search explicitly succeeded with zero results"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Update Spinner to Show Retry Progress
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:458-467` (loading state)
|
||||
|
||||
- [ ] **Step 1: Update the spinner section**
|
||||
|
||||
Replace the loading state block (lines 458-467):
|
||||
|
||||
```tsx
|
||||
{isSearching && (
|
||||
<div className="flex flex-col items-center justify-center py-12 gap-3">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
This usually takes 15-30 seconds
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
```
|
||||
|
||||
With:
|
||||
|
||||
```tsx
|
||||
{searchStatus.phase === 'searching' && (
|
||||
<div className="flex flex-col items-center justify-center py-12 gap-3">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
{searchStatus.attempt > 1
|
||||
? `Retry ${searchStatus.attempt - 1} of ${MAX_SEARCH_ATTEMPTS - 1} — this usually takes 15-30 seconds`
|
||||
: 'This usually takes 15-30 seconds'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify the file compiles**
|
||||
|
||||
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "feat: show retry progress in search spinner"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Update Remaining Conditionals to Use searchStatus.phase
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx`
|
||||
|
||||
The derived `isSearching` boolean handles most rendering conditions, but a few spots should use `searchStatus.phase` directly for clarity and safety.
|
||||
|
||||
- [ ] **Step 1: Update the fallback section conditional**
|
||||
|
||||
Line 534:
|
||||
|
||||
```tsx
|
||||
{!isSearching && (confidence.tier !== 3 || results.length === 0) && (
|
||||
```
|
||||
|
||||
Replace with:
|
||||
|
||||
```tsx
|
||||
{searchStatus.phase !== 'searching' && searchStatus.phase !== 'idle' && (confidence.tier !== 3 || results.length === 0) && (
|
||||
```
|
||||
|
||||
This prevents the fallback section (upload/YouTube URL) from showing during the `idle` phase. In practice `idle` is never reached since we initialize to `searching`, but it's defensive.
|
||||
|
||||
- [ ] **Step 2: Verify no other references to the old state setters remain**
|
||||
|
||||
Search for any remaining direct calls to `setIsSearching`, `setError`, or `setIsCreditError`:
|
||||
|
||||
Run: `grep -n 'setIsSearching\|setError\|setIsCreditError' frontend/components/job/steps/AudioSourceStep.tsx`
|
||||
|
||||
If any remain, replace them with appropriate `setSearchStatus` calls. (Tasks 1-3 should have caught them all.)
|
||||
|
||||
- [ ] **Step 3: Verify the file compiles**
|
||||
|
||||
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "refactor: use searchStatus.phase in remaining conditionals"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Manual Smoke Test
|
||||
|
||||
**Files:** None (testing only)
|
||||
|
||||
- [ ] **Step 1: Start the dev server**
|
||||
|
||||
Run: `cd frontend && npx next dev`
|
||||
|
||||
- [ ] **Step 2: Test the happy path**
|
||||
|
||||
Navigate to the Create Karaoke Video flow, enter an artist and title that has results (e.g., "Queen - Bohemian Rhapsody"). Verify:
|
||||
- Spinner appears with "Searching for audio sources..."
|
||||
- Results appear after search completes
|
||||
- No flash of "No audio sources found" before results load
|
||||
|
||||
- [ ] **Step 3: Test no-results path**
|
||||
|
||||
Enter a made-up song (e.g., "Asdfghjkl - Zxcvbnm"). Verify:
|
||||
- Spinner appears
|
||||
- "No audio sources found" appears (correctly this time — search succeeded with 0 results)
|
||||
- Upload/YouTube fallback options are available
|
||||
|
||||
- [ ] **Step 4: Test error path (simulate network failure)**
|
||||
|
||||
In browser DevTools, go to Network tab, set throttling to "Offline" after clicking to the Choose Audio step. Verify:
|
||||
- Spinner shows retry progress ("Retry 1 of 2", "Retry 2 of 2")
|
||||
- After all retries, an error banner appears — NOT "No audio sources found"
|
||||
- Retry button is present and works when back online
|
||||
|
||||
- [ ] **Step 5: Commit any fixes from smoke test**
|
||||
|
||||
If anything needed fixing:
|
||||
```bash
|
||||
git add frontend/components/job/steps/AudioSourceStep.tsx
|
||||
git commit -m "fix: address issues found during smoke test"
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
# Plan: Fix Ensemble Preset Stem Tag Parsing Bug
|
||||
|
||||
**Created:** 2026-03-27
|
||||
**Branch:** feat/sess-20260326-2142-prod-broken-jobs
|
||||
**Status:** Complete
|
||||
|
||||
## Overview
|
||||
|
||||
The ensemble preset stem filename parser in `audio_processor.py` uses naive substring matching (`"instrumental" in basename`) to classify output files as vocals vs instrumental. This breaks when the preset name itself contains the word "instrumental" (e.g., `instrumental_clean`), causing the Vocals file to be misclassified. Stage 2 (backing vocals separation) never runs, so users only get `instrumental_clean` — no backing vocals, no combined instrumentals, and the instrumental review page shows "No backing vocals detected."
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] Fix Stage 1 stem tag parsing to correctly identify Vocals vs Instrumental files regardless of preset name
|
||||
- [x] Fix Stage 2 stem tag parsing with the same approach (same bug pattern)
|
||||
- [ ] Add unit tests for stem tag parsing with various preset names
|
||||
- [ ] Add regression test specifically for `instrumental_clean` preset name
|
||||
- [ ] Verify upload function correctly handles the now-populated backing vocals data
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Root cause:** Output filenames follow the pattern `{base}_(StemTag)_preset_{name}.flac` where StemTag is `Vocals`, `Instrumental`, or `No Vocal`. The old code matched substrings against the entire filename, so preset name `instrumental_clean` caused the Vocals file to match `"instrumental" in basename`.
|
||||
|
||||
**Fix:** Extract the stem tag from between `_(` and `)_` delimiters and match only against that, not the full filename. This is already implemented — just needs tests and verification.
|
||||
|
||||
**Fallback:** If the stem tag extraction fails (no `_(...)_` pattern found), log a warning. This handles edge cases where the separator library changes its naming convention.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [x] Fix stem tag parsing in Stage 1 (lines 308-331) — **already done**
|
||||
2. [x] Fix stem tag parsing in Stage 2 (lines 364-380) — **already done**
|
||||
3. [ ] Write unit tests for `process_audio_separation` ensemble path:
|
||||
- Test Stage 1 correctly classifies files with `instrumental_clean` preset
|
||||
- Test Stage 1 correctly classifies files with `karaoke` preset
|
||||
- Test Stage 2 correctly classifies backing vocal files
|
||||
- Test unrecognized stem tags produce warnings
|
||||
- Test fallback when `_(...)_` pattern not present
|
||||
4. [ ] Run existing tests to verify no regressions
|
||||
5. [ ] Manual verification: check that a test job produces all stems (instrumental_clean, backing_vocals, lead_vocals, instrumental_with_backing)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `karaoke_gen/audio_processor.py` | Modified | Fixed stem tag parsing in Stage 1 (L308-331) and Stage 2 (L364-380) |
|
||||
| `tests/unit/test_audio_processor_local_gpu.py` | Modify | Add tests for ensemble stem tag parsing |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Mock the `Separator` to return filenames with various preset names, verify correct classification into vocals/instrumental/backing_vocals
|
||||
- **Regression test:** Specifically test `instrumental_clean` preset to ensure it never regresses
|
||||
- **Existing tests:** Run full test suite to verify no regressions
|
||||
- **Manual:** After deploy, trigger a test job and verify all stems appear in GCS and on the instrumental review page
|
||||
|
||||
## Open Questions
|
||||
|
||||
None — root cause is confirmed and fix is verified.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Revert the single commit. The old behavior (only instrumental_clean uploaded) would return as a known limitation. No data loss risk.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,165 @@
|
||||
# Reference Lyrics Search & Relevance Filtering
|
||||
|
||||
## Problem
|
||||
|
||||
When a track has a remix, "feat." artist, or unusual naming, the automatic lyrics search during job processing often returns irrelevant results (wrong song entirely) or nothing useful. Users must then manually Google lyrics, copy/paste into the "Add Reference Lyrics" modal — introducing formatting errors and friction. Additionally, irrelevant reference lyrics that do get through skew anchor/gap statistics and confuse correction tooling.
|
||||
|
||||
## Solution
|
||||
|
||||
Three interconnected improvements:
|
||||
|
||||
1. **Relevance filtering in the correction pipeline** — automatically reject reference lyrics that don't match the transcription
|
||||
2. **Search with alternate artist/title** — let users retry the lyrics search with adjusted metadata from the review UI
|
||||
3. **Better empty state** — when no valid references exist, show the search/paste UI inline in the Reference panel
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Relevance Filtering in the Correction Pipeline
|
||||
|
||||
**Location:** Inside `LyricsCorrector`, after anchor sequences are found but before corrections are applied.
|
||||
|
||||
**Per-source relevance score:**
|
||||
```
|
||||
relevance = (reference words appearing in anchor sequences) / (total words in reference source)
|
||||
```
|
||||
|
||||
Sources below `MIN_REFERENCE_RELEVANCE` (default TBD — see Section 5) are removed from `reference_lyrics` and excluded from gap/correction processing.
|
||||
|
||||
**Applies to all code paths:**
|
||||
- Initial job processing — irrelevant sources filtered before corrections saved to GCS
|
||||
- Add lyrics (paste) — pasted text subject to same threshold
|
||||
- Search lyrics (new endpoint) — results filtered automatically
|
||||
|
||||
**Edge case:** If all sources are filtered out, the job proceeds with zero reference sources. The transcription stands as-is with no corrections. The frontend shows the empty state (Section 4).
|
||||
|
||||
**Metadata:** Filtered-out sources are logged in correction metadata (source name + score) for debugging but not stored in `reference_lyrics`.
|
||||
|
||||
**Override:** The `search-lyrics` endpoint and `add-lyrics` endpoint accept a `force: true` flag to bypass the threshold for user-selected sources. This handles cases where the transcription is poor and a low match % doesn't mean wrong song.
|
||||
|
||||
### 2. New Backend Endpoint — Search Lyrics
|
||||
|
||||
**Endpoint:** `POST /api/review/{job_id}/search-lyrics`
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"artist": "Billie Eilish",
|
||||
"title": "What Was I Made For",
|
||||
"force_sources": []
|
||||
}
|
||||
```
|
||||
|
||||
- `artist` and `title`: Used for the lyrics search across all providers
|
||||
- `force_sources`: Optional list of source names to add regardless of threshold (for the override flow)
|
||||
|
||||
**Behavior:**
|
||||
1. Download current `corrections.json` from GCS
|
||||
2. Create all standard lyrics providers (Genius, Spotify, Musixmatch, LRCLIB) with provided artist/title
|
||||
3. Fetch lyrics from all providers
|
||||
4. Run through the correction pipeline with relevance filtering
|
||||
5. Sources passing threshold are added to `reference_lyrics`, corrections recomputed
|
||||
6. Sources in `force_sources` bypass the threshold
|
||||
7. Upload updated `corrections.json` to GCS
|
||||
|
||||
**Response — success (at least one source passed or force-added):**
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"data": { "...full CorrectionData..." },
|
||||
"sources_added": ["genius", "lrclib"],
|
||||
"sources_rejected": {
|
||||
"spotify": {"relevance": 0.12, "track_name": "What Was I Made For", "artist": "Billie Eilish"},
|
||||
"musixmatch": {"relevance": 0.08, "track_name": "What Was I Made For", "artist": "Billie Eilish"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Response — no valid results:**
|
||||
```json
|
||||
{
|
||||
"status": "no_results",
|
||||
"message": "No lyrics sources passed the relevance threshold",
|
||||
"sources_rejected": {
|
||||
"genius": {"relevance": 0.15, "track_name": "What Was I Made For", "artist": "Billie Eilish"},
|
||||
"spotify": {"relevance": 0.09, "track_name": "What Was I Made For", "artist": "Billie Eilish"}
|
||||
},
|
||||
"sources_not_found": ["lrclib", "musixmatch"]
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Frontend — Add Reference Lyrics Modal Redesign
|
||||
|
||||
The modal gets two tabs: **Search** (default) and **Paste**.
|
||||
|
||||
#### Search Tab
|
||||
|
||||
- Two input fields pre-populated from job metadata: **Artist** and **Title**
|
||||
- Helpful tip: "Try removing 'feat.', 'remix', or other extras from the title"
|
||||
- "Search All Providers" button
|
||||
- **Loading state:** Spinner with "Searching providers..."
|
||||
- **Success (sources passed threshold):** Modal closes, new sources appear in Reference Lyrics panel
|
||||
- **No results state:** Modal stays open, shows rejected sources as selectable cards:
|
||||
- Each card shows: provider name, match %, track name/artist found
|
||||
- Checkbox on each to select for force-add
|
||||
- Providers that returned nothing shown grayed out (no checkbox)
|
||||
- Explanation: "These sources were found but had low word match with your transcription. This could mean wrong song — or the transcription may just be inaccurate."
|
||||
- "Add Selected" button (disabled until something checked) to force-add
|
||||
- "Search Again" button to retry with adjusted terms
|
||||
- Suggestion to try different terms or switch to Paste tab
|
||||
|
||||
#### Paste Tab
|
||||
|
||||
Identical to current modal: Source Name input + Lyrics textarea. No changes to the paste flow — still calls existing `add-lyrics` endpoint, still subject to relevance filtering. If pasted lyrics fail the threshold, the user gets a similar rejection message with option to force-add.
|
||||
|
||||
### 4. Empty State — Reference Panel Inline UI
|
||||
|
||||
When no valid reference sources exist after job processing (all filtered or none found), the Reference Lyrics panel shows:
|
||||
|
||||
1. **Explanation banner:** "No valid reference lyrics found" with context about why (remixes, feat., live versions)
|
||||
2. **Inline Search/Paste tabbed UI** — same as the modal content but embedded directly in the panel. No "+ New" button click needed.
|
||||
3. Artist/Title fields pre-populated from job metadata
|
||||
|
||||
Once a valid source is added (via search or paste), the panel switches back to the normal view: source buttons + lyrics display + "+ New" button for the modal.
|
||||
|
||||
### 5. Empirical Threshold Analysis
|
||||
|
||||
**Goal:** Determine the right `MIN_REFERENCE_RELEVANCE` value from real data.
|
||||
|
||||
**Method:**
|
||||
1. Pull ~30 prod jobs from Firestore that have correction data with reference lyrics
|
||||
2. Bias sampling toward jobs with mixed results (at least one source with low match %) — pure high-match jobs aren't useful for threshold tuning
|
||||
3. For each job × source, compute: `(reference words in anchor sequences) / (total reference words)`
|
||||
4. Generate a report with: job ID, source name, match %, first ~2 lines of transcription and reference (for quick visual comparison)
|
||||
5. User visually classifies each source as "correct song" or "wrong song"
|
||||
6. Find the threshold that best separates the two groups
|
||||
|
||||
**Output:** A concrete `MIN_REFERENCE_RELEVANCE` value backed by data. Stored as a constant in the corrector module, easily tunable later.
|
||||
|
||||
**Timing:** Research step early in implementation, before filtering logic is finalized.
|
||||
|
||||
## API Changes Summary
|
||||
|
||||
| Endpoint | Change |
|
||||
|----------|--------|
|
||||
| `POST /api/review/{job_id}/search-lyrics` | **New** — search with alternate artist/title |
|
||||
| `POST /api/review/{job_id}/add-lyrics` | **Modified** — add `force` flag for threshold bypass |
|
||||
|
||||
## Files Likely Modified
|
||||
|
||||
### Backend
|
||||
- `karaoke_gen/lyrics_transcriber/correction/corrector.py` — relevance filtering after anchor finding
|
||||
- `karaoke_gen/lyrics_transcriber/correction/anchor_sequence.py` — expose per-source word match stats
|
||||
- `backend/api/routes/review.py` — new `search-lyrics` endpoint, `force` flag on `add-lyrics`
|
||||
- `karaoke_gen/lyrics_transcriber/correction/operations.py` — new operation for search-and-add flow
|
||||
|
||||
### Frontend
|
||||
- `frontend/components/lyrics-review/modals/AddLyricsModal.tsx` — tabbed redesign with Search/Paste
|
||||
- `frontend/components/lyrics-review/ReferenceView.tsx` — empty state inline UI
|
||||
- `frontend/lib/api.ts` — new `searchLyrics()` method
|
||||
- `frontend/lib/lyrics-review/types.ts` — types for search response
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Changing which providers are used during initial job processing
|
||||
- Provider-specific configuration (API keys, rate limits)
|
||||
- Lyrics quality beyond relevance (e.g., formatting, completeness)
|
||||
@@ -15,6 +15,7 @@
|
||||
import { render, screen, waitFor, act } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import { getSearchConfidence } from "@/lib/audio-search-utils"
|
||||
|
||||
// Mock the api module
|
||||
jest.mock("@/lib/api", () => ({
|
||||
@@ -61,6 +62,7 @@ jest.mock("@/lib/audio-search-utils", () => ({
|
||||
}))
|
||||
|
||||
const mockApi = api as jest.Mocked<typeof api>
|
||||
const mockGetSearchConfidence = getSearchConfidence as jest.Mock
|
||||
|
||||
import { AudioSourceStep } from "../steps/AudioSourceStep"
|
||||
|
||||
@@ -187,15 +189,26 @@ describe("AudioSourceStep", () => {
|
||||
})
|
||||
|
||||
it("shows error message when search fails with ApiError", async () => {
|
||||
mockApi.searchStandalone.mockRejectedValue(
|
||||
new ApiError("Internal server error", 500)
|
||||
)
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
mockApi.searchStandalone.mockRejectedValue(
|
||||
new ApiError("Internal server error", 500)
|
||||
)
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Internal server error")).toBeInTheDocument()
|
||||
})
|
||||
// 500 errors are retried up to 3 times with delays (0, 2s, 4s).
|
||||
// Advance timers and flush microtasks between each retry.
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await act(async () => { jest.advanceTimersByTime(5000) })
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Internal server error")).toBeInTheDocument()
|
||||
})
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("shows credit error with Buy Credits link on 402", async () => {
|
||||
@@ -274,4 +287,111 @@ describe("AudioSourceStep", () => {
|
||||
screen.queryByText("A karaoke version of this song already exists!")
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
// --- Search robustness tests (state machine + retry) ---
|
||||
|
||||
it("does NOT show 'No audio sources found' when search fails with network error", async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
mockApi.searchStandalone.mockRejectedValue(new TypeError("Failed to fetch"))
|
||||
mockGetSearchConfidence.mockReturnValue({
|
||||
tier: 3, bestResult: null, bestCategory: null, reason: "", warnings: [],
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// Advance through all retry attempts
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await act(async () => { jest.advanceTimersByTime(5000) })
|
||||
}
|
||||
|
||||
// Should show error message, NOT "No audio sources found"
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/network error/i)).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.queryByTestId("no-results-section")).not.toBeInTheDocument()
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("retries 500 errors up to 3 times before showing error", async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
mockApi.searchStandalone.mockRejectedValue(
|
||||
new ApiError("Server error", 500)
|
||||
)
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// Advance through all retry attempts
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await act(async () => { jest.advanceTimersByTime(5000) })
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Server error")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// Should have been called 3 times (1 initial + 2 retries)
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalledTimes(3)
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("shows retry progress text during retries", async () => {
|
||||
jest.useFakeTimers()
|
||||
try {
|
||||
mockApi.searchStandalone.mockRejectedValue(
|
||||
new ApiError("Server error", 500)
|
||||
)
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
// After first failure + 2s delay, should show retry text
|
||||
await act(async () => { jest.advanceTimersByTime(3000) })
|
||||
|
||||
expect(screen.getByText(/Retry 1 of 2/)).toBeInTheDocument()
|
||||
|
||||
// Clean up remaining retries
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await act(async () => { jest.advanceTimersByTime(5000) })
|
||||
}
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("does not retry 402 credit errors", async () => {
|
||||
mockApi.searchStandalone.mockRejectedValue(
|
||||
new ApiError("No credits", 402)
|
||||
)
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/out of credits/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// Should have been called only once — no retries
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows 'No audio sources found' only after successful search with 0 results", async () => {
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: "sess-empty",
|
||||
results: [],
|
||||
results_count: 0,
|
||||
})
|
||||
mockGetSearchConfidence.mockReturnValue({
|
||||
tier: 3, bestResult: null, bestCategory: null, reason: "", warnings: [],
|
||||
})
|
||||
|
||||
render(<AudioSourceStep {...defaultProps} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("no-results-section")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -38,6 +38,24 @@ type PendingChoice =
|
||||
| { type: "url"; url: string }
|
||||
| { type: "file"; file: File }
|
||||
|
||||
type SearchStatus =
|
||||
| { phase: 'searching'; attempt: number }
|
||||
| { phase: 'succeeded' }
|
||||
| { phase: 'failed'; reason: string; isCreditError: boolean; attempt: number }
|
||||
|
||||
const MAX_SEARCH_ATTEMPTS = 3
|
||||
const RETRY_DELAYS = [0, 2000, 4000] // ms delay before each attempt
|
||||
|
||||
/** Returns true for transient errors that should be auto-retried */
|
||||
function isRetryableError(err: unknown): boolean {
|
||||
// Network errors (TypeError: Failed to fetch, connection refused, CORS)
|
||||
if (!(err instanceof ApiError)) return true
|
||||
// Server errors (5xx) are retryable
|
||||
if (err.status >= 500) return true
|
||||
// Everything else (4xx) is not
|
||||
return false
|
||||
}
|
||||
|
||||
/** Render an availability badge with tooltip */
|
||||
function AvailabilityBadge({ seeders }: { seeders: number | undefined | null }) {
|
||||
if (seeders === undefined || seeders === null) return null
|
||||
@@ -108,10 +126,13 @@ export function AudioSourceStep({
|
||||
onAudioEditChange,
|
||||
}: AudioSourceStepProps) {
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [isSearching, setIsSearching] = useState(true)
|
||||
const [error, setError] = useState("")
|
||||
const [searchStatus, setSearchStatus] = useState<SearchStatus>({ phase: 'searching', attempt: 1 })
|
||||
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
|
||||
const [isCreditError, setIsCreditError] = useState(false)
|
||||
|
||||
// Derived from searchStatus for rendering convenience
|
||||
const isSearching = searchStatus.phase === 'searching'
|
||||
const error = searchStatus.phase === 'failed' ? searchStatus.reason : ''
|
||||
const isCreditError = searchStatus.phase === 'failed' && searchStatus.isCreditError
|
||||
const [showOtherOptions, setShowOtherOptions] = useState(false)
|
||||
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
|
||||
const searchTriggered = useRef(false)
|
||||
@@ -137,30 +158,48 @@ export function AudioSourceStep({
|
||||
const [youtubeUrl, setYoutubeUrl] = useState("")
|
||||
const [fallbackMode, setFallbackMode] = useState<"upload" | "url" | null>(null)
|
||||
|
||||
// Search with retry for network failures
|
||||
const doSearch = useCallback(async (retryCount = 0): Promise<void> => {
|
||||
setIsSearching(true)
|
||||
setError("")
|
||||
setIsCreditError(false)
|
||||
// Search with automatic retry for transient failures
|
||||
const doSearch = useCallback(async (attempt = 1): Promise<void> => {
|
||||
setSearchStatus({ phase: 'searching', attempt })
|
||||
|
||||
// Delay before retry attempts
|
||||
if (attempt > 1) {
|
||||
await new Promise(r => setTimeout(r, RETRY_DELAYS[attempt - 1] ?? RETRY_DELAYS[RETRY_DELAYS.length - 1]))
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.searchStandalone(artist, title)
|
||||
// Notify parent of completed session (no job created yet)
|
||||
onSearchCompleted(response.search_session_id)
|
||||
setResults(response.results as ExtendedAudioSearchResult[])
|
||||
setSearchStatus({ phase: 'succeeded' })
|
||||
} catch (err) {
|
||||
// Credit errors — never retry
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else if (retryCount < 1) {
|
||||
// Network errors (CORS, timeout, connection reset) - auto-retry once
|
||||
return doSearch(retryCount + 1)
|
||||
} else {
|
||||
setError("Search failed due to a network error. Please try again.")
|
||||
setSearchStatus({
|
||||
phase: 'failed',
|
||||
reason: "You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
isCreditError: true,
|
||||
attempt,
|
||||
})
|
||||
return
|
||||
}
|
||||
} finally {
|
||||
setIsSearching(false)
|
||||
|
||||
// Retryable errors — try again if attempts remain
|
||||
if (isRetryableError(err) && attempt < MAX_SEARCH_ATTEMPTS) {
|
||||
return doSearch(attempt + 1)
|
||||
}
|
||||
|
||||
// All retries exhausted or non-retryable error — show failure
|
||||
let reason: string
|
||||
if (err instanceof ApiError) {
|
||||
reason = err.message
|
||||
} else if (err instanceof DOMException && err.name === 'AbortError') {
|
||||
reason = "Search timed out. Please try again."
|
||||
} else {
|
||||
reason = "Search failed due to a network error. Please try again."
|
||||
}
|
||||
|
||||
setSearchStatus({ phase: 'failed', reason, isCreditError: false, attempt })
|
||||
}
|
||||
}, [artist, title, onSearchCompleted])
|
||||
|
||||
@@ -232,8 +271,7 @@ export function AudioSourceStep({
|
||||
setFuzzyAlternatives([])
|
||||
setFuzzyDismissed(true)
|
||||
setResults([])
|
||||
setIsSearching(true)
|
||||
setError("")
|
||||
setSearchStatus({ phase: 'searching', attempt: 1 })
|
||||
setCatalogResults([])
|
||||
setCatalogDismissed(false)
|
||||
setCommunityData(null)
|
||||
@@ -241,29 +279,9 @@ export function AudioSourceStep({
|
||||
setShowOtherOptions(false)
|
||||
searchTriggered.current = false
|
||||
fuzzyTriggered.current = false
|
||||
// doSearch will re-fire via the useEffect since searchTriggered is reset
|
||||
// But artist/title are props — they update on next render, so we need to
|
||||
// let the parent re-render us with new props first. Use a microtask.
|
||||
Promise.resolve().then(() => {
|
||||
searchTriggered.current = true
|
||||
api.searchStandalone(chosen.artist_name, chosen.track_name)
|
||||
.then((response) => {
|
||||
onSearchCompleted(response.search_session_id)
|
||||
setResults(response.results as ExtendedAudioSearchResult[])
|
||||
})
|
||||
.catch((err) => {
|
||||
if (err instanceof ApiError) setError(err.message)
|
||||
else setError("Search failed. Please try again.")
|
||||
})
|
||||
.finally(() => setIsSearching(false))
|
||||
// Also re-run catalog + community check with corrected name
|
||||
api.searchCatalogTracks(chosen.track_name, chosen.artist_name, 5)
|
||||
.then((tracks) => setCatalogResults(tracks))
|
||||
.catch(() => {})
|
||||
api.checkCommunityVersions(chosen.artist_name, chosen.track_name)
|
||||
.then((data) => setCommunityData(data))
|
||||
.catch(() => {})
|
||||
})
|
||||
// doSearch (and catalog/community searches) will re-fire via the useEffect
|
||||
// when the parent re-renders us with corrected artist/title props, since
|
||||
// searchTriggered.current is reset and doSearch is recreated with new props.
|
||||
}
|
||||
|
||||
function handleSelect(index: number) {
|
||||
@@ -312,6 +330,11 @@ export function AudioSourceStep({
|
||||
}
|
||||
}
|
||||
|
||||
const handleRetry = useCallback(() => {
|
||||
searchTriggered.current = false
|
||||
doSearch()
|
||||
}, [doSearch])
|
||||
|
||||
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
|
||||
|
||||
// Audio edit question — shown after user selects audio, before advancing
|
||||
@@ -445,7 +468,7 @@ export function AudioSourceStep({
|
||||
)}
|
||||
{!isCreditError && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1">
|
||||
<button onClick={() => { searchTriggered.current = false; doSearch() }} className="font-medium underline" style={{ color: 'var(--brand-pink)' }}>Retry</button>
|
||||
<button onClick={handleRetry} className="font-medium underline" style={{ color: 'var(--brand-pink)' }}>Retry</button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Still not working? <a href="mailto:andrew@nomadkaraoke.com" className="underline hover:text-foreground">Email andrew@nomadkaraoke.com</a>
|
||||
</span>
|
||||
@@ -455,13 +478,15 @@ export function AudioSourceStep({
|
||||
)}
|
||||
|
||||
{/* Loading state */}
|
||||
{isSearching && (
|
||||
{searchStatus.phase === 'searching' && (
|
||||
<div className="flex flex-col items-center justify-center py-12 gap-3">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
This usually takes 15-30 seconds
|
||||
{searchStatus.attempt > 1
|
||||
? `Retry ${searchStatus.attempt - 1} of ${MAX_SEARCH_ATTEMPTS - 1} — this usually takes 15-30 seconds`
|
||||
: 'This usually takes 15-30 seconds'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -526,12 +551,12 @@ export function AudioSourceStep({
|
||||
)}
|
||||
|
||||
{/* No results */}
|
||||
{!isSearching && results.length === 0 && !error && (
|
||||
{searchStatus.phase === 'succeeded' && results.length === 0 && (
|
||||
<NoResultsSection />
|
||||
)}
|
||||
|
||||
{/* Fallback section for Tier 1/2 and no-results — at the bottom */}
|
||||
{!isSearching && (confidence.tier !== 3 || results.length === 0) && (
|
||||
{searchStatus.phase !== 'searching' && (confidence.tier !== 3 || results.length === 0) && (
|
||||
<FallbackSection
|
||||
tier={confidence.tier}
|
||||
hasResults={results.length > 0}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
Word,
|
||||
WordClickInfo,
|
||||
ModalContent,
|
||||
SearchLyricsResponse,
|
||||
} from '@/lib/lyrics-review/types'
|
||||
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
|
||||
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
|
||||
@@ -71,6 +72,7 @@ interface ApiClient {
|
||||
submitEditLog: (editLog: EditLog) => Promise<void>
|
||||
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
|
||||
addLyrics: (source: string, lyrics: string) => Promise<CorrectionData>
|
||||
searchLyrics?: (artist: string, title: string, forceSources?: string[]) => Promise<SearchLyricsResponse>
|
||||
getAudioUrl: (hash: string) => string
|
||||
generatePreviewVideo: (data: CorrectionData) => Promise<{
|
||||
status: string
|
||||
@@ -1047,6 +1049,21 @@ export default function LyricsAnalyzer({
|
||||
[apiClient, updateDataWithHistory]
|
||||
)
|
||||
|
||||
// Search lyrics (reference lyrics search)
|
||||
const handleSearchLyrics = useCallback(
|
||||
async (artist: string, title: string, forceSources: string[]): Promise<SearchLyricsResponse> => {
|
||||
if (!apiClient || !apiClient.searchLyrics) {
|
||||
return { status: 'no_results', message: 'No API client', sources_added: [], sources_rejected: {}, sources_not_found: [] }
|
||||
}
|
||||
const result = await apiClient.searchLyrics(artist, title, forceSources)
|
||||
if (result.status === 'success' && result.data) {
|
||||
updateDataWithHistory(result.data, 'search lyrics')
|
||||
}
|
||||
return result
|
||||
},
|
||||
[apiClient, updateDataWithHistory],
|
||||
)
|
||||
|
||||
// Find/replace
|
||||
const handleFindReplace = useCallback(
|
||||
(
|
||||
@@ -1250,6 +1267,10 @@ export default function LyricsAnalyzer({
|
||||
corrected_segments={data.corrected_segments}
|
||||
corrections={data.corrections}
|
||||
onAddLyrics={() => setIsAddLyricsModalOpen(true)}
|
||||
onAddLyricsInline={handleAddLyrics}
|
||||
onSearchLyrics={handleSearchLyrics}
|
||||
defaultArtist={data.metadata?.artist || ''}
|
||||
defaultTitle={data.metadata?.title || ''}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1374,6 +1395,9 @@ export default function LyricsAnalyzer({
|
||||
open={isAddLyricsModalOpen}
|
||||
onClose={() => setIsAddLyricsModalOpen(false)}
|
||||
onAdd={handleAddLyrics}
|
||||
onSearch={handleSearchLyrics}
|
||||
defaultArtist={data.metadata?.artist || ''}
|
||||
defaultTitle={data.metadata?.title || ''}
|
||||
/>
|
||||
|
||||
<FindReplaceModal
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
'use client'
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Info } from 'lucide-react'
|
||||
import { SearchLyricsResponse } from '@/lib/lyrics-review/types'
|
||||
import SearchLyricsTab from './modals/SearchLyricsTab'
|
||||
import PasteLyricsTab from './modals/PasteLyricsTab'
|
||||
|
||||
interface ReferenceEmptyStateProps {
|
||||
defaultArtist: string
|
||||
defaultTitle: string
|
||||
onAdd: (source: string, lyrics: string) => Promise<void>
|
||||
onSearch: (artist: string, title: string, forceSources: string[]) => Promise<SearchLyricsResponse>
|
||||
}
|
||||
|
||||
export default function ReferenceEmptyState({
|
||||
defaultArtist,
|
||||
defaultTitle,
|
||||
onAdd,
|
||||
onSearch,
|
||||
}: ReferenceEmptyStateProps) {
|
||||
// onClose is a no-op here — it's inline, not a modal
|
||||
const handleClose = () => {}
|
||||
|
||||
return (
|
||||
<div className="space-y-4 p-2">
|
||||
<Alert>
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No reference lyrics were found for this song. Search all configured lyrics providers or
|
||||
paste lyrics manually to enable gap correction.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Tabs defaultValue="search">
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="search" className="flex-1">
|
||||
Search
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="paste" className="flex-1">
|
||||
Paste
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="search">
|
||||
<SearchLyricsTab
|
||||
defaultArtist={defaultArtist}
|
||||
defaultTitle={defaultTitle}
|
||||
onSearch={onSearch}
|
||||
onClose={handleClose}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="paste">
|
||||
<PasteLyricsTab onAdd={onAdd} onClose={handleClose} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { calculateReferenceLinePositions } from '@/lib/lyrics-review/utils/refer
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import { SourceSelector } from './shared/SourceSelector'
|
||||
import { HighlightedText } from './shared/HighlightedText'
|
||||
import ReferenceEmptyState from './ReferenceEmptyState'
|
||||
|
||||
export default function ReferenceView({
|
||||
referenceSources,
|
||||
@@ -24,6 +25,10 @@ export default function ReferenceView({
|
||||
gaps,
|
||||
corrections,
|
||||
onAddLyrics,
|
||||
onAddLyricsInline,
|
||||
onSearchLyrics,
|
||||
defaultArtist = '',
|
||||
defaultTitle = '',
|
||||
}: ReferenceViewProps) {
|
||||
const availableSources = useMemo(() => Object.keys(referenceSources), [referenceSources])
|
||||
|
||||
@@ -180,6 +185,15 @@ export default function ReferenceView({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{availableSources.length === 0 && onAddLyricsInline && onSearchLyrics && (
|
||||
<ReferenceEmptyState
|
||||
defaultArtist={defaultArtist}
|
||||
defaultTitle={defaultTitle}
|
||||
onAdd={onAddLyricsInline}
|
||||
onSearch={onSearchLyrics}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{currentSourceSegments.map((segment, index) => (
|
||||
<div key={index} className="flex items-start w-full hover:bg-muted/50 transition-colors">
|
||||
|
||||
@@ -1,50 +1,34 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { SearchLyricsResponse } from '@/lib/lyrics-review/types'
|
||||
import SearchLyricsTab from './SearchLyricsTab'
|
||||
import PasteLyricsTab from './PasteLyricsTab'
|
||||
|
||||
interface AddLyricsModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onAdd: (source: string, lyrics: string) => Promise<void>
|
||||
onSearch: (artist: string, title: string, forceSources: string[]) => Promise<SearchLyricsResponse>
|
||||
defaultArtist: string
|
||||
defaultTitle: string
|
||||
}
|
||||
|
||||
export default function AddLyricsModal({ open, onClose, onAdd }: AddLyricsModalProps) {
|
||||
const [source, setSource] = useState('')
|
||||
const [lyrics, setLyrics] = useState('')
|
||||
const [isAdding, setIsAdding] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!source.trim() || !lyrics.trim()) return
|
||||
|
||||
setIsAdding(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
await onAdd(source.trim(), lyrics.trim())
|
||||
setSource('')
|
||||
setLyrics('')
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to add lyrics')
|
||||
} finally {
|
||||
setIsAdding(false)
|
||||
}
|
||||
}
|
||||
export default function AddLyricsModal({
|
||||
open,
|
||||
onClose,
|
||||
onAdd,
|
||||
onSearch,
|
||||
defaultArtist,
|
||||
defaultTitle,
|
||||
}: AddLyricsModalProps) {
|
||||
const [activeTab, setActiveTab] = useState('search')
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isAdding) {
|
||||
setSource('')
|
||||
setLyrics('')
|
||||
setError(null)
|
||||
onClose()
|
||||
}
|
||||
setActiveTab('search')
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -54,52 +38,29 @@ export default function AddLyricsModal({ open, onClose, onAdd }: AddLyricsModalP
|
||||
<DialogTitle>Add Reference Lyrics</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="source">Source Name</Label>
|
||||
<Input
|
||||
id="source"
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value)}
|
||||
placeholder="e.g., manual, genius, azlyrics..."
|
||||
disabled={isAdding}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="search" className="flex-1">
|
||||
Search
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="paste" className="flex-1">
|
||||
Paste
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="search">
|
||||
<SearchLyricsTab
|
||||
defaultArtist={defaultArtist}
|
||||
defaultTitle={defaultTitle}
|
||||
onSearch={onSearch}
|
||||
onClose={handleClose}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="lyrics">Lyrics</Label>
|
||||
<Textarea
|
||||
id="lyrics"
|
||||
value={lyrics}
|
||||
onChange={(e) => setLyrics(e.target.value)}
|
||||
placeholder="Paste lyrics here..."
|
||||
rows={10}
|
||||
disabled={isAdding}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose} disabled={isAdding}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={isAdding || !source.trim() || !lyrics.trim()}
|
||||
>
|
||||
{isAdding ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Adding...
|
||||
</>
|
||||
) : (
|
||||
'Add Lyrics'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<TabsContent value="paste">
|
||||
<PasteLyricsTab onAdd={onAdd} onClose={handleClose} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface PasteLyricsTabProps {
|
||||
onAdd: (source: string, lyrics: string) => Promise<void>
|
||||
onClose: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export default function PasteLyricsTab({
|
||||
onAdd,
|
||||
onClose,
|
||||
disabled = false,
|
||||
}: PasteLyricsTabProps) {
|
||||
const [source, setSource] = useState('')
|
||||
const [lyrics, setLyrics] = useState('')
|
||||
const [isAdding, setIsAdding] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!source.trim() || !lyrics.trim()) return
|
||||
|
||||
setIsAdding(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
await onAdd(source.trim(), lyrics.trim())
|
||||
setSource('')
|
||||
setLyrics('')
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to add lyrics')
|
||||
} finally {
|
||||
setIsAdding(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
if (!isAdding) {
|
||||
setSource('')
|
||||
setLyrics('')
|
||||
setError(null)
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="paste-source">Source Name</Label>
|
||||
<Input
|
||||
id="paste-source"
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value)}
|
||||
placeholder="e.g., manual, genius, azlyrics..."
|
||||
disabled={isAdding || disabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="paste-lyrics">Lyrics</Label>
|
||||
<Textarea
|
||||
id="paste-lyrics"
|
||||
value={lyrics}
|
||||
onChange={(e) => setLyrics(e.target.value)}
|
||||
placeholder="Paste lyrics here..."
|
||||
rows={10}
|
||||
disabled={isAdding || disabled}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button variant="outline" onClick={handleCancel} disabled={isAdding || disabled}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={isAdding || disabled || !source.trim() || !lyrics.trim()}
|
||||
>
|
||||
{isAdding ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Adding...
|
||||
</>
|
||||
) : (
|
||||
'Add Lyrics'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { SearchLyricsResponse, RejectedSource } from '@/lib/lyrics-review/types'
|
||||
|
||||
interface SearchLyricsTabProps {
|
||||
defaultArtist: string
|
||||
defaultTitle: string
|
||||
onSearch: (artist: string, title: string, forceSources: string[]) => Promise<SearchLyricsResponse>
|
||||
onClose: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export default function SearchLyricsTab({
|
||||
defaultArtist,
|
||||
defaultTitle,
|
||||
onSearch,
|
||||
onClose,
|
||||
disabled = false,
|
||||
}: SearchLyricsTabProps) {
|
||||
const [artist, setArtist] = useState(defaultArtist)
|
||||
const [title, setTitle] = useState(defaultTitle)
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const [searchResult, setSearchResult] = useState<SearchLyricsResponse | null>(null)
|
||||
const [selectedForce, setSelectedForce] = useState<Set<string>>(new Set())
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleSearch = async (forceSources: string[] = []) => {
|
||||
if (!artist.trim() || !title.trim()) return
|
||||
|
||||
setIsSearching(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const result = await onSearch(artist.trim(), title.trim(), forceSources)
|
||||
if (result.status === 'success') {
|
||||
// Success: parent handles closing and updating data
|
||||
onClose()
|
||||
} else {
|
||||
// No results: store result to show rejected sources
|
||||
setSearchResult(result)
|
||||
setSelectedForce(new Set())
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Search failed')
|
||||
} finally {
|
||||
setIsSearching(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleForceAdd = async () => {
|
||||
await handleSearch(Array.from(selectedForce))
|
||||
}
|
||||
|
||||
const toggleForceSource = (source: string) => {
|
||||
setSelectedForce((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(source)) {
|
||||
next.delete(source)
|
||||
} else {
|
||||
next.add(source)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const rejectedEntries = searchResult
|
||||
? Object.entries(searchResult.sources_rejected ?? {})
|
||||
: []
|
||||
const notFoundSources = searchResult?.sources_not_found ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="search-artist">Artist</Label>
|
||||
<Input
|
||||
id="search-artist"
|
||||
value={artist}
|
||||
onChange={(e) => setArtist(e.target.value)}
|
||||
placeholder="Artist name"
|
||||
disabled={isSearching || disabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="search-title">Title</Label>
|
||||
<Input
|
||||
id="search-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Song title"
|
||||
disabled={isSearching || disabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Searches all configured lyrics providers (Genius, AZLyrics, etc.) and adds any
|
||||
results that are a close match to this song.
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{searchResult && searchResult.status === 'no_results' && (
|
||||
<div className="space-y-3">
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
{searchResult.message || 'No matching lyrics found across all providers.'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{notFoundSources.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Not found: {notFoundSources.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{rejectedEntries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">
|
||||
Low-confidence results — select any to force-add:
|
||||
</p>
|
||||
{rejectedEntries.map(([source, info]: [string, RejectedSource]) => (
|
||||
<div
|
||||
key={source}
|
||||
className="flex items-start gap-3 rounded-md border p-3 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
id={`force-${source}`}
|
||||
checked={selectedForce.has(source)}
|
||||
onCheckedChange={() => toggleForceSource(source)}
|
||||
disabled={isSearching || disabled}
|
||||
/>
|
||||
<div className="flex-1 space-y-1">
|
||||
<label
|
||||
htmlFor={`force-${source}`}
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{source}
|
||||
</label>
|
||||
<p className="text-muted-foreground">
|
||||
“{info.track_name}” by {info.artist_names}
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Match: {info.matched_words}/{info.total_words} words (
|
||||
{Math.round(info.relevance * 100)}% relevance)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
{searchResult && searchResult.status === 'no_results' ? (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleSearch()}
|
||||
disabled={isSearching || disabled || !artist.trim() || !title.trim()}
|
||||
>
|
||||
{isSearching ? (
|
||||
<>
|
||||
<Spinner className="mr-2 h-4 w-4" />
|
||||
Searching...
|
||||
</>
|
||||
) : (
|
||||
'Search Again'
|
||||
)}
|
||||
</Button>
|
||||
{rejectedEntries.length > 0 && (
|
||||
<Button
|
||||
onClick={handleForceAdd}
|
||||
disabled={isSearching || disabled || selectedForce.size === 0}
|
||||
>
|
||||
{isSearching ? (
|
||||
<>
|
||||
<Spinner className="mr-2 h-4 w-4" />
|
||||
Adding...
|
||||
</>
|
||||
) : (
|
||||
`Add Selected (${selectedForce.size})`
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
onClick={() => handleSearch()}
|
||||
disabled={isSearching || disabled || !artist.trim() || !title.trim()}
|
||||
>
|
||||
{isSearching ? (
|
||||
<>
|
||||
<Spinner className="mr-2 h-4 w-4" />
|
||||
Searching...
|
||||
</>
|
||||
) : (
|
||||
'Search All Providers'
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
export { default as AddLyricsModal } from './AddLyricsModal'
|
||||
export { default as PasteLyricsTab } from './PasteLyricsTab'
|
||||
export { default as SearchLyricsTab } from './SearchLyricsTab'
|
||||
export { default as AIFeedbackModal } from './AIFeedbackModal'
|
||||
export { default as CorrectionAnnotationModal } from './CorrectionAnnotationModal'
|
||||
export { default as EditModal } from './EditModal'
|
||||
|
||||
@@ -335,11 +335,29 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
await page.goto(magicLinkUrl);
|
||||
console.log(' Navigated to magic link verification page');
|
||||
|
||||
// Wait for successful verification
|
||||
await expect(
|
||||
page.getByText(/successfully signed in/i)
|
||||
).toBeVisible({ timeout: 15000 });
|
||||
console.log(' Successfully signed in via magic link');
|
||||
// Wait for verification to complete — new users see a credit interstitial
|
||||
// (credits_granted, credits_denied, or credits_pending), returning users
|
||||
// see "Successfully signed in!". Handle all cases.
|
||||
const verifyResult = await Promise.race([
|
||||
page.getByText(/successfully signed in/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'success'),
|
||||
page.getByText(/welcome to nomad karaoke/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'credits_interstitial'),
|
||||
page.getByText(/sign-in failed/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'error'),
|
||||
]);
|
||||
console.log(` Verification result: ${verifyResult}`);
|
||||
await page.screenshot({ path: 'test-results/02b2-verify-result.png' });
|
||||
|
||||
if (verifyResult === 'error') {
|
||||
const errorText = await page.locator('.text-muted-foreground').first().textContent();
|
||||
throw new Error(`Magic link verification failed: ${errorText}`);
|
||||
}
|
||||
|
||||
if (verifyResult === 'credits_interstitial') {
|
||||
// Click through the credit interstitial to get to /app
|
||||
const startButton = page.getByRole('button', { name: /start creating|go to dashboard|explore the app/i });
|
||||
await expect(startButton).toBeVisible({ timeout: 5000 });
|
||||
await startButton.click();
|
||||
console.log(' Clicked through credit interstitial');
|
||||
}
|
||||
|
||||
// Wait for redirect to /app
|
||||
await page.waitForURL(/\/app/, { timeout: 15000 });
|
||||
@@ -355,9 +373,38 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
await page.screenshot({ path: 'test-results/02c-app-after-signup.png' });
|
||||
console.log('STEP 2-3 COMPLETE: Magic link signup and auth successful');
|
||||
|
||||
// Verify credits are visible
|
||||
// Verify credits — if 0 (credit eval denied), grant via admin API
|
||||
const creditText = await page.getByText(/credit/i).first().textContent();
|
||||
console.log(` Credits visible: ${creditText}`);
|
||||
|
||||
if (creditText?.includes('0 credit')) {
|
||||
const adminToken = process.env.E2E_ADMIN_TOKEN;
|
||||
if (adminToken && inbox?.emailAddress) {
|
||||
console.log(' User has 0 credits — granting via admin API...');
|
||||
const grantResponse = await fetch(`${API_URL}/api/users/admin/credits`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Admin-Token': adminToken,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: inbox.emailAddress,
|
||||
amount: 1,
|
||||
reason: 'e2e_test_grant',
|
||||
}),
|
||||
});
|
||||
const grantResult = await grantResponse.json();
|
||||
console.log(` Credit grant result: ${JSON.stringify(grantResult)}`);
|
||||
|
||||
// Reload to pick up new credit balance
|
||||
await page.reload();
|
||||
await page.waitForURL(/\/app/, { timeout: 15000 });
|
||||
const newCreditText = await page.getByText(/credit/i).first().textContent();
|
||||
console.log(` Credits after grant: ${newCreditText}`);
|
||||
} else {
|
||||
throw new Error('User has 0 credits and no E2E_ADMIN_TOKEN to grant them');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
|
||||
+21
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
|
||||
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse } from './types';
|
||||
import type { CorrectionData, CorrectionAnnotation, EditLog } from './lyrics-review/types';
|
||||
import type { CorrectionData, CorrectionAnnotation, EditLog, SearchLyricsResponse } from './lyrics-review/types';
|
||||
|
||||
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
|
||||
// In production (static export), use the full backend URL
|
||||
@@ -2732,6 +2732,7 @@ export interface LyricsReviewApiClient {
|
||||
submitEditLog: (editLog: EditLog) => Promise<void>
|
||||
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
|
||||
addLyrics: (source: string, lyrics: string) => Promise<CorrectionData>
|
||||
searchLyrics: (artist: string, title: string, forceSources?: string[]) => Promise<SearchLyricsResponse>
|
||||
getAudioUrl: (hash: string) => string
|
||||
generatePreviewVideo: (data: CorrectionData) => Promise<{
|
||||
status: string
|
||||
@@ -2839,6 +2840,25 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
|
||||
return result.data
|
||||
},
|
||||
|
||||
/**
|
||||
* Search for lyrics from configured providers
|
||||
*/
|
||||
async searchLyrics(artist: string, title: string, forceSources: string[] = []): Promise<SearchLyricsResponse> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/review/${jobId}/search-lyrics`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({
|
||||
artist,
|
||||
title,
|
||||
force_sources: forceSources,
|
||||
}),
|
||||
})
|
||||
return handleResponse<SearchLyricsResponse>(response)
|
||||
},
|
||||
|
||||
/**
|
||||
* Get audio URL for playback
|
||||
*/
|
||||
|
||||
@@ -122,6 +122,8 @@ export interface CorrectionData {
|
||||
audio_hash?: string
|
||||
available_handlers?: CorrectionHandler[]
|
||||
enabled_handlers?: string[]
|
||||
artist?: string
|
||||
title?: string
|
||||
}
|
||||
correction_steps: CorrectionStep[]
|
||||
word_id_map: Record<string, string>
|
||||
@@ -390,6 +392,27 @@ export interface ReferenceViewProps extends BaseViewProps {
|
||||
corrected_segments: LyricsSegment[]
|
||||
corrections: WordCorrection[]
|
||||
onAddLyrics?: () => void
|
||||
onAddLyricsInline?: (source: string, lyrics: string) => Promise<void>
|
||||
onSearchLyrics?: (artist: string, title: string, forceSources: string[]) => Promise<SearchLyricsResponse>
|
||||
defaultArtist?: string
|
||||
defaultTitle?: string
|
||||
}
|
||||
|
||||
export interface RejectedSource {
|
||||
relevance: number
|
||||
matched_words: number
|
||||
total_words: number
|
||||
track_name: string
|
||||
artist_names: string
|
||||
}
|
||||
|
||||
export interface SearchLyricsResponse {
|
||||
status: 'success' | 'no_results'
|
||||
data?: CorrectionData
|
||||
message?: string
|
||||
sources_added: string[]
|
||||
sources_rejected: Record<string, RejectedSource>
|
||||
sources_not_found: string[]
|
||||
}
|
||||
|
||||
export interface HighlightedTextProps extends BaseViewProps {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "karaoke-gen-frontend",
|
||||
"version": "0.85.8",
|
||||
"version": "0.85.9",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "next build && node scripts/spa-redirect-404.js",
|
||||
|
||||
@@ -40,6 +40,7 @@ from modules import database, storage as storage_module, artifact_registry, secr
|
||||
from modules import cloud_tasks, cloud_run, monitoring, networking, runner_manager
|
||||
from modules import divebar_mirror, kn_data_sync, divebar_lookup
|
||||
from modules import audio_separator_service
|
||||
from modules import gpu_artifact_registry
|
||||
from modules import encoding_worker_manager
|
||||
from modules.iam import backend_sa, github_actions_sa, claude_automation_sa, worker_sas
|
||||
from compute import encoding_worker_vm, github_runners, divebar_sync_vm
|
||||
@@ -55,6 +56,9 @@ bucket = storage_module.create_bucket()
|
||||
# Artifact Registry for Docker images
|
||||
artifact_repo = artifact_registry.create_repository()
|
||||
|
||||
# GPU Artifact Registry in us-east4 (for audio worker GPU images)
|
||||
gpu_artifact_repo = gpu_artifact_registry.create_gpu_artifact_repo()
|
||||
|
||||
# Secret Manager secrets
|
||||
all_secrets = secrets.create_secrets()
|
||||
|
||||
@@ -85,6 +89,15 @@ artifact_registry_iam = artifactregistry.RepositoryIamBinding(
|
||||
members=cloudbuild_service_accounts,
|
||||
)
|
||||
|
||||
# Grant Cloud Build access to GPU Artifact Registry (us-east4)
|
||||
gpu_artifact_registry_iam = artifactregistry.RepositoryIamBinding(
|
||||
"cloudbuild-gpu-artifact-registry-access",
|
||||
repository=gpu_artifact_repo.name,
|
||||
location=gpu_artifact_repo.location,
|
||||
role="roles/artifactregistry.writer",
|
||||
members=cloudbuild_service_accounts,
|
||||
)
|
||||
|
||||
# Grant Cloud Build compute service account logging permissions
|
||||
cloudbuild_logging_iam = gcp.projects.IAMMember(
|
||||
"cloudbuild-logging-access",
|
||||
@@ -437,6 +450,16 @@ divebar_sync_compute_admin = gcp.projects.IAMMember(
|
||||
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
|
||||
audio_separator_resources = audio_separator_service.create_all_resources()
|
||||
|
||||
# Grant audio separator read access to main storage bucket (for GCS URI passthrough)
|
||||
gcp.storage.BucketIAMMember(
|
||||
"audio-separator-storage-reader",
|
||||
bucket=bucket.name,
|
||||
role="roles/storage.objectViewer",
|
||||
member=audio_separator_resources["service_account"].email.apply(
|
||||
lambda email: f"serviceAccount:{email}"
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Compute VMs ====================
|
||||
|
||||
# Encoding Worker VMs (blue-green pair for zero-downtime deployments)
|
||||
|
||||
@@ -43,6 +43,26 @@ def create_service_account() -> serviceaccount.Account:
|
||||
)
|
||||
|
||||
|
||||
def create_output_bucket() -> gcp.storage.Bucket:
|
||||
"""Create GCS bucket for separation output files with auto-cleanup."""
|
||||
bucket = gcp.storage.Bucket(
|
||||
"audio-separator-output-bucket",
|
||||
name="nomadkaraoke-audio-separator-outputs",
|
||||
location="US",
|
||||
force_destroy=True,
|
||||
uniform_bucket_level_access=True,
|
||||
lifecycle_rules=[
|
||||
gcp.storage.BucketLifecycleRuleArgs(
|
||||
action=gcp.storage.BucketLifecycleRuleActionArgs(type="Delete"),
|
||||
condition=gcp.storage.BucketLifecycleRuleConditionArgs(
|
||||
age=1, # Delete after 1 day (minimum GCS lifecycle granularity)
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
return bucket
|
||||
|
||||
|
||||
def grant_permissions(
|
||||
sa: serviceaccount.Account,
|
||||
) -> dict:
|
||||
@@ -73,6 +93,14 @@ def grant_permissions(
|
||||
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Read/write Firestore for async job status
|
||||
bindings["firestore"] = gcp.projects.IAMMember(
|
||||
"audio-separator-firestore-access",
|
||||
project=PROJECT_ID,
|
||||
role="roles/datastore.user",
|
||||
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
return bindings
|
||||
|
||||
|
||||
@@ -96,7 +124,7 @@ def create_service(
|
||||
min_instance_count=0,
|
||||
max_instance_count=5, # Cloud Run GPU services limited to 5 max instances
|
||||
),
|
||||
max_instance_request_concurrency=1, # Each separation uses the full GPU; route new requests to new instances
|
||||
max_instance_request_concurrency=1, # One GPU job per instance; forces Cloud Run to scale to new instances for concurrent jobs
|
||||
gpu_zonal_redundancy_disabled=True, # Not needed for batch workloads
|
||||
# Keep instances warm for 600s (10 min) between Stage 1 → Stage 2
|
||||
session_affinity=True,
|
||||
@@ -128,6 +156,14 @@ def create_service(
|
||||
name="STORAGE_DIR",
|
||||
value="/tmp/storage",
|
||||
),
|
||||
cloudrunv2.ServiceTemplateContainerEnvArgs(
|
||||
name="OUTPUT_BUCKET",
|
||||
value="nomadkaraoke-audio-separator-outputs",
|
||||
),
|
||||
cloudrunv2.ServiceTemplateContainerEnvArgs(
|
||||
name="GCP_PROJECT",
|
||||
value=PROJECT_ID,
|
||||
),
|
||||
],
|
||||
startup_probe=cloudrunv2.ServiceTemplateContainerStartupProbeArgs(
|
||||
http_get=cloudrunv2.ServiceTemplateContainerStartupProbeHttpGetArgs(
|
||||
@@ -185,13 +221,24 @@ def create_all_resources() -> dict:
|
||||
"""
|
||||
artifact_repo = create_audio_separator_artifact_repo()
|
||||
sa = create_service_account()
|
||||
output_bucket = create_output_bucket()
|
||||
iam_bindings = grant_permissions(sa)
|
||||
|
||||
# Output bucket IAM (separate from grant_permissions since it needs the bucket)
|
||||
output_bucket_iam = gcp.storage.BucketIAMMember(
|
||||
"audio-separator-output-bucket-access",
|
||||
bucket=output_bucket.name,
|
||||
role="roles/storage.objectAdmin",
|
||||
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
service = create_service(sa, artifact_repo)
|
||||
unauthenticated_access = allow_unauthenticated_access(service)
|
||||
|
||||
return {
|
||||
"artifact_repo": artifact_repo,
|
||||
"service_account": sa,
|
||||
"output_bucket": output_bucket,
|
||||
"service": service,
|
||||
"iam_bindings": iam_bindings,
|
||||
}
|
||||
@@ -10,6 +10,8 @@ from pulumi_gcp import cloudrun, cloudrunv2
|
||||
|
||||
from config import PROJECT_ID, REGION
|
||||
|
||||
AUDIO_WORKER_GPU_REGION = "us-east4" # L4 GPU quota available here
|
||||
|
||||
|
||||
def create_domain_mapping() -> cloudrun.DomainMapping:
|
||||
"""
|
||||
@@ -165,13 +167,14 @@ def create_audio_separation_job(
|
||||
service_account: gcp.serviceaccount.Account,
|
||||
) -> cloudrunv2.Job:
|
||||
"""
|
||||
Create the Cloud Run Job for audio separation.
|
||||
Create the Cloud Run Job for audio separation with L4 GPU.
|
||||
|
||||
Cloud Run Jobs run to completion without HTTP request lifecycle concerns,
|
||||
avoiding the instance termination issue where Cloud Run would shut down
|
||||
instances mid-processing when using BackgroundTasks.
|
||||
Runs the Separator class directly with GPU acceleration, eliminating
|
||||
the HTTP call to the separate audio-separator service.
|
||||
|
||||
Typical duration: 10-20 minutes (Modal API for GPU separation)
|
||||
Deployed in us-east4 where L4 GPU quota is available.
|
||||
|
||||
Typical duration: 5-10 minutes (local GPU separation)
|
||||
|
||||
Args:
|
||||
bucket: The GCS bucket for job artifacts.
|
||||
@@ -183,17 +186,19 @@ def create_audio_separation_job(
|
||||
audio_separation_job = cloudrunv2.Job(
|
||||
"audio-separation-job",
|
||||
name="audio-separation-job",
|
||||
location=REGION,
|
||||
location=AUDIO_WORKER_GPU_REGION,
|
||||
deletion_protection=False, # Allow Pulumi to replace (region change requires delete+create)
|
||||
template=cloudrunv2.JobTemplateArgs(
|
||||
template=cloudrunv2.JobTemplateTemplateArgs(
|
||||
containers=[
|
||||
cloudrunv2.JobTemplateTemplateContainerArgs(
|
||||
image=f"{REGION}-docker.pkg.dev/{PROJECT_ID}/karaoke-repo/karaoke-backend:latest",
|
||||
image=f"{AUDIO_WORKER_GPU_REGION}-docker.pkg.dev/{PROJECT_ID}/karaoke-backend-gpu/karaoke-backend:latest",
|
||||
args=["python", "-m", "backend.workers.audio_worker"],
|
||||
resources=cloudrunv2.JobTemplateTemplateContainerResourcesArgs(
|
||||
limits={
|
||||
"cpu": "2",
|
||||
"memory": "4Gi",
|
||||
"cpu": "4",
|
||||
"memory": "16Gi",
|
||||
"nvidia.com/gpu": "1",
|
||||
},
|
||||
),
|
||||
envs=[
|
||||
@@ -207,10 +212,10 @@ def create_audio_separation_job(
|
||||
),
|
||||
),
|
||||
),
|
||||
# Audio separator API (Cloud Run GPU service in us-east4)
|
||||
# Model directory (baked into GPU image, triggers local GPU mode)
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="AUDIO_SEPARATOR_API_URL",
|
||||
value="https://audio-separator-718638054799.us-east4.run.app",
|
||||
name="MODEL_DIR",
|
||||
value="/models",
|
||||
),
|
||||
# Cloud Run service URL for Cloud Tasks targeting
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
@@ -229,7 +234,7 @@ def create_audio_separation_job(
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GCP_REGION",
|
||||
value=REGION,
|
||||
value=AUDIO_WORKER_GPU_REGION,
|
||||
),
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GCS_BUCKET_NAME",
|
||||
@@ -242,8 +247,12 @@ def create_audio_separation_job(
|
||||
],
|
||||
)
|
||||
],
|
||||
node_selector=cloudrunv2.JobTemplateTemplateNodeSelectorArgs(
|
||||
accelerator="nvidia-l4",
|
||||
),
|
||||
gpu_zonal_redundancy_disabled=True, # Required for GPU Jobs (capacity limitation)
|
||||
service_account=service_account.email,
|
||||
timeout="2400s", # 40 minutes max per task (Modal can be slow)
|
||||
timeout="1800s", # 30 minutes (local GPU is faster than remote API)
|
||||
max_retries=2,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -222,6 +222,19 @@ def create_database() -> dict:
|
||||
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
|
||||
)
|
||||
|
||||
# Audio separation jobs: query by status + updated_at (for cleanup of old jobs)
|
||||
resources["firestore_index_audio_separation_jobs_cleanup"] = firestore.Index(
|
||||
"firestore-index-audio-separation-jobs-cleanup",
|
||||
project=PROJECT_ID,
|
||||
database=firestore_db.name,
|
||||
collection="audio_separation_jobs",
|
||||
fields=[
|
||||
firestore.IndexFieldArgs(field_path="status", order="ASCENDING"),
|
||||
firestore.IndexFieldArgs(field_path="updated_at", order="ASCENDING"),
|
||||
],
|
||||
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
|
||||
)
|
||||
|
||||
# ==================== Firestore TTL Field Configuration ====================
|
||||
# TTL policies automatically delete documents after expiration.
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Artifact Registry for GPU Docker images.
|
||||
|
||||
Located in us-east4 (co-located with L4 GPU instances).
|
||||
Stores the karaoke-backend-gpu base image used by the audio worker.
|
||||
"""
|
||||
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import artifactregistry
|
||||
|
||||
from config import PROJECT_ID
|
||||
|
||||
GPU_REGION = "us-east4"
|
||||
|
||||
|
||||
def create_gpu_artifact_repo() -> artifactregistry.Repository:
|
||||
"""Create Artifact Registry repo for GPU Docker images in us-east4."""
|
||||
return artifactregistry.Repository(
|
||||
"karaoke-backend-gpu-artifact-repo",
|
||||
repository_id="karaoke-backend-gpu",
|
||||
location=GPU_REGION,
|
||||
format="DOCKER",
|
||||
description="Docker repository for GPU-enabled karaoke-backend images (audio worker)",
|
||||
)
|
||||
@@ -185,6 +185,9 @@ def grant_github_actions_permissions(
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/karaoke-decide"
|
||||
),
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/nomadkaraoke/python-audio-separator"
|
||||
),
|
||||
pool.name.apply(
|
||||
lambda pool_name: f"principalSet://iam.googleapis.com/{pool_name}/attribute.repository/beveradb/cryptotrader"
|
||||
),
|
||||
|
||||
@@ -96,7 +96,7 @@ echo "Creating Python virtual environment..."
|
||||
# Install base Python dependencies (wheel will add more at runtime)
|
||||
source venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp
|
||||
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp packaging
|
||||
|
||||
# Create bootstrap script (runs via ExecStartPre before service starts)
|
||||
# This minimal script downloads the REAL startup script from GCS.
|
||||
|
||||
+140
-24
@@ -20,6 +20,14 @@ except ImportError:
|
||||
REMOTE_API_AVAILABLE = False
|
||||
AudioSeparatorAPIClient = None
|
||||
|
||||
# Try to import the Separator for local GPU processing
|
||||
try:
|
||||
from audio_separator.separator import Separator
|
||||
SEPARATOR_AVAILABLE = True
|
||||
except ImportError:
|
||||
SEPARATOR_AVAILABLE = False
|
||||
Separator = None
|
||||
|
||||
|
||||
# Placeholder class or functions for audio processing
|
||||
class AudioProcessor:
|
||||
@@ -116,8 +124,6 @@ class AudioProcessor:
|
||||
f"instantiating Separator with model_file_dir: {self.model_file_dir}, model_filename: {model_name} output_format: {self.lossless_output_format}"
|
||||
)
|
||||
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
@@ -198,7 +204,10 @@ class AudioProcessor:
|
||||
self.logger.info("AUDIO_SEPARATOR_API_URL not set, using local audio separation. "
|
||||
"Set this environment variable to use remote GPU processing.")
|
||||
|
||||
from audio_separator.separator import Separator
|
||||
if not SEPARATOR_AVAILABLE:
|
||||
raise ImportError(
|
||||
"audio-separator package not installed. Install with: pip install audio-separator[gpu]"
|
||||
)
|
||||
|
||||
self.logger.info(f"Starting local audio separation process for {artist_title}")
|
||||
|
||||
@@ -271,29 +280,127 @@ class AudioProcessor:
|
||||
continue
|
||||
|
||||
try:
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
)
|
||||
|
||||
stems_dir = self._create_stems_directory(track_output_dir)
|
||||
result = {"clean_instrumental": {}, "other_stems": {}, "backing_vocals": {}, "combined_instrumentals": {}}
|
||||
|
||||
if os.environ.get("KARAOKE_GEN_SKIP_AUDIO_SEPARATION"):
|
||||
return result
|
||||
|
||||
result["clean_instrumental"] = self._separate_clean_instrumental(
|
||||
separator, audio_file, artist_title, track_output_dir, stems_dir
|
||||
)
|
||||
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
|
||||
result["backing_vocals"] = self._separate_backing_vocals(
|
||||
separator, result["clean_instrumental"]["vocals"], artist_title, stems_dir
|
||||
)
|
||||
result["combined_instrumentals"] = self._generate_combined_instrumentals(
|
||||
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
|
||||
)
|
||||
# Check if we have ensemble presets configured
|
||||
instrumental_preset = getattr(self, 'instrumental_preset', None)
|
||||
karaoke_preset = getattr(self, 'karaoke_preset', None)
|
||||
|
||||
if instrumental_preset:
|
||||
# Stage 1: Ensemble preset mode — higher quality, uses multiple models
|
||||
self.logger.info(f"Stage 1: Using ensemble preset '{instrumental_preset}'")
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
output_dir=stems_dir,
|
||||
ensemble_preset=instrumental_preset,
|
||||
)
|
||||
separator.load_model()
|
||||
output_files = separator.separate(audio_file)
|
||||
self.logger.info(f"Stage 1 ensemble produced {len(output_files)} files: {output_files}")
|
||||
|
||||
# Find vocals and instrumental from ensemble output
|
||||
# Output filenames follow: {base}_(StemTag)_preset_{name}.flac
|
||||
# where StemTag is "Vocals", "Instrumental", or "No Vocal"
|
||||
# Must match the stem tag specifically, not the preset name
|
||||
# (e.g., preset "instrumental_clean" contains "instrumental")
|
||||
for f in output_files:
|
||||
basename = os.path.basename(f).lower()
|
||||
# Extract stem tag: text between _( and )_ in the filename
|
||||
stem_tag = ""
|
||||
tag_start = basename.rfind("_(")
|
||||
tag_end = basename.find(")_", tag_start) if tag_start >= 0 else -1
|
||||
if tag_start >= 0 and tag_end >= 0:
|
||||
stem_tag = basename[tag_start + 2:tag_end]
|
||||
|
||||
if stem_tag in ("no vocal", "instrumental", "no_vocal"):
|
||||
# Move instrumental to track_output_dir per convention
|
||||
final_path = os.path.join(track_output_dir, os.path.basename(f))
|
||||
if f != final_path:
|
||||
shutil.move(f, final_path)
|
||||
result["clean_instrumental"]["instrumental"] = final_path
|
||||
elif stem_tag in ("vocals", "vocal"):
|
||||
result["clean_instrumental"]["vocals"] = f
|
||||
else:
|
||||
self.logger.warning(f"Stage 1: Unrecognized stem tag '{stem_tag}' in {basename}")
|
||||
else:
|
||||
# Legacy mode — individual model calls (existing code)
|
||||
separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
)
|
||||
result["clean_instrumental"] = self._separate_clean_instrumental(
|
||||
separator, audio_file, artist_title, track_output_dir, stems_dir
|
||||
)
|
||||
result["other_stems"] = self._separate_other_stems(separator, audio_file, artist_title, stems_dir)
|
||||
|
||||
# Stage 2: Backing vocals separation
|
||||
vocals_path = result["clean_instrumental"].get("vocals")
|
||||
has_backing_config = karaoke_preset or self.backing_vocals_models
|
||||
|
||||
if vocals_path and has_backing_config:
|
||||
if karaoke_preset:
|
||||
self.logger.info(f"Stage 2: Using ensemble preset '{karaoke_preset}'")
|
||||
|
||||
# Rename vocals file to strip Stage 1 stem tags before passing
|
||||
# to Stage 2. The ensemble code uses regex to find the FIRST
|
||||
# _(Tag)_ in intermediate filenames to classify stems. If the
|
||||
# input already has _(Vocals)_preset_instrumental_clean in its
|
||||
# name, the regex matches that instead of the Stage 2 tag,
|
||||
# causing all stems to be classified as "Vocals".
|
||||
clean_vocals_name = f"{artist_title} (Vocals).{self.lossless_output_format.lower()}"
|
||||
clean_vocals_path = os.path.join(stems_dir, clean_vocals_name)
|
||||
shutil.copy2(vocals_path, clean_vocals_path)
|
||||
self.logger.info(f"Stage 2: Renamed vocals input to avoid stem tag collision: {os.path.basename(clean_vocals_path)}")
|
||||
|
||||
bv_separator = Separator(
|
||||
log_level=self.log_level,
|
||||
log_formatter=self.log_formatter,
|
||||
model_file_dir=self.model_file_dir,
|
||||
output_format=self.lossless_output_format,
|
||||
output_dir=stems_dir,
|
||||
ensemble_preset=karaoke_preset,
|
||||
)
|
||||
bv_separator.load_model()
|
||||
bv_output_files = bv_separator.separate(clean_vocals_path)
|
||||
self.logger.info(f"Stage 2 ensemble produced {len(bv_output_files)} files: {bv_output_files}")
|
||||
|
||||
bv_key = karaoke_preset
|
||||
result["backing_vocals"][bv_key] = {}
|
||||
for f in bv_output_files:
|
||||
basename = os.path.basename(f).lower()
|
||||
# Extract stem tag: text between _( and )_ in the filename
|
||||
stem_tag = ""
|
||||
tag_start = basename.rfind("_(")
|
||||
tag_end = basename.find(")_", tag_start) if tag_start >= 0 else -1
|
||||
if tag_start >= 0 and tag_end >= 0:
|
||||
stem_tag = basename[tag_start + 2:tag_end]
|
||||
|
||||
if stem_tag in ("no vocal", "instrumental", "no_vocal", "backing"):
|
||||
result["backing_vocals"][bv_key]["backing_vocals"] = f
|
||||
elif stem_tag in ("vocals", "vocal"):
|
||||
result["backing_vocals"][bv_key]["lead_vocals"] = f
|
||||
else:
|
||||
self.logger.warning(f"Stage 2: Unrecognized stem tag '{stem_tag}' in {basename}")
|
||||
else:
|
||||
# Legacy: individual model calls (existing code)
|
||||
result["backing_vocals"] = self._separate_backing_vocals(
|
||||
separator, vocals_path, artist_title, stems_dir
|
||||
)
|
||||
|
||||
# Combined instrumentals + normalization
|
||||
if result["clean_instrumental"].get("instrumental") and result["backing_vocals"]:
|
||||
result["combined_instrumentals"] = self._generate_combined_instrumentals(
|
||||
result["clean_instrumental"]["instrumental"], result["backing_vocals"], artist_title, track_output_dir
|
||||
)
|
||||
self._normalize_audio_files(result, artist_title, track_output_dir)
|
||||
|
||||
self.logger.info("Audio separation, combination, and normalization process completed")
|
||||
@@ -348,10 +455,19 @@ class AudioProcessor:
|
||||
self.logger.info(f"Stage 1: Using explicit models: {stage1_models}")
|
||||
stage1_kwargs["models"] = stage1_models
|
||||
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
audio_file,
|
||||
**stage1_kwargs,
|
||||
)
|
||||
# Use GCS URI for Stage 1 if available (avoids 413 for large files)
|
||||
input_gcs_uri = getattr(self, 'input_gcs_uri', None)
|
||||
if input_gcs_uri:
|
||||
self.logger.info(f"Stage 1: Using GCS URI: {input_gcs_uri}")
|
||||
stage1_kwargs["gcs_uri"] = input_gcs_uri
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
**stage1_kwargs,
|
||||
)
|
||||
else:
|
||||
stage1_result = api_client.separate_audio_and_wait(
|
||||
audio_file,
|
||||
**stage1_kwargs,
|
||||
)
|
||||
|
||||
if stage1_result["status"] != "completed":
|
||||
raise Exception(f"Stage 1 remote audio separation failed: {stage1_result.get('error', 'Unknown error')}")
|
||||
|
||||
@@ -1134,6 +1134,10 @@ class AnchorSequenceFinder:
|
||||
|
||||
gap_position = current_end
|
||||
|
||||
# Bounds check: gap_position must be a valid index into all_words
|
||||
if gap_position >= len(all_words):
|
||||
continue
|
||||
|
||||
# Skip if this gap was already absorbed by a previous extension
|
||||
if gap_position in absorbed_gaps:
|
||||
continue
|
||||
@@ -1464,7 +1468,9 @@ class AnchorSequenceFinder:
|
||||
ref_start = anchor.reference_positions[source]
|
||||
ref_end = ref_start + len(word_ids)
|
||||
|
||||
if source in ref_words and ref_end < len(ref_words[source]):
|
||||
# Bounds check: ref_end must be within ref_words (which may be shorter
|
||||
# than ref_texts_clean due to clean_text() normalizing word boundaries)
|
||||
if source in ref_words and 0 <= ref_end < len(ref_words[source]):
|
||||
new_ref_word = ref_words[source][ref_end]
|
||||
new_reference_word_ids[source] = list(word_ids) + [new_ref_word.id]
|
||||
else:
|
||||
@@ -1519,7 +1525,9 @@ class AnchorSequenceFinder:
|
||||
ref_start = anchor.reference_positions[source]
|
||||
new_ref_start = ref_start - 1
|
||||
|
||||
if source in ref_words and new_ref_start >= 0:
|
||||
# Bounds check: new_ref_start must be within ref_words (which may be shorter
|
||||
# than ref_texts_clean due to clean_text() normalizing word boundaries)
|
||||
if source in ref_words and 0 <= new_ref_start < len(ref_words[source]):
|
||||
new_ref_word = ref_words[source][new_ref_start]
|
||||
new_reference_word_ids[source] = [new_ref_word.id] + list(word_ids)
|
||||
new_reference_positions[source] = new_ref_start
|
||||
|
||||
@@ -24,6 +24,7 @@ from karaoke_gen.lyrics_transcriber.types import (
|
||||
Word,
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.correction.anchor_sequence import AnchorSequenceFinder
|
||||
from karaoke_gen.lyrics_transcriber.correction.relevance import filter_irrelevant_sources
|
||||
from karaoke_gen.lyrics_transcriber.correction.handlers.base import GapCorrectionHandler
|
||||
from karaoke_gen.lyrics_transcriber.correction.handlers.extend_anchor import ExtendAnchorHandler
|
||||
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
|
||||
@@ -142,9 +143,6 @@ class LyricsCorrector:
|
||||
self.logger.error("No transcription results available")
|
||||
raise ValueError("No primary transcription data available")
|
||||
|
||||
# Store reference lyrics for use in word map
|
||||
self.reference_lyrics = lyrics_results
|
||||
|
||||
# Get primary transcription
|
||||
primary_transcription_result = sorted(transcription_results, key=lambda x: x.priority)[0]
|
||||
primary_transcription = primary_transcription_result.result
|
||||
@@ -152,12 +150,41 @@ class LyricsCorrector:
|
||||
|
||||
# Find anchor sequences and gaps
|
||||
self.logger.debug("Finding anchor sequences and gaps")
|
||||
rejected_sources = {}
|
||||
with create_span("lyrics_corrector.find_anchors_and_gaps") as anchor_span:
|
||||
anchor_sequences = self.anchor_finder.find_anchors(transcribed_text, lyrics_results, primary_transcription_result)
|
||||
|
||||
# Filter irrelevant reference sources based on anchor match quality
|
||||
filtered_lyrics, rejected_sources = filter_irrelevant_sources(
|
||||
lyrics_results, anchor_sequences, logger=self.logger,
|
||||
)
|
||||
|
||||
# If sources were filtered, re-run anchor finding with only valid sources
|
||||
if len(filtered_lyrics) < len(lyrics_results):
|
||||
self.logger.info(
|
||||
f"Relevance filter: {len(lyrics_results)} -> {len(filtered_lyrics)} sources "
|
||||
f"(rejected: {', '.join(rejected_sources.keys())})"
|
||||
)
|
||||
if filtered_lyrics:
|
||||
# Re-find anchors with only the valid sources
|
||||
self._anchor_finder = None # Reset to clear cached state
|
||||
anchor_sequences = self.anchor_finder.find_anchors(
|
||||
transcribed_text, filtered_lyrics, primary_transcription_result
|
||||
)
|
||||
else:
|
||||
anchor_sequences = []
|
||||
|
||||
# Update lyrics_results to only include filtered sources
|
||||
lyrics_results = filtered_lyrics
|
||||
|
||||
# Store filtered reference lyrics for use in word map
|
||||
self.reference_lyrics = lyrics_results
|
||||
|
||||
gap_sequences = self.anchor_finder.find_gaps(transcribed_text, anchor_sequences, lyrics_results, primary_transcription_result)
|
||||
if anchor_span:
|
||||
anchor_span.set_attribute("anchor_count", len(anchor_sequences))
|
||||
anchor_span.set_attribute("gap_count", len(gap_sequences))
|
||||
anchor_span.set_attribute("sources_rejected", len(rejected_sources))
|
||||
|
||||
# Store anchor sequences for use in correction handlers
|
||||
self._anchor_sequences = anchor_sequences
|
||||
@@ -199,6 +226,19 @@ class LyricsCorrector:
|
||||
"agentic_routing": "agentic" if agentic_enabled else "rule-based",
|
||||
}
|
||||
|
||||
# Add rejected sources to metadata for debugging and frontend display
|
||||
if rejected_sources:
|
||||
result_metadata["rejected_sources"] = {
|
||||
name: {
|
||||
"relevance": result.relevance,
|
||||
"matched_words": result.matched_words,
|
||||
"total_words": result.total_words,
|
||||
"track_name": result.track_name,
|
||||
"artist_names": result.artist_names,
|
||||
}
|
||||
for name, result in rejected_sources.items()
|
||||
}
|
||||
|
||||
# Pass through primary transcription metadata (e.g., AudioShake task_id, asset_id)
|
||||
if primary_transcription.metadata:
|
||||
result_metadata["transcription_metadata"] = primary_transcription.metadata
|
||||
|
||||
@@ -14,13 +14,14 @@ These operations handle dynamic updates to correction results including:
|
||||
import json
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
from typing import Dict, Any, List, Optional
|
||||
from pathlib import Path
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.types import (
|
||||
CorrectionResult,
|
||||
WordCorrection,
|
||||
LyricsSegment,
|
||||
CorrectionResult,
|
||||
WordCorrection,
|
||||
LyricsSegment,
|
||||
Word,
|
||||
TranscriptionResult,
|
||||
TranscriptionData,
|
||||
@@ -28,10 +29,76 @@ from karaoke_gen.lyrics_transcriber.types import (
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.user_input_provider import UserInputProvider
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.base_lyrics_provider import LyricsProviderConfig, BaseLyricsProvider
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
|
||||
|
||||
def create_lyrics_providers(
|
||||
cache_dir: Optional[str] = None,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
) -> List[BaseLyricsProvider]:
|
||||
"""
|
||||
Create lyrics providers based on available environment variables.
|
||||
|
||||
Reads API keys from environment and returns a list of providers that are
|
||||
configured and ready to use. Providers with missing required credentials
|
||||
are silently skipped.
|
||||
|
||||
Args:
|
||||
cache_dir: Optional cache directory for provider caching.
|
||||
logger: Optional logger instance.
|
||||
|
||||
Returns:
|
||||
List of configured BaseLyricsProvider instances.
|
||||
"""
|
||||
if not logger:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Import provider classes here to keep them mockable in tests
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.genius import GeniusProvider
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.spotify import SpotifyProvider
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.musixmatch import MusixmatchProvider
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.lrclib import LRCLIBProvider
|
||||
|
||||
genius_api_token = os.environ.get("GENIUS_API_KEY")
|
||||
rapidapi_key = os.environ.get("RAPIDAPI_KEY")
|
||||
spotify_cookie = os.environ.get("SPOTIFY_COOKIE_SP_DC")
|
||||
|
||||
config = LyricsProviderConfig(
|
||||
genius_api_token=genius_api_token,
|
||||
rapidapi_key=rapidapi_key,
|
||||
spotify_cookie=spotify_cookie,
|
||||
cache_dir=cache_dir,
|
||||
)
|
||||
|
||||
providers: List[BaseLyricsProvider] = []
|
||||
|
||||
if genius_api_token or rapidapi_key:
|
||||
providers.append(GeniusProvider(config=config, logger=logger))
|
||||
logger.info("GeniusProvider configured")
|
||||
else:
|
||||
logger.info("Skipping GeniusProvider: no GENIUS_API_KEY or RAPIDAPI_KEY")
|
||||
|
||||
if spotify_cookie or rapidapi_key:
|
||||
providers.append(SpotifyProvider(config=config, logger=logger))
|
||||
logger.info("SpotifyProvider configured")
|
||||
else:
|
||||
logger.info("Skipping SpotifyProvider: no SPOTIFY_COOKIE_SP_DC or RAPIDAPI_KEY")
|
||||
|
||||
if rapidapi_key:
|
||||
providers.append(MusixmatchProvider(config=config, logger=logger))
|
||||
logger.info("MusixmatchProvider configured")
|
||||
else:
|
||||
logger.info("Skipping MusixmatchProvider: no RAPIDAPI_KEY")
|
||||
|
||||
# LRCLIB needs no API key
|
||||
providers.append(LRCLIBProvider(config=config, logger=logger))
|
||||
logger.info("LRCLIBProvider configured")
|
||||
|
||||
return providers
|
||||
|
||||
|
||||
class CorrectionOperations:
|
||||
"""Static methods for common correction operations."""
|
||||
|
||||
@@ -104,21 +171,24 @@ class CorrectionOperations:
|
||||
source: str,
|
||||
lyrics_text: str,
|
||||
cache_dir: str,
|
||||
logger: Optional[logging.Logger] = None
|
||||
logger: Optional[logging.Logger] = None,
|
||||
force: bool = False,
|
||||
) -> CorrectionResult:
|
||||
"""
|
||||
Add a new lyrics source and rerun correction.
|
||||
|
||||
|
||||
Args:
|
||||
correction_result: Current correction result
|
||||
source: Name of the new lyrics source
|
||||
lyrics_text: The lyrics text content
|
||||
cache_dir: Cache directory for correction operations
|
||||
logger: Optional logger instance
|
||||
|
||||
force: If True and the source is rejected by the relevance filter, re-add
|
||||
it to reference_lyrics anyway so it is preserved in the result.
|
||||
|
||||
Returns:
|
||||
Updated CorrectionResult with new lyrics source and corrections
|
||||
|
||||
|
||||
Raises:
|
||||
ValueError: If source name is already in use or inputs are invalid
|
||||
"""
|
||||
@@ -194,10 +264,167 @@ class CorrectionOperations:
|
||||
# Restore audio hash
|
||||
if audio_hash:
|
||||
updated_result.metadata["audio_hash"] = audio_hash
|
||||
|
||||
|
||||
# If force=True and the source was rejected by the relevance filter, put it back
|
||||
# so the frontend can see it and the user's intent is respected.
|
||||
if force:
|
||||
rejected_sources = updated_result.metadata.get("rejected_sources", {})
|
||||
if source in rejected_sources:
|
||||
logger.info(
|
||||
f"force=True: re-adding rejected source '{source}' to reference_lyrics"
|
||||
)
|
||||
updated_result.reference_lyrics[source] = lyrics_data
|
||||
|
||||
logger.info(f"Successfully added lyrics source '{source}' and updated corrections")
|
||||
return updated_result
|
||||
|
||||
|
||||
@staticmethod
|
||||
def search_lyrics_sources(
|
||||
correction_result: CorrectionResult,
|
||||
artist: str,
|
||||
title: str,
|
||||
cache_dir: str,
|
||||
force_sources: Optional[List[str]] = None,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Search for lyrics from all configured providers and run correction.
|
||||
|
||||
Fetches lyrics from Genius, Spotify, Musixmatch, and LRCLIB using the
|
||||
supplied artist/title, then runs them through the correction pipeline
|
||||
(which includes the relevance filter from Task 2).
|
||||
|
||||
Args:
|
||||
correction_result: Current correction result (provides transcription data).
|
||||
artist: Artist name to search for.
|
||||
title: Song title to search for.
|
||||
cache_dir: Cache directory for providers and correction operations.
|
||||
force_sources: Optional list of provider names whose results should bypass
|
||||
the relevance filter and be included regardless of score.
|
||||
logger: Optional logger instance.
|
||||
|
||||
Returns:
|
||||
Dict with keys:
|
||||
- ``updated_result``: Updated CorrectionResult (or None if nothing passed).
|
||||
- ``sources_added``: List of source names that passed the filter.
|
||||
- ``sources_rejected``: Dict mapping rejected source names to relevance info.
|
||||
- ``sources_not_found``: List of provider names that returned no lyrics.
|
||||
"""
|
||||
if not logger:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
force_sources = force_sources or []
|
||||
|
||||
logger.info(f"Searching lyrics for artist='{artist}' title='{title}'")
|
||||
|
||||
# Store existing audio hash
|
||||
audio_hash = correction_result.metadata.get("audio_hash") if correction_result.metadata else None
|
||||
|
||||
# Create and query all configured providers
|
||||
providers = create_lyrics_providers(cache_dir=cache_dir, logger=logger)
|
||||
|
||||
new_lyrics: Dict[str, LyricsData] = {}
|
||||
sources_not_found: List[str] = []
|
||||
|
||||
for provider in providers:
|
||||
provider_name = provider.get_name()
|
||||
# Skip providers whose source name is already in the existing reference_lyrics
|
||||
if provider_name in correction_result.reference_lyrics:
|
||||
logger.info(f"Skipping provider '{provider_name}': already present in reference_lyrics")
|
||||
continue
|
||||
try:
|
||||
lyrics_data = provider.fetch_lyrics(artist, title)
|
||||
if lyrics_data:
|
||||
new_lyrics[provider_name] = lyrics_data
|
||||
logger.info(f"Provider '{provider_name}' returned lyrics")
|
||||
else:
|
||||
sources_not_found.append(provider_name)
|
||||
logger.info(f"Provider '{provider_name}' found no lyrics")
|
||||
except Exception as e:
|
||||
logger.warning(f"Provider '{provider_name}' raised an error: {e}")
|
||||
sources_not_found.append(provider_name)
|
||||
|
||||
if not new_lyrics:
|
||||
logger.info("No new lyrics found from any provider")
|
||||
return {
|
||||
"updated_result": None,
|
||||
"sources_added": [],
|
||||
"sources_rejected": {},
|
||||
"sources_not_found": sources_not_found,
|
||||
}
|
||||
|
||||
# Combine new lyrics with existing reference_lyrics
|
||||
combined_lyrics = correction_result.reference_lyrics.copy()
|
||||
combined_lyrics.update(new_lyrics)
|
||||
|
||||
# Create TranscriptionData from original segments
|
||||
transcription_data = TranscriptionData(
|
||||
segments=correction_result.original_segments,
|
||||
words=[word for segment in correction_result.original_segments for word in segment.words],
|
||||
text="\n".join(segment.text for segment in correction_result.original_segments),
|
||||
source="original",
|
||||
)
|
||||
|
||||
# Get currently enabled handlers from metadata
|
||||
enabled_handlers = None
|
||||
if correction_result.metadata:
|
||||
enabled_handlers = correction_result.metadata.get("enabled_handlers")
|
||||
|
||||
# Run correction (relevance filter is automatic inside corrector.run)
|
||||
logger.info(f"Running correction with {len(combined_lyrics)} combined reference sources")
|
||||
corrector = LyricsCorrector(
|
||||
cache_dir=cache_dir,
|
||||
enabled_handlers=enabled_handlers,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
updated_result = corrector.run(
|
||||
transcription_results=[TranscriptionResult(name="original", priority=1, result=transcription_data)],
|
||||
lyrics_results=combined_lyrics,
|
||||
metadata=correction_result.metadata,
|
||||
)
|
||||
|
||||
# Update metadata with handler state
|
||||
if not updated_result.metadata:
|
||||
updated_result.metadata = {}
|
||||
updated_result.metadata.update({
|
||||
"available_handlers": corrector.all_handlers,
|
||||
"enabled_handlers": [getattr(handler, "name", handler.__class__.__name__) for handler in corrector.handlers],
|
||||
})
|
||||
|
||||
# Restore audio hash
|
||||
if audio_hash:
|
||||
updated_result.metadata["audio_hash"] = audio_hash
|
||||
|
||||
# Determine which of the *new* sources were accepted vs rejected
|
||||
rejected_sources_meta = updated_result.metadata.get("rejected_sources", {})
|
||||
|
||||
sources_added = [name for name in new_lyrics if name not in rejected_sources_meta]
|
||||
sources_rejected = {name: info for name, info in rejected_sources_meta.items() if name in new_lyrics}
|
||||
|
||||
# Re-add force_sources that were rejected
|
||||
for source_name in force_sources:
|
||||
if source_name in sources_rejected and source_name in new_lyrics:
|
||||
logger.info(
|
||||
f"force_sources: re-adding rejected source '{source_name}' to reference_lyrics"
|
||||
)
|
||||
updated_result.reference_lyrics[source_name] = new_lyrics[source_name]
|
||||
sources_added.append(source_name)
|
||||
del sources_rejected[source_name]
|
||||
|
||||
logger.info(
|
||||
f"Search complete: added={sources_added}, "
|
||||
f"rejected={list(sources_rejected.keys())}, "
|
||||
f"not_found={sources_not_found}"
|
||||
)
|
||||
|
||||
return {
|
||||
"updated_result": updated_result,
|
||||
"sources_added": sources_added,
|
||||
"sources_rejected": sources_rejected,
|
||||
"sources_not_found": sources_not_found,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def update_correction_handlers(
|
||||
correction_result: CorrectionResult,
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Reference lyrics relevance scoring and filtering.
|
||||
|
||||
Computes how well each reference source matches the transcription based on
|
||||
anchor sequence coverage. Sources below the relevance threshold are filtered
|
||||
out to prevent wrong-song lyrics from polluting corrections.
|
||||
"""
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.types import AnchorSequence, LyricsData
|
||||
|
||||
# Default threshold — determined by empirical analysis of production jobs.
|
||||
# See scripts/analyze_reference_relevance.py and the design spec for methodology.
|
||||
MIN_REFERENCE_RELEVANCE = 0.30 # Empirical: wrong-song max 3.5%, correct-song min 26.8%
|
||||
|
||||
|
||||
@dataclass
|
||||
class SourceRelevanceResult:
|
||||
"""Relevance scoring result for a single reference source."""
|
||||
source: str
|
||||
relevance: float # 0.0 to 1.0 — fraction of reference words in anchors
|
||||
matched_words: int
|
||||
total_words: int
|
||||
track_name: str = ""
|
||||
artist_names: str = ""
|
||||
|
||||
|
||||
def compute_source_relevance(
|
||||
source_name: str,
|
||||
lyrics_data: LyricsData,
|
||||
anchor_sequences: List[AnchorSequence],
|
||||
) -> SourceRelevanceResult:
|
||||
"""Compute relevance score for a single reference source.
|
||||
|
||||
Relevance = (reference words appearing in anchor sequences) / (total reference words).
|
||||
"""
|
||||
total_words = sum(len(seg.words) for seg in lyrics_data.segments)
|
||||
if total_words == 0:
|
||||
return SourceRelevanceResult(
|
||||
source=source_name,
|
||||
relevance=0.0,
|
||||
matched_words=0,
|
||||
total_words=0,
|
||||
track_name=lyrics_data.metadata.track_name or "",
|
||||
artist_names=lyrics_data.metadata.artist_names or "",
|
||||
)
|
||||
|
||||
# Collect all reference word IDs for this source across all anchors.
|
||||
# Handle both AnchorSequence and ScoredAnchor (which wraps AnchorSequence).
|
||||
all_ref_word_ids = set()
|
||||
for anchor_or_scored in anchor_sequences:
|
||||
anchor = getattr(anchor_or_scored, "anchor", anchor_or_scored)
|
||||
source_word_ids = anchor.reference_word_ids.get(source_name, [])
|
||||
all_ref_word_ids.update(source_word_ids)
|
||||
|
||||
# Count how many of this source's word IDs appear in anchors
|
||||
source_word_ids = {w.id for seg in lyrics_data.segments for w in seg.words}
|
||||
matched = len(all_ref_word_ids & source_word_ids)
|
||||
|
||||
return SourceRelevanceResult(
|
||||
source=source_name,
|
||||
relevance=matched / total_words,
|
||||
matched_words=matched,
|
||||
total_words=total_words,
|
||||
track_name=lyrics_data.metadata.track_name or "",
|
||||
artist_names=lyrics_data.metadata.artist_names or "",
|
||||
)
|
||||
|
||||
|
||||
def filter_irrelevant_sources(
|
||||
lyrics_results: Dict[str, LyricsData],
|
||||
anchor_sequences: List[AnchorSequence],
|
||||
min_relevance: float = MIN_REFERENCE_RELEVANCE,
|
||||
logger: logging.Logger = None,
|
||||
) -> Tuple[Dict[str, LyricsData], Dict[str, SourceRelevanceResult]]:
|
||||
"""Filter out reference sources below the relevance threshold.
|
||||
|
||||
Args:
|
||||
lyrics_results: Dict mapping source name to LyricsData.
|
||||
anchor_sequences: Anchor sequences from the anchor finder.
|
||||
min_relevance: Minimum relevance score to keep a source.
|
||||
logger: Optional logger.
|
||||
|
||||
Returns:
|
||||
Tuple of (filtered_lyrics_results, rejected_sources).
|
||||
filtered_lyrics_results: Sources that passed the threshold.
|
||||
rejected_sources: Dict mapping source name to SourceRelevanceResult for rejected sources.
|
||||
"""
|
||||
if not logger:
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
filtered = {}
|
||||
rejected = {}
|
||||
|
||||
for source_name, lyrics_data in lyrics_results.items():
|
||||
result = compute_source_relevance(source_name, lyrics_data, anchor_sequences)
|
||||
|
||||
if result.relevance >= min_relevance:
|
||||
filtered[source_name] = lyrics_data
|
||||
logger.info(
|
||||
f"Source '{source_name}' passed relevance filter: "
|
||||
f"{result.relevance:.1%} ({result.matched_words}/{result.total_words} words)"
|
||||
)
|
||||
else:
|
||||
rejected[source_name] = result
|
||||
logger.info(
|
||||
f"Source '{source_name}' rejected by relevance filter: "
|
||||
f"{result.relevance:.1%} ({result.matched_words}/{result.total_words} words)"
|
||||
)
|
||||
|
||||
return filtered, rejected
|
||||
Generated
+26
-4
@@ -350,14 +350,14 @@ files = [
|
||||
|
||||
[[package]]
|
||||
name = "audio-separator"
|
||||
version = "0.43.0"
|
||||
version = "0.44.1"
|
||||
description = "Easy to use audio stem separation, using various models from UVR trained primarily by @Anjok07"
|
||||
optional = false
|
||||
python-versions = ">=3.10"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "audio_separator-0.43.0-py3-none-any.whl", hash = "sha256:7315f26fd0715e5cb3ddd02532565f2b63f77f208391463ad6bccd7cf4583454"},
|
||||
{file = "audio_separator-0.43.0.tar.gz", hash = "sha256:4628c2f1c43fc2d17a93e5451921bd6f5f720791d2bbf4bb6b70bda7114ac633"},
|
||||
{file = "audio_separator-0.44.1-py3-none-any.whl", hash = "sha256:6d9d3f570dceba16dd49116cf72a9764225e5aebb48ab117796bb79c8e1be4cd"},
|
||||
{file = "audio_separator-0.44.1.tar.gz", hash = "sha256:505c78c205ce2e6af27a7e73c1b4a59b0cc7c834a2abdd93b3f5cdaf8f3cb26f"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
@@ -2546,6 +2546,28 @@ requests-oauthlib = ">=0.7.0"
|
||||
[package.extras]
|
||||
tool = ["click (>=6.0.0)"]
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-compute"
|
||||
version = "1.46.0"
|
||||
description = "Google Cloud Compute API client library"
|
||||
optional = false
|
||||
python-versions = ">=3.7"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "google_cloud_compute-1.46.0-py3-none-any.whl", hash = "sha256:f92d9a7c32454b8a719ff937bfd46e794ee35d65e141ec5d20797aad6988dfb0"},
|
||||
{file = "google_cloud_compute-1.46.0.tar.gz", hash = "sha256:8b0f8d5a1115e8beae5fafdc7050f1ad15e922a5cdf6c634e5a745e47cb49281"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
google-api-core = {version = ">=1.34.1,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
|
||||
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
|
||||
grpcio = ">=1.33.2,<2.0.0"
|
||||
proto-plus = [
|
||||
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
|
||||
{version = ">=1.22.3,<2.0.0"},
|
||||
]
|
||||
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-core"
|
||||
version = "2.5.0"
|
||||
@@ -10680,4 +10702,4 @@ local-whisper = ["whisper-timestamped"]
|
||||
[metadata]
|
||||
lock-version = "2.1"
|
||||
python-versions = ">=3.10,<3.14"
|
||||
content-hash = "bfb710412104ada6da5504e2afb3181da05cac4d6ed1238d08e9a712c254f22d"
|
||||
content-hash = "fd26762a0d3f754ddc150bb24dc6d1ee1a15cb8154584950b213029751315ed2"
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.151.0"
|
||||
version = "0.154.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
@@ -88,6 +88,7 @@ pydantic-settings = ">=2.1.0"
|
||||
httpx = ">=0.25.0"
|
||||
tenacity = "^8.2.0" # Retry logic for external service calls
|
||||
google-cloud-firestore = "2.26.0"
|
||||
google-cloud-compute = "^1.0.0"
|
||||
google-cloud-storage = "3.10.1"
|
||||
google-cloud-secret-manager = "2.26.0"
|
||||
google-cloud-monitoring = "2.29.1" # Cloud Monitoring for YouTube API quota metrics
|
||||
|
||||
Executable
+369
@@ -0,0 +1,369 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Empirical threshold analysis: measure per-source reference relevance scores
|
||||
from production jobs that have corrections.json files.
|
||||
|
||||
Relevance score = (reference words appearing in anchor sequences) / (total reference words)
|
||||
|
||||
This helps determine appropriate thresholds for filtering low-quality reference
|
||||
sources before running anchor sequence detection.
|
||||
|
||||
Usage:
|
||||
python scripts/analyze_reference_relevance.py
|
||||
python scripts/analyze_reference_relevance.py --limit 50
|
||||
python scripts/analyze_reference_relevance.py --output results.json
|
||||
|
||||
Requires:
|
||||
- google-cloud-firestore
|
||||
- google-cloud-storage
|
||||
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
|
||||
"""
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore, storage
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PROJECT = "nomadkaraoke"
|
||||
GCS_BUCKET = "karaoke-gen-storage-nomadkaraoke"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Firestore helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def fetch_candidate_jobs(db: firestore.Client, limit: int) -> list[dict]:
|
||||
"""
|
||||
Pull jobs that have a corrections file URL from Firestore.
|
||||
|
||||
We over-fetch (up to 3x the limit) so we can bias toward jobs where at
|
||||
least one source has a low match score (mixed results). We filter down
|
||||
after computing scores.
|
||||
"""
|
||||
logger.info("Querying Firestore for completed jobs with correction data...")
|
||||
|
||||
# Query jobs that are complete and have lyrics corrections URL stored
|
||||
query = (
|
||||
db.collection("jobs")
|
||||
.where("status", "==", "complete")
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(limit * 3)
|
||||
)
|
||||
|
||||
jobs = []
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
data["_job_id"] = doc.id
|
||||
|
||||
# Require a corrections URL
|
||||
corrections_url = _get_corrections_url(data)
|
||||
if corrections_url:
|
||||
data["_corrections_url"] = corrections_url
|
||||
jobs.append(data)
|
||||
|
||||
logger.info(f"Found {len(jobs)} jobs with corrections URL")
|
||||
return jobs
|
||||
|
||||
|
||||
def _get_corrections_url(job_data: dict) -> Optional[str]:
|
||||
"""Extract the GCS path for the corrections.json from a Firestore job doc."""
|
||||
file_urls = job_data.get("file_urls", {})
|
||||
lyrics = file_urls.get("lyrics", {})
|
||||
corrections = lyrics.get("corrections")
|
||||
if corrections:
|
||||
return corrections
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GCS helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def download_corrections(gcs_client: storage.Client, gcs_path: str) -> Optional[dict]:
|
||||
"""
|
||||
Download and parse a corrections.json from GCS.
|
||||
|
||||
gcs_path may be:
|
||||
- A full gs:// URL: gs://karaoke-gen-outputs/jobs/.../lyrics/corrections.json
|
||||
- A bare object path: jobs/.../lyrics/corrections.json
|
||||
"""
|
||||
if gcs_path.startswith("gs://"):
|
||||
# Strip gs://<bucket>/
|
||||
parts = gcs_path[5:].split("/", 1)
|
||||
bucket_name = parts[0]
|
||||
blob_path = parts[1] if len(parts) > 1 else ""
|
||||
else:
|
||||
bucket_name = GCS_BUCKET
|
||||
blob_path = gcs_path
|
||||
|
||||
try:
|
||||
bucket = gcs_client.bucket(bucket_name)
|
||||
blob = bucket.blob(blob_path)
|
||||
content = blob.download_as_bytes()
|
||||
return json.loads(content)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to download {gcs_path}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Relevance computation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def compute_relevance_scores(corrections: dict) -> dict[str, dict]:
|
||||
"""
|
||||
Compute per-source relevance scores from a corrections.json dict.
|
||||
|
||||
Relevance = (# reference words that appear in at least one anchor) /
|
||||
(total words in that source's reference lyrics)
|
||||
|
||||
Returns a dict keyed by source name, each value being:
|
||||
{
|
||||
"total_words": int,
|
||||
"anchored_words": int,
|
||||
"score": float,
|
||||
}
|
||||
"""
|
||||
reference_lyrics: dict = corrections.get("reference_lyrics", {})
|
||||
anchor_sequences: list = corrections.get("anchor_sequences", [])
|
||||
|
||||
# Build set of anchored word IDs per source
|
||||
anchored_ids: dict[str, set] = defaultdict(set)
|
||||
for anchor in anchor_sequences:
|
||||
ref_word_ids: dict = anchor.get("reference_word_ids", {})
|
||||
for source, word_ids in ref_word_ids.items():
|
||||
anchored_ids[source].update(word_ids)
|
||||
|
||||
scores = {}
|
||||
for source, ref_data in reference_lyrics.items():
|
||||
if not ref_data:
|
||||
continue
|
||||
|
||||
# Count total words in this source
|
||||
total_words = 0
|
||||
for segment in ref_data.get("segments", []):
|
||||
total_words += len(segment.get("words", []))
|
||||
|
||||
if total_words == 0:
|
||||
scores[source] = {"total_words": 0, "anchored_words": 0, "score": 0.0}
|
||||
continue
|
||||
|
||||
anchored_count = len(anchored_ids.get(source, set()))
|
||||
score = anchored_count / total_words
|
||||
|
||||
scores[source] = {
|
||||
"total_words": total_words,
|
||||
"anchored_words": anchored_count,
|
||||
"score": round(score, 4),
|
||||
}
|
||||
|
||||
return scores
|
||||
|
||||
|
||||
def has_mixed_results(scores: dict[str, dict], low_threshold: float = 0.5) -> bool:
|
||||
"""Return True if at least one source has a score below low_threshold."""
|
||||
if len(scores) < 2:
|
||||
return False
|
||||
score_values = [v["score"] for v in scores.values()]
|
||||
return min(score_values) < low_threshold
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Report generation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def build_report(job_results: list[dict]) -> str:
|
||||
"""Build a human-readable text report sorted by min source score."""
|
||||
lines = []
|
||||
lines.append("=" * 72)
|
||||
lines.append("REFERENCE LYRICS RELEVANCE ANALYSIS")
|
||||
lines.append(f"Jobs analyzed: {len(job_results)}")
|
||||
lines.append("=" * 72)
|
||||
lines.append("")
|
||||
|
||||
# Sort: mixed-result jobs first (most interesting), then by min score asc
|
||||
def sort_key(r):
|
||||
scores = [v["score"] for v in r["scores"].values()] if r["scores"] else [1.0]
|
||||
return (0 if r["is_mixed"] else 1, min(scores))
|
||||
|
||||
sorted_results = sorted(job_results, key=sort_key)
|
||||
|
||||
for idx, result in enumerate(sorted_results, 1):
|
||||
job_id = result["job_id"]
|
||||
artist = result.get("artist", "Unknown")
|
||||
title = result.get("title", "Unknown")
|
||||
mixed_flag = " [MIXED]" if result["is_mixed"] else ""
|
||||
|
||||
lines.append(f"{idx:3d}. {artist} - {title} ({job_id}){mixed_flag}")
|
||||
|
||||
scores = result["scores"]
|
||||
if not scores:
|
||||
lines.append(" (no reference sources found)")
|
||||
else:
|
||||
for source, info in sorted(scores.items(), key=lambda x: x[1]["score"]):
|
||||
bar_len = int(info["score"] * 20)
|
||||
bar = "#" * bar_len + "-" * (20 - bar_len)
|
||||
lines.append(
|
||||
f" {source:<12s} [{bar}] {info['score']:.1%}"
|
||||
f" ({info['anchored_words']}/{info['total_words']} words)"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# --- Aggregate statistics ---
|
||||
lines.append("=" * 72)
|
||||
lines.append("AGGREGATE STATISTICS")
|
||||
lines.append("=" * 72)
|
||||
|
||||
all_source_scores: dict[str, list[float]] = defaultdict(list)
|
||||
for result in job_results:
|
||||
for source, info in result["scores"].items():
|
||||
all_source_scores[source].append(info["score"])
|
||||
|
||||
for source in sorted(all_source_scores):
|
||||
vals = all_source_scores[source]
|
||||
avg = sum(vals) / len(vals) if vals else 0
|
||||
below_50 = sum(1 for v in vals if v < 0.5)
|
||||
below_30 = sum(1 for v in vals if v < 0.3)
|
||||
below_10 = sum(1 for v in vals if v < 0.1)
|
||||
lines.append(
|
||||
f" {source:<12s} n={len(vals):3d} avg={avg:.1%}"
|
||||
f" <50%: {below_50:3d} <30%: {below_30:3d} <10%: {below_10:3d}"
|
||||
)
|
||||
|
||||
mixed_count = sum(1 for r in job_results if r["is_mixed"])
|
||||
lines.append("")
|
||||
lines.append(f" Jobs with mixed results (at least 1 source <50%): {mixed_count}/{len(job_results)}")
|
||||
|
||||
# Score distribution across ALL sources
|
||||
all_scores = [
|
||||
info["score"]
|
||||
for result in job_results
|
||||
for info in result["scores"].values()
|
||||
]
|
||||
if all_scores:
|
||||
thresholds = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
|
||||
lines.append("")
|
||||
lines.append(" Score distribution (all sources):")
|
||||
for t in thresholds:
|
||||
count = sum(1 for s in all_scores if s < t)
|
||||
pct = count / len(all_scores) * 100
|
||||
lines.append(f" < {t:.0%}: {count:4d} / {len(all_scores)} ({pct:.1f}%)")
|
||||
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Analyze reference lyrics relevance scores from production jobs"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=30,
|
||||
help="Target number of jobs to analyze (default: 30)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Write raw JSON results to this file (optional)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-mixed-bias",
|
||||
action="store_true",
|
||||
help="Disable bias toward jobs with mixed results",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
db = firestore.Client(project=PROJECT)
|
||||
gcs_client = storage.Client(project=PROJECT)
|
||||
|
||||
# Step 1: Fetch candidate jobs from Firestore
|
||||
candidate_jobs = fetch_candidate_jobs(db, limit=args.limit)
|
||||
if not candidate_jobs:
|
||||
logger.error("No candidate jobs found. Check Firestore access.")
|
||||
sys.exit(1)
|
||||
|
||||
# Step 2: Download corrections and compute scores
|
||||
job_results = []
|
||||
skipped = 0
|
||||
|
||||
for job in candidate_jobs:
|
||||
job_id = job["_job_id"]
|
||||
corrections_url = job["_corrections_url"]
|
||||
artist = job.get("artist", job.get("state_data", {}).get("artist", "Unknown"))
|
||||
title = job.get("title", job.get("state_data", {}).get("title", "Unknown"))
|
||||
|
||||
logger.info(f"Processing {job_id}: {artist} - {title}")
|
||||
|
||||
corrections = download_corrections(gcs_client, corrections_url)
|
||||
if not corrections:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
scores = compute_relevance_scores(corrections)
|
||||
if not scores:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
is_mixed = has_mixed_results(scores)
|
||||
|
||||
job_results.append({
|
||||
"job_id": job_id,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"corrections_url": corrections_url,
|
||||
"scores": scores,
|
||||
"is_mixed": is_mixed,
|
||||
})
|
||||
|
||||
if skipped:
|
||||
logger.info(f"Skipped {skipped} jobs (download failure or no reference sources)")
|
||||
|
||||
if not job_results:
|
||||
logger.error("No results to report.")
|
||||
sys.exit(1)
|
||||
|
||||
# Step 3: Optionally bias toward mixed-result jobs
|
||||
if not args.no_mixed_bias:
|
||||
mixed = [r for r in job_results if r["is_mixed"]]
|
||||
non_mixed = [r for r in job_results if not r["is_mixed"]]
|
||||
# Aim for at least half mixed, rest filled with non-mixed
|
||||
target_mixed = min(len(mixed), max(args.limit // 2, len(mixed)))
|
||||
target_non_mixed = min(len(non_mixed), args.limit - target_mixed)
|
||||
job_results = mixed[:target_mixed] + non_mixed[:target_non_mixed]
|
||||
logger.info(
|
||||
f"After mixed-bias selection: {len(job_results)} jobs "
|
||||
f"({target_mixed} mixed, {target_non_mixed} non-mixed)"
|
||||
)
|
||||
else:
|
||||
job_results = job_results[: args.limit]
|
||||
|
||||
# Step 4: Print report
|
||||
report = build_report(job_results)
|
||||
print(report)
|
||||
|
||||
# Step 5: Optionally write JSON
|
||||
if args.output:
|
||||
with open(args.output, "w") as f:
|
||||
json.dump(job_results, f, indent=2)
|
||||
logger.info(f"Raw results written to {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
Executable
+1198
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
@@ -0,0 +1,257 @@
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.correction.relevance import (
|
||||
compute_source_relevance,
|
||||
filter_irrelevant_sources,
|
||||
SourceRelevanceResult,
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.types import (
|
||||
AnchorSequence,
|
||||
LyricsData,
|
||||
LyricsMetadata,
|
||||
LyricsSegment,
|
||||
TranscriptionData,
|
||||
TranscriptionResult,
|
||||
Word,
|
||||
)
|
||||
|
||||
|
||||
def _make_words(texts: list[str], id_prefix: str = "w") -> list[Word]:
|
||||
"""Create Word objects from text strings."""
|
||||
return [
|
||||
Word(id=f"{id_prefix}_{i}", text=t, start_time=0.0, end_time=0.0)
|
||||
for i, t in enumerate(texts)
|
||||
]
|
||||
|
||||
|
||||
def _make_lyrics_data(word_texts: list[list[str]], source: str) -> LyricsData:
|
||||
"""Create LyricsData from a list of lines (each line is a list of word strings)."""
|
||||
segments = []
|
||||
for i, line_words in enumerate(word_texts):
|
||||
words = _make_words(line_words, id_prefix=f"{source}_s{i}_w")
|
||||
segments.append(
|
||||
LyricsSegment(
|
||||
id=f"{source}_seg_{i}",
|
||||
text=" ".join(line_words),
|
||||
words=words,
|
||||
start_time=0.0,
|
||||
end_time=0.0,
|
||||
)
|
||||
)
|
||||
return LyricsData(
|
||||
segments=segments,
|
||||
metadata=LyricsMetadata(source=source, track_name="Test", artist_names="Test"),
|
||||
source=source,
|
||||
)
|
||||
|
||||
|
||||
def _make_anchor(
|
||||
trans_word_ids: list[str],
|
||||
reference_word_ids: dict[str, list[str]],
|
||||
confidence: float = 1.0,
|
||||
) -> AnchorSequence:
|
||||
"""Create an AnchorSequence with given word ID mappings."""
|
||||
return AnchorSequence(
|
||||
id=f"anchor_{trans_word_ids[0]}",
|
||||
transcribed_word_ids=trans_word_ids,
|
||||
transcription_position=0,
|
||||
reference_positions={s: 0 for s in reference_word_ids},
|
||||
reference_word_ids=reference_word_ids,
|
||||
confidence=confidence,
|
||||
)
|
||||
|
||||
|
||||
class TestComputeSourceRelevance:
|
||||
def test_high_match_returns_high_score(self):
|
||||
"""Source with 8/10 words in anchors scores 0.8."""
|
||||
lyrics = _make_lyrics_data([["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]], "genius")
|
||||
all_word_ids = [w.id for seg in lyrics.segments for w in seg.words]
|
||||
# 8 of 10 words matched
|
||||
anchors = [
|
||||
_make_anchor(["t1", "t2"], {"genius": all_word_ids[0:2]}),
|
||||
_make_anchor(["t3", "t4", "t5"], {"genius": all_word_ids[2:5]}),
|
||||
_make_anchor(["t6", "t7", "t8"], {"genius": all_word_ids[5:8]}),
|
||||
]
|
||||
result = compute_source_relevance("genius", lyrics, anchors)
|
||||
assert result.relevance == pytest.approx(0.8)
|
||||
assert result.matched_words == 8
|
||||
assert result.total_words == 10
|
||||
|
||||
def test_no_match_returns_zero(self):
|
||||
"""Source with no words in any anchors scores 0.0."""
|
||||
lyrics = _make_lyrics_data([["a", "b", "c"]], "spotify")
|
||||
anchors = [
|
||||
_make_anchor(["t1"], {"genius": ["other_id"]}), # Different source
|
||||
]
|
||||
result = compute_source_relevance("spotify", lyrics, anchors)
|
||||
assert result.relevance == 0.0
|
||||
assert result.matched_words == 0
|
||||
|
||||
def test_empty_source_returns_zero(self):
|
||||
"""Source with zero words scores 0.0."""
|
||||
lyrics = _make_lyrics_data([], "empty")
|
||||
result = compute_source_relevance("empty", lyrics, [])
|
||||
assert result.relevance == 0.0
|
||||
|
||||
|
||||
class TestFilterIrrelevantSources:
|
||||
def test_filters_below_threshold(self):
|
||||
"""Sources below threshold are removed from lyrics_results."""
|
||||
good_lyrics = _make_lyrics_data([["a", "b", "c", "d", "e"]], "genius")
|
||||
bad_lyrics = _make_lyrics_data([["x", "y", "z", "q", "r"]], "spotify")
|
||||
good_word_ids = [w.id for seg in good_lyrics.segments for w in seg.words]
|
||||
|
||||
lyrics_results = {"genius": good_lyrics, "spotify": bad_lyrics}
|
||||
anchors = [
|
||||
_make_anchor(["t1", "t2", "t3", "t4"], {"genius": good_word_ids[0:4]}),
|
||||
]
|
||||
|
||||
filtered, rejected = filter_irrelevant_sources(
|
||||
lyrics_results, anchors, min_relevance=0.5
|
||||
)
|
||||
assert "genius" in filtered
|
||||
assert "spotify" not in filtered
|
||||
assert "spotify" in rejected
|
||||
assert rejected["spotify"].relevance == 0.0
|
||||
|
||||
def test_keeps_all_above_threshold(self):
|
||||
"""All sources above threshold are kept."""
|
||||
lyrics_a = _make_lyrics_data([["a", "b"]], "src_a")
|
||||
lyrics_b = _make_lyrics_data([["a", "b"]], "src_b")
|
||||
a_ids = [w.id for seg in lyrics_a.segments for w in seg.words]
|
||||
b_ids = [w.id for seg in lyrics_b.segments for w in seg.words]
|
||||
|
||||
anchors = [
|
||||
_make_anchor(["t1", "t2"], {"src_a": a_ids, "src_b": b_ids}),
|
||||
]
|
||||
filtered, rejected = filter_irrelevant_sources(
|
||||
{"src_a": lyrics_a, "src_b": lyrics_b}, anchors, min_relevance=0.5
|
||||
)
|
||||
assert len(filtered) == 2
|
||||
assert len(rejected) == 0
|
||||
|
||||
def test_empty_input_returns_empty(self):
|
||||
"""No sources in, no sources out."""
|
||||
filtered, rejected = filter_irrelevant_sources({}, [], min_relevance=0.5)
|
||||
assert filtered == {}
|
||||
assert rejected == {}
|
||||
|
||||
|
||||
class TestCorrectorRelevanceIntegration:
|
||||
"""Test that LyricsCorrector filters irrelevant sources."""
|
||||
|
||||
def test_corrector_removes_irrelevant_source(self, tmp_path):
|
||||
"""A source with 0% match should be excluded from the CorrectionResult."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
|
||||
# Transcription: "hello world foo bar"
|
||||
trans_words = _make_words(["hello", "world", "foo", "bar"], "trans")
|
||||
trans_segment = LyricsSegment(
|
||||
id="trans_seg_0",
|
||||
text="hello world foo bar",
|
||||
words=trans_words,
|
||||
start_time=0.0,
|
||||
end_time=1.0,
|
||||
)
|
||||
transcription = TranscriptionData(
|
||||
segments=[trans_segment],
|
||||
words=trans_words,
|
||||
text="hello world foo bar",
|
||||
source="test",
|
||||
)
|
||||
|
||||
# Good source: matching words
|
||||
good_lyrics = _make_lyrics_data([["hello", "world", "foo", "bar"]], "good_source")
|
||||
# Bad source: completely different words
|
||||
bad_lyrics = _make_lyrics_data([["alpha", "beta", "gamma", "delta"]], "bad_source")
|
||||
|
||||
corrector = LyricsCorrector(cache_dir=str(tmp_path))
|
||||
result = corrector.run(
|
||||
transcription_results=[
|
||||
TranscriptionResult(name="test", priority=1, result=transcription)
|
||||
],
|
||||
lyrics_results={"good_source": good_lyrics, "bad_source": bad_lyrics},
|
||||
)
|
||||
|
||||
# Good source should be in result, bad source should not
|
||||
assert "good_source" in result.reference_lyrics
|
||||
assert "bad_source" not in result.reference_lyrics
|
||||
|
||||
# Rejected sources should be logged in metadata
|
||||
assert "rejected_sources" in result.metadata
|
||||
assert "bad_source" in result.metadata["rejected_sources"]
|
||||
|
||||
def test_corrector_keeps_all_relevant_sources(self, tmp_path):
|
||||
"""Sources that match the transcription should all be kept."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
|
||||
trans_words = _make_words(["hello", "world", "foo", "bar"], "trans")
|
||||
trans_segment = LyricsSegment(
|
||||
id="trans_seg_0",
|
||||
text="hello world foo bar",
|
||||
words=trans_words,
|
||||
start_time=0.0,
|
||||
end_time=1.0,
|
||||
)
|
||||
transcription = TranscriptionData(
|
||||
segments=[trans_segment],
|
||||
words=trans_words,
|
||||
text="hello world foo bar",
|
||||
source="test",
|
||||
)
|
||||
|
||||
# Both sources match the transcription
|
||||
source_a = _make_lyrics_data([["hello", "world", "foo", "bar"]], "source_a")
|
||||
source_b = _make_lyrics_data([["hello", "world", "foo", "bar"]], "source_b")
|
||||
|
||||
corrector = LyricsCorrector(cache_dir=str(tmp_path))
|
||||
result = corrector.run(
|
||||
transcription_results=[
|
||||
TranscriptionResult(name="test", priority=1, result=transcription)
|
||||
],
|
||||
lyrics_results={"source_a": source_a, "source_b": source_b},
|
||||
)
|
||||
|
||||
assert "source_a" in result.reference_lyrics
|
||||
assert "source_b" in result.reference_lyrics
|
||||
assert "rejected_sources" not in result.metadata
|
||||
|
||||
def test_corrector_handles_all_sources_filtered_out(self, tmp_path):
|
||||
"""When ALL sources fail relevance, corrector returns empty references and no corrections."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
|
||||
trans_words = _make_words(["hello", "world", "foo", "bar"], "trans")
|
||||
trans_segment = LyricsSegment(
|
||||
id="trans_seg_0",
|
||||
text="hello world foo bar",
|
||||
words=trans_words,
|
||||
start_time=0.0,
|
||||
end_time=1.0,
|
||||
)
|
||||
transcription = TranscriptionData(
|
||||
segments=[trans_segment],
|
||||
words=trans_words,
|
||||
text="hello world foo bar",
|
||||
source="test",
|
||||
)
|
||||
|
||||
# All sources have completely different words — all will be filtered
|
||||
bad_a = _make_lyrics_data([["alpha", "beta", "gamma", "delta"]], "bad_a")
|
||||
bad_b = _make_lyrics_data([["uno", "dos", "tres", "cuatro"]], "bad_b")
|
||||
bad_c = _make_lyrics_data([["eins", "zwei", "drei", "vier"]], "bad_c")
|
||||
|
||||
corrector = LyricsCorrector(cache_dir=str(tmp_path))
|
||||
result = corrector.run(
|
||||
transcription_results=[
|
||||
TranscriptionResult(name="test", priority=1, result=transcription)
|
||||
],
|
||||
lyrics_results={"bad_a": bad_a, "bad_b": bad_b, "bad_c": bad_c},
|
||||
)
|
||||
|
||||
# All sources should be rejected
|
||||
assert len(result.reference_lyrics) == 0
|
||||
assert "rejected_sources" in result.metadata
|
||||
assert len(result.metadata["rejected_sources"]) == 3
|
||||
# No corrections should have been made (no references to correct against)
|
||||
assert result.corrections_made == 0
|
||||
# Original segments should be preserved
|
||||
assert len(result.original_segments) == 1
|
||||
+16792
File diff suppressed because it is too large.
Load diff
@@ -746,6 +746,91 @@ class TestExtendAnchorsIntoSingleWordGaps:
|
||||
assert result[0].anchor.length == 2
|
||||
assert result[1].anchor.length == 2
|
||||
|
||||
def test_gap_at_end_of_transcription_skipped(self, finder):
|
||||
"""Gap position at or beyond all_words length does not crash (IndexError regression)."""
|
||||
# Last anchor ends at position 4 (len=2, start=3), gap_position = 5
|
||||
# But all_words only has 6 items (indices 0-5), and next_anchor starts at 6
|
||||
# which means gap_position = 5 is valid, but test the exact boundary
|
||||
anchor1 = create_scored_anchor(
|
||||
words=["hello", "world", "foo"],
|
||||
transcription_position=0,
|
||||
reference_positions={"src1": 0},
|
||||
)
|
||||
anchor2 = create_scored_anchor(
|
||||
words=["bar", "baz"],
|
||||
transcription_position=4, # gap_position = 3, within bounds
|
||||
reference_positions={"src1": 4},
|
||||
)
|
||||
# Anchor that would create an out-of-bounds gap
|
||||
anchor3 = create_scored_anchor(
|
||||
words=["end"],
|
||||
transcription_position=7, # gap_position = 6, but all_words has 7 items (0-6)
|
||||
reference_positions={"src1": 7},
|
||||
)
|
||||
|
||||
all_words = [
|
||||
create_word("w0", "hello", 0),
|
||||
create_word("w1", "world", 1),
|
||||
create_word("w2", "foo", 2),
|
||||
create_word("w3", "gap1", 3),
|
||||
create_word("w4", "bar", 4),
|
||||
create_word("w5", "baz", 5),
|
||||
# gap at position 6 would be out of bounds if all_words only has 6 items
|
||||
# but we have 7 items, so let's test with exactly 7 to make gap_position = 6 valid
|
||||
create_word("w6", "gap2", 6),
|
||||
]
|
||||
|
||||
ref_texts_clean = {"src1": ["hello", "world", "foo", "gap1", "bar", "baz", "gap2", "end"]}
|
||||
ref_words = {"src1": [create_word(f"r{i}", w, i) for i, w in
|
||||
enumerate(["hello", "world", "foo", "gap1", "bar", "baz", "gap2", "end"])]}
|
||||
|
||||
# Should not raise IndexError
|
||||
result = finder._extend_anchors_into_single_word_gaps(
|
||||
filtered_scored=[anchor1, anchor2, anchor3],
|
||||
all_words=all_words,
|
||||
ref_texts_clean=ref_texts_clean,
|
||||
ref_words=ref_words,
|
||||
)
|
||||
assert len(result) == 3
|
||||
|
||||
def test_gap_beyond_all_words_length_skipped(self, finder):
|
||||
"""When gap_position >= len(all_words), the gap is safely skipped."""
|
||||
# anchor1 ends at position 3, anchor2 starts at 4, gap at 3
|
||||
# But all_words only has 3 items — gap_position is out of bounds
|
||||
anchor1 = create_scored_anchor(
|
||||
words=["hello", "world", "test"],
|
||||
transcription_position=0,
|
||||
reference_positions={"src1": 0},
|
||||
)
|
||||
anchor2 = create_scored_anchor(
|
||||
words=["more"],
|
||||
transcription_position=4, # gap_position = 3 = len(all_words)
|
||||
reference_positions={"src1": 4},
|
||||
)
|
||||
|
||||
all_words = [
|
||||
create_word("w0", "hello", 0),
|
||||
create_word("w1", "world", 1),
|
||||
create_word("w2", "test", 2),
|
||||
# No word at position 3 — gap_position is out of bounds
|
||||
]
|
||||
|
||||
ref_texts_clean = {"src1": ["hello", "world", "test", "gap", "more"]}
|
||||
ref_words = {"src1": [create_word(f"r{i}", w, i) for i, w in
|
||||
enumerate(["hello", "world", "test", "gap", "more"])]}
|
||||
|
||||
# Should not raise IndexError — gap is skipped
|
||||
result = finder._extend_anchors_into_single_word_gaps(
|
||||
filtered_scored=[anchor1, anchor2],
|
||||
all_words=all_words,
|
||||
ref_texts_clean=ref_texts_clean,
|
||||
ref_words=ref_words,
|
||||
)
|
||||
|
||||
# Both anchors unchanged — gap was skipped
|
||||
assert result[0].anchor.length == 3
|
||||
assert result[1].anchor.length == 1
|
||||
|
||||
def test_prefers_longer_anchor_when_both_valid(self, finder):
|
||||
"""When both directions valid, extends the longer anchor."""
|
||||
# Longer anchor1 (3 words) vs shorter anchor2 (2 words)
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
Regression test for IndexError in anchor gap extension (job b7e8c96d).
|
||||
|
||||
Root cause: ref_texts_clean and ref_words have different lengths because
|
||||
clean_text() normalizes text (merging/splitting words), but anchor positions
|
||||
are computed against ref_texts_clean and then used to index ref_words.
|
||||
|
||||
When ref_texts_clean[source] has MORE words than ref_words[source],
|
||||
anchor reference_positions can exceed ref_words bounds.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.correction.anchor_sequence import AnchorSequenceFinder
|
||||
from karaoke_gen.lyrics_transcriber.types import (
|
||||
AnchorSequence,
|
||||
PhraseScore,
|
||||
PhraseType,
|
||||
ScoredAnchor,
|
||||
Word,
|
||||
)
|
||||
|
||||
FIXTURE_PATH = Path(__file__).parent.parent / "fixtures" / "anchor_crash_b7e8c96d.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def finder():
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
yield AnchorSequenceFinder(
|
||||
cache_dir=temp_dir,
|
||||
min_sequence_length=3,
|
||||
min_sources=1,
|
||||
timeout_seconds=60,
|
||||
logger=logging.getLogger(__name__),
|
||||
)
|
||||
|
||||
|
||||
def _load_fixture():
|
||||
"""Load the production crash fixture data."""
|
||||
with open(FIXTURE_PATH) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _rebuild_scored_anchors(fixture_data):
|
||||
"""Rebuild ScoredAnchor objects from fixture JSON."""
|
||||
scored_anchors = []
|
||||
for sa_data in fixture_data["filtered_scored"]:
|
||||
a = sa_data["anchor"]
|
||||
anchor = AnchorSequence(
|
||||
id=a["id"],
|
||||
transcribed_word_ids=a["transcribed_word_ids"],
|
||||
transcription_position=a["transcription_position"],
|
||||
reference_positions=a["reference_positions"],
|
||||
reference_word_ids=a["reference_word_ids"],
|
||||
confidence=a["confidence"],
|
||||
_words=a["words"],
|
||||
)
|
||||
phrase_score = PhraseScore(
|
||||
phrase_type=PhraseType(sa_data["phrase_score"]["phrase_type"]),
|
||||
natural_break_score=sa_data["phrase_score"]["natural_break_score"],
|
||||
length_score=sa_data["phrase_score"]["length_score"],
|
||||
)
|
||||
scored_anchors.append(ScoredAnchor(anchor=anchor, phrase_score=phrase_score))
|
||||
return scored_anchors
|
||||
|
||||
|
||||
def _rebuild_words(word_dicts):
|
||||
"""Rebuild Word objects from fixture JSON."""
|
||||
return [
|
||||
Word(id=w["id"], text=w["text"], start_time=w["start_time"], end_time=w["end_time"])
|
||||
for w in word_dicts
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not FIXTURE_PATH.exists(), reason="Fixture not available")
|
||||
class TestProductionCrashB7e8c96d:
|
||||
"""Regression tests using production data from job b7e8c96d."""
|
||||
|
||||
def test_gap_extension_does_not_crash(self, finder):
|
||||
"""_extend_anchors_into_single_word_gaps must not IndexError on mismatched ref lengths."""
|
||||
data = _load_fixture()
|
||||
scored_anchors = _rebuild_scored_anchors(data)
|
||||
all_words = _rebuild_words(data["all_words"])
|
||||
ref_texts_clean = data["ref_texts_clean"]
|
||||
ref_words = {src: _rebuild_words(words) for src, words in data["ref_words"].items()}
|
||||
|
||||
# This crashed with IndexError before the fix
|
||||
result = finder._extend_anchors_into_single_word_gaps(
|
||||
scored_anchors, all_words, ref_texts_clean, ref_words
|
||||
)
|
||||
|
||||
assert len(result) == len(scored_anchors)
|
||||
|
||||
def test_ref_texts_and_ref_words_length_mismatch(self, finder):
|
||||
"""Verify the fixture actually has the length mismatch that causes the bug."""
|
||||
data = _load_fixture()
|
||||
mismatched = False
|
||||
for source in data["ref_texts_clean"]:
|
||||
clean_len = len(data["ref_texts_clean"][source])
|
||||
words_len = len(data["ref_words"].get(source, []))
|
||||
if clean_len != words_len:
|
||||
mismatched = True
|
||||
assert mismatched, "Fixture should have ref_texts_clean/ref_words length mismatch"
|
||||
|
||||
|
||||
class TestBoundsCheckInExtension:
|
||||
"""Unit tests for bounds checking in forward/backward extension."""
|
||||
|
||||
def _make_anchor(self, words, trans_pos, ref_positions, ref_word_ids=None):
|
||||
anchor = AnchorSequence(
|
||||
words=words,
|
||||
transcription_position=trans_pos,
|
||||
reference_positions=ref_positions,
|
||||
confidence=1.0,
|
||||
)
|
||||
if ref_word_ids:
|
||||
anchor.reference_word_ids = ref_word_ids
|
||||
return ScoredAnchor(
|
||||
anchor=anchor,
|
||||
phrase_score=PhraseScore(
|
||||
phrase_type=PhraseType.COMPLETE,
|
||||
natural_break_score=1.0,
|
||||
length_score=1.0,
|
||||
),
|
||||
)
|
||||
|
||||
def _make_word(self, idx, text="word"):
|
||||
return Word(id=f"w{idx}", text=text, start_time=float(idx), end_time=float(idx + 1))
|
||||
|
||||
def test_backward_extension_ref_position_exceeds_ref_words(self, finder):
|
||||
"""Backward extension must not crash when ref position > len(ref_words)."""
|
||||
# ref_texts_clean has 10 words, but ref_words only has 5
|
||||
# Anchor at ref_position=8 would crash when doing ref_words[source][8-1]
|
||||
all_words = [self._make_word(i, f"w{i}") for i in range(10)]
|
||||
ref_words = {"src": [self._make_word(i, f"r{i}") for i in range(5)]}
|
||||
ref_texts_clean = {"src": [f"r{i}" for i in range(10)]}
|
||||
|
||||
anchor1 = self._make_anchor(
|
||||
["w5", "w6"], trans_pos=5, ref_positions={"src": 5},
|
||||
ref_word_ids={"src": ["r5_id", "r6_id"]},
|
||||
)
|
||||
anchor2 = self._make_anchor(
|
||||
["w8", "w9"], trans_pos=8, ref_positions={"src": 8},
|
||||
ref_word_ids={"src": ["r8_id", "r9_id"]},
|
||||
)
|
||||
|
||||
# gap at position 7, backward extension would try ref_words["src"][7]
|
||||
# which exceeds len(ref_words["src"]) = 5
|
||||
result = finder._extend_anchors_into_single_word_gaps(
|
||||
[anchor1, anchor2], all_words, ref_texts_clean, ref_words
|
||||
)
|
||||
assert len(result) == 2
|
||||
|
||||
def test_forward_extension_ref_end_exceeds_ref_words(self, finder):
|
||||
"""Forward extension must not crash when ref_end > len(ref_words)."""
|
||||
all_words = [self._make_word(i, f"w{i}") for i in range(10)]
|
||||
ref_words = {"src": [self._make_word(i, f"r{i}") for i in range(5)]}
|
||||
ref_texts_clean = {"src": [f"r{i}" for i in range(10)]}
|
||||
|
||||
anchor1 = self._make_anchor(
|
||||
["w3", "w4"], trans_pos=3, ref_positions={"src": 3},
|
||||
ref_word_ids={"src": ["r3_id", "r4_id"]},
|
||||
)
|
||||
anchor2 = self._make_anchor(
|
||||
["w6", "w7"], trans_pos=6, ref_positions={"src": 6},
|
||||
ref_word_ids={"src": ["r6_id", "r7_id"]},
|
||||
)
|
||||
|
||||
# gap at position 5, forward extension would try ref_words["src"][5]
|
||||
# which is exactly at the boundary (len=5, index 5 is out of bounds)
|
||||
result = finder._extend_anchors_into_single_word_gaps(
|
||||
[anchor1, anchor2], all_words, ref_texts_clean, ref_words
|
||||
)
|
||||
assert len(result) == 2
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import shutil
|
||||
import pytest
|
||||
import glob
|
||||
import json
|
||||
@@ -8,7 +9,6 @@ import datetime as dt # Use alias to avoid conflict
|
||||
import fcntl
|
||||
from pydub import AudioSegment
|
||||
from karaoke_gen.karaoke_gen import KaraokePrep
|
||||
from audio_separator.separator import Separator # Keep for patching target
|
||||
|
||||
class TestAudio:
|
||||
def test_separate_audio(self, basic_karaoke_gen, temp_dir):
|
||||
@@ -34,7 +34,7 @@ class TestAudio:
|
||||
]
|
||||
|
||||
# Mock dependencies
|
||||
with patch('audio_separator.separator.Separator', return_value=mock_separator), \
|
||||
with patch('karaoke_gen.audio_processor.Separator', return_value=mock_separator), \
|
||||
patch('os.rename') as mock_rename:
|
||||
|
||||
# Call the method
|
||||
@@ -130,7 +130,7 @@ class TestAudio:
|
||||
]
|
||||
|
||||
# Mock dependencies
|
||||
with patch('audio_separator.separator.Separator', return_value=mock_separator), \
|
||||
with patch('karaoke_gen.audio_processor.Separator', return_value=mock_separator), \
|
||||
patch('os.rename') as mock_rename, \
|
||||
patch('os.path.exists', return_value=True), \
|
||||
patch('os.getpid', return_value=12345), \
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
import os
|
||||
import logging
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
from backend.workers.audio_worker import create_audio_processor, process_audio_separation
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
|
||||
|
||||
class TestCreateAudioProcessorLocalGPU:
|
||||
"""Tests for create_audio_processor with local GPU (model_file_dir set)."""
|
||||
|
||||
def test_model_file_dir_passed_through(self):
|
||||
"""When model_file_dir is provided, AudioProcessor gets it for local separation."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
model_file_dir="/models",
|
||||
)
|
||||
assert processor.model_file_dir == "/models"
|
||||
|
||||
def test_model_file_dir_none_by_default(self):
|
||||
"""When model_file_dir is not provided, AudioProcessor gets None (remote mode)."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
)
|
||||
assert processor.model_file_dir is None
|
||||
|
||||
def test_presets_set_by_default(self):
|
||||
"""Ensemble presets are always set on the processor."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
model_file_dir="/models",
|
||||
)
|
||||
assert processor.instrumental_preset == "instrumental_clean"
|
||||
assert processor.karaoke_preset == "karaoke"
|
||||
|
||||
def test_custom_presets_override_defaults(self):
|
||||
"""Custom presets override the defaults."""
|
||||
processor = create_audio_processor(
|
||||
temp_dir="/tmp/test",
|
||||
model_file_dir="/models",
|
||||
instrumental_preset="instrumental_full",
|
||||
karaoke_preset="vocal_clean",
|
||||
)
|
||||
assert processor.instrumental_preset == "instrumental_full"
|
||||
assert processor.karaoke_preset == "vocal_clean"
|
||||
|
||||
|
||||
class TestProcessAudioSeparationMode:
|
||||
"""Tests for separation mode selection (remote API vs local GPU)."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.worker_registry")
|
||||
@patch("backend.workers.audio_worker.setup_job_logging")
|
||||
@patch("backend.workers.audio_worker.create_job_logger")
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
@patch("backend.workers.audio_worker.StorageService")
|
||||
@patch("backend.workers.audio_worker.get_settings")
|
||||
@patch("backend.workers.audio_worker.validate_worker_can_run", return_value=None)
|
||||
@patch("backend.workers.audio_worker.download_audio")
|
||||
@patch("backend.workers.audio_worker._store_audio_source_metadata")
|
||||
@patch("backend.workers.audio_worker.create_audio_processor")
|
||||
@patch("backend.workers.audio_worker.upload_separation_results", new_callable=AsyncMock)
|
||||
async def test_model_dir_enables_local_gpu(
|
||||
self,
|
||||
mock_upload,
|
||||
mock_create_processor,
|
||||
mock_store_metadata,
|
||||
mock_download,
|
||||
mock_validate,
|
||||
mock_settings,
|
||||
mock_storage,
|
||||
mock_job_manager_cls,
|
||||
mock_create_logger,
|
||||
mock_setup_logging,
|
||||
mock_registry,
|
||||
):
|
||||
"""When MODEL_DIR is set and AUDIO_SEPARATOR_API_URL is not, uses local GPU."""
|
||||
# Make async methods on the registry work properly
|
||||
mock_registry.register = AsyncMock()
|
||||
mock_registry.unregister = AsyncMock()
|
||||
|
||||
# Set up environment
|
||||
env = {k: v for k, v in os.environ.items()}
|
||||
env.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
env["MODEL_DIR"] = "/models"
|
||||
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
# Set up mocks
|
||||
mock_job = MagicMock()
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.url = None
|
||||
mock_job.input_media_gcs_path = "audio/test.wav"
|
||||
mock_job.clean_instrumental_model = None
|
||||
mock_job.backing_vocals_models = None
|
||||
mock_job.other_stems_models = None
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_job_manager_cls.return_value = mock_jm
|
||||
|
||||
mock_settings_obj = MagicMock()
|
||||
mock_settings_obj.gcs_bucket_name = "test-bucket"
|
||||
mock_settings.return_value = mock_settings_obj
|
||||
|
||||
mock_download.return_value = "/tmp/test.wav"
|
||||
mock_create_logger.return_value = MagicMock()
|
||||
|
||||
mock_processor = MagicMock()
|
||||
mock_processor.process_audio_separation.return_value = {
|
||||
"clean_instrumental": {"vocals": "/tmp/v.flac", "instrumental": "/tmp/i.flac"},
|
||||
"other_stems": {},
|
||||
"backing_vocals": {},
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
mock_create_processor.return_value = mock_processor
|
||||
|
||||
result = await process_audio_separation("test-job-id")
|
||||
|
||||
assert result is True
|
||||
# Verify model_file_dir="/models" was passed
|
||||
mock_create_processor.assert_called_once()
|
||||
call_kwargs = mock_create_processor.call_args[1]
|
||||
assert call_kwargs.get("model_file_dir") == "/models"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.worker_registry")
|
||||
@patch("backend.workers.audio_worker.setup_job_logging")
|
||||
@patch("backend.workers.audio_worker.create_job_logger")
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
@patch("backend.workers.audio_worker.StorageService")
|
||||
@patch("backend.workers.audio_worker.get_settings")
|
||||
@patch("backend.workers.audio_worker.validate_worker_can_run", return_value=None)
|
||||
async def test_no_api_url_no_model_dir_raises(
|
||||
self,
|
||||
mock_validate,
|
||||
mock_settings,
|
||||
mock_storage,
|
||||
mock_job_manager_cls,
|
||||
mock_create_logger,
|
||||
mock_setup_logging,
|
||||
mock_registry,
|
||||
):
|
||||
"""When neither AUDIO_SEPARATOR_API_URL nor MODEL_DIR is set, raises error."""
|
||||
# Make async methods on the registry work properly
|
||||
mock_registry.register = AsyncMock()
|
||||
mock_registry.unregister = AsyncMock()
|
||||
|
||||
env = {k: v for k, v in os.environ.items()}
|
||||
env.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
env.pop("MODEL_DIR", None)
|
||||
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
mock_job = MagicMock()
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.url = None
|
||||
mock_job.input_media_gcs_path = "audio/test.wav"
|
||||
mock_job.clean_instrumental_model = None
|
||||
mock_job.backing_vocals_models = None
|
||||
mock_job.other_stems_models = None
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_job_manager_cls.return_value = mock_jm
|
||||
|
||||
mock_settings_obj = MagicMock()
|
||||
mock_settings_obj.gcs_bucket_name = "test-bucket"
|
||||
mock_settings.return_value = mock_settings_obj
|
||||
mock_create_logger.return_value = MagicMock()
|
||||
|
||||
# Should fail because no separation mode is configured
|
||||
result = await process_audio_separation("test-job-id")
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestLocalSeparationWithPresets:
|
||||
"""Tests for local audio separation using ensemble presets."""
|
||||
|
||||
def setup_method(self):
|
||||
self.processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.DEBUG,
|
||||
log_formatter=None,
|
||||
model_file_dir="/models",
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
self.processor.instrumental_preset = "instrumental_clean"
|
||||
self.processor.karaoke_preset = "karaoke"
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_local_separation_uses_ensemble_preset_for_stage1(self, mock_separator_cls, mock_shutil):
|
||||
"""Stage 1 uses instrumental_preset on the Separator constructor."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
|
||||
# Disable karaoke_preset so stage 2 is skipped, isolating stage 1
|
||||
self.processor.karaoke_preset = None
|
||||
self.processor.backing_vocals_models = []
|
||||
|
||||
# Use realistic ensemble preset filenames
|
||||
stems_dir = "/tmp/stems"
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = [
|
||||
f"{stems_dir}/Song_(Vocals)_preset_instrumental_clean.flac",
|
||||
f"{stems_dir}/Song_(Instrumental)_preset_instrumental_clean.flac",
|
||||
]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
mock_shutil.move.side_effect = lambda src, dst: dst
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Title", "/tmp/output"
|
||||
)
|
||||
|
||||
# Verify Separator was constructed with ensemble_preset="instrumental_clean"
|
||||
mock_separator_cls.assert_called_once()
|
||||
constructor_kwargs = mock_separator_cls.call_args[1]
|
||||
assert constructor_kwargs.get("ensemble_preset") == "instrumental_clean"
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_local_separation_uses_karaoke_preset_for_stage2(self, mock_separator_cls, mock_shutil):
|
||||
"""Stage 2 uses karaoke_preset on a fresh Separator for BV separation."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
|
||||
stems_dir = "/tmp/stems"
|
||||
|
||||
# Stage 1 output
|
||||
s1_vocals = f"{stems_dir}/Song_(Vocals)_preset_instrumental_clean.flac"
|
||||
s1_instrumental = f"{stems_dir}/Song_(Instrumental)_preset_instrumental_clean.flac"
|
||||
# Stage 2 output (uses clean-named input)
|
||||
s2_lead = f"{stems_dir}/Artist - Title (Vocals)_(Vocals)_preset_karaoke.flac"
|
||||
s2_backing = f"{stems_dir}/Artist - Title (Vocals)_(No Vocal)_preset_karaoke.flac"
|
||||
|
||||
mock_sep1 = MagicMock()
|
||||
mock_sep1.separate.return_value = [s1_vocals, s1_instrumental]
|
||||
mock_sep2 = MagicMock()
|
||||
mock_sep2.separate.return_value = [s2_lead, s2_backing]
|
||||
mock_separator_cls.side_effect = [mock_sep1, mock_sep2]
|
||||
mock_shutil.move.side_effect = lambda src, dst: dst
|
||||
mock_shutil.copy2 = MagicMock()
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Title", "/tmp/output"
|
||||
)
|
||||
|
||||
# Separator should be instantiated twice: once for stage 1, once for stage 2
|
||||
assert mock_separator_cls.call_count == 2
|
||||
stage2_kwargs = mock_separator_cls.call_args_list[1][1]
|
||||
assert stage2_kwargs.get("ensemble_preset") == "karaoke"
|
||||
|
||||
|
||||
class TestEnsembleStemTagParsing:
|
||||
"""Tests for stem tag extraction from ensemble preset output filenames.
|
||||
|
||||
Ensemble presets produce files named: {base}_(StemTag)_preset_{name}.flac
|
||||
The parser must identify the StemTag (between _( and )_) and NOT be confused
|
||||
by the preset name (e.g., "instrumental_clean" contains "instrumental").
|
||||
"""
|
||||
|
||||
def setup_method(self):
|
||||
self.processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.DEBUG,
|
||||
log_formatter=None,
|
||||
model_file_dir="/models",
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||
backing_vocals_models=["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
self.processor.instrumental_preset = "instrumental_clean"
|
||||
self.processor.karaoke_preset = "karaoke"
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_stage1_instrumental_clean_preset_classifies_vocals_correctly(
|
||||
self, mock_separator_cls, mock_shutil
|
||||
):
|
||||
"""Regression: preset name 'instrumental_clean' must not cause Vocals file
|
||||
to be classified as instrumental (the old substring match bug)."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
|
||||
# Disable stage 2 to isolate stage 1
|
||||
self.processor.karaoke_preset = None
|
||||
self.processor.backing_vocals_models = []
|
||||
|
||||
# Realistic filenames from instrumental_clean ensemble preset
|
||||
stems_dir = "/tmp/stems"
|
||||
vocals_file = f"{stems_dir}/Song_(Vocals)_preset_instrumental_clean.flac"
|
||||
instrumental_file = f"{stems_dir}/Song_(Instrumental)_preset_instrumental_clean.flac"
|
||||
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = [vocals_file, instrumental_file]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
|
||||
# shutil.move returns the destination path
|
||||
mock_shutil.move.side_effect = lambda src, dst: dst
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
result = self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Song", "/tmp/output"
|
||||
)
|
||||
|
||||
# Vocals must be set (this is what the bug prevented)
|
||||
assert result["clean_instrumental"]["vocals"] == vocals_file
|
||||
# Instrumental must also be set
|
||||
assert result["clean_instrumental"]["instrumental"] is not None
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_stage1_vocals_path_enables_stage2(self, mock_separator_cls, mock_shutil):
|
||||
"""When Stage 1 correctly identifies vocals, Stage 2 runs and produces
|
||||
backing vocals + lead vocals stems."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
|
||||
stems_dir = "/tmp/stems"
|
||||
|
||||
# Stage 1 output (instrumental_clean preset)
|
||||
s1_vocals = f"{stems_dir}/Song_(Vocals)_preset_instrumental_clean.flac"
|
||||
s1_instrumental = f"{stems_dir}/Song_(Instrumental)_preset_instrumental_clean.flac"
|
||||
|
||||
# Stage 2 output uses the RENAMED clean input, so filenames don't have
|
||||
# nested stem tags (this is the fix for the regex collision bug)
|
||||
s2_lead = f"{stems_dir}/Artist - Song (Vocals)_(Vocals)_preset_karaoke.flac"
|
||||
s2_backing = f"{stems_dir}/Artist - Song (Vocals)_(No Vocal)_preset_karaoke.flac"
|
||||
|
||||
mock_sep1 = MagicMock()
|
||||
mock_sep1.separate.return_value = [s1_vocals, s1_instrumental]
|
||||
mock_sep2 = MagicMock()
|
||||
mock_sep2.separate.return_value = [s2_lead, s2_backing]
|
||||
mock_separator_cls.side_effect = [mock_sep1, mock_sep2]
|
||||
|
||||
mock_shutil.move.side_effect = lambda src, dst: dst
|
||||
mock_shutil.copy2 = MagicMock() # For the vocals rename
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
result = self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Song", "/tmp/output"
|
||||
)
|
||||
|
||||
# Stage 2 should have run (Separator instantiated twice)
|
||||
assert mock_separator_cls.call_count == 2
|
||||
|
||||
# Vocals file should have been copied to a clean name for Stage 2
|
||||
mock_shutil.copy2.assert_called_once()
|
||||
copy_dest = mock_shutil.copy2.call_args[0][1]
|
||||
assert "_(Vocals)_preset_instrumental_clean" not in copy_dest
|
||||
assert "Artist - Song (Vocals).flac" in copy_dest
|
||||
|
||||
# Stage 2 separator should receive the clean-named file
|
||||
stage2_input = mock_sep2.separate.call_args[0][0]
|
||||
assert "_(Vocals)_preset_instrumental_clean" not in stage2_input
|
||||
|
||||
# Backing vocals correctly classified
|
||||
bv = result["backing_vocals"]["karaoke"]
|
||||
assert bv["lead_vocals"] == s2_lead
|
||||
assert bv["backing_vocals"] == s2_backing
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_stage1_no_vocal_tag_recognized(self, mock_separator_cls, mock_shutil):
|
||||
"""Files with '(No Vocal)' stem tag are correctly classified as instrumental."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
self.processor.karaoke_preset = None
|
||||
self.processor.backing_vocals_models = []
|
||||
|
||||
stems_dir = "/tmp/stems"
|
||||
vocals_file = f"{stems_dir}/Song_(Vocals)_preset_instrumental_clean.flac"
|
||||
no_vocal_file = f"{stems_dir}/Song_(No Vocal)_preset_instrumental_clean.flac"
|
||||
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = [vocals_file, no_vocal_file]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
mock_shutil.move.side_effect = lambda src, dst: dst
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
result = self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Song", "/tmp/output"
|
||||
)
|
||||
|
||||
assert result["clean_instrumental"]["vocals"] == vocals_file
|
||||
assert result["clean_instrumental"]["instrumental"] is not None
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_unrecognized_stem_tag_logs_warning(self, mock_separator_cls, mock_shutil):
|
||||
"""Files with unrecognized stem tags produce a warning log."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
self.processor.karaoke_preset = None
|
||||
self.processor.backing_vocals_models = []
|
||||
|
||||
stems_dir = "/tmp/stems"
|
||||
weird_file = f"{stems_dir}/Song_(Drums)_preset_instrumental_clean.flac"
|
||||
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = [weird_file]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
with patch.object(self.processor.logger, 'warning') as mock_warn:
|
||||
result = self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Song", "/tmp/output"
|
||||
)
|
||||
|
||||
mock_warn.assert_called_once()
|
||||
assert "drums" in mock_warn.call_args[0][0].lower()
|
||||
|
||||
@patch.dict(os.environ, {}, clear=False)
|
||||
@patch("karaoke_gen.audio_processor.shutil")
|
||||
@patch("karaoke_gen.audio_processor.Separator")
|
||||
def test_filename_without_stem_tag_pattern_logs_warning(self, mock_separator_cls, mock_shutil):
|
||||
"""Files missing the _(Tag)_ pattern produce a warning."""
|
||||
os.environ.pop("AUDIO_SEPARATOR_API_URL", None)
|
||||
self.processor.karaoke_preset = None
|
||||
self.processor.backing_vocals_models = []
|
||||
|
||||
stems_dir = "/tmp/stems"
|
||||
plain_file = f"{stems_dir}/vocals.flac"
|
||||
|
||||
mock_sep = MagicMock()
|
||||
mock_sep.separate.return_value = [plain_file]
|
||||
mock_separator_cls.return_value = mock_sep
|
||||
|
||||
with patch.object(self.processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(self.processor, '_normalize_audio_files'):
|
||||
with patch.object(self.processor, '_generate_combined_instrumentals', return_value={}):
|
||||
with patch.object(self.processor.logger, 'warning') as mock_warn:
|
||||
result = self.processor.process_audio_separation(
|
||||
"/tmp/test.wav", "Artist - Song", "/tmp/output"
|
||||
)
|
||||
|
||||
mock_warn.assert_called_once()
|
||||
# Should not have classified anything
|
||||
assert result["clean_instrumental"].get("vocals") is None
|
||||
assert result["clean_instrumental"].get("instrumental") is None
|
||||
@@ -106,7 +106,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
|
||||
@patch.dict(os.environ, {}, clear=True) # Clear AUDIO_SEPARATOR_API_URL
|
||||
def test_local_fallback_when_no_env_var(self):
|
||||
"""Test that local processing is used when environment variable is not set."""
|
||||
with patch('audio_separator.separator.Separator') as mock_separator_class:
|
||||
with patch('karaoke_gen.audio_processor.Separator') as mock_separator_class:
|
||||
mock_separator = MagicMock()
|
||||
mock_separator_class.return_value = mock_separator
|
||||
mock_separator.separate.return_value = []
|
||||
@@ -139,7 +139,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
|
||||
@patch('karaoke_gen.audio_processor.REMOTE_API_AVAILABLE', False)
|
||||
def test_local_fallback_when_remote_unavailable(self):
|
||||
"""Test that local processing is used when remote API is unavailable."""
|
||||
with patch('audio_separator.separator.Separator') as mock_separator_class:
|
||||
with patch('karaoke_gen.audio_processor.Separator') as mock_separator_class:
|
||||
mock_separator = MagicMock()
|
||||
mock_separator_class.return_value = mock_separator
|
||||
mock_separator.separate.return_value = []
|
||||
@@ -179,7 +179,7 @@ class TestRemoteAudioSeparation(unittest.TestCase):
|
||||
# Mock API failure
|
||||
mock_client.separate_audio_and_wait.side_effect = Exception("API Error")
|
||||
|
||||
with patch('audio_separator.separator.Separator') as mock_separator_class:
|
||||
with patch('karaoke_gen.audio_processor.Separator') as mock_separator_class:
|
||||
mock_separator = MagicMock()
|
||||
mock_separator_class.return_value = mock_separator
|
||||
mock_separator.separate.return_value = []
|
||||
|
||||
Reference in new issue
Block a user