mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
No files matched your search
+181
-23
@@ -902,6 +902,22 @@ jobs:
|
||||
# - / (main app)
|
||||
# - /app/jobs/{id}/lyrics (lyrics review)
|
||||
# - /app/jobs/{id}/instrumental (instrumental review)
|
||||
- name: Capture build metadata
|
||||
id: frontend-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
|
||||
if [ -n "$PR_NUM" ]; then
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
else
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
@@ -911,6 +927,10 @@ jobs:
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
|
||||
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
|
||||
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
|
||||
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy consumer to Cloudflare Pages
|
||||
@@ -929,6 +949,10 @@ jobs:
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_TENANT_PORTAL: "true"
|
||||
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
|
||||
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
|
||||
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
|
||||
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy tenant portal to Cloudflare Pages
|
||||
@@ -959,6 +983,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: |
|
||||
@@ -1003,6 +1032,23 @@ jobs:
|
||||
echo "📋 Current version: $VERSION"
|
||||
echo "🚀 Deploying on every push to main"
|
||||
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
# For squash-merge commits, PR number is in the commit message as (#NNN)
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
|
||||
if [ -n "$PR_NUM" ]; then
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
else
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Authenticate to Google Cloud (Workload Identity)
|
||||
id: auth
|
||||
uses: google-github-actions/auth@v2
|
||||
@@ -1181,24 +1227,37 @@ jobs:
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
|
||||
|
||||
echo "Uploading test assets to GCS..."
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
|
||||
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
|
||||
"${DEPLOY_TEST_PATH}/test-preview.ass"
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
|
||||
"${DEPLOY_TEST_PATH}/test-audio.flac"
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
|
||||
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
-H "X-API-Key: $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"job_id": "deploy-health-check",
|
||||
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
|
||||
"duration_seconds": 10
|
||||
}')
|
||||
-d "{
|
||||
\"job_id\": \"deploy-health-check\",
|
||||
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
|
||||
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
|
||||
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
|
||||
}") || HTTP_CODE="000"
|
||||
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
|
||||
|
||||
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
|
||||
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
|
||||
echo "::error::Encode request failed with HTTP $HTTP_CODE"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Encode response: $RESPONSE"
|
||||
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
|
||||
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; then
|
||||
echo "::error::Encode test failed with status: $STATUS"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
@@ -1206,11 +1265,11 @@ jobs:
|
||||
|
||||
for i in $(seq 1 12); do
|
||||
sleep 5
|
||||
JOB_STATUS=$(curl -sf \
|
||||
JOB_STATUS=$(curl -s \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
|
||||
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
|
||||
echo "Encode status: $JOB_STATUS (attempt $i/12)"
|
||||
if [ "$JOB_STATUS" = "completed" ]; then
|
||||
if [ "$JOB_STATUS" = "complete" ]; then
|
||||
echo "Encode test passed!"
|
||||
echo "passed=true" >> $GITHUB_OUTPUT
|
||||
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
|
||||
@@ -1227,7 +1286,7 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
@@ -1319,7 +1378,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
|
||||
@@ -1438,6 +1499,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
|
||||
# ============================================
|
||||
@@ -1456,33 +1599,48 @@ jobs:
|
||||
--region us-central1 \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
--memory 16Gi \
|
||||
--cpu 8 \
|
||||
--memory 2Gi \
|
||||
--cpu 2 \
|
||||
--cpu-boost \
|
||||
--no-cpu-throttling \
|
||||
--cpu-throttling \
|
||||
--execution-environment gen2 \
|
||||
--timeout 1800 \
|
||||
--concurrency 1 \
|
||||
--max-instances 50 \
|
||||
--min-instances 4 \
|
||||
--concurrency 80 \
|
||||
--max-instances 20 \
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://audio-separator-718638054799.us-east4.run.app,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,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,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}"
|
||||
@@ -5,10 +5,12 @@ import os
|
||||
import logging
|
||||
import subprocess
|
||||
import platform
|
||||
from fastapi import APIRouter
|
||||
from typing import Dict, Any, Optional
|
||||
from fastapi import APIRouter, Depends
|
||||
from typing import Dict, Any, Optional, Tuple
|
||||
|
||||
from backend.version import VERSION
|
||||
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
|
||||
from backend.api.dependencies import optional_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.flacfetch_client import get_flacfetch_client
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
@@ -308,6 +310,30 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def check_audio_separator_status() -> Dict[str, Any]:
|
||||
"""Check audio separator availability without calling the remote GPU service."""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -341,6 +367,118 @@ async def audio_separator_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _get_encoding_worker_manager():
|
||||
"""Get the EncodingWorkerManager instance. Separated for testability."""
|
||||
try:
|
||||
encoding_service = get_encoding_service()
|
||||
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
|
||||
return encoding_service._worker_manager
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/health/system-status")
|
||||
async def system_status(
|
||||
auth: Optional[Tuple] = Depends(optional_auth),
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Aggregated system status for all services.
|
||||
|
||||
Returns basic info for everyone. Admin users get additional
|
||||
blue-green deployment details for the encoder.
|
||||
"""
|
||||
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
|
||||
|
||||
# Fetch all health statuses concurrently
|
||||
import asyncio
|
||||
encoding_task = check_encoding_worker_status()
|
||||
flacfetch_task = check_flacfetch_service_status()
|
||||
encoding_status, flacfetch_status = await asyncio.gather(
|
||||
encoding_task, flacfetch_task
|
||||
)
|
||||
separator_status = check_audio_separator_status()
|
||||
|
||||
# Build frontend service info (from env vars baked at build time — returned as-is)
|
||||
frontend_svc = {
|
||||
"status": "ok",
|
||||
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
|
||||
}
|
||||
|
||||
# Build backend service info
|
||||
backend_svc = {
|
||||
"status": "ok",
|
||||
"version": VERSION,
|
||||
"deployed_at": STARTUP_TIME,
|
||||
}
|
||||
if COMMIT_SHA:
|
||||
backend_svc["commit_sha"] = COMMIT_SHA
|
||||
if PR_NUMBER:
|
||||
backend_svc["pr_number"] = PR_NUMBER
|
||||
if PR_TITLE:
|
||||
backend_svc["pr_title"] = PR_TITLE
|
||||
|
||||
# Build encoder service info
|
||||
encoder_svc = {
|
||||
"status": "ok" if encoding_status.get("available") else "offline",
|
||||
"version": encoding_status.get("wheel_version"),
|
||||
"active_jobs": encoding_status.get("active_jobs", 0),
|
||||
}
|
||||
|
||||
# Build flacfetch service info
|
||||
flacfetch_svc = {
|
||||
"status": "ok" if flacfetch_status.get("available") else "offline",
|
||||
"version": flacfetch_status.get("version"),
|
||||
}
|
||||
|
||||
# Build separator service info
|
||||
separator_svc = {
|
||||
"status": "ok" if separator_status.get("available") else "offline",
|
||||
"version": separator_status.get("version"),
|
||||
}
|
||||
|
||||
# Admin-only: blue-green encoder details from Firestore
|
||||
if is_admin:
|
||||
manager = _get_encoding_worker_manager()
|
||||
if manager:
|
||||
try:
|
||||
config = manager.get_config()
|
||||
encoder_svc["admin_details"] = {
|
||||
"primary_vm": config.primary_vm,
|
||||
"primary_ip": config.primary_ip,
|
||||
"primary_version": config.primary_version,
|
||||
"primary_deployed_at": config.primary_deployed_at,
|
||||
"secondary_vm": config.secondary_vm,
|
||||
"secondary_ip": config.secondary_ip,
|
||||
"secondary_version": config.secondary_version,
|
||||
"secondary_deployed_at": config.secondary_deployed_at,
|
||||
"last_swap_at": config.last_swap_at,
|
||||
"deploy_in_progress": config.deploy_in_progress,
|
||||
"active_jobs": encoding_status.get("active_jobs", 0),
|
||||
"queue_length": encoding_status.get("queue_length", 0),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get blue-green config: {e}")
|
||||
|
||||
# Add error details for offline services
|
||||
if not flacfetch_status.get("available"):
|
||||
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
|
||||
if not separator_status.get("available"):
|
||||
separator_svc["admin_details"] = {"error": separator_status.get("error")}
|
||||
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
|
||||
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
|
||||
|
||||
return {
|
||||
"services": {
|
||||
"frontend": frontend_svc,
|
||||
"backend": backend_svc,
|
||||
"encoder": encoder_svc,
|
||||
"flacfetch": flacfetch_svc,
|
||||
"separator": separator_svc,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
+71
-24
@@ -519,7 +519,7 @@ _SUMMARY_STATE_DATA_KEYS = {
|
||||
'backing_vocals_analysis', 'visibility_change_in_progress',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
|
||||
|
||||
|
||||
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
@@ -538,6 +538,21 @@ def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[str, Any]]:
|
||||
"""Filter job dicts by case-insensitive substring match across key fields."""
|
||||
if not search:
|
||||
return jobs
|
||||
term = search.lower()
|
||||
results = []
|
||||
for job in jobs:
|
||||
searchable = " ".join(
|
||||
str(job.get(f) or "") for f in ("job_id", "artist", "title", "audio_search_artist", "audio_search_title")
|
||||
)
|
||||
if term in searchable.lower():
|
||||
results.append(job)
|
||||
return results
|
||||
|
||||
|
||||
@router.get("", response_model=None)
|
||||
async def list_jobs(
|
||||
request: Request,
|
||||
@@ -550,6 +565,7 @@ async def list_jobs(
|
||||
limit: int = 100,
|
||||
fields: Optional[str] = None,
|
||||
hide_completed: bool = False,
|
||||
search: Optional[str] = None,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -568,6 +584,7 @@ async def list_jobs(
|
||||
limit: Maximum number of jobs to return (default 100)
|
||||
fields: Set to "summary" for reduced payload with only dashboard-required fields
|
||||
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
|
||||
search: Text search filter - matches against artist, title, audio_search_artist, audio_search_title, and job_id (case-insensitive substring). Only works with fields=summary.
|
||||
|
||||
Returns:
|
||||
List of jobs matching filters, ordered by created_at descending.
|
||||
@@ -615,6 +632,8 @@ async def list_jobs(
|
||||
# --- Summary mode: field-projected query returning dicts ---
|
||||
if fields == "summary":
|
||||
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
|
||||
# When searching, fetch more results and filter in Python
|
||||
fetch_limit = 1000 if search else limit
|
||||
jobs_dicts = job_manager.list_jobs_summary(
|
||||
status=status,
|
||||
exclude_statuses=exclude_statuses,
|
||||
@@ -624,13 +643,18 @@ async def list_jobs(
|
||||
created_before=created_before_dt,
|
||||
user_email=user_email_filter,
|
||||
tenant_id=effective_tenant_id,
|
||||
limit=limit,
|
||||
limit=fetch_limit,
|
||||
)
|
||||
|
||||
# Exclude test user jobs (Python-side, same as full mode)
|
||||
if exclude_test and auth_result.is_admin:
|
||||
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
|
||||
|
||||
# Apply search filter if provided
|
||||
if search:
|
||||
jobs_dicts = _search_filter_jobs(jobs_dicts, search)
|
||||
jobs_dicts = jobs_dicts[:limit] # Apply original limit after filtering
|
||||
|
||||
# Safety-net pruning (in case Firestore returned extra nested keys)
|
||||
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
|
||||
|
||||
@@ -1423,18 +1447,12 @@ async def get_download_urls(
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
|
||||
if job.status != JobStatus.COMPLETE:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not complete (current status: {job.status})"
|
||||
)
|
||||
|
||||
file_urls = job.file_urls or {}
|
||||
download_urls = {}
|
||||
|
||||
|
||||
# Build download URLs using the streaming endpoint
|
||||
base_url = f"/api/jobs/{job_id}/download"
|
||||
|
||||
|
||||
for category, files in file_urls.items():
|
||||
if isinstance(files, dict):
|
||||
download_urls[category] = {}
|
||||
@@ -1444,7 +1462,7 @@ async def get_download_urls(
|
||||
elif isinstance(files, str) and files:
|
||||
# For single-file categories, use the category name as the file_key
|
||||
download_urls[category] = f"{base_url}/{category}/{category}"
|
||||
|
||||
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"artist": job.artist,
|
||||
@@ -1490,12 +1508,6 @@ async def download_file(
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
|
||||
if job.status != JobStatus.COMPLETE:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not complete (current status: {job.status})"
|
||||
)
|
||||
|
||||
file_urls = job.file_urls or {}
|
||||
category_files = file_urls.get(category)
|
||||
|
||||
@@ -1693,11 +1705,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 +1732,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
|
||||
|
||||
+163
-11
@@ -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
|
||||
@@ -331,12 +331,16 @@ async def complete_review(
|
||||
# (it's stored separately in state_data)
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Save updated corrections to GCS
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, corrections_to_save)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
|
||||
logger.info(f"Job {job_id}: Saved updated corrections")
|
||||
# Only write corrections_updated.json if there's actual correction data.
|
||||
# Writing an empty dict causes KeyError downstream when render workers
|
||||
# try to access updated_data["corrections"].
|
||||
if corrections_to_save and "corrections" in corrections_to_save:
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, corrections_to_save)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
logger.info(f"Job {job_id}: Saved updated corrections")
|
||||
else:
|
||||
logger.info(f"Job {job_id}: No corrections data in request, skipping corrections_updated.json")
|
||||
|
||||
# === Store instrumental selection in state_data ===
|
||||
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
|
||||
@@ -427,8 +431,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 +471,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 +508,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,
|
||||
@@ -870,7 +1022,7 @@ async def get_instrumental_analysis(
|
||||
"has_audible_content": backing_analysis.get('has_audible_content', False),
|
||||
"total_duration_seconds": backing_analysis.get('total_duration_seconds', 0),
|
||||
"audible_segments": backing_analysis.get('audible_segments', []),
|
||||
"recommended_selection": backing_analysis.get('recommended_selection', 'with_backing'),
|
||||
"recommended_selection": backing_analysis.get('recommended_selection', 'clean'),
|
||||
"total_audible_duration_seconds": backing_analysis.get('total_audible_duration_seconds', 0),
|
||||
"audible_percentage": backing_analysis.get('audible_percentage', 0),
|
||||
"silence_threshold_db": backing_analysis.get('silence_threshold_db', -40),
|
||||
|
||||
@@ -280,7 +280,8 @@ async def send_magic_link(
|
||||
# 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:
|
||||
# Skip for test emails — they get auto-granted without evaluation.
|
||||
if existing_user is None and not is_test_email(email):
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, 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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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}. "
|
||||
@@ -560,6 +584,116 @@ class EncodingService:
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def submit_render_video_job(
|
||||
self,
|
||||
job_id: str,
|
||||
render_config: Dict[str, Any],
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit a render-video job to the GCE worker.
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
render_config: Configuration dict containing original_corrections_gcs_path,
|
||||
audio_gcs_path, output_gcs_prefix, artist, title, and any other render params.
|
||||
|
||||
Returns:
|
||||
Response from the encoding worker
|
||||
|
||||
Raises:
|
||||
RuntimeError: If submission fails
|
||||
"""
|
||||
self._load_credentials()
|
||||
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._get_worker_url()}/render-video"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {"job_id": job_id, **render_config}
|
||||
|
||||
logger.info(f"[job:{job_id}] Submitting render-video job to GCE worker: {url}")
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
method="POST",
|
||||
url=url,
|
||||
headers=headers,
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
# Job already exists on worker — check if it already completed
|
||||
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
job_status = status.get("status", "unknown")
|
||||
if job_status == "complete":
|
||||
logger.info(f"[job:{job_id}] Render-video job already complete on GCE worker, returning cached result")
|
||||
return {
|
||||
"status": "cached",
|
||||
"job_id": job_id,
|
||||
"output_files": status.get("output_files"),
|
||||
"metadata": status.get("metadata"),
|
||||
}
|
||||
elif job_status in ("pending", "running"):
|
||||
logger.info(f"[job:{job_id}] Render-video job still in progress on GCE worker")
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
else:
|
||||
raise RuntimeError(f"Render-video job {job_id} already exists with status: {job_status}")
|
||||
except RuntimeError as e:
|
||||
if "not found" in str(e).lower():
|
||||
raise RuntimeError(f"Render-video job {job_id} conflict: 409 but job not found on status check")
|
||||
raise
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit render-video job: {resp['status']} - {resp['text']}")
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def render_video_on_gce(
|
||||
self,
|
||||
job_id: str,
|
||||
render_config: Dict[str, Any],
|
||||
progress_callback=None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit render-video job and wait for completion.
|
||||
|
||||
This is a convenience method that combines submit + wait.
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
render_config: Configuration dict for the render-video worker endpoint
|
||||
progress_callback: Optional callback for progress updates
|
||||
|
||||
Returns:
|
||||
Final job status with output files and metadata
|
||||
"""
|
||||
# Submit the job
|
||||
submit_result = await self.submit_render_video_job(job_id, render_config)
|
||||
|
||||
# If cached, return immediately — rendering already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
|
||||
return {
|
||||
"status": "complete",
|
||||
"output_files": submit_result.get("output_files"),
|
||||
"metadata": submit_result.get("metadata"),
|
||||
}
|
||||
|
||||
# If in_progress, another request is rendering it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Check the health of the encoding worker.
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import asyncio
|
||||
import glob as glob_module
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -59,12 +61,27 @@ class EncodePreviewRequest(BaseModel):
|
||||
font_gcs_path: Optional[str] = None # gs://bucket/path/to/custom-font.ttf
|
||||
|
||||
|
||||
class RenderVideoRequest(BaseModel):
|
||||
job_id: str
|
||||
original_corrections_gcs_path: str
|
||||
updated_corrections_gcs_path: Optional[str] = None
|
||||
audio_gcs_path: str
|
||||
style_params_gcs_path: Optional[str] = None
|
||||
style_assets: Optional[dict] = None
|
||||
output_gcs_prefix: str
|
||||
artist: str
|
||||
title: str
|
||||
subtitle_offset_ms: int = 0
|
||||
video_resolution: str = "4k"
|
||||
|
||||
|
||||
class JobStatus(BaseModel):
|
||||
job_id: str
|
||||
status: str # pending, running, complete, failed
|
||||
progress: int # 0-100
|
||||
error: Optional[str] = None
|
||||
output_files: Optional[list[str]] = None
|
||||
metadata: Optional[dict] = None
|
||||
|
||||
|
||||
def download_from_gcs(gcs_uri: str, local_path: Path):
|
||||
@@ -136,6 +153,59 @@ def upload_single_file_to_gcs(local_path: Path, gcs_uri: str):
|
||||
logger.info(f"Uploaded: {local_path} -> {gcs_uri}")
|
||||
|
||||
|
||||
# Style asset disk cache directory
|
||||
# Persists across jobs to avoid re-downloading the same theme assets (fonts, backgrounds)
|
||||
STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
|
||||
|
||||
|
||||
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
|
||||
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
|
||||
|
||||
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
|
||||
the cached file size against the GCS object size (via a lightweight metadata
|
||||
call). On size mismatch the stale entry is replaced.
|
||||
When cache_dir is None, downloads directly (no caching).
|
||||
"""
|
||||
if cache_dir is None:
|
||||
download_single_file_from_gcs(gcs_uri, local_path)
|
||||
return
|
||||
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_key = hashlib.sha256(gcs_uri.encode()).hexdigest()
|
||||
cached_path = cache_dir / cache_key
|
||||
|
||||
if cached_path.exists():
|
||||
# Validate cached file against GCS object size
|
||||
try:
|
||||
parts = gcs_uri.replace("gs://", "").split("/", 1)
|
||||
bucket_name = parts[0]
|
||||
blob_name = parts[1] if len(parts) > 1 else ""
|
||||
blob = storage_client.bucket(bucket_name).blob(blob_name)
|
||||
blob.reload() # Fetch metadata (lightweight HEAD request)
|
||||
gcs_size = blob.size
|
||||
|
||||
cached_size = cached_path.stat().st_size
|
||||
if gcs_size is not None and cached_size != gcs_size:
|
||||
logger.warning(
|
||||
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
|
||||
)
|
||||
cached_path.unlink()
|
||||
else:
|
||||
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
except Exception as e:
|
||||
# On transient GCS errors, serve from cache rather than failing the job
|
||||
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
|
||||
logger.info(f"Cache miss for {gcs_uri}, downloading...")
|
||||
download_single_file_from_gcs(gcs_uri, local_path)
|
||||
# Store in cache
|
||||
shutil.copy2(str(local_path), str(cached_path))
|
||||
|
||||
|
||||
def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewRequest"):
|
||||
# Run FFmpeg encoding for preview video (480x270, fast settings)
|
||||
jobs[job_id]["status"] = "running"
|
||||
@@ -239,6 +309,192 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
raise
|
||||
|
||||
|
||||
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
|
||||
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
|
||||
|
||||
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
|
||||
to produce with_vocals.mkv and subtitle files, then uploads results.
|
||||
Style assets use disk cache to avoid repeated downloads of the same theme.
|
||||
|
||||
This mirrors the logic in render_video_worker.py but runs on the GCE VM
|
||||
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
|
||||
"""
|
||||
jobs[job_id]["status"] = "running"
|
||||
jobs[job_id]["progress"] = 5
|
||||
|
||||
try:
|
||||
# Import from installed karaoke-gen wheel
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
# 1. Download original corrections
|
||||
corrections_path = work_dir / "corrections.json"
|
||||
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
|
||||
jobs[job_id]["progress"] = 15
|
||||
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 2. Apply user corrections if available
|
||||
if request.updated_corrections_gcs_path:
|
||||
updated_path = work_dir / "corrections_updated.json"
|
||||
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
if isinstance(updated_data, dict) and "corrections" in updated_data:
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
logger.info(f"[job:{job_id}] Applied user corrections")
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
|
||||
correction_result = base_result
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
audio_path = work_dir / "audio.flac"
|
||||
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
|
||||
jobs[job_id]["progress"] = 35
|
||||
|
||||
# 4. Process countdown intro
|
||||
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
|
||||
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=str(audio_path),
|
||||
)
|
||||
audio_path = Path(audio_path_str)
|
||||
jobs[job_id]["progress"] = 40
|
||||
|
||||
# 5. Download style assets (with disk cache for repeated themes)
|
||||
def cached_download(gcs_path, local_path):
|
||||
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=request.style_params_gcs_path,
|
||||
style_assets=request.style_assets,
|
||||
temp_dir=str(work_dir),
|
||||
download_func=cached_download,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Register any downloaded fonts with fontconfig
|
||||
for asset_key, gcs_path in (request.style_assets or {}).items():
|
||||
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
|
||||
fonts_dir = Path("/usr/local/share/fonts/custom")
|
||||
fonts_dir.mkdir(parents=True, exist_ok=True)
|
||||
font_filename = gcs_path.split("/")[-1]
|
||||
font_dest = fonts_dir / font_filename
|
||||
if not font_dest.exists():
|
||||
ext = os.path.splitext(gcs_path)[1]
|
||||
style_font = work_dir / "style" / f"{asset_key}{ext}"
|
||||
if style_font.exists():
|
||||
shutil.copy2(str(style_font), str(font_dest))
|
||||
subprocess.run(["fc-cache", "-fv"], capture_output=True)
|
||||
logger.info(f"Registered font: {font_filename}")
|
||||
|
||||
jobs[job_id]["progress"] = 50
|
||||
|
||||
# 6. Configure and run OutputGenerator
|
||||
output_dir = work_dir / "output"
|
||||
cache_dir = work_dir / "cache"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
cache_dir.mkdir(exist_ok=True)
|
||||
|
||||
config = OutputConfig(
|
||||
output_dir=str(output_dir),
|
||||
cache_dir=str(cache_dir),
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False,
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution=request.video_resolution,
|
||||
subtitle_offset_ms=request.subtitle_offset_ms,
|
||||
)
|
||||
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
|
||||
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
|
||||
output_prefix = f"{safe_artist} - {safe_title}"
|
||||
|
||||
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
|
||||
jobs[job_id]["progress"] = 55
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={},
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=str(audio_path),
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
)
|
||||
|
||||
jobs[job_id]["progress"] = 85
|
||||
|
||||
# 7. Upload outputs to GCS
|
||||
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
|
||||
output_files = []
|
||||
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
|
||||
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
|
||||
else:
|
||||
raise RuntimeError("Video generation failed - no output file produced")
|
||||
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
|
||||
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
|
||||
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
|
||||
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
jobs[job_id]["progress"] = 95
|
||||
jobs[job_id]["output_files"] = output_files
|
||||
jobs[job_id]["metadata"] = {
|
||||
"countdown_padding_added": padding_added,
|
||||
"countdown_padding_seconds": padding_seconds if padding_added else 0,
|
||||
}
|
||||
|
||||
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
|
||||
|
||||
except ImportError as e:
|
||||
error_msg = (
|
||||
f"OutputGenerator not available: {e}. "
|
||||
"The karaoke-gen wheel must be installed. "
|
||||
"Check that ensure_latest_wheel() succeeded."
|
||||
)
|
||||
logger.error(error_msg)
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = error_msg
|
||||
raise RuntimeError(error_msg) from e
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Render video failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
raise
|
||||
|
||||
|
||||
def ensure_latest_wheel():
|
||||
'''Download and install latest karaoke-gen wheel from GCS.
|
||||
|
||||
@@ -307,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
|
||||
return None
|
||||
|
||||
|
||||
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
|
||||
"""Generate a MOV video from a static PNG image using FFmpeg.
|
||||
|
||||
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
|
||||
encoding requires more memory than the right-sized Cloud Run container
|
||||
provides (2Gi). See PR #640 / #647.
|
||||
|
||||
Args:
|
||||
png_path: Path to input PNG image
|
||||
mov_path: Path for output MOV video
|
||||
duration: Video duration in seconds (default 5)
|
||||
|
||||
Returns:
|
||||
Path to generated MOV file
|
||||
|
||||
Raises:
|
||||
RuntimeError: If FFmpeg fails
|
||||
"""
|
||||
command = [
|
||||
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
|
||||
"-loop", "1", "-framerate", "30", "-i", str(png_path),
|
||||
"-f", "lavfi", "-i", "anullsrc",
|
||||
"-c:v", "libx264", "-r", "30", "-t", str(duration),
|
||||
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
|
||||
"-c:a", "aac", "-shortest",
|
||||
str(mov_path),
|
||||
]
|
||||
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
|
||||
if not mov_path.exists() or mov_path.stat().st_size < 1024:
|
||||
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
|
||||
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
|
||||
return mov_path
|
||||
|
||||
|
||||
def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
'''Run encoding using LocalEncodingService (single source of truth).
|
||||
|
||||
@@ -336,10 +629,36 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
logger.info(f"Encoding for: {base_name}")
|
||||
|
||||
# Find input files in work_dir
|
||||
# Title/end screens are in screens/ subdirectory
|
||||
# Title/end screens: look for MOV first, fall back to generating from PNG.
|
||||
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
|
||||
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
|
||||
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
|
||||
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
|
||||
|
||||
# Get intro/end video durations from style config (default 5s)
|
||||
intro_duration = config.get("intro_video_duration", 5)
|
||||
end_duration = config.get("end_video_duration", 5)
|
||||
|
||||
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
|
||||
if not title_video or title_video.stat().st_size < 1024:
|
||||
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
|
||||
if title_png:
|
||||
title_mov_path = title_png.parent / "title.mov"
|
||||
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
|
||||
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
|
||||
elif title_video:
|
||||
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Generate end MOV from PNG if missing or invalid
|
||||
if not end_video or (end_video and end_video.stat().st_size < 1024):
|
||||
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
|
||||
if end_png:
|
||||
end_mov_path = end_png.parent / "end.mov"
|
||||
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
|
||||
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
|
||||
elif end_video:
|
||||
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Karaoke video - search for With Vocals or main karaoke video
|
||||
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
|
||||
# old encoding outputs from finals/ directory when re-encoding after reset
|
||||
@@ -584,6 +903,36 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
jobs[job_id]["error"] = str(e)
|
||||
|
||||
|
||||
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
# Process a render-video job asynchronously
|
||||
try:
|
||||
# Download and install latest wheel at job start (allows hot updates without restart)
|
||||
ensure_latest_wheel()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
work_dir.mkdir()
|
||||
|
||||
# Run render-video in thread pool (CPU-bound)
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(
|
||||
executor,
|
||||
run_render_video,
|
||||
job_id,
|
||||
work_dir,
|
||||
request
|
||||
)
|
||||
|
||||
jobs[job_id]["status"] = "complete"
|
||||
jobs[job_id]["progress"] = 100
|
||||
logger.info(f"Render video job {job_id} complete")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Render video job {job_id} failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
|
||||
|
||||
@app.post("/encode-preview")
|
||||
async def submit_preview_encode_job(request: EncodePreviewRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
|
||||
# Submit a preview encoding job
|
||||
@@ -615,6 +964,37 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
|
||||
@app.post("/render-video")
|
||||
async def submit_render_video_job(request: RenderVideoRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
|
||||
# Submit a render-video job
|
||||
job_id = request.job_id
|
||||
|
||||
# If job already exists, return cached result or current status
|
||||
if job_id in jobs:
|
||||
existing_job = jobs[job_id]
|
||||
if existing_job["status"] == "complete":
|
||||
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files"), "metadata": existing_job.get("metadata")}
|
||||
elif existing_job["status"] == "failed":
|
||||
# Previous attempt failed, allow retry by replacing the job
|
||||
pass
|
||||
else:
|
||||
# Job is still in progress
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
|
||||
jobs[job_id] = {
|
||||
"job_id": job_id,
|
||||
"status": "pending",
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
"metadata": None,
|
||||
}
|
||||
|
||||
background_tasks.add_task(process_render_video_job, job_id, request)
|
||||
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
|
||||
@app.post("/encode")
|
||||
async def submit_encode_job(request: EncodeRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
|
||||
# Submit an encoding job
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -410,64 +410,70 @@ class UserService:
|
||||
if txn.reason == "welcome_credit":
|
||||
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,
|
||||
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"),
|
||||
# Skip AI evaluation for test emails (e.g. E2E test accounts)
|
||||
# to avoid wasting LLM credits and sending unnecessary denial emails
|
||||
from backend.utils.test_data import is_test_email
|
||||
if not is_test_email(email):
|
||||
# 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,
|
||||
CreditEvaluation,
|
||||
)
|
||||
else:
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
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
|
||||
self.update_user(email, welcome_credits_granted=True)
|
||||
logger.info(
|
||||
f"Denied welcome credits to {email}: {evaluation.reasoning}"
|
||||
)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_denied_email(email, "welcome")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send credit denied email to {email}")
|
||||
return False, "denied"
|
||||
if evaluation.decision == "deny":
|
||||
# Mark as evaluated but not granted so we don't re-evaluate
|
||||
self.update_user(email, welcome_credits_granted=True)
|
||||
logger.info(
|
||||
f"Denied welcome credits to {email}: {evaluation.reasoning}"
|
||||
)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_denied_email(email, "welcome")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send credit denied email to {email}")
|
||||
return False, "denied"
|
||||
|
||||
if evaluation.decision == "pending_review":
|
||||
# Don't mark welcome_credits_granted — allow retry after manual review
|
||||
logger.info(
|
||||
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
|
||||
)
|
||||
if evaluation.decision == "pending_review":
|
||||
# Don't mark welcome_credits_granted — allow retry after manual review
|
||||
logger.info(
|
||||
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
|
||||
)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_credit_review_needed_email(
|
||||
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send review needed email for {email}")
|
||||
return False, "pending_review"
|
||||
except Exception:
|
||||
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_credit_review_needed_email(
|
||||
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
|
||||
email, "welcome", f"Evaluation error: {email}",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send review needed email for {email}")
|
||||
pass
|
||||
return False, "pending_review"
|
||||
except Exception:
|
||||
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_credit_review_needed_email(
|
||||
email, "welcome", f"Evaluation error: {email}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, "pending_review"
|
||||
else:
|
||||
logger.info(f"Skipping credit evaluation for test email {email}")
|
||||
|
||||
# Grant welcome credits
|
||||
welcome_credit = self.NEW_USER_FREE_CREDITS
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -236,6 +236,30 @@ class TestGrantWelcomeCredits:
|
||||
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_evaluation_for_test_emails(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible skips AI evaluation for @inbox.testmail.app emails."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="e2e.test@inbox.testmail.app", 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("e2e.test@inbox.testmail.app")
|
||||
# AI evaluation should NOT have been called
|
||||
mock_eval.return_value.evaluate.assert_not_called()
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 2: Per-IP Signup Rate Limiting
|
||||
|
||||
@@ -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
|
||||
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
|
||||
# Metadata and original_segments preserved
|
||||
assert original_data['metadata']['preserved'] is True
|
||||
assert original_data['original_segments'][0]['id'] == 1
|
||||
|
||||
|
||||
class TestCompleteReviewSkipsEmptyCorrections:
|
||||
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
|
||||
|
||||
Bug scenario: Completing review via admin API without corrections payload writes
|
||||
an empty {} to corrections_updated.json. Downstream render workers then get
|
||||
KeyError: 'corrections' when processing it.
|
||||
"""
|
||||
|
||||
def test_no_corrections_key_skips_upload(self):
|
||||
"""When updated_data has only instrumental_selection, no corrections file is written."""
|
||||
# Simulate what the endpoint does with the corrections_to_save logic
|
||||
updated_data = {"instrumental_selection": "clean"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# This is the guard we added
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert not should_write, "Should not write corrections_updated.json for empty payload"
|
||||
|
||||
def test_with_corrections_key_allows_upload(self):
|
||||
"""When updated_data has corrections, the file should be written."""
|
||||
updated_data = {
|
||||
"corrections": [{"id": 1, "type": "edit"}],
|
||||
"corrected_segments": [{"id": 1, "text": "fixed"}],
|
||||
"instrumental_selection": "with_backing",
|
||||
}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert should_write, "Should write corrections_updated.json when corrections present"
|
||||
|
||||
def test_empty_dict_payload_skips_upload(self):
|
||||
"""When updated_data is effectively empty after removing instrumental_selection."""
|
||||
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Has content but no "corrections" key
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert not should_write, "Should not write without corrections key"
|
||||
|
||||
def test_render_worker_handles_empty_corrections_gracefully(self):
|
||||
"""Document that render workers skip empty corrections_updated.json.
|
||||
|
||||
Both GCE and Cloud Run workers now check for 'corrections' key
|
||||
before passing to CorrectionOperations.update_correction_result_with_data().
|
||||
"""
|
||||
# Simulates what the workers do on download
|
||||
empty_updated_data = {}
|
||||
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
|
||||
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
|
||||
|
||||
# Dict with irrelevant keys
|
||||
bad_updated_data = {"some_key": "value"}
|
||||
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
|
||||
assert not has_valid_corrections, "Dict without corrections key should not be valid"
|
||||
@@ -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)
|
||||
|
||||
@@ -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."""
|
||||
@@ -525,14 +558,14 @@ class TestSummaryEndpoint:
|
||||
assert list(result['file_urls'].keys()) == ['finals']
|
||||
|
||||
def test_hide_completed_statuses(self):
|
||||
"""Verify _HIDE_COMPLETED_STATUSES only hides successful completions (not failed/cancelled)."""
|
||||
"""Verify _HIDE_COMPLETED_STATUSES hides terminal statuses (not failed or active)."""
|
||||
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
|
||||
|
||||
assert 'complete' in _HIDE_COMPLETED_STATUSES
|
||||
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
|
||||
# Failed/cancelled should NOT be hidden - users need to see these
|
||||
assert 'cancelled' in _HIDE_COMPLETED_STATUSES
|
||||
# Failed should NOT be hidden - users need to see these
|
||||
assert 'failed' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'cancelled' not in _HIDE_COMPLETED_STATUSES
|
||||
# Active statuses should NOT be in the list
|
||||
assert 'pending' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
|
||||
@@ -703,3 +736,95 @@ class TestContentDispositionHeader:
|
||||
decoded = unquote(utf8_part)
|
||||
assert decoded == "周杰倫 - 青花瓷.mp4"
|
||||
|
||||
|
||||
class TestSearchFiltering:
|
||||
"""Tests for the search parameter on list_jobs summary mode."""
|
||||
|
||||
def _make_job_dict(self, job_id="job1", artist="Queen", title="Bohemian Rhapsody",
|
||||
audio_search_artist=None, audio_search_title=None, status="complete"):
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"audio_search_artist": audio_search_artist,
|
||||
"audio_search_title": audio_search_title,
|
||||
"status": status,
|
||||
"user_email": "admin@nomadkaraoke.com",
|
||||
}
|
||||
|
||||
def test_search_filters_by_artist(self):
|
||||
"""Search 'queen' should match job with artist='Queen'."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [
|
||||
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
|
||||
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
|
||||
]
|
||||
result = _search_filter_jobs(jobs, "queen")
|
||||
assert len(result) == 1
|
||||
assert result[0]["job_id"] == "j1"
|
||||
|
||||
def test_search_filters_by_title(self):
|
||||
"""Search 'california' should match job with title containing it."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [
|
||||
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
|
||||
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
|
||||
]
|
||||
result = _search_filter_jobs(jobs, "california")
|
||||
assert len(result) == 1
|
||||
assert result[0]["job_id"] == "j2"
|
||||
|
||||
def test_search_filters_by_job_id(self):
|
||||
"""Search by partial job_id."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [
|
||||
self._make_job_dict(job_id="abc-123-def"),
|
||||
self._make_job_dict(job_id="xyz-789-ghi"),
|
||||
]
|
||||
result = _search_filter_jobs(jobs, "abc-123")
|
||||
assert len(result) == 1
|
||||
assert result[0]["job_id"] == "abc-123-def"
|
||||
|
||||
def test_search_filters_by_audio_search_fields(self):
|
||||
"""Search should also check audio_search_artist and audio_search_title."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [
|
||||
self._make_job_dict(job_id="j1", artist="Display Name", title="Display Title",
|
||||
audio_search_artist="Original Artist", audio_search_title="Original Song"),
|
||||
]
|
||||
result = _search_filter_jobs(jobs, "original artist")
|
||||
assert len(result) == 1
|
||||
|
||||
def test_search_is_case_insensitive(self):
|
||||
"""Search should be case-insensitive."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [self._make_job_dict(artist="QUEEN", title="Bohemian Rhapsody")]
|
||||
result = _search_filter_jobs(jobs, "queen")
|
||||
assert len(result) == 1
|
||||
|
||||
def test_search_handles_none_fields(self):
|
||||
"""Search should not crash on None artist/title fields."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [self._make_job_dict(artist=None, title=None)]
|
||||
result = _search_filter_jobs(jobs, "queen")
|
||||
assert len(result) == 0
|
||||
|
||||
def test_search_empty_string_returns_all(self):
|
||||
"""Empty search string should return all jobs."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [
|
||||
self._make_job_dict(job_id="j1"),
|
||||
self._make_job_dict(job_id="j2"),
|
||||
]
|
||||
result = _search_filter_jobs(jobs, "")
|
||||
assert len(result) == 2
|
||||
|
||||
def test_search_returns_all_matches_for_limit_slicing(self):
|
||||
"""Search returns all matches — caller applies limit separately."""
|
||||
from backend.api.routes.jobs import _search_filter_jobs
|
||||
jobs = [self._make_job_dict(job_id=f"j{i}", artist="Queen", title=f"Song {i}") for i in range(10)]
|
||||
result = _search_filter_jobs(jobs, "queen")
|
||||
assert len(result) == 10 # All 10 match; limit slicing is caller's job
|
||||
# Verify caller can slice: simulates jobs_dicts[:limit] in route handler
|
||||
assert len(result[:3]) == 3
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Tests for the /api/health/system-status endpoint."""
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_encoding_status():
|
||||
return {
|
||||
"configured": True,
|
||||
"enabled": True,
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"active_jobs": 0,
|
||||
"queue_length": 0,
|
||||
"wheel_version": "0.155.3",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_flacfetch_status():
|
||||
return {
|
||||
"configured": True,
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": "0.19.1",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_separator_status():
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": "0.4.3",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_encoding_worker_config():
|
||||
"""Mock EncodingWorkerConfig dataclass."""
|
||||
config = MagicMock()
|
||||
config.primary_vm = "encoding-worker-b"
|
||||
config.primary_ip = "34.10.189.118"
|
||||
config.primary_version = "0.155.3"
|
||||
config.primary_deployed_at = "2026-03-31T18:10:00Z"
|
||||
config.secondary_vm = "encoding-worker-a"
|
||||
config.secondary_ip = "34.57.78.246"
|
||||
config.secondary_version = "0.155.2"
|
||||
config.secondary_deployed_at = "2026-03-29T14:00:00Z"
|
||||
config.last_swap_at = "2026-03-31T18:10:00Z"
|
||||
config.deploy_in_progress = False
|
||||
config.deploy_in_progress_since = None
|
||||
config.last_activity_at = None
|
||||
return config
|
||||
|
||||
|
||||
class TestSystemStatusPublic:
|
||||
"""Tests for unauthenticated /api/health/system-status."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_all_services(
|
||||
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status
|
||||
):
|
||||
from backend.api.routes.health import system_status
|
||||
|
||||
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
|
||||
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
|
||||
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
|
||||
patch("backend.api.routes.health.VERSION", "0.155.3"), \
|
||||
patch("backend.api.routes.health.COMMIT_SHA", "8e2a949a"), \
|
||||
patch("backend.api.routes.health.PR_NUMBER", "644"), \
|
||||
patch("backend.api.routes.health.PR_TITLE", "fix: blue-green deploy"), \
|
||||
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
|
||||
|
||||
result = await system_status(auth=None)
|
||||
|
||||
assert "services" in result
|
||||
services = result["services"]
|
||||
|
||||
# All 5 services present
|
||||
assert "frontend" in services
|
||||
assert "backend" in services
|
||||
assert "encoder" in services
|
||||
assert "flacfetch" in services
|
||||
assert "separator" in services
|
||||
|
||||
# Backend has build metadata
|
||||
backend_svc = services["backend"]
|
||||
assert backend_svc["version"] == "0.155.3"
|
||||
assert backend_svc["commit_sha"] == "8e2a949a"
|
||||
assert backend_svc["pr_number"] == "644"
|
||||
|
||||
# Encoder has status
|
||||
assert services["encoder"]["status"] == "ok"
|
||||
assert services["encoder"]["version"] == "0.155.3"
|
||||
|
||||
# No admin_details without auth
|
||||
assert "admin_details" not in services["encoder"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_offline_service(self, mock_flacfetch_status, mock_separator_status):
|
||||
from backend.api.routes.health import system_status
|
||||
|
||||
offline_encoding = {
|
||||
"configured": True,
|
||||
"enabled": True,
|
||||
"available": False,
|
||||
"error": "Connection refused",
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=offline_encoding), \
|
||||
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
|
||||
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
|
||||
patch("backend.api.routes.health.VERSION", "0.155.3"), \
|
||||
patch("backend.api.routes.health.COMMIT_SHA", ""), \
|
||||
patch("backend.api.routes.health.PR_NUMBER", ""), \
|
||||
patch("backend.api.routes.health.PR_TITLE", ""), \
|
||||
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
|
||||
|
||||
result = await system_status(auth=None)
|
||||
|
||||
assert result["services"]["encoder"]["status"] == "offline"
|
||||
|
||||
|
||||
class TestSystemStatusAdmin:
|
||||
"""Tests for admin-authenticated /api/health/system-status."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_gets_bluegreen_details(
|
||||
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
|
||||
):
|
||||
from backend.api.routes.health import system_status
|
||||
from backend.services.auth_service import UserType
|
||||
|
||||
mock_auth = ("token123", UserType.ADMIN, -1)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_config.return_value = mock_encoding_worker_config
|
||||
|
||||
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
|
||||
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
|
||||
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
|
||||
patch("backend.api.routes.health.VERSION", "0.155.3"), \
|
||||
patch("backend.api.routes.health.COMMIT_SHA", ""), \
|
||||
patch("backend.api.routes.health.PR_NUMBER", ""), \
|
||||
patch("backend.api.routes.health.PR_TITLE", ""), \
|
||||
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
|
||||
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
|
||||
|
||||
result = await system_status(auth=mock_auth)
|
||||
|
||||
encoder = result["services"]["encoder"]
|
||||
assert "admin_details" in encoder
|
||||
admin = encoder["admin_details"]
|
||||
assert admin["primary_vm"] == "encoding-worker-b"
|
||||
assert admin["secondary_vm"] == "encoding-worker-a"
|
||||
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
|
||||
assert admin["deploy_in_progress"] is False
|
||||
@@ -1256,6 +1256,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.file_urls = {'screens': {'title_png': 'jobs/test-123/screens/title.png', 'end_png': 'jobs/test-123/screens/end.png'}}
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
@@ -1269,7 +1270,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
assert config.title == "Test Title"
|
||||
assert config.enable_cdg is True
|
||||
assert config.enable_youtube_upload is True
|
||||
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).mov"
|
||||
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).png"
|
||||
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental Clean).flac"
|
||||
|
||||
def test_create_config_from_job_with_existing_instrumental(self):
|
||||
@@ -1290,6 +1291,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = "gs://bucket/instrumental.mp3"
|
||||
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
@@ -1329,6 +1331,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -25,3 +25,18 @@ def get_version() -> str:
|
||||
|
||||
|
||||
VERSION = get_version()
|
||||
|
||||
# Build metadata — set by CI during deployment
|
||||
COMMIT_SHA = os.environ.get("COMMIT_SHA", "")
|
||||
PR_NUMBER = os.environ.get("PR_NUMBER", "")
|
||||
PR_TITLE = os.environ.get("PR_TITLE", "")
|
||||
STARTUP_TIME = None # Set on first import
|
||||
|
||||
|
||||
def _get_startup_time() -> str:
|
||||
"""Record when the backend process started (proxy for deploy time)."""
|
||||
from datetime import datetime, timezone
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
STARTUP_TIME = _get_startup_time()
|
||||
@@ -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,6 +392,7 @@ 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)
|
||||
|
||||
@@ -397,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
|
||||
@@ -413,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,
|
||||
@@ -460,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'],
|
||||
@@ -469,6 +491,15 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
})
|
||||
job_manager.update_processing_metadata(job_id, "timing.audio_worker_seconds", round(duration, 1))
|
||||
|
||||
# Analyze backing vocals for instrumental selection recommendation
|
||||
# This must run here (after stems are uploaded) rather than in screens_worker,
|
||||
# because screens_worker triggers on lyrics completion and audio may not be done yet
|
||||
from backend.workers.screens_worker import _analyze_backing_vocals
|
||||
try:
|
||||
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Backing vocals analysis failed (non-fatal): {e}")
|
||||
|
||||
# Mark audio processing complete
|
||||
# This will check if lyrics are also complete and transition to next stage if so
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
@@ -801,7 +832,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")
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ from backend.services.job_health_service import validate_worker_can_run
|
||||
from backend.config import get_settings
|
||||
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
|
||||
from backend.services.tracing import job_span, add_span_event, add_span_attribute
|
||||
from backend.services.encoding_service import get_encoding_service
|
||||
|
||||
# Import from lyrics_transcriber (submodule)
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
@@ -119,259 +120,403 @@ async def process_render_video(job_id: str) -> bool:
|
||||
# This ensures logs from third-party libraries (lyrics_transcriber.output) are only
|
||||
# captured by this job's handler, not handlers from other concurrent jobs
|
||||
with job_logging_context(job_id):
|
||||
# Transition to RENDERING_VIDEO
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDERING_VIDEO,
|
||||
progress=75,
|
||||
message="Rendering karaoke video with corrected lyrics"
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
job_log.info(f"Created temp directory: {temp_dir}")
|
||||
|
||||
# Try updated corrections first (from human review), fall back to original
|
||||
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
|
||||
# Get GCS path from file_urls
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
if not corrections_url:
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
|
||||
if not corrections_url:
|
||||
# Try direct GCS paths
|
||||
if storage.file_exists(corrections_gcs_updated):
|
||||
corrections_gcs = corrections_gcs_updated
|
||||
elif storage.file_exists(corrections_gcs_original):
|
||||
corrections_gcs = corrections_gcs_original
|
||||
else:
|
||||
raise FileNotFoundError(f"No corrections file found for job {job_id}")
|
||||
else:
|
||||
# Extract GCS path from URL
|
||||
corrections_gcs = _extract_gcs_path(corrections_url)
|
||||
|
||||
# 2. Load the ORIGINAL corrections (has full structure)
|
||||
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
|
||||
|
||||
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
|
||||
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
|
||||
storage.download_file(original_corrections_gcs, original_corrections_path)
|
||||
|
||||
with open(original_corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 3. Load base CorrectionResult from original data
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
# Check if GCE encoding is enabled
|
||||
encoding_service = get_encoding_service()
|
||||
use_gce = encoding_service.is_enabled
|
||||
|
||||
# 4. Apply user corrections if available (from review UI)
|
||||
# Uses the same method as preview generation to ensure
|
||||
# identical CorrectionResult construction (DRY).
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
if use_gce:
|
||||
# ============ GCE RENDER VIDEO PATH ============
|
||||
job_log.info("GCE encoding enabled - delegating render_video to encoding worker")
|
||||
logger.info(f"[job:{job_id}] Using GCE encoding worker for render_video")
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, applying via shared method")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# 5. Download audio file
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
|
||||
if not audio_gcs_path:
|
||||
raise FileNotFoundError(f"No input audio path for job {job_id}")
|
||||
|
||||
job_log.info(f"Downloading audio from {audio_gcs_path}")
|
||||
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
|
||||
storage.download_file(audio_gcs_path, audio_path)
|
||||
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
|
||||
|
||||
# Process countdown intro if needed (for songs that start too quickly)
|
||||
# This adds "3... 2... 1..." segment and pads audio with 3s silence
|
||||
# Note: Countdown is deferred to this stage (not during lyrics transcription)
|
||||
# so the review UI can show the original timing without the 3s shift
|
||||
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
|
||||
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
# Transition to RENDERING_VIDEO
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDERING_VIDEO,
|
||||
progress=75,
|
||||
message="Rendering karaoke video on encoding worker"
|
||||
)
|
||||
if padding_added:
|
||||
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
|
||||
else:
|
||||
job_log.info("No countdown needed - song starts after 3 seconds")
|
||||
|
||||
# Update lyrics_metadata with countdown info so video_worker knows to pad instrumental
|
||||
# This is critical for audio sync - without this, instrumental won't match padded vocals
|
||||
# Build render config from job metadata (no downloads needed on Cloud Run!)
|
||||
bucket_name = settings.gcs_bucket_name
|
||||
|
||||
# Check for updated corrections
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
has_updated = storage.file_exists(updated_corrections_gcs)
|
||||
|
||||
render_config = {
|
||||
"original_corrections_gcs_path": f"gs://{bucket_name}/jobs/{job_id}/lyrics/corrections.json",
|
||||
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
|
||||
"output_gcs_prefix": f"gs://{bucket_name}/jobs/{job_id}/",
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"subtitle_offset_ms": getattr(job, 'subtitle_offset_ms', 0) or 0,
|
||||
"video_resolution": "4k",
|
||||
}
|
||||
|
||||
if has_updated:
|
||||
render_config["updated_corrections_gcs_path"] = f"gs://{bucket_name}/{updated_corrections_gcs}"
|
||||
|
||||
if job.style_params_gcs_path:
|
||||
render_config["style_params_gcs_path"] = f"gs://{bucket_name}/{job.style_params_gcs_path}" if not job.style_params_gcs_path.startswith("gs://") else job.style_params_gcs_path
|
||||
|
||||
if job.style_assets:
|
||||
render_config["style_assets"] = {
|
||||
k: f"gs://{bucket_name}/{v}" if not v.startswith("gs://") else v
|
||||
for k, v in job.style_assets.items()
|
||||
}
|
||||
|
||||
def progress_callback(progress: int):
|
||||
scaled = 75 + int(progress * 0.07) # Map 0-100 to 75-82
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDERING_VIDEO,
|
||||
progress=scaled,
|
||||
message=f"Rendering video ({progress}%)"
|
||||
)
|
||||
|
||||
with job_span("gce-render-video", job_id) as render_span:
|
||||
render_start = time.time()
|
||||
result = await encoding_service.render_video_on_gce(
|
||||
job_id, render_config, progress_callback=progress_callback
|
||||
)
|
||||
render_duration = time.time() - render_start
|
||||
render_span.set_attribute("duration_seconds", render_duration)
|
||||
|
||||
job_log.info(f"GCE render_video complete in {render_duration:.1f}s")
|
||||
logger.info(f"[job:{job_id}] GCE render_video complete in {render_duration:.1f}s")
|
||||
|
||||
# Parse response and update Firestore
|
||||
output_files = result.get("output_files", [])
|
||||
metadata = result.get("metadata", {})
|
||||
|
||||
# Update file URLs from GCE response
|
||||
for gcs_path in output_files:
|
||||
blob_path = gcs_path
|
||||
if blob_path.startswith("gs://"):
|
||||
blob_path = blob_path.split("/", 3)[3] if blob_path.count("/") >= 3 else blob_path
|
||||
if "with_vocals.mkv" in blob_path:
|
||||
job_manager.update_file_url(job_id, 'videos', 'with_vocals', blob_path)
|
||||
elif "karaoke.ass" in blob_path:
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'ass', blob_path)
|
||||
elif "karaoke.lrc" in blob_path:
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'lrc', blob_path)
|
||||
elif "corrected.txt" in blob_path:
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', blob_path)
|
||||
|
||||
# Handle countdown padding metadata
|
||||
padding_added = metadata.get("countdown_padding_added", False)
|
||||
padding_seconds = metadata.get("countdown_padding_seconds", 0)
|
||||
if padding_added:
|
||||
existing_lyrics_metadata = job.state_data.get('lyrics_metadata', {})
|
||||
existing_lyrics_metadata['has_countdown_padding'] = True
|
||||
existing_lyrics_metadata['countdown_padding_seconds'] = padding_seconds
|
||||
job_manager.update_state_data(job_id, 'lyrics_metadata', existing_lyrics_metadata)
|
||||
job_log.info(f"Updated lyrics_metadata: has_countdown_padding=True, countdown_padding_seconds={padding_seconds}")
|
||||
job_log.info(f"Countdown padding: {padding_seconds}s")
|
||||
|
||||
# 6. Get or create styles using the unified style loader
|
||||
job_log.info("Loading style configuration...")
|
||||
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
|
||||
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=job_log,
|
||||
)
|
||||
|
||||
# 7. Configure OutputGenerator
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
job_log.info(f"Using styles from: {styles_path}")
|
||||
|
||||
# Get subtitle offset from job (user-specified timing adjustment)
|
||||
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
|
||||
if subtitle_offset != 0:
|
||||
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
|
||||
|
||||
config = OutputConfig(
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False, # CDG optional, generated separately
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution="4k",
|
||||
subtitle_offset_ms=subtitle_offset
|
||||
)
|
||||
|
||||
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
|
||||
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
# 8. Generate outputs (video, LRC, ASS, etc.)
|
||||
# Sanitize artist/title to handle Unicode characters (curly quotes, em dashes, etc.)
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
output_prefix = f"{safe_artist} - {safe_title}"
|
||||
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
|
||||
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={}, # Reference lyrics already in correction_result
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title
|
||||
)
|
||||
|
||||
# 9. Upload video to GCS
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
video_size = os.path.getsize(outputs.video)
|
||||
job_log.info(f"Video generated: {video_size} bytes")
|
||||
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
|
||||
video_url = storage.upload_file(outputs.video, video_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
|
||||
job_log.info(f"Uploaded with_vocals.mkv to GCS")
|
||||
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
|
||||
else:
|
||||
job_log.error("Video generation failed - no output file produced!")
|
||||
raise Exception("Video generation failed - no output file produced")
|
||||
|
||||
# 10. Upload LRC file
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
|
||||
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
|
||||
job_log.info("Uploaded karaoke.lrc")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
|
||||
|
||||
# 11. Upload ASS subtitle file
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
|
||||
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
|
||||
job_log.info("Uploaded karaoke.ass")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
|
||||
|
||||
# 12. Upload corrected text files
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
|
||||
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
|
||||
job_log.info("Uploaded corrected.txt")
|
||||
logger.info(f"Job {job_id}: Uploaded corrected.txt")
|
||||
|
||||
# Store render timing in processing metadata
|
||||
render_duration = time.time() - start_time
|
||||
# Store render timing
|
||||
job_manager.update_processing_metadata(job_id, "rendering", {
|
||||
"render_duration_seconds": round(render_duration, 1),
|
||||
"countdown_padding_added": padding_added,
|
||||
"countdown_padding_seconds": padding_seconds if padding_added else 0,
|
||||
"rendered_on": "gce",
|
||||
})
|
||||
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
|
||||
|
||||
# 13. Transition based on prep_only flag
|
||||
# Note: Instrumental selection was already made during combined review
|
||||
# (stored in state_data['instrumental_selection'])
|
||||
# Transition state (same as local path)
|
||||
if getattr(job, 'prep_only', False):
|
||||
# Prep-only mode: stop here and mark as prep complete
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.PREP_COMPLETE,
|
||||
progress=100,
|
||||
message="Prep phase complete - download outputs to continue locally"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY, GCE) ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("prep_only", True)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
|
||||
root_span.set_attribute("rendered_on", "gce")
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s gce=true prep_only=true")
|
||||
else:
|
||||
# Normal mode: instrumental was selected during combined review
|
||||
# Transition directly to INSTRUMENTAL_SELECTED and trigger video worker
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.INSTRUMENTAL_SELECTED,
|
||||
progress=82,
|
||||
message="Video rendered, starting final encoding"
|
||||
message="Video rendered on encoding worker, starting final encoding"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (GCE) ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
|
||||
root_span.set_attribute("rendered_on", "gce")
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s gce=true")
|
||||
|
||||
# Trigger video worker for final encoding
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
worker_service = get_worker_service()
|
||||
job_log.info("Triggering video worker for final encoding...")
|
||||
await worker_service.trigger_video_worker(job_id)
|
||||
|
||||
# Mark render progress as complete for idempotency
|
||||
# This allows the worker to be re-triggered after admin reset
|
||||
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
|
||||
return True
|
||||
|
||||
else:
|
||||
# ============ LOCAL RENDER VIDEO PATH ============
|
||||
# Transition to RENDERING_VIDEO
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDERING_VIDEO,
|
||||
progress=75,
|
||||
message="Rendering karaoke video with corrected lyrics"
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
job_log.info(f"Created temp directory: {temp_dir}")
|
||||
|
||||
# Try updated corrections first (from human review), fall back to original
|
||||
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
|
||||
# Get GCS path from file_urls
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
if not corrections_url:
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
|
||||
if not corrections_url:
|
||||
# Try direct GCS paths
|
||||
if storage.file_exists(corrections_gcs_updated):
|
||||
corrections_gcs = corrections_gcs_updated
|
||||
elif storage.file_exists(corrections_gcs_original):
|
||||
corrections_gcs = corrections_gcs_original
|
||||
else:
|
||||
raise FileNotFoundError(f"No corrections file found for job {job_id}")
|
||||
else:
|
||||
# Extract GCS path from URL
|
||||
corrections_gcs = _extract_gcs_path(corrections_url)
|
||||
|
||||
# 2. Load the ORIGINAL corrections (has full structure)
|
||||
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
|
||||
|
||||
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
|
||||
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
|
||||
storage.download_file(original_corrections_gcs, original_corrections_path)
|
||||
|
||||
with open(original_corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 3. Load base CorrectionResult from original data
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 4. Apply user corrections if available (from review UI)
|
||||
# Uses the same method as preview generation to ensure
|
||||
# identical CorrectionResult construction (DRY).
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, applying via shared method")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
if isinstance(updated_data, dict) and "corrections" in updated_data:
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
job_log.warning("corrections_updated.json exists but has no 'corrections' key, using base result")
|
||||
logger.warning(f"Job {job_id}: corrections_updated.json has no 'corrections' key, using base result")
|
||||
correction_result = base_result
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# 5. Download audio file
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
|
||||
if not audio_gcs_path:
|
||||
raise FileNotFoundError(f"No input audio path for job {job_id}")
|
||||
|
||||
job_log.info(f"Downloading audio from {audio_gcs_path}")
|
||||
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
|
||||
storage.download_file(audio_gcs_path, audio_path)
|
||||
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
|
||||
|
||||
# Process countdown intro if needed (for songs that start too quickly)
|
||||
# This adds "3... 2... 1..." segment and pads audio with 3s silence
|
||||
# Note: Countdown is deferred to this stage (not during lyrics transcription)
|
||||
# so the review UI can show the original timing without the 3s shift
|
||||
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
|
||||
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
)
|
||||
if padding_added:
|
||||
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
|
||||
else:
|
||||
job_log.info("No countdown needed - song starts after 3 seconds")
|
||||
|
||||
# Update lyrics_metadata with countdown info so video_worker knows to pad instrumental
|
||||
# This is critical for audio sync - without this, instrumental won't match padded vocals
|
||||
if padding_added:
|
||||
existing_lyrics_metadata = job.state_data.get('lyrics_metadata', {})
|
||||
existing_lyrics_metadata['has_countdown_padding'] = True
|
||||
existing_lyrics_metadata['countdown_padding_seconds'] = padding_seconds
|
||||
job_manager.update_state_data(job_id, 'lyrics_metadata', existing_lyrics_metadata)
|
||||
job_log.info(f"Updated lyrics_metadata: has_countdown_padding=True, countdown_padding_seconds={padding_seconds}")
|
||||
|
||||
# 6. Get or create styles using the unified style loader
|
||||
job_log.info("Loading style configuration...")
|
||||
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
|
||||
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=job_log,
|
||||
)
|
||||
|
||||
# 7. Configure OutputGenerator
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
job_log.info(f"Using styles from: {styles_path}")
|
||||
|
||||
# Get subtitle offset from job (user-specified timing adjustment)
|
||||
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
|
||||
if subtitle_offset != 0:
|
||||
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
|
||||
|
||||
config = OutputConfig(
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False, # CDG optional, generated separately
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution="4k",
|
||||
subtitle_offset_ms=subtitle_offset
|
||||
)
|
||||
|
||||
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
|
||||
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
# 8. Generate outputs (video, LRC, ASS, etc.)
|
||||
# Sanitize artist/title to handle Unicode characters (curly quotes, em dashes, etc.)
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
output_prefix = f"{safe_artist} - {safe_title}"
|
||||
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
|
||||
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={}, # Reference lyrics already in correction_result
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title
|
||||
)
|
||||
|
||||
# 9. Upload video to GCS
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
video_size = os.path.getsize(outputs.video)
|
||||
job_log.info(f"Video generated: {video_size} bytes")
|
||||
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
|
||||
video_url = storage.upload_file(outputs.video, video_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
|
||||
job_log.info(f"Uploaded with_vocals.mkv to GCS")
|
||||
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
|
||||
else:
|
||||
job_log.error("Video generation failed - no output file produced!")
|
||||
raise Exception("Video generation failed - no output file produced")
|
||||
|
||||
# 10. Upload LRC file
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
|
||||
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
|
||||
job_log.info("Uploaded karaoke.lrc")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
|
||||
|
||||
# 11. Upload ASS subtitle file
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
|
||||
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
|
||||
job_log.info("Uploaded karaoke.ass")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
|
||||
|
||||
# 12. Upload corrected text files
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
|
||||
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
|
||||
job_log.info("Uploaded corrected.txt")
|
||||
logger.info(f"Job {job_id}: Uploaded corrected.txt")
|
||||
|
||||
# Store render timing in processing metadata
|
||||
render_duration = time.time() - start_time
|
||||
job_manager.update_processing_metadata(job_id, "rendering", {
|
||||
"render_duration_seconds": round(render_duration, 1),
|
||||
"countdown_padding_added": padding_added,
|
||||
"countdown_padding_seconds": padding_seconds if padding_added else 0,
|
||||
})
|
||||
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
|
||||
|
||||
# 13. Transition based on prep_only flag
|
||||
# Note: Instrumental selection was already made during combined review
|
||||
# (stored in state_data['instrumental_selection'])
|
||||
if getattr(job, 'prep_only', False):
|
||||
# Prep-only mode: stop here and mark as prep complete
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.PREP_COMPLETE,
|
||||
progress=100,
|
||||
message="Prep phase complete - download outputs to continue locally"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("prep_only", True)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
|
||||
else:
|
||||
# Normal mode: instrumental was selected during combined review
|
||||
# Transition directly to INSTRUMENTAL_SELECTED and trigger video worker
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.INSTRUMENTAL_SELECTED,
|
||||
progress=82,
|
||||
message="Video rendered, starting final encoding"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
|
||||
|
||||
# Trigger video worker for final encoding
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
worker_service = get_worker_service()
|
||||
job_log.info("Triggering video worker for final encoding...")
|
||||
await worker_service.trigger_video_worker(job_id)
|
||||
|
||||
# Mark render progress as complete for idempotency
|
||||
# This allows the worker to be re-triggered after admin reset
|
||||
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
duration = time.time() - start_time
|
||||
|
||||
@@ -178,11 +178,8 @@ async def generate_screens(job_id: str) -> bool:
|
||||
# Apply countdown padding if needed
|
||||
await _apply_countdown_padding_if_needed(job_id, job_manager, job)
|
||||
|
||||
# Analyze backing vocals for combined review
|
||||
# This runs BEFORE review so user can select instrumental during lyrics review
|
||||
with job_span("analyze-backing-vocals", job_id):
|
||||
job_log.info("Analyzing backing vocals for instrumental selection...")
|
||||
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
|
||||
# Note: backing vocals analysis now runs in audio_worker after stems are uploaded,
|
||||
# since screens_worker triggers on lyrics completion and audio may not be done yet.
|
||||
|
||||
# Transcode review audio to OGG Opus for fast browser playback
|
||||
# This runs BEFORE review so all files are cached when the user opens the UI
|
||||
@@ -388,7 +385,9 @@ async def _generate_title_screen(
|
||||
|
||||
logger.info(f"Job {job_id}: Title format - bg_image: {title_format.get('background_image')}, font: {title_format.get('font')}")
|
||||
|
||||
# Generate title screen (synchronous method)
|
||||
# Generate title screen images only (MOV video is generated on GCE encoding worker)
|
||||
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
|
||||
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
|
||||
video_generator.create_title_video(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
@@ -396,12 +395,13 @@ async def _generate_title_screen(
|
||||
output_image_filepath_noext=output_image_filepath_noext,
|
||||
output_video_filepath=output_video_filepath,
|
||||
existing_title_image=title_format.get('existing_image'),
|
||||
intro_video_duration=intro_duration
|
||||
intro_video_duration=0,
|
||||
)
|
||||
|
||||
if os.path.exists(output_video_filepath):
|
||||
logger.info(f"Job {job_id}: Title screen generated at {output_video_filepath}")
|
||||
return output_video_filepath
|
||||
|
||||
output_png = f"{output_image_filepath_noext}.png"
|
||||
if os.path.exists(output_png):
|
||||
logger.info(f"Job {job_id}: Title screen image generated at {output_png}")
|
||||
return output_png
|
||||
else:
|
||||
logger.error(f"Job {job_id}: Title screen generation returned no file")
|
||||
return None
|
||||
@@ -460,7 +460,9 @@ async def _generate_end_screen(
|
||||
|
||||
logger.info(f"Job {job_id}: End format - bg_image: {end_format.get('background_image')}, font: {end_format.get('font')}")
|
||||
|
||||
# Generate end screen (synchronous method)
|
||||
# Generate end screen images only (MOV video is generated on GCE encoding worker)
|
||||
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
|
||||
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
|
||||
video_generator.create_end_video(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
@@ -468,12 +470,13 @@ async def _generate_end_screen(
|
||||
output_image_filepath_noext=output_image_filepath_noext,
|
||||
output_video_filepath=output_video_filepath,
|
||||
existing_end_image=end_format.get('existing_image'),
|
||||
end_video_duration=end_duration
|
||||
end_video_duration=0,
|
||||
)
|
||||
|
||||
if os.path.exists(output_video_filepath):
|
||||
logger.info(f"Job {job_id}: End screen generated at {output_video_filepath}")
|
||||
return output_video_filepath
|
||||
|
||||
output_png = f"{output_image_filepath_noext}.png"
|
||||
if os.path.exists(output_png):
|
||||
logger.info(f"Job {job_id}: End screen image generated at {output_png}")
|
||||
return output_png
|
||||
else:
|
||||
logger.error(f"Job {job_id}: End screen generation returned no file")
|
||||
return None
|
||||
@@ -491,46 +494,34 @@ async def _upload_screens(
|
||||
end_screen_path: str
|
||||
) -> None:
|
||||
"""
|
||||
Upload title and end screens to GCS (video + images).
|
||||
|
||||
Upload title and end screen images to GCS.
|
||||
|
||||
Single Responsibility: Only handles uploads.
|
||||
|
||||
VideoGenerator creates .mov, .jpg, and .png files when configured with
|
||||
output_png=True and output_jpg=True. We upload all three formats
|
||||
for feature parity with the local CLI.
|
||||
|
||||
|
||||
VideoGenerator creates .jpg and .png files when configured with
|
||||
output_png=True and output_jpg=True. MOV video generation is handled
|
||||
by the GCE encoding worker (not Cloud Run) to avoid OOM with 4K H.264.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
job_manager: Job manager instance
|
||||
storage: Storage service instance
|
||||
title_screen_path: Path to title screen video (.mov)
|
||||
end_screen_path: Path to end screen video (.mov)
|
||||
title_screen_path: Path to title screen image (.png)
|
||||
end_screen_path: Path to end screen image (.png)
|
||||
"""
|
||||
# Upload title screen video
|
||||
title_gcs_path = f"jobs/{job_id}/screens/title.mov"
|
||||
title_url = storage.upload_file(title_screen_path, title_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'screens', 'title', title_url)
|
||||
logger.info(f"Job {job_id}: Uploaded title screen video")
|
||||
|
||||
# Upload title screen images (.jpg and .png - created by VideoGenerator)
|
||||
title_base = title_screen_path.replace('.mov', '')
|
||||
for ext, key in [('.jpg', 'title_jpg'), ('.png', 'title_png')]:
|
||||
# Upload title screen images (.png and .jpg)
|
||||
title_base = title_screen_path.replace('.png', '')
|
||||
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
|
||||
image_path = f"{title_base}{ext}"
|
||||
if os.path.exists(image_path):
|
||||
gcs_path = f"jobs/{job_id}/screens/title{ext}"
|
||||
url = storage.upload_file(image_path, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'screens', key, url)
|
||||
logger.info(f"Job {job_id}: Uploaded title screen image ({ext})")
|
||||
|
||||
# Upload end screen video
|
||||
end_gcs_path = f"jobs/{job_id}/screens/end.mov"
|
||||
end_url = storage.upload_file(end_screen_path, end_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'screens', 'end', end_url)
|
||||
logger.info(f"Job {job_id}: Uploaded end screen video")
|
||||
|
||||
# Upload end screen images (.jpg and .png - created by VideoGenerator)
|
||||
end_base = end_screen_path.replace('.mov', '')
|
||||
for ext, key in [('.jpg', 'end_jpg'), ('.png', 'end_png')]:
|
||||
|
||||
# Upload end screen images (.png and .jpg)
|
||||
end_base = end_screen_path.replace('.png', '')
|
||||
for ext, key in [('.png', 'end_png'), ('.jpg', 'end_jpg')]:
|
||||
image_path = f"{end_base}{ext}"
|
||||
if os.path.exists(image_path):
|
||||
gcs_path = f"jobs/{job_id}/screens/end{ext}"
|
||||
@@ -642,7 +633,7 @@ async def _analyze_backing_vocals(
|
||||
job_manager.update_state_data(job_id, 'backing_vocals_analysis', {
|
||||
'has_audible_content': None,
|
||||
'analysis_error': str(e),
|
||||
'recommended_selection': 'review_needed',
|
||||
'recommended_selection': 'clean',
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -121,13 +121,12 @@ async def _encode_via_gce(
|
||||
|
||||
def progress_callback(progress: int):
|
||||
# Update job progress (encoding is 75-95% of total)
|
||||
# Use update_job instead of transition_to_state since job is already in ENCODING state
|
||||
scaled_progress = 75 + int(progress * 0.2) # Map 0-100 to 75-95
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.ENCODING,
|
||||
progress=scaled_progress,
|
||||
message=f"Encoding videos ({progress}%)"
|
||||
)
|
||||
job_manager.update_job(job_id, {
|
||||
'progress': scaled_progress,
|
||||
'message': f"Encoding videos ({progress}%)",
|
||||
})
|
||||
|
||||
try:
|
||||
# Submit and wait for encoding
|
||||
@@ -1219,7 +1218,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')
|
||||
@@ -1232,9 +1231,11 @@ def _validate_prerequisites(job) -> bool:
|
||||
logger.error(f"Job {job.job_id}: Invalid instrumental selection: {instrumental_selection}")
|
||||
return False
|
||||
|
||||
# Check screens exist
|
||||
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
|
||||
screens = job.file_urls.get('screens', {})
|
||||
if not screens.get('title') or not screens.get('end'):
|
||||
has_title = screens.get('title') or screens.get('title_png')
|
||||
has_end = screens.get('end') or screens.get('end_png')
|
||||
if not has_title or not has_end:
|
||||
logger.error(f"Job {job.job_id}: Missing title or end screen")
|
||||
return False
|
||||
|
||||
@@ -1288,19 +1289,24 @@ async def _setup_working_directory(
|
||||
|
||||
log_progress("Setting up working directory")
|
||||
|
||||
# Download title screen
|
||||
log_progress("Downloading title screen...")
|
||||
title_url = job.file_urls['screens']['title']
|
||||
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
|
||||
storage.download_file(title_url, title_path)
|
||||
log_progress("Downloaded title screen")
|
||||
|
||||
# Download end screen
|
||||
log_progress("Downloading end screen...")
|
||||
end_url = job.file_urls['screens']['end']
|
||||
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
|
||||
storage.download_file(end_url, end_path)
|
||||
log_progress("Downloaded end screen")
|
||||
# Download title screen (PNG — MOV video is generated by the GCE encoding worker)
|
||||
screens = job.file_urls.get('screens', {})
|
||||
title_url = screens.get('title') or screens.get('title_png')
|
||||
if title_url:
|
||||
ext = os.path.splitext(title_url)[1] or '.png'
|
||||
title_path = os.path.join(temp_dir, f"{base_name} (Title){ext}")
|
||||
log_progress(f"Downloading title screen ({ext})...")
|
||||
storage.download_file(title_url, title_path)
|
||||
log_progress("Downloaded title screen")
|
||||
|
||||
# Download end screen (PNG — MOV video is generated by the GCE encoding worker)
|
||||
end_url = screens.get('end') or screens.get('end_png')
|
||||
if end_url:
|
||||
ext = os.path.splitext(end_url)[1] or '.png'
|
||||
end_path = os.path.join(temp_dir, f"{base_name} (End){ext}")
|
||||
log_progress(f"Downloading end screen ({ext})...")
|
||||
storage.download_file(end_url, end_path)
|
||||
log_progress("Downloaded end screen")
|
||||
|
||||
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
|
||||
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
|
||||
|
||||
@@ -836,6 +836,22 @@ class VideoWorkerOrchestrator:
|
||||
# Never fail the pipeline for validation
|
||||
|
||||
|
||||
def _screen_ext(job, screen_type: str) -> str:
|
||||
"""Get the file extension for a screen (title/end) based on what's in GCS.
|
||||
|
||||
New jobs have only PNG (MOV is generated by GCE encoding worker).
|
||||
Legacy jobs may still have MOV uploaded by the old screens_worker.
|
||||
"""
|
||||
screens = job.file_urls.get('screens', {})
|
||||
# Check for MOV first (legacy), then fall back to PNG (new)
|
||||
url = screens.get(screen_type) or screens.get(f'{screen_type}_png')
|
||||
if url:
|
||||
ext = os.path.splitext(url)[1]
|
||||
if ext:
|
||||
return ext
|
||||
return '.png'
|
||||
|
||||
|
||||
def create_orchestrator_config_from_job(
|
||||
job,
|
||||
temp_dir: str,
|
||||
@@ -893,12 +909,12 @@ def create_orchestrator_config_from_job(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
|
||||
# Input files
|
||||
title_video_path=os.path.join(temp_dir, f"{base_name} (Title).mov"),
|
||||
# Input files — use actual extension from GCS (PNG for new jobs, MOV for legacy)
|
||||
title_video_path=os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}"),
|
||||
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
|
||||
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
|
||||
instrumental_audio_path=instrumental_path,
|
||||
end_video_path=os.path.join(temp_dir, f"{base_name} (End).mov"),
|
||||
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}"),
|
||||
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
|
||||
title_jpg_path=os.path.join(temp_dir, f"{base_name} (Title).jpg"),
|
||||
|
||||
|
||||
+57
@@ -141,6 +141,7 @@ GET /api/jobs?status=complete
|
||||
GET /api/jobs?limit=10&offset=0
|
||||
GET /api/jobs?exclude_test=false
|
||||
GET /api/jobs?fields=summary&hide_completed=true
|
||||
GET /api/jobs?fields=summary&search=bohemian
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
@@ -149,6 +150,7 @@ Query parameters:
|
||||
- `limit` / `offset` - Pagination
|
||||
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
|
||||
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
|
||||
- `search` (string, optional) - Text search filter (summary mode only). Case-insensitive substring match against artist, title, audio_search_artist, audio_search_title, and job_id. When active, fetches up to 1000 results internally and filters in Python.
|
||||
|
||||
#### Delete Job
|
||||
|
||||
@@ -441,6 +443,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}`.
|
||||
|
||||
+32
-5
@@ -67,11 +67,12 @@
|
||||
• Instrumental track selection (clean vs with_backing)
|
||||
• Single submit saves both lyrics + instrumental choice
|
||||
▼
|
||||
5. VIDEO RENDERING
|
||||
5. VIDEO RENDERING (optionally via GCE for speed + memory)
|
||||
• Merge corrections with original data
|
||||
• Generate karaoke video with lyrics
|
||||
• Generate karaoke video with lyrics (OutputGenerator + ffmpeg/libass)
|
||||
• Style assets cached on GCE worker disk between jobs
|
||||
▼
|
||||
6. FINAL VIDEO (INSTRUMENTAL_SELECTED)
|
||||
6. FINAL VIDEO (INSTRUMENTAL_SELECTED, via GCE)
|
||||
• Remux with selected instrumental
|
||||
• Concatenate: title + karaoke + end
|
||||
• Encode to 4 formats
|
||||
@@ -161,7 +162,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 +370,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 +407,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=...
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
# Disaster Recovery Runbook
|
||||
|
||||
**Last updated:** 2026-03-29
|
||||
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Data | Backup Location | Recovery Method | RPO |
|
||||
|------|----------------|-----------------|-----|
|
||||
| Firestore | S3 `firestore/YYYY-MM-DD/` | Import to new GCP project | 24h |
|
||||
| BigQuery (weekly) | S3 `bigquery/daily-refresh/` | Load Parquet files | 7 days |
|
||||
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
|
||||
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
|
||||
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
|
||||
| Secrets | AWS Secrets Manager | Decrypt with KMS, configure | On-change |
|
||||
|
||||
## Scenario 1: Accidental Data Deletion (GCP Still Available)
|
||||
|
||||
### Firestore Recovery
|
||||
|
||||
**Option A — PITR (fastest, within 7 days):**
|
||||
```bash
|
||||
gcloud firestore databases restore \
|
||||
--source-database="(default)" \
|
||||
--destination-database="(default)-restored" \
|
||||
--snapshot-time="2026-03-28T12:00:00Z" \
|
||||
--project=nomadkaraoke
|
||||
```
|
||||
|
||||
**Option B — Import from S3 backup:**
|
||||
```bash
|
||||
# Download latest export from S3
|
||||
aws s3 sync s3://nomadkaraoke-backup/firestore/LATEST_DATE/ /tmp/firestore-restore/ \
|
||||
--profile nomadkaraoke-backup
|
||||
|
||||
# Upload to GCS
|
||||
gsutil -m cp -r /tmp/firestore-restore/ gs://nomadkaraoke-backup-staging/firestore-import/
|
||||
|
||||
# Import
|
||||
gcloud firestore import gs://nomadkaraoke-backup-staging/firestore-import/ --project=nomadkaraoke
|
||||
```
|
||||
|
||||
### BigQuery Recovery
|
||||
|
||||
**Option A — Time Travel (within 7 days):**
|
||||
```sql
|
||||
-- Query historical data
|
||||
SELECT * FROM `nomadkaraoke.karaoke_decide.TABLE_NAME`
|
||||
FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR);
|
||||
|
||||
-- Restore to a new table
|
||||
CREATE TABLE `nomadkaraoke.karaoke_decide.TABLE_NAME_restored` AS
|
||||
SELECT * FROM `nomadkaraoke.karaoke_decide.TABLE_NAME`
|
||||
FOR SYSTEM_TIME AS OF TIMESTAMP("2026-03-28 12:00:00 UTC");
|
||||
```
|
||||
|
||||
**Option B — Load from S3 backup:**
|
||||
```bash
|
||||
# Download Parquet exports
|
||||
aws s3 sync s3://nomadkaraoke-backup/bigquery/daily-refresh/LATEST_DATE/ /tmp/bq-restore/ \
|
||||
--profile nomadkaraoke-backup
|
||||
|
||||
# Load each table
|
||||
bq load --source_format=PARQUET \
|
||||
nomadkaraoke:karaoke_decide.TABLE_NAME \
|
||||
/tmp/bq-restore/TABLE_NAME/*.parquet
|
||||
```
|
||||
|
||||
### GCS Recovery
|
||||
|
||||
**Option A — Object versioning (within 30 days):**
|
||||
```bash
|
||||
# List versions of a deleted/overwritten object
|
||||
gsutil ls -a gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/
|
||||
|
||||
# Restore a specific version
|
||||
gsutil cp gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac#VERSION \
|
||||
gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac
|
||||
```
|
||||
|
||||
**Option B — Restore from S3:**
|
||||
```bash
|
||||
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/jobs/JOB_ID/ /tmp/gcs-restore/ \
|
||||
--profile nomadkaraoke-backup
|
||||
|
||||
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/
|
||||
```
|
||||
|
||||
## Scenario 2: Complete GCP Project Loss
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- AWS credentials from password manager
|
||||
- AWS KMS key ARN from password manager
|
||||
- All GitHub repos (code + IaC)
|
||||
|
||||
### Step-by-Step Recovery
|
||||
|
||||
**1. Create new GCP project**
|
||||
```bash
|
||||
gcloud projects create nomadkaraoke-v2 --name="Nomad Karaoke"
|
||||
gcloud config set project nomadkaraoke-v2
|
||||
gcloud services enable firestore.googleapis.com run.googleapis.com \
|
||||
cloudfunctions.googleapis.com cloudscheduler.googleapis.com \
|
||||
secretmanager.googleapis.com bigquery.googleapis.com \
|
||||
cloudtasks.googleapis.com artifactregistry.googleapis.com
|
||||
```
|
||||
|
||||
**2. Retrieve AWS credentials**
|
||||
|
||||
Get from password manager: AWS access key, secret key, KMS key ARN.
|
||||
|
||||
**3. Restore Firestore**
|
||||
```bash
|
||||
aws s3 sync s3://nomadkaraoke-backup/firestore/LATEST_DATE/ /tmp/firestore-restore/ \
|
||||
--profile nomadkaraoke-backup
|
||||
gsutil -m cp -r /tmp/firestore-restore/ gs://NEW_BUCKET/firestore-import/
|
||||
gcloud firestore import gs://NEW_BUCKET/firestore-import/ --project=nomadkaraoke-v2
|
||||
```
|
||||
|
||||
**4. Restore BigQuery**
|
||||
```bash
|
||||
# Create dataset
|
||||
bq mk --dataset nomadkaraoke-v2:karaoke_decide
|
||||
|
||||
# Download and load each table
|
||||
for prefix in daily-refresh musicbrainz; do
|
||||
aws s3 sync s3://nomadkaraoke-backup/bigquery/$prefix/LATEST_DATE/ /tmp/bq-$prefix/ \
|
||||
--profile nomadkaraoke-backup
|
||||
for dir in /tmp/bq-$prefix/*/; do
|
||||
table=$(basename $dir)
|
||||
bq load --source_format=PARQUET nomadkaraoke-v2:karaoke_decide.$table "$dir*.parquet"
|
||||
done
|
||||
done
|
||||
```
|
||||
|
||||
**Spotify tables (Glacier Deep Archive):** Retrieval takes 12-48 hours.
|
||||
```bash
|
||||
# Initiate restore (bulk = cheapest, ~$150 for 1TB)
|
||||
aws s3api restore-object --bucket nomadkaraoke-backup \
|
||||
--key "bigquery/spotify/TABLE/part-000.parquet" \
|
||||
--restore-request '{"Days":7,"GlacierJobParameters":{"Tier":"Bulk"}}' \
|
||||
--profile nomadkaraoke-backup
|
||||
# Wait 12-48 hours, then download and load
|
||||
```
|
||||
|
||||
**5. Restore GCS files**
|
||||
```bash
|
||||
# Create new bucket
|
||||
gsutil mb -l US-CENTRAL1 gs://karaoke-gen-storage-nomadkaraoke-v2/
|
||||
|
||||
# Sync from S3
|
||||
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/ /tmp/gcs-restore/ \
|
||||
--profile nomadkaraoke-backup
|
||||
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke-v2/
|
||||
```
|
||||
|
||||
**6. Restore secrets**
|
||||
```bash
|
||||
# Retrieve all secrets from AWS Secrets Manager
|
||||
aws secretsmanager get-secret-value --secret-id nomadkaraoke-gcp-secrets \
|
||||
--profile nomadkaraoke-backup | jq -r '.SecretString' > /tmp/secrets.json
|
||||
|
||||
# Create each secret in new project
|
||||
python3 -c "
|
||||
import json
|
||||
with open('/tmp/secrets.json') as f:
|
||||
secrets = json.load(f)
|
||||
for name, value in secrets.items():
|
||||
print(f'echo -n \"{value}\" | gcloud secrets create {name} --data-file=- --project=nomadkaraoke-v2')
|
||||
"
|
||||
# Review and run the generated commands
|
||||
rm /tmp/secrets.json
|
||||
```
|
||||
|
||||
**7. Rebuild infrastructure**
|
||||
```bash
|
||||
cd karaoke-gen/infrastructure
|
||||
# Update config.py with new project ID
|
||||
pulumi config set gcp:project nomadkaraoke-v2
|
||||
pulumi up
|
||||
```
|
||||
|
||||
**8. Deploy services**
|
||||
```bash
|
||||
# Push to GitHub triggers CI/CD, or deploy manually:
|
||||
gcloud run deploy karaoke-backend --source=. --project=nomadkaraoke-v2
|
||||
```
|
||||
|
||||
**9. Update DNS (Cloudflare)**
|
||||
|
||||
Update DNS records to point to new Cloud Run URLs. See `docs/archive/2026-03-29-external-services-config.md`.
|
||||
|
||||
**10. Re-register OAuth apps**
|
||||
|
||||
Re-create OAuth apps at Spotify, Google, Dropbox with redirect URIs from `docs/archive/2026-03-29-external-services-config.md`.
|
||||
|
||||
## Cost Estimates for Recovery
|
||||
|
||||
| Action | Cost |
|
||||
|--------|------|
|
||||
| S3 Glacier Deep Archive retrieval (1 TB, bulk) | ~$150 |
|
||||
| S3 Glacier Deep Archive retrieval (1 TB, standard) | ~$750 |
|
||||
| S3 data transfer out to GCP | ~$0.09/GB |
|
||||
| Full Spotify dataset retrieval + transfer (~1 TB) | ~$250 total |
|
||||
@@ -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,44 @@ 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.
|
||||
|
||||
### GCE Disk Cache Must Validate Content, Not Just URI (Mar 2026)
|
||||
|
||||
**Problem:** The GCE encoding worker's style asset disk cache (`/var/cache/karaoke-gen/styles/`) keyed on `SHA-256(GCS URI)`. When a file at a GCS path was replaced with different content (e.g., fixing corrupt 106-byte placeholder PNGs with correct 2.8MB files), the cache served the stale version indefinitely.
|
||||
|
||||
**Fix:** On cache hit, do a lightweight `blob.reload()` (HEAD request) to get the GCS object's current size. Compare with cached file size — re-download on mismatch. One metadata call per cache hit is a small price vs serving corrupt assets.
|
||||
|
||||
**Key insight:** Any local disk cache of remote objects needs a staleness check. URI-only cache keys assume content is immutable at that path — which is rarely guaranteed in GCS/S3. Size is the cheapest validation; for stronger guarantees, compare ETags or generation numbers.
|
||||
|
||||
### Don't Write Empty Sentinel Files to GCS (Mar 2026)
|
||||
|
||||
**Problem:** The review complete endpoint wrote `corrections_updated.json` to GCS even when no corrections were provided (e.g., admin API reset + complete without correction data). It wrote `{}` (empty dict). Downstream, render workers check `file_exists("corrections_updated.json")` — if present, they download and pass it to `CorrectionOperations.update_correction_result_with_data()` which does `updated_data["corrections"]`, causing `KeyError`.
|
||||
|
||||
**Fix:** (1) Root cause: Don't write `corrections_updated.json` unless the payload actually contains a `"corrections"` key. (2) Defensive: Both GCE and Cloud Run workers validate the downloaded JSON has the expected structure before processing, falling back to base result if not.
|
||||
|
||||
**Key insight:** When a file's existence is used as a boolean signal ("corrections were updated"), never write it with empty/invalid content. The existence check and content processing must agree on what constitutes a valid file. Apply defense in depth: fix the writer AND validate in readers.
|
||||
@@ -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
|
||||
|
||||
+3
-1
@@ -98,6 +98,8 @@
|
||||
|
||||
- **Custom Instrumental Upload Fix** (2026-02-26): Fixed critical bug where uploaded custom instrumentals were ignored during encoding — GCE encoding worker and orchestrator had no `"custom"` case, falling back to clean instrumental instead. Upload endpoint now converts all formats to FLAC for pipeline consistency. Three fixes: (1) GCE encoding worker `find_file` now searches for `custom_instrumental*.flac` when selection is `"custom"`, (2) orchestrator config constructs correct `(Instrumental Custom).flac` path, (3) upload endpoint converts mp3/m4a/wav/etc. to FLAC before storing. Added 10 new regression tests for GCE resolution and orchestrator paths. See [API.md](API.md#upload-custom-instrumental).
|
||||
|
||||
- **Render Video GCE Routing** (2026-03-31): Routed the `render_video_worker` (OutputGenerator/ffmpeg lyrics rendering) to the GCE encoding worker instead of running on Cloud Run. Previously, render_video always ran on Cloud Run and OOM'd after memory was right-sized to 2Gi. Now when `USE_GCE_ENCODING=true`, Cloud Run constructs GCS paths from job metadata and delegates to the GCE worker's new `/render-video` endpoint. Style assets (fonts, backgrounds) are cached on the GCE worker's disk between jobs to avoid repeated downloads of the same default theme. Local fallback preserved when GCE is disabled. See [spec](superpowers/specs/2026-03-31-render-video-gce-routing-design.md).
|
||||
|
||||
- **Store Processing Metadata Permanently** (2026-03-10): Added `processing_metadata` field to the Job model — a top-level dict where each worker writes immutable provenance data during processing. Stores AudioShake task_id/asset_id (the original ask — these were previously lost after processing), worker timing, separation model names, ffprobe audio properties, correction stats, cache hit/miss data, video encoding details, and auth context at job creation. All metadata writes are non-fatal (wrapped in try/except). Includes `update_processing_metadata` helper on JobManager using Firestore dot-notation for atomic section updates. 23 tests covering model, helpers, all worker functions, and a SUMMARY_FIELD_PATHS regression guard. See [archive/2026-03-10-store-job-processing-metadata.md](archive/2026-03-10-store-job-processing-metadata.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#store-processing-metadata-when-you-have-it-mar-2026).
|
||||
|
||||
- **Custom Instrumental Upload** (2026-02-25): Added `POST /api/jobs/{job_id}/upload-instrumental` endpoint — was missing from backend, causing 404 in production when users tried to upload custom instrumental files during review. Validates uploaded audio duration matches original (±0.5s tolerance) using ffprobe on GCS signed URLs. Fixed frontend bug where "uploaded" selection type was sent to API instead of "custom" (the only value the backend accepts). Added 22 tests covering upload validation, duration checks, and frontend/backend contract. See [API.md](API.md#upload-custom-instrumental).
|
||||
@@ -237,7 +239,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,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,312 @@
|
||||
# Business Continuity & Disaster Recovery Design
|
||||
|
||||
**Date:** 2026-03-27
|
||||
**Status:** Design approved, pending implementation
|
||||
**Budget:** ~$50-100/month recurring (actual estimate: $20-40/month) + ~$900 one-time egress for Phase 3
|
||||
**RPO:** 24 hours for Tier 1 (critical), 1 week for Tier 2 (high), N/A for Tier 3 (one-time)
|
||||
**RTO:** Days (acceptable downtime while rebuilding from git/Pulumi + restoring data from backups)
|
||||
|
||||
## Risk Model
|
||||
|
||||
Ranked by priority:
|
||||
|
||||
1. **Errant Claude session** — AI agent with admin gcloud credentials accidentally deletes production data
|
||||
2. **Google account termination** — GCP project suspended due to ToS concerns (Spotify dataset, YouTube cookies, torrent tracker integration)
|
||||
3. **Accidental human error** — Destructive gcloud/bq command run by mistake
|
||||
|
||||
## Strategy: Two-Tier Protection
|
||||
|
||||
- **Tier A (GCP-native):** Fast recovery from mistakes — object versioning, PITR, deny policies, read-only SA
|
||||
- **Tier B (Cross-cloud):** Catastrophic recovery — nightly exports to AWS S3 in a separate account
|
||||
|
||||
---
|
||||
|
||||
## 1. Data Classification
|
||||
|
||||
### Tier 1 — Critical (irreplaceable user-generated data)
|
||||
|
||||
| Data | Location | Size | Backup Freq | S3 Destination |
|
||||
|------|----------|------|-------------|----------------|
|
||||
| Firestore (all collections) | `nomadkaraoke` default DB | ~MBs | Nightly | Standard-IA |
|
||||
| GCS job files | `karaoke-gen-storage-nomadkaraoke` | 249 GB | Nightly delta sync | Standard-IA |
|
||||
| Secrets Manager | 48 secrets | Tiny | On-change + quarterly | AWS Secrets Manager |
|
||||
| Stripe config | External service | N/A | Documented | AWS Secrets Manager |
|
||||
|
||||
**Firestore collections (gen):** `gen_users`, `jobs`, `jobs/{id}/logs`, `sessions`, `magic_links`, `user_feedback`, `beta_feedback`, `youtube_quota_pending`, `youtube_upload_queue`
|
||||
|
||||
**Firestore collections (decide):** `decide_users`, `lastfm_users`, `music_services`, `karaoke_songs`, `user_songs`, `user_artists`, `playlists`, `sync_jobs`, `sung_records`
|
||||
|
||||
### Tier 2 — High (expensive to recreate)
|
||||
|
||||
| Data | Location | Size | Backup Freq | S3 Destination |
|
||||
|------|----------|------|-------------|----------------|
|
||||
| BigQuery daily-refresh tables | `karaokenerds_raw`, `karaokenerds_community`, `divebar_catalog`, `kn_divebar_xref` | ~MBs | Weekly | Standard-IA |
|
||||
| BigQuery MusicBrainz tables | `mb_artists`, `mb_recordings`, `mb_artist_tags`, `mb_recording_isrc`, `mbid_spotify_mapping`, `mb_artists_normalized`, `karaoke_recording_links` | ~5 GB | Monthly | Standard-IA |
|
||||
| BigQuery MLHD+ | `mlhd_artist_similarity` | ~50 MB | One-time | Standard-IA |
|
||||
| GCS MusicBrainz data | `nomadkaraoke-musicbrainz-data` | 17 GB | One-time | Glacier |
|
||||
| GCS MLHD data | `nomadkaraoke-mlhd-data` | 252 GB | One-time | Glacier |
|
||||
| GCS KN data | `nomadkaraoke-kn-data` | 44 MB | Weekly | Standard-IA |
|
||||
|
||||
### Tier 3 — Replaceable (can re-derive)
|
||||
|
||||
| Data | Location | Size | Backup Freq | S3 Destination |
|
||||
|------|----------|------|-------------|----------------|
|
||||
| BigQuery Spotify tables (13 tables) | `karaoke_decide` dataset | ~1 TB logical | One-time | Glacier Deep Archive |
|
||||
| GCS raw archives | `nomadkaraoke-raw-archives` | 7.2 TB | One-time | Glacier Deep Archive |
|
||||
|
||||
### Not Backed Up
|
||||
|
||||
| Data | Reason |
|
||||
|------|--------|
|
||||
| GCS `nomad-usb-backup` (593 GB) | Already a backup itself |
|
||||
| Artifact Registry (390 GB) | Rebuild from git |
|
||||
| Cloud Run services | Code in GitHub, deploy via Pulumi |
|
||||
| Cloud Scheduler / Cloud Tasks | Defined in Pulumi IaC |
|
||||
| GCE VMs | Pulumi + Packer, recreatable |
|
||||
| Firestore indexes | Defined in Pulumi |
|
||||
| IAM / Service accounts | Defined in Pulumi |
|
||||
| GCS `nomadkaraoke-audio-separator-models` | Empty bucket |
|
||||
| GCS `karaoke-decide-data` | Empty bucket |
|
||||
|
||||
---
|
||||
|
||||
## 2. Prevention Layer: Read-Only Claude SA
|
||||
|
||||
### Service Account: `claude-readonly@nomadkaraoke.iam.gserviceaccount.com`
|
||||
|
||||
**Granted roles:**
|
||||
|
||||
| Role | Purpose |
|
||||
|------|---------|
|
||||
| `roles/viewer` | Project-wide read access |
|
||||
| `roles/firestore.viewer` | Read Firestore documents |
|
||||
| `roles/bigquery.dataViewer` | Query BigQuery tables |
|
||||
| `roles/bigquery.jobUser` | Execute BigQuery queries |
|
||||
| `roles/storage.objectViewer` | Read GCS objects |
|
||||
| `roles/secretmanager.viewer` | List secrets (NOT access values) |
|
||||
| `roles/run.viewer` | View Cloud Run services/logs |
|
||||
| `roles/compute.viewer` | View GCE instances |
|
||||
| `roles/logging.viewer` | Read Cloud Logging |
|
||||
|
||||
### Usage Pattern
|
||||
|
||||
- Default: `GOOGLE_APPLICATION_CREDENTIALS` points to read-only SA key
|
||||
- Write access: User explicitly switches to admin credentials for specific tasks
|
||||
- Alternative: Claude asks user to run write commands via `!` prefix
|
||||
|
||||
### IAM Deny Policies (apply to ALL principals except break-glass SA)
|
||||
|
||||
Protect against catastrophic deletes even with admin credentials:
|
||||
|
||||
```yaml
|
||||
deniedPermissions:
|
||||
- firestore.googleapis.com/databases.delete
|
||||
- storage.googleapis.com/buckets.delete
|
||||
- bigquery.googleapis.com/datasets.delete
|
||||
- bigquery.googleapis.com/tables.delete # scoped to karaoke_decide dataset only
|
||||
exceptionPrincipals:
|
||||
- serviceAccount:break-glass@nomadkaraoke.iam.gserviceaccount.com
|
||||
```
|
||||
|
||||
The `break-glass` SA key is stored offline (password manager / local encrypted file). For legitimate deletes, use the break-glass SA rather than removing the deny policy itself.
|
||||
|
||||
**Note:** `bigquery.tables.delete` is scoped to the `karaoke_decide` dataset only (not project-wide) to avoid blocking temp table cleanup by the backup pipeline or other automation.
|
||||
|
||||
---
|
||||
|
||||
## 3. GCP-Native Protections
|
||||
|
||||
| Protection | Resource | Config | Cost |
|
||||
|------------|----------|--------|------|
|
||||
| Object Versioning | `karaoke-gen-storage-nomadkaraoke` | Enable + lifecycle: delete old versions after 30 days | ~$5-10/month |
|
||||
| Firestore PITR | Default database | Enable 7-day Point-in-Time Recovery | Free |
|
||||
| BigQuery Time Travel | `karaoke_decide` dataset | Already enabled (7-day window) | Free |
|
||||
| GCS Soft Delete | All critical buckets | 7-day soft delete retention | Minimal |
|
||||
|
||||
---
|
||||
|
||||
## 4. AWS Backup Infrastructure
|
||||
|
||||
### Account Setup
|
||||
|
||||
- New AWS account: dedicated to Nomad Karaoke backups
|
||||
- Region: `us-east-1`
|
||||
- IAM user for backup pipeline: write-only S3 access (no delete)
|
||||
|
||||
### S3 Bucket Structure
|
||||
|
||||
```
|
||||
s3://nomadkaraoke-backup/
|
||||
├── firestore/
|
||||
│ └── YYYY-MM-DD/ # Nightly Firestore exports
|
||||
├── bigquery/
|
||||
│ ├── daily-refresh/ # KN, Divebar tables (weekly)
|
||||
│ ├── musicbrainz/ # Monthly
|
||||
│ ├── spotify/ # One-time, Glacier Deep Archive
|
||||
│ └── mlhd/ # One-time
|
||||
├── gcs/
|
||||
│ ├── job-files/ # Mirror of karaoke-gen-storage
|
||||
│ ├── kn-data/ # Weekly
|
||||
│ └── musicbrainz-data/ # One-time
|
||||
└── secrets/
|
||||
└── YYYY-MM-DD.enc # Encrypted secrets snapshot
|
||||
```
|
||||
|
||||
### S3 Lifecycle Policies
|
||||
|
||||
| Prefix | Storage Class | Retention |
|
||||
|--------|---------------|-----------|
|
||||
| `firestore/` | Standard-IA | Keep last 30 daily, delete older |
|
||||
| `bigquery/daily-refresh/` | Standard-IA | Keep last 8 weekly |
|
||||
| `bigquery/spotify/` | Glacier Deep Archive | Indefinite |
|
||||
| `gcs/job-files/` | Standard-IA | Mirror (sync, no retention limit) |
|
||||
| `secrets/` | Standard | Keep last 4 quarterly snapshots |
|
||||
|
||||
### Backup Pipeline
|
||||
|
||||
**Cloud Function `backup-to-aws`** (2nd gen, Python, 60-min timeout) triggered by Cloud Scheduler nightly at 1:00 AM ET.
|
||||
|
||||
Uses Python client libraries (NOT CLI tools — `gcloud`/`bq`/`gsutil` are not available in Cloud Functions):
|
||||
|
||||
1. **Firestore export** → `google.cloud.firestore_admin_v1` client to export to `gs://nomadkaraoke-backup-staging/firestore/YYYY-MM-DD/`
|
||||
2. **BigQuery export** (weekly, based on day-of-week check) → `google.cloud.bigquery` client `extract_table()` to GCS staging as Parquet
|
||||
3. **GCS sync** → `google.cloud.storage` client to copy new/changed job files to staging bucket
|
||||
4. **AWS sync** → `boto3` to upload from GCS staging to S3
|
||||
5. **Cleanup** → Remove GCS staging files after confirmed S3 upload
|
||||
6. **Alert** → Discord webhook notification with backup summary + any failures
|
||||
|
||||
**Required IAM roles for backup function SA (`backup-to-aws@nomadkaraoke.iam.gserviceaccount.com`):**
|
||||
- `roles/datastore.importExportAdmin` — Firestore export
|
||||
- `roles/bigquery.dataViewer` + `roles/bigquery.jobUser` — BigQuery export
|
||||
- `roles/storage.objectAdmin` on staging bucket — Write exports
|
||||
- `roles/storage.objectViewer` on source buckets — Read job files
|
||||
|
||||
**Note:** For the 249 GB job-files bucket, delta sync may exceed Cloud Function timeout on first run. If needed, split into a separate Cloud Run job for the initial catchup, then use the Cloud Function for incremental deltas.
|
||||
|
||||
### Cost Estimate
|
||||
|
||||
**Recurring (monthly):**
|
||||
|
||||
| Component | Monthly Cost |
|
||||
|-----------|-------------|
|
||||
| S3 Glacier Deep Archive (7.5 TB) | ~$7 |
|
||||
| S3 Standard-IA (~300 GB active) | ~$4 |
|
||||
| GCP egress for nightly deltas | ~$5-15 |
|
||||
| Cloud Function execution | ~$1 |
|
||||
| GCS staging bucket | ~$2 |
|
||||
| **Total recurring** | **~$20-40** |
|
||||
|
||||
**One-time (Phase 3 bulk transfer):**
|
||||
|
||||
| Component | Cost |
|
||||
|-----------|------|
|
||||
| GCP egress for ~7.5 TB to AWS | ~$900 |
|
||||
| S3 Glacier Deep Archive retrieval (if ever needed) | ~$150 (bulk) to ~$750 (standard) |
|
||||
|
||||
---
|
||||
|
||||
## 5. Additional Single Points of Failure
|
||||
|
||||
Beyond GCP, these external dependencies should be documented/protected:
|
||||
|
||||
| Dependency | Risk | Mitigation |
|
||||
|------------|------|------------|
|
||||
| **GitHub** (all repos, IaC, CI/CD) | Org suspended/deleted | Keep local clones of all repos; consider periodic mirror to AWS CodeCommit |
|
||||
| **Cloudflare** (DNS, Pages, Workers) | Account compromised/terminated | Export DNS zone records, document Pages/Worker config in this repo |
|
||||
| **External OAuth apps** (Spotify, Google, Dropbox) | Losing Google account = losing OAuth app registrations | Document all OAuth redirect URIs, client IDs, app settings in encrypted backup |
|
||||
| **Flacfetch VM data disk** | Chrome profile, cookies, tracker config | Document manual setup steps; cookies auto-refresh so only config matters |
|
||||
|
||||
## 6. Secrets Encryption & Key Management
|
||||
|
||||
Secrets backup files (`secrets/YYYY-MM-DD.enc`) are encrypted with an **AWS KMS key** (not GCP KMS — must survive GCP termination).
|
||||
|
||||
- AWS KMS key created in the backup AWS account
|
||||
- Key ARN also stored in password manager as a failsafe
|
||||
- The backup Cloud Function encrypts secrets client-side using `boto3` KMS before uploading to S3
|
||||
|
||||
**Critical:** AWS IAM credentials for the backup pipeline are stored in GCP Secret Manager for the Cloud Function to use, BUT must also be stored **outside GCP** (password manager) since they are needed to access backups if GCP is terminated.
|
||||
|
||||
## 7. Verification & Monitoring
|
||||
|
||||
| Check | Frequency | Method |
|
||||
|-------|-----------|--------|
|
||||
| Backup completed | Daily | Discord webhook alert from backup function |
|
||||
| Backup freshness (external) | Daily | External cron (e.g., free-tier UptimeRobot or AWS Lambda) checks S3 last-modified; alerts if >48h stale |
|
||||
| Backup integrity | Monthly | Script downloads random Firestore export, verifies doc count |
|
||||
| S3 bucket growth | Weekly | CloudWatch alarm if bucket stops growing |
|
||||
| Restore drill | Quarterly | Restore Firestore to test GCP project, verify data |
|
||||
|
||||
**Why external monitoring?** The backup pipeline runs on GCP. If GCP is terminated (Risk #2), backups stop silently. The external freshness check ensures you are alerted even if GCP is down.
|
||||
|
||||
## 8. High-Level Restore Procedure
|
||||
|
||||
For a catastrophic GCP termination, the restore flow would be:
|
||||
|
||||
1. **Create new GCP project** (or use a different cloud provider)
|
||||
2. **Retrieve AWS credentials** from password manager
|
||||
3. **Download Firestore export** from S3 → `firestore import` to new project
|
||||
4. **Download BigQuery exports** from S3 → load Parquet files into new BigQuery (or equivalent)
|
||||
5. **Sync GCS data** from S3 → new cloud storage
|
||||
6. **Retrieve secrets** from AWS Secrets Manager → decrypt with AWS KMS → configure new project
|
||||
7. **Run Pulumi** targeting new project to recreate all infrastructure
|
||||
8. **Deploy services** from GitHub repos
|
||||
9. **Update DNS** (Cloudflare) to point to new services
|
||||
10. **Re-register OAuth apps** at Spotify, Google, etc. using documented config
|
||||
|
||||
---
|
||||
|
||||
## 9. Implementation Phases
|
||||
|
||||
### Phase 0: Audit (verify assumptions)
|
||||
1. Run `pulumi stack export` and diff against actual GCP resources to catch any console-created resources not in IaC
|
||||
2. Verify all Cloud Scheduler jobs are defined in Pulumi
|
||||
3. Document Cloudflare configuration (DNS records, Pages projects, Worker scripts, custom domains)
|
||||
4. Document external OAuth app registrations (Spotify, Google, Dropbox redirect URIs and client IDs)
|
||||
|
||||
### Phase 1: GCP-Native Protections (no AWS needed)
|
||||
1. Create `claude-readonly` service account via Pulumi
|
||||
2. Grant read-only roles
|
||||
3. Create `break-glass` service account, store key in password manager
|
||||
4. Create IAM deny policies for destructive operations (with break-glass exception)
|
||||
5. Enable Firestore PITR
|
||||
6. Enable GCS object versioning on `karaoke-gen-storage-nomadkaraoke`
|
||||
7. Enable GCS soft delete on critical buckets
|
||||
8. Generate `claude-readonly` SA key, store at `~/.config/gcloud/claude-readonly.json`
|
||||
9. Configure direnv (`.envrc`) to set `GOOGLE_APPLICATION_CREDENTIALS` to read-only SA by default
|
||||
|
||||
### Phase 2: AWS Account & Bucket Setup
|
||||
1. Create dedicated AWS account
|
||||
2. Create S3 bucket with lifecycle policies
|
||||
3. Enable S3 Object Lock (Governance mode) on backup bucket
|
||||
4. Create write-only IAM user (`s3:PutObject` only, no delete)
|
||||
5. Create AWS KMS key for secrets encryption
|
||||
6. Create AWS Secrets Manager entries for external service config
|
||||
7. Store AWS credentials in GCP Secret Manager (for backup function) AND in password manager (for catastrophic recovery)
|
||||
|
||||
### Phase 3: One-Time Bulk Exports (~$900 egress cost)
|
||||
1. Export all BigQuery Spotify tables to GCS staging
|
||||
2. Use GCP Storage Transfer Service (direct GCS→S3, no staging needed) for 7.2 TB raw archives to Glacier Deep Archive
|
||||
3. Sync MusicBrainz and MLHD GCS buckets to S3 Glacier
|
||||
4. Export and sync MLHD+ BigQuery table
|
||||
5. Export all secrets, encrypt with AWS KMS, store in AWS Secrets Manager
|
||||
6. Store KMS key ARN in password manager
|
||||
|
||||
### Phase 4: Automated Nightly Backups
|
||||
1. Create GCS staging bucket (`nomadkaraoke-backup-staging`)
|
||||
2. Create backup function SA with required roles (`datastore.importExportAdmin`, `bigquery.dataViewer`, `bigquery.jobUser`, `storage.objectAdmin` on staging, `storage.objectViewer` on sources)
|
||||
3. Create 2nd-gen Cloud Function `backup-to-aws` (Python, 60-min timeout)
|
||||
4. Create Cloud Scheduler trigger (1:00 AM ET daily)
|
||||
5. Implement Firestore nightly export (via `firestore_admin_v1` Python client)
|
||||
6. Implement BigQuery weekly export (via `bigquery` Python client, day-of-week check)
|
||||
7. Implement BigQuery monthly export for MusicBrainz tables
|
||||
8. Implement GCS job files delta sync (via `google.cloud.storage` + `boto3`)
|
||||
9. Implement Discord webhook alerting on success/failure
|
||||
10. Set up external backup freshness monitor (AWS Lambda or free-tier service, alerts if S3 not updated in 48h)
|
||||
|
||||
### Phase 5: Verification & Documentation
|
||||
1. Run first full backup, verify all data landed in S3
|
||||
2. Test Firestore restore to a test GCP project
|
||||
3. Write detailed restore runbook (step-by-step for each data tier, including cost estimates for Glacier retrieval)
|
||||
4. Set up CloudWatch monitoring on S3
|
||||
5. Mirror GitHub repos to secondary git host (AWS CodeCommit or similar)
|
||||
6. Schedule first quarterly restore drill
|
||||
@@ -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
@@ -0,0 +1,82 @@
|
||||
# External Services Configuration (DR Reference)
|
||||
|
||||
**Purpose:** If GCP or other services are terminated, this documents what needs to be re-created at the external service level. Actual secrets are in AWS Secrets Manager.
|
||||
|
||||
**Last verified:** 2026-03-29
|
||||
|
||||
## Cloudflare
|
||||
|
||||
- **Zone:** nomadkaraoke.com
|
||||
- **DNS Records:**
|
||||
- `api` → CNAME → `ghs.googlehosted.com` (proxied: false)
|
||||
- `gen` → CNAME → Cloudflare Pages
|
||||
- `decide` → CNAME → GitHub Pages
|
||||
- `vocalstar` → CNAME → Cloudflare Pages (tenant portal)
|
||||
- `singa` → CNAME → Cloudflare Pages (tenant portal)
|
||||
- **Pages Projects:**
|
||||
- `karaoke-gen` — gen.nomadkaraoke.com (consumer frontend)
|
||||
- `karaoke-gen-tenant` — vocalstar/singa subdomains (B2B tenant portal)
|
||||
- **Workers:**
|
||||
- `karaoke-decide-api-proxy` — proxies decide.nomadkaraoke.com/api/* to Cloud Run
|
||||
|
||||
## Spotify Developer App
|
||||
|
||||
- **App name:** Nomad Karaoke Decide
|
||||
- **Client ID:** stored in Secret Manager as `spotipy-client-id`
|
||||
- **Client Secret:** stored in Secret Manager as `spotipy-client-secret`
|
||||
- **Redirect URIs:**
|
||||
- `https://decide.nomadkaraoke.com/api/services/spotify/callback`
|
||||
- `http://localhost:8000/api/services/spotify/callback`
|
||||
|
||||
## Google (Flacfetch)
|
||||
|
||||
- **Account:** nomadflacfetch@gmail.com (no 2FA)
|
||||
- **Used for:** YouTube cookies (refreshed every 8h), Spotify "Login with Google" (refreshed every 12h)
|
||||
- **Managed by:** Flacfetch credential keeper systemd service on GCE VM
|
||||
|
||||
## Stripe
|
||||
|
||||
- **Webhook endpoint:** `https://api.nomadkaraoke.com/api/users/webhooks/stripe`
|
||||
- **Events:** `checkout.session.completed`, `checkout.session.expired`, `payment_intent.payment_failed`
|
||||
- **Keys:** `stripe-secret-key`, `stripe-webhook-secret` in Secret Manager
|
||||
|
||||
## SendGrid
|
||||
|
||||
- **Sender:** gen@nomadkaraoke.com
|
||||
- **Used by:** karaoke-gen (job notifications, idle reminders), karaoke-decide (magic link auth)
|
||||
- **Key:** `sendgrid-api-key` in Secret Manager
|
||||
|
||||
## AudioShake
|
||||
|
||||
- **Purpose:** Lyrics transcription API
|
||||
- **Key:** `audioshake-api-key` in Secret Manager
|
||||
|
||||
## Genius
|
||||
|
||||
- **Purpose:** Reference lyrics lookup
|
||||
- **Key:** `genius-api-key` in Secret Manager
|
||||
|
||||
## KaraokeNerds
|
||||
|
||||
- **Purpose:** Karaoke catalog API (daily sync)
|
||||
- **Key:** `karaokenerds-api-key` in Secret Manager
|
||||
|
||||
## Dropbox
|
||||
|
||||
- **Purpose:** Karaoke file distribution (per-job upload)
|
||||
- **Credentials:** `dropbox-oauth-credentials` in Secret Manager
|
||||
|
||||
## YouTube
|
||||
|
||||
- **Purpose:** Karaoke video upload + API quota tracking
|
||||
- **Credentials:** `youtube-oauth-credentials`, `youtube-client-credentials`, `youtube-cookies` in Secret Manager
|
||||
|
||||
## Last.fm
|
||||
|
||||
- **Purpose:** User listening history for Decide recommendations
|
||||
- **Keys:** `lastfm-api-key`, `lastfm-shared-secret` in Secret Manager
|
||||
|
||||
## Private Trackers (RED, OPS)
|
||||
|
||||
- **Purpose:** High-quality audio source downloads via Flacfetch
|
||||
- **Keys:** `red-api-key`, `red-api-url`, `ops-api-key`, `ops-api-url` in Secret Manager
|
||||
@@ -0,0 +1,66 @@
|
||||
# Plan: Move Screen Video Generation to GCE Encoding Worker
|
||||
|
||||
**Created:** 2026-03-31
|
||||
**Branch:** feat/sess-20260331-1619-investigate-render-failure
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Screen video generation (title.mov, end.mov) currently runs FFmpeg in the Cloud Run API container via `VideoGenerator._create_video_from_image()`. After PR #640 right-sized Cloud Run to 2CPU/2Gi, the 4K H.264 encoding OOMs silently (producing 36-byte empty MOV shells). This breaks all downstream encoding since `encode_lossless_mp4` can't concatenate corrupt inputs.
|
||||
|
||||
Fix: Stop generating MOV in screens_worker. Generate them on the GCE encoding worker (which has adequate resources) just before the encoding step.
|
||||
|
||||
## Root Cause
|
||||
|
||||
- `VideoGenerator._create_video_from_image()` uses `os.system()` — silently swallows FFmpeg failures
|
||||
- 4K H.264 encoding needs more than 2Gi RAM
|
||||
- screens_worker checks `os.path.exists(output_video_filepath)` — the 36-byte shell passes this check
|
||||
- All jobs since the Cloud Run right-sizing (March 31) are affected
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### 1. screens_worker.py — Stop generating MOV videos
|
||||
|
||||
**Changes:**
|
||||
- In `_generate_title_screen`: pass `intro_video_duration=0` to skip MOV creation, return PNG path
|
||||
- In `_generate_end_screen`: pass `end_video_duration=0` to skip MOV creation, return PNG path
|
||||
- In `_upload_screens`: only upload PNG and JPG (remove MOV upload logic)
|
||||
- Update function return types/docstrings to reflect image-only output
|
||||
|
||||
**Why duration=0 works:** `VideoGenerator._save_output_files` already has `if duration > 0:` guard around `_create_video_from_image`.
|
||||
|
||||
### 2. gce_encoding/main.py — Generate MOV from PNG before encoding
|
||||
|
||||
**Changes in `run_encoding()`:**
|
||||
- After `find_file` for title/end videos, check if they're missing or invalid (< 1KB)
|
||||
- If missing/invalid, look for corresponding PNG: `screens/title.png`, `screens/end.png`
|
||||
- Generate MOV from PNG using `subprocess.run()` with proper error handling
|
||||
- Use same FFmpeg command as `_create_video_from_image` but with error checking
|
||||
- Log clearly when generating MOV from PNG vs using existing MOV
|
||||
|
||||
**Backwards compatible:** Old jobs with valid MOVs still work. New jobs with only PNGs get MOVs generated on GCE.
|
||||
|
||||
### 3. Fix `_create_video_from_image` error handling (defensive)
|
||||
|
||||
**Changes in `karaoke_gen/video_generator.py`:**
|
||||
- Replace `os.system()` with `subprocess.run(check=True)`
|
||||
- Log stderr on failure
|
||||
- This protects the local CLI path too
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/workers/screens_worker.py` | Modify | Stop generating MOV, return/upload images only |
|
||||
| `backend/services/gce_encoding/main.py` | Modify | Generate MOV from PNG in `run_encoding()` |
|
||||
| `karaoke_gen/video_generator.py` | Modify | Replace `os.system()` with `subprocess.run()` |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Unit tests for GCE worker MOV generation helper
|
||||
- Verify existing encoding tests still pass
|
||||
- Manually re-run job f0d51a0a after deploy to confirm fix
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Revert the 3 files. The old behavior (generating MOV in Cloud Run) would still fail with 2Gi, but increasing memory to 4Gi would restore it.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
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)
|
||||
@@ -0,0 +1,135 @@
|
||||
# Route render_video to GCE Encoding Worker
|
||||
|
||||
**Date:** 2026-03-31
|
||||
**Status:** Approved
|
||||
**Branch:** feat/sess-20260331-1123-video-render-routing
|
||||
|
||||
## Problem
|
||||
|
||||
The `render_video_worker` runs OutputGenerator (ffmpeg/libass video rendering) on Cloud Run. After right-sizing Cloud Run to 2Gi memory, this OOMs. The GCE encoding worker handles final encoding (`/encode`) and preview encoding (`/encode-preview`), but render_video was never routed there — it was an intentional scope limitation from the original Jan 2026 PR #164, since render_video_worker predated the GCE encoding worker.
|
||||
|
||||
This also explains why karaoke jobs are slower than expected: the most resource-intensive rendering step runs on a constrained Cloud Run instance instead of the dedicated high-performance GCE VM.
|
||||
|
||||
## Solution
|
||||
|
||||
Add a `/render-video` endpoint to the GCE encoding worker and route render_video through `EncodingService`, following the same pattern as `/encode` and `/encode-preview`.
|
||||
|
||||
## Architecture
|
||||
|
||||
### GCE Worker: New `/render-video` endpoint
|
||||
|
||||
**Request model** (`RenderVideoRequest`):
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `job_id` | str | Job identifier |
|
||||
| `original_corrections_gcs_path` | str | `gs://` path to corrections.json |
|
||||
| `updated_corrections_gcs_path` | str (optional) | `gs://` path to corrections_updated.json |
|
||||
| `audio_gcs_path` | str | `gs://` path to input audio |
|
||||
| `style_params_gcs_path` | str (optional) | `gs://` path to style_params.json |
|
||||
| `style_assets` | dict (optional) | Map of asset key → GCS path |
|
||||
| `output_gcs_prefix` | str | `gs://` prefix for outputs (e.g. `gs://bucket/jobs/{id}/`) |
|
||||
| `artist` | str | Artist name |
|
||||
| `title` | str | Song title |
|
||||
| `subtitle_offset_ms` | int | Subtitle timing offset (default 0) |
|
||||
| `video_resolution` | str | Resolution (default "4k") |
|
||||
|
||||
**Processing** (`run_render_video()`):
|
||||
1. `ensure_latest_wheel()` — hot code updates, same as `/encode`
|
||||
2. Download inputs from GCS (with disk cache for style assets)
|
||||
3. Load `CorrectionResult` from original corrections
|
||||
4. Apply user corrections if `updated_corrections_gcs_path` provided (via `CorrectionOperations.update_correction_result_with_data`)
|
||||
5. Run `CountdownProcessor` on correction result + audio
|
||||
6. Load styles via `load_styles_from_gcs`
|
||||
7. Configure and run `OutputGenerator.generate_outputs()`
|
||||
8. Upload outputs to GCS:
|
||||
- `{output_gcs_prefix}videos/with_vocals.mkv`
|
||||
- `{output_gcs_prefix}lyrics/karaoke.ass`
|
||||
- `{output_gcs_prefix}lyrics/karaoke.lrc`
|
||||
- `{output_gcs_prefix}lyrics/corrected.txt`
|
||||
9. Return output file paths + countdown metadata in job status
|
||||
|
||||
**Response:** Standard `JobStatus` model, with `output_files` listing GCS blob paths and `metadata` containing:
|
||||
- `countdown_padding_added` (bool)
|
||||
- `countdown_padding_seconds` (float)
|
||||
- `render_duration_seconds` (float)
|
||||
|
||||
### Style Asset Disk Cache
|
||||
|
||||
To avoid repeated GCS downloads of the same default theme assets across jobs:
|
||||
|
||||
- **Location:** `/var/cache/karaoke-gen/{fonts,backgrounds,styles}/`
|
||||
- **Cache key:** SHA-256 hash of the GCS path (deterministic, changes when asset path changes)
|
||||
- **Lookup:** Before downloading, check if cached file exists; skip GCS download on hit
|
||||
- **Scope:** Fonts, background images, style_params.json
|
||||
- **No TTL needed:** GCS paths are versioned by theme ID — when a theme's assets change, the path changes, so the cache key changes naturally
|
||||
- **Startup:** Create cache directories on worker boot
|
||||
|
||||
This is a simple wrapper around `download_single_file_from_gcs` — a `download_with_cache(gcs_uri, local_path, cache_dir)` helper that checks the cache first.
|
||||
|
||||
### EncodingService: New methods
|
||||
|
||||
```python
|
||||
async def submit_render_video_job(self, job_id, render_config) -> dict:
|
||||
"""POST to /render-video, with retry logic."""
|
||||
|
||||
async def render_video_on_gce(self, job_id, render_config, progress_callback=None) -> dict:
|
||||
"""Submit + wait convenience method (like encode_videos)."""
|
||||
```
|
||||
|
||||
Uses the same `_request_with_retry`, `wait_for_completion`, retry/backoff, and poll failure tolerance as existing methods.
|
||||
|
||||
### render_video_worker: Conditional routing
|
||||
|
||||
```python
|
||||
encoding_service = get_encoding_service()
|
||||
|
||||
if encoding_service.is_enabled:
|
||||
# GCE path: build config from job data, delegate to GCE
|
||||
render_config = RenderVideoConfig(
|
||||
original_corrections_gcs_path=f"gs://{bucket}/jobs/{job_id}/lyrics/corrections.json",
|
||||
updated_corrections_gcs_path=..., # if exists
|
||||
audio_gcs_path=f"gs://{bucket}/{job.input_media_gcs_path}",
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
output_gcs_prefix=f"gs://{bucket}/jobs/{job_id}/",
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
subtitle_offset_ms=job.subtitle_offset_ms or 0,
|
||||
video_resolution="4k",
|
||||
)
|
||||
result = await encoding_service.render_video_on_gce(job_id, render_config)
|
||||
# Parse result: update file_urls, lyrics_metadata from response
|
||||
else:
|
||||
# Local fallback: existing OutputGenerator code (unchanged)
|
||||
```
|
||||
|
||||
Cloud Run does zero downloads in the GCE path — it just reads job metadata from Firestore and constructs GCS paths.
|
||||
|
||||
### Configuration
|
||||
|
||||
No new env vars. Reuses `USE_GCE_ENCODING` — render_video is video work that follows the same routing decision.
|
||||
|
||||
## What doesn't change
|
||||
|
||||
- The job pipeline flow (states, transitions, triggering video_worker after)
|
||||
- The local fallback path (existing code stays as-is for when GCE is disabled)
|
||||
- OutputGenerator itself (same library, same wheel, same output)
|
||||
- The GCE encoding worker's existing `/encode` and `/encode-preview` endpoints
|
||||
|
||||
## Risk: Code path divergence
|
||||
|
||||
Per LESSONS-LEARNED.md ("Alternative Code Paths Must Implement All Features"), both paths must produce identical output. This is inherently guaranteed because:
|
||||
- Both use the same `OutputGenerator` from the karaoke-gen wheel
|
||||
- Both use the same `load_styles_from_gcs` for style loading
|
||||
- Both use the same `CorrectionOperations` for applying user corrections
|
||||
- The GCE worker runs `ensure_latest_wheel()` to stay current
|
||||
|
||||
The only divergence risk is in the orchestration layer (Firestore updates, file URL construction), which stays on Cloud Run in both paths.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests for the new EncodingService methods (mock HTTP)
|
||||
- Unit tests for render_video_worker GCE routing logic (mock encoding_service)
|
||||
- Integration test: GCE worker `/render-video` endpoint with test fixtures
|
||||
- E2E: existing happy-path CI test validates the full pipeline
|
||||
@@ -0,0 +1,213 @@
|
||||
# Service Health Status Modal — Design Spec
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the static footer version/status line with a clickable element that opens a modal showing detailed system status. Non-admin users see service health, versions, and deploy info. Admin users additionally see blue-green encoder deployment details. Each service links to the PR that produced its current version.
|
||||
|
||||
## Footer Changes
|
||||
|
||||
The existing footer line (`Frontend: v0.155.3 | Backend: v0.155.3 | ● Encoder: v0.155.3 | ...`) becomes a single clickable element. On hover: `cursor: pointer`, slight opacity change. No other visual changes to the footer layout.
|
||||
|
||||
Clicking anywhere on the version/status line opens the modal.
|
||||
|
||||
## Modal — Public View (everyone)
|
||||
|
||||
### Layout
|
||||
|
||||
- Standard modal: dark backdrop (click to dismiss), X close button, title "System Status"
|
||||
- Responsive card grid: 2 columns on desktop, 1 column on mobile
|
||||
- 5 service cards: **Frontend**, **Backend**, **Encoder**, **Flacfetch**, **Separator**
|
||||
|
||||
### Card Contents
|
||||
|
||||
Each card shows:
|
||||
|
||||
| Element | Example |
|
||||
|---------|---------|
|
||||
| Status indicator | Green dot (●) + "Healthy" or red dot (○) + "Offline" |
|
||||
| Version | `v0.155.3` |
|
||||
| Deploy time | "Deployed 2 hours ago" (relative) |
|
||||
| Latest change | `#644 — fix blue-green deploy` (clickable link to GitHub PR) |
|
||||
|
||||
The "Latest change" line links to the GitHub PR that produced the currently deployed version. If unavailable, this line is omitted.
|
||||
|
||||
## Modal — Admin View (additional detail)
|
||||
|
||||
When the user has an admin token (stored in localStorage from login), the modal request includes it and the response includes extra data.
|
||||
|
||||
### Encoder Blue-Green Section
|
||||
|
||||
Inside the Encoder card, below the standard info, an expandable section labeled "Blue-Green Deployment" shows:
|
||||
|
||||
- **Two side-by-side mini-cards**: Primary (green-tinted border) and Secondary (muted/grey)
|
||||
- Each mini-card shows:
|
||||
- VM name (e.g., `encoding-worker-b`)
|
||||
- Version (e.g., `v0.155.3`)
|
||||
- Role label: "PRIMARY" (green) or "SECONDARY (stopped)" (muted)
|
||||
- **Deploy status line**: "Last swap: 2 hours ago" or "⚠ Deploy in progress..." (amber)
|
||||
- **Active jobs**: count on primary, if > 0
|
||||
|
||||
### Admin Detail on Other Cards
|
||||
|
||||
For Backend, Flacfetch, and Separator cards, admin view additionally shows:
|
||||
- Error message if status is offline (from the health check error field)
|
||||
|
||||
No extra admin detail needed for Frontend (it's a static site).
|
||||
|
||||
## New Backend Endpoint
|
||||
|
||||
### `GET /api/health/system-status`
|
||||
|
||||
Single endpoint that aggregates all service health data. Avoids the current pattern of 4 separate fetches.
|
||||
|
||||
**Authentication**: Optional `X-Admin-Token` header. If valid admin token, response includes `admin_details`. If omitted or invalid, those fields are absent.
|
||||
|
||||
**Response (public fields)**:
|
||||
|
||||
```json
|
||||
{
|
||||
"services": {
|
||||
"frontend": {
|
||||
"status": "ok",
|
||||
"version": "0.155.3",
|
||||
"deployed_at": "2026-03-31T18:10:00Z",
|
||||
"commit_sha": "8e2a949a",
|
||||
"pr_number": 644,
|
||||
"pr_title": "fix: complete blue-green deploy test payload and status check"
|
||||
},
|
||||
"backend": {
|
||||
"status": "ok",
|
||||
"version": "0.155.3",
|
||||
"deployed_at": "2026-03-31T18:10:00Z",
|
||||
"commit_sha": "8e2a949a",
|
||||
"pr_number": 644,
|
||||
"pr_title": "fix: complete blue-green deploy test payload and status check"
|
||||
},
|
||||
"encoder": {
|
||||
"status": "ok",
|
||||
"version": "0.155.3",
|
||||
"deployed_at": "2026-03-31T18:10:00Z",
|
||||
"active_jobs": 0
|
||||
},
|
||||
"flacfetch": {
|
||||
"status": "ok",
|
||||
"version": "0.19.1"
|
||||
},
|
||||
"separator": {
|
||||
"status": "ok",
|
||||
"version": "0.4.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Additional fields when admin token is valid**:
|
||||
|
||||
```json
|
||||
{
|
||||
"services": {
|
||||
"encoder": {
|
||||
"admin_details": {
|
||||
"primary_vm": "encoding-worker-b",
|
||||
"primary_ip": "34.10.189.118",
|
||||
"primary_version": "0.155.3",
|
||||
"primary_deployed_at": "2026-03-31T18:10:00Z",
|
||||
"secondary_vm": "encoding-worker-a",
|
||||
"secondary_ip": "34.57.78.246",
|
||||
"secondary_version": "0.155.2",
|
||||
"secondary_deployed_at": "2026-03-29T14:00:00Z",
|
||||
"last_swap_at": "2026-03-31T18:10:00Z",
|
||||
"deploy_in_progress": false,
|
||||
"active_jobs": 0,
|
||||
"queue_length": 0
|
||||
}
|
||||
},
|
||||
"flacfetch": {
|
||||
"admin_details": {
|
||||
"error": null
|
||||
}
|
||||
},
|
||||
"separator": {
|
||||
"admin_details": {
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Build Metadata — Git SHA and PR Info
|
||||
|
||||
Currently no git metadata is baked into builds. We need to add this.
|
||||
|
||||
### CI Changes (`.github/workflows/ci.yml`)
|
||||
|
||||
Add a step early in the deploy job that captures git info:
|
||||
|
||||
```yaml
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
# For merge commits, extract PR number from commit message
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '#\K[0-9]+' | head -1)
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
```
|
||||
|
||||
### Where metadata is stored
|
||||
|
||||
| Service | Storage mechanism |
|
||||
|---------|------------------|
|
||||
| **Frontend** | New env vars `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE`, `NEXT_PUBLIC_BUILD_TIME` set in CI before `npm run build`. Baked into the static bundle at build time via `next.config.mjs`. The `deployed_at` for frontend is the build timestamp (close enough to deploy time for Cloudflare Pages). |
|
||||
| **Backend** | New env vars `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` set on the Cloud Run service. Read at runtime in `backend/version.py`. |
|
||||
| **Encoder** | Written to GCS version manifest alongside the existing `version.txt`. The GCE worker reads it on startup and includes in `/health` response. |
|
||||
| **Flacfetch / Separator** | These are separate repos with their own CI. PR info can be added later — for now, omit the "Latest change" line for these services. |
|
||||
|
||||
### GitHub PR Link Format
|
||||
|
||||
The frontend constructs the PR link as:
|
||||
```
|
||||
https://github.com/nomadkaraoke/karaoke-gen/pull/{pr_number}
|
||||
```
|
||||
|
||||
Displayed as: `#{pr_number} — {pr_title}` (truncated to ~60 chars if needed).
|
||||
|
||||
## Frontend Components
|
||||
|
||||
### New files
|
||||
- `frontend/components/system-status-modal.tsx` — the modal component
|
||||
|
||||
### Modified files
|
||||
- `frontend/components/version-footer.tsx` — make status line clickable, add modal toggle state
|
||||
- `frontend/lib/api.ts` — add `SystemStatus` types and `getSystemStatus()` method
|
||||
- `frontend/next.config.mjs` — pass through new `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE` env vars
|
||||
|
||||
### Modified backend files
|
||||
- `backend/api/routes/health.py` — new `/api/health/system-status` endpoint
|
||||
- `backend/version.py` — read `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` env vars
|
||||
- `.github/workflows/ci.yml` — capture build metadata, pass to builds/deploys
|
||||
|
||||
### Data Flow
|
||||
|
||||
1. User clicks footer → modal opens, state set to loading
|
||||
2. Modal calls `GET /api/health/system-status` (with admin token header if available in localStorage)
|
||||
3. Endpoint aggregates: existing health checks + Firestore blue-green config + build metadata env vars
|
||||
4. Frontend renders cards from response
|
||||
5. No auto-refresh — data is fresh on each open
|
||||
|
||||
## Styling
|
||||
|
||||
- Follow existing project design patterns (Tailwind, CSS variables for theming)
|
||||
- Modal uses the same dark theme as the rest of the app
|
||||
- Cards use `var(--card-border)`, `var(--card-bg)` etc. for consistency
|
||||
- Green: `text-green-500` for healthy, red: `text-red-500` for offline
|
||||
- Blue-green section uses amber accent (`text-amber-500`, `border-amber-500/30`) to distinguish it as an operational detail
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Auto-refresh / polling in the modal (can be added later)
|
||||
- Flacfetch and Separator PR info (separate repos, separate CI)
|
||||
- Historical deploy data or deploy log
|
||||
- Notifications or alerts for status changes
|
||||
@@ -2,7 +2,7 @@
|
||||
* Unit tests for job-status.ts utility functions
|
||||
*/
|
||||
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, getDisplayJobs, JobStep } from '../lib/job-status';
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, JobStep } from '../lib/job-status';
|
||||
import type { Job } from '../lib/api';
|
||||
|
||||
// Helper to create a minimal Job object for testing
|
||||
@@ -556,152 +556,5 @@ describe('sortJobsByDate', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDisplayJobs', () => {
|
||||
// Helper: create jobs sorted by date (newest first)
|
||||
function createDateSortedJobs(jobSpecs: Array<{ status: string; date: string }>): Job[] {
|
||||
return jobSpecs
|
||||
.map((spec, i) => ({
|
||||
job_id: `job-${i}`,
|
||||
status: spec.status,
|
||||
progress: spec.status === 'complete' ? 100 : 0,
|
||||
created_at: spec.date,
|
||||
updated_at: spec.date,
|
||||
}))
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
}
|
||||
|
||||
it('returns all jobs when fewer than display limit', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'complete', date: '2024-01-01T10:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-01T11:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs).toHaveLength(3);
|
||||
expect(totalFetched).toBe(3);
|
||||
});
|
||||
|
||||
it('returns empty array for empty input', () => {
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs([], 5);
|
||||
expect(displayedJobs).toHaveLength(0);
|
||||
expect(totalFetched).toBe(0);
|
||||
});
|
||||
|
||||
it('limits to displayLimit', () => {
|
||||
const jobs = createDateSortedJobs(
|
||||
Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
|
||||
);
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
expect(totalFetched).toBe(10);
|
||||
});
|
||||
|
||||
it('returns all jobs when displayLimit is -1 (All mode)', () => {
|
||||
const jobs = createDateSortedJobs(
|
||||
Array.from({ length: 22 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
|
||||
);
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1);
|
||||
expect(displayedJobs).toHaveLength(22);
|
||||
expect(totalFetched).toBe(22);
|
||||
});
|
||||
|
||||
it('preserves date sort order from input', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-04T12:00:00Z' },
|
||||
{ status: 'awaiting_review', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
|
||||
]);
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 10);
|
||||
// Should be newest first
|
||||
expect(displayedJobs[0].created_at).toBe('2024-01-05T12:00:00Z');
|
||||
expect(displayedJobs[1].created_at).toBe('2024-01-04T12:00:00Z');
|
||||
expect(displayedJobs[2].created_at).toBe('2024-01-03T12:00:00Z');
|
||||
expect(displayedJobs[3].created_at).toBe('2024-01-02T12:00:00Z');
|
||||
});
|
||||
|
||||
describe('hideCompleted filter', () => {
|
||||
it('filters out only complete and prep_complete when hideCompleted is true (keeps failed)', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'awaiting_review', date: '2024-01-05T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'prep_complete', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1, true);
|
||||
expect(totalFetched).toBe(5);
|
||||
expect(displayedJobs).toHaveLength(3); // blocking + processing + failed
|
||||
expect(displayedJobs.some(j => j.status === 'failed')).toBe(true);
|
||||
expect(displayedJobs.some(j => j.status === 'complete')).toBe(false);
|
||||
expect(displayedJobs.some(j => j.status === 'prep_complete')).toBe(false);
|
||||
});
|
||||
|
||||
it('respects display limit after filtering', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'rendering_video', date: '2024-01-10T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-09T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-08T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-07T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-06T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
|
||||
...Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T10:00:00Z` })),
|
||||
]);
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5, true);
|
||||
// 7 non-complete jobs after filtering, but limit is 5
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('returns empty when all jobs are complete and hideCompleted is true', () => {
|
||||
const jobs = createDateSortedJobs(
|
||||
Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
|
||||
);
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5, true);
|
||||
expect(displayedJobs).toHaveLength(0);
|
||||
expect(totalFetched).toBe(10);
|
||||
});
|
||||
|
||||
it('does not filter when hideCompleted is false', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'awaiting_review', date: '2024-01-04T12:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const { displayedJobs } = getDisplayJobs(jobs, -1, false);
|
||||
expect(displayedJobs).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('defaults to showing all when hideCompleted is omitted', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const { displayedJobs } = getDisplayJobs(jobs, -1);
|
||||
expect(displayedJobs).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('core bug fix: recently failed job appears at top of list', () => {
|
||||
// The original bug: a newly failed job was invisible because priority sorting
|
||||
// put all 45 complete jobs above it, and the limit of 10 truncated it.
|
||||
// With date-based sorting, the newest job (failed) appears first.
|
||||
const jobs = sortJobsByDate([
|
||||
{ job_id: 'new-failed', status: 'failed', progress: 0, created_at: '2024-01-10T15:00:00Z', updated_at: '2024-01-10T15:00:00Z' },
|
||||
...Array.from({ length: 45 }, (_, i) => ({
|
||||
job_id: `complete-${i}`,
|
||||
status: 'complete',
|
||||
progress: 100,
|
||||
created_at: `2024-01-${String(10 - Math.floor(i / 5)).padStart(2, '0')}T${String(12 - (i % 5)).padStart(2, '0')}:00:00Z`,
|
||||
updated_at: '2024-01-01T00:00:00Z',
|
||||
})),
|
||||
]);
|
||||
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 10);
|
||||
// The failed job should be first (newest)
|
||||
expect(displayedJobs[0].job_id).toBe('new-failed');
|
||||
expect(displayedJobs[0].status).toBe('failed');
|
||||
expect(displayedJobs).toHaveLength(10);
|
||||
});
|
||||
});
|
||||
// Note: getDisplayJobs was removed — filtering is now handled server-side
|
||||
// via the status and search query parameters on GET /api/jobs
|
||||
@@ -184,7 +184,7 @@ export default function AdminUserDetailPage() {
|
||||
setImpersonating(true)
|
||||
const success = await startImpersonation(email)
|
||||
if (success) {
|
||||
router.push("/dashboard")
|
||||
router.push("/app")
|
||||
} else {
|
||||
const authError = useAuth.getState().error
|
||||
toast({
|
||||
|
||||
+81
-49
@@ -15,8 +15,8 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
|
||||
import { sortJobsByDate, getDisplayJobs } from "@/lib/job-status"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
|
||||
import { sortJobsByDate } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
@@ -50,6 +50,7 @@ function AppPageContent() {
|
||||
const [allJobs, setAllJobs] = useState<Job[]>([])
|
||||
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true)
|
||||
const [hasFetchedSuccessfully, setHasFetchedSuccessfully] = useState(false)
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
|
||||
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
@@ -62,10 +63,12 @@ function AppPageContent() {
|
||||
const saved = localStorage.getItem("nomad-karaoke-job-limit")
|
||||
return saved ? Number(saved) : 10
|
||||
})
|
||||
const [hideCompleted, setHideCompleted] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-hide-completed") === "true"
|
||||
const [statusFilter, setStatusFilter] = useState<string>(() => {
|
||||
if (typeof window === "undefined") return "active"
|
||||
return localStorage.getItem("nomad-karaoke-status-filter") || "active"
|
||||
})
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [showAdminControls, setShowAdminControls] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
|
||||
@@ -80,16 +83,16 @@ function AppPageContent() {
|
||||
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
|
||||
|
||||
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
|
||||
const visibleJobs = useMemo(
|
||||
const jobs = useMemo(
|
||||
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
|
||||
[allJobs]
|
||||
)
|
||||
|
||||
// Derive displayed jobs from visibleJobs + display limit + filter (instant, no re-fetch)
|
||||
const { displayedJobs: jobs, totalFetched } = useMemo(
|
||||
() => getDisplayJobs(visibleJobs, jobLimit, hideCompleted),
|
||||
[visibleJobs, jobLimit, hideCompleted]
|
||||
)
|
||||
// Debounce search input — only update the query (which triggers API calls) after 300ms
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSearchQuery(searchInput), 300)
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
const loadJobs = useCallback(async () => {
|
||||
@@ -99,25 +102,25 @@ function AppPageContent() {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Use summary mode for reduced payload (~12 fields instead of 50+)
|
||||
const data = await api.listJobs({
|
||||
limit: 100,
|
||||
limit: jobLimit,
|
||||
exclude_test: isAdmin ? !showTestData : undefined,
|
||||
fields: 'summary',
|
||||
hide_completed: hideCompleted,
|
||||
status: statusFilter !== 'all' && statusFilter !== 'active' ? statusFilter : undefined,
|
||||
hide_completed: statusFilter === 'active' ? true : undefined,
|
||||
search: searchQuery || undefined,
|
||||
})
|
||||
// Sort by creation date (newest first)
|
||||
setAllJobs(sortJobsByDate(data))
|
||||
} catch (err: any) {
|
||||
// Don't log auth errors - user just needs to authenticate
|
||||
if (err?.status !== 401) {
|
||||
console.error("Failed to load jobs:", err)
|
||||
}
|
||||
} finally {
|
||||
setIsLoadingJobs(false)
|
||||
setIsInitialLoad(false)
|
||||
setHasFetchedSuccessfully(true)
|
||||
}
|
||||
}, [isAdmin, showTestData, hideCompleted])
|
||||
}, [isAdmin, showTestData, jobLimit, statusFilter, searchQuery])
|
||||
|
||||
// Enable notifications for job status changes (sound + title animation)
|
||||
useJobNotifications(allJobs)
|
||||
@@ -389,62 +392,91 @@ function AppPageContent() {
|
||||
{/* Jobs List Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader className="px-3 sm:px-6">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
|
||||
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
onClick={() => {
|
||||
const next = !hideCompleted
|
||||
setHideCompleted(next)
|
||||
localStorage.setItem("nomad-karaoke-hide-completed", String(next))
|
||||
}}
|
||||
>
|
||||
{hideCompleted ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{hideCompleted ? "Show all jobs" : "Hide completed jobs"}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5" style={{ color: 'var(--text-muted)' }} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search..."
|
||||
aria-label="Search jobs"
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="h-7 w-[160px] sm:w-[200px] text-xs rounded-md border pl-7 pr-2"
|
||||
style={{
|
||||
backgroundColor: 'var(--input)',
|
||||
borderColor: 'var(--border)',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={(v) => {
|
||||
setStatusFilter(v)
|
||||
localStorage.setItem("nomad-karaoke-status-filter", v)
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[130px] text-xs" aria-label="Filter by status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
<SelectItem value="active">Active</SelectItem>
|
||||
<SelectItem value="failed">Failed</SelectItem>
|
||||
<SelectItem value="complete">Completed</SelectItem>
|
||||
<SelectItem value="cancelled">Cancelled</SelectItem>
|
||||
<SelectItem value="awaiting_review">Awaiting review</SelectItem>
|
||||
<SelectItem value="processing">Processing</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={String(jobLimit)} onValueChange={(v) => {
|
||||
const val = Number(v)
|
||||
setJobLimit(val)
|
||||
localStorage.setItem("nomad-karaoke-job-limit", String(val))
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[80px] text-xs">
|
||||
<SelectTrigger className="h-7 w-[70px] text-xs" aria-label="Results per page">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5</SelectItem>
|
||||
<SelectItem value="10">10</SelectItem>
|
||||
<SelectItem value="20">20</SelectItem>
|
||||
<SelectItem value="-1">All</SelectItem>
|
||||
<SelectItem value="50">50</SelectItem>
|
||||
<SelectItem value="100">100</SelectItem>
|
||||
<SelectItem value="1000">1000</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{hideCompleted
|
||||
? `${jobs.length} incomplete of ${totalFetched} total`
|
||||
: jobs.length < totalFetched
|
||||
? `Showing ${jobs.length} of ${totalFetched} jobs`
|
||||
{!hasFetchedSuccessfully
|
||||
? 'Loading...'
|
||||
: searchQuery || statusFilter !== 'active'
|
||||
? `${jobs.length} job${jobs.length !== 1 ? 's' : ''} matching filters`
|
||||
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="px-3 sm:px-6">
|
||||
{jobs.length === 0 ? (
|
||||
<div className="text-center py-8" style={{ color: 'var(--text-muted)' }}>
|
||||
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No jobs yet. Create one to get started!</p>
|
||||
{!hasFetchedSuccessfully ? (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 mx-auto mb-3 opacity-50 animate-spin" />
|
||||
<p>Loading jobs...</p>
|
||||
</>
|
||||
) : searchQuery || statusFilter !== 'active' ? (
|
||||
<>
|
||||
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No jobs match your filters.</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No jobs yet. Create one to get started!</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
|
||||
@@ -34,12 +34,12 @@ export function AppHeader() {
|
||||
return (
|
||||
<header className="sticky top-0 z-50 border-b border-border/50 bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="container mx-auto px-4 h-16 flex items-center justify-between">
|
||||
<Link href="/dashboard" className="h-10">
|
||||
<Link href="/app" className="h-10">
|
||||
<Logo className="h-10" />
|
||||
</Link>
|
||||
|
||||
<nav className="hidden md:flex items-center gap-6">
|
||||
<Link href="/dashboard" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
<Link href="/app" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
Dashboard
|
||||
</Link>
|
||||
<Link href="/jobs" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -171,7 +171,9 @@ export default function GuidancePanel({
|
||||
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
|
||||
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
|
||||
{totalGaps === 0 ? (
|
||||
{totalGaps === 0 && Object.keys(data.reference_lyrics).length === 0 ? (
|
||||
<p>No reference lyrics were found for this track. You can still review the transcription and click any word to edit. Use the <strong>Reference Lyrics</strong> panel on the right to search for lyrics with a different artist/title.</p>
|
||||
) : totalGaps === 0 ? (
|
||||
<p>All lyrics matched the reference — no corrections needed. You can still click any word to edit.</p>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -91,13 +91,24 @@ describe('GuidancePanel', () => {
|
||||
expect(screen.getByText(/Synced Lyrics/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows zero-gap message when no gaps exist', () => {
|
||||
const data = makeMockData({ gap_sequences: [], corrections: [] })
|
||||
it('shows zero-gap message when no gaps exist and references are present', () => {
|
||||
const data = makeMockData({
|
||||
gap_sequences: [],
|
||||
corrections: [],
|
||||
reference_lyrics: { genius: { segments: [], metadata: { source: 'genius' }, source: 'genius' } },
|
||||
})
|
||||
render(<GuidancePanel data={data} {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText(/All lyrics matched the reference/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows no-reference message when no reference sources exist', () => {
|
||||
const data = makeMockData({ gap_sequences: [], corrections: [], reference_lyrics: {} })
|
||||
render(<GuidancePanel data={data} {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText(/No reference lyrics were found/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('dismisses tip and stores in localStorage', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<GuidancePanel data={makeMockData()} {...defaultProps} />)
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -19,7 +19,7 @@ export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRout
|
||||
if (!user) {
|
||||
router.push("/")
|
||||
} else if (requireAdmin && user.role !== "admin") {
|
||||
router.push("/dashboard")
|
||||
router.push("/app")
|
||||
}
|
||||
}, [user, requireAdmin, router])
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { api, SystemStatus, ServiceStatus } from "@/lib/api";
|
||||
|
||||
interface SystemStatusModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function formatRelativeTime(isoString: string | null | undefined): string {
|
||||
if (!isoString) return "";
|
||||
const date = new Date(isoString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMin = Math.floor(diffMs / 60000);
|
||||
if (diffMin < 1) return "just now";
|
||||
if (diffMin < 60) return `${diffMin}m ago`;
|
||||
const diffHours = Math.floor(diffMin / 60);
|
||||
if (diffHours < 24) return `${diffHours}h ago`;
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
return `${diffDays}d ago`;
|
||||
}
|
||||
|
||||
function truncate(str: string, maxLen: number): string {
|
||||
if (str.length <= maxLen) return str;
|
||||
return str.slice(0, maxLen - 1) + "\u2026";
|
||||
}
|
||||
|
||||
function StatusDot({ status }: { status: string }) {
|
||||
const isOk = status === "ok";
|
||||
return (
|
||||
<span className={isOk ? "text-green-500" : "text-red-500"}>
|
||||
{isOk ? "\u25CF" : "\u25CB"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ServiceCard({
|
||||
name,
|
||||
service,
|
||||
children,
|
||||
}: {
|
||||
name: string;
|
||||
service: ServiceStatus;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
const isOk = service.status === "ok";
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border p-4"
|
||||
style={{
|
||||
borderColor: "var(--card-border)",
|
||||
backgroundColor: "var(--card-bg)",
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot status={service.status} />
|
||||
<span className="font-medium text-sm">{name}</span>
|
||||
</div>
|
||||
<span className="text-xs opacity-60">
|
||||
{isOk ? "Healthy" : "Offline"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{service.version && (
|
||||
<div className="text-xs opacity-75 mt-1">v{service.version}</div>
|
||||
)}
|
||||
|
||||
{service.deployed_at && (
|
||||
<div className="text-xs opacity-50 mt-0.5">
|
||||
Deployed {formatRelativeTime(service.deployed_at)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{service.pr_number && (
|
||||
<div className="text-xs mt-1">
|
||||
<a
|
||||
href={`https://github.com/nomadkaraoke/karaoke-gen/pull/${service.pr_number}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-amber-500 hover:underline"
|
||||
>
|
||||
#{service.pr_number}
|
||||
</a>
|
||||
{service.pr_title && (
|
||||
<span className="opacity-60">
|
||||
{" \u2014 "}
|
||||
{truncate(service.pr_title, 50)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BlueGreenSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="mt-3">
|
||||
<button
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
className="text-xs text-amber-500 hover:text-amber-400 flex items-center gap-1"
|
||||
>
|
||||
<span>{expanded ? "\u25BE" : "\u25B8"}</span>
|
||||
Blue-Green Deployment
|
||||
{details.deploy_in_progress && (
|
||||
<span className="text-amber-400 animate-pulse ml-1">\u26A0 deploying...</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="mt-2 grid grid-cols-2 gap-2">
|
||||
{/* Primary */}
|
||||
<div
|
||||
className="rounded p-2 text-xs border"
|
||||
style={{
|
||||
borderColor: "rgba(74,222,128,0.3)",
|
||||
backgroundColor: "rgba(74,222,128,0.05)",
|
||||
}}
|
||||
>
|
||||
<div className="text-green-500 text-[10px] font-semibold uppercase tracking-wider">
|
||||
Primary
|
||||
</div>
|
||||
<div className="mt-1 font-mono">{details.primary_vm}</div>
|
||||
<div className="opacity-60">v{details.primary_version}</div>
|
||||
{details.primary_deployed_at && (
|
||||
<div className="opacity-40">
|
||||
{formatRelativeTime(details.primary_deployed_at)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Secondary */}
|
||||
<div
|
||||
className="rounded p-2 text-xs border"
|
||||
style={{
|
||||
borderColor: "var(--card-border)",
|
||||
backgroundColor: "rgba(255,255,255,0.02)",
|
||||
}}
|
||||
>
|
||||
<div className="text-[10px] font-semibold uppercase tracking-wider opacity-50">
|
||||
Secondary (stopped)
|
||||
</div>
|
||||
<div className="mt-1 font-mono">{details.secondary_vm}</div>
|
||||
{details.secondary_version && (
|
||||
<div className="opacity-60">v{details.secondary_version}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Metadata row */}
|
||||
<div className="col-span-2 text-[10px] opacity-40 mt-1">
|
||||
{details.last_swap_at && (
|
||||
<span>Last swap: {formatRelativeTime(details.last_swap_at)}</span>
|
||||
)}
|
||||
{details.active_jobs != null && details.active_jobs > 0 && (
|
||||
<span className="ml-3">Active jobs: {details.active_jobs}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
|
||||
const [status, setStatus] = useState<SystemStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
api
|
||||
.getSystemStatus()
|
||||
.then(setStatus)
|
||||
.catch((e) => setError(e.message || "Failed to fetch status"))
|
||||
.finally(() => setLoading(false));
|
||||
}, [open]);
|
||||
|
||||
const frontendVersion = process.env.NEXT_PUBLIC_APP_VERSION || "dev";
|
||||
const frontendCommitSha = process.env.NEXT_PUBLIC_COMMIT_SHA || "";
|
||||
const frontendPrNumber = process.env.NEXT_PUBLIC_PR_NUMBER || "";
|
||||
const frontendPrTitle = process.env.NEXT_PUBLIC_PR_TITLE || "";
|
||||
const frontendBuildTime = process.env.NEXT_PUBLIC_BUILD_TIME || "";
|
||||
|
||||
// Override frontend service with build-time values
|
||||
const services = status?.services;
|
||||
const frontendService: ServiceStatus = {
|
||||
status: "ok",
|
||||
version: frontendVersion,
|
||||
deployed_at: frontendBuildTime || undefined,
|
||||
commit_sha: frontendCommitSha || undefined,
|
||||
pr_number: frontendPrNumber || undefined,
|
||||
pr_title: frontendPrTitle || undefined,
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--card-bg)", borderColor: "var(--card-border)" }}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground">System Status</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{loading && (
|
||||
<div className="py-8 text-center text-sm opacity-60">Loading...</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="py-8 text-center text-sm text-red-500">{error}</div>
|
||||
)}
|
||||
|
||||
{services && !loading && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
|
||||
<ServiceCard name="Frontend" service={frontendService} />
|
||||
<ServiceCard name="Backend" service={services.backend} />
|
||||
<ServiceCard name="Encoder" service={services.encoder}>
|
||||
{services.encoder.admin_details &&
|
||||
services.encoder.admin_details.primary_vm && (
|
||||
<BlueGreenSection details={services.encoder.admin_details} />
|
||||
)}
|
||||
</ServiceCard>
|
||||
<ServiceCard name="Flacfetch" service={services.flacfetch} />
|
||||
<ServiceCard name="Separator" service={services.separator} />
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, EncodingWorkerHealth, FlacfetchHealth, AudioSeparatorHealth } from "@/lib/api";
|
||||
import { SystemStatusModal } from "./system-status-modal";
|
||||
|
||||
export function VersionFooter() {
|
||||
const [backendVersion, setBackendVersion] = useState<string | null>(null);
|
||||
const [encodingWorker, setEncodingWorker] = useState<EncodingWorkerHealth | null>(null);
|
||||
const [flacfetch, setFlacfetch] = useState<FlacfetchHealth | null>(null);
|
||||
const [audioSeparator, setAudioSeparator] = useState<AudioSeparatorHealth | null>(null);
|
||||
// Frontend version is injected at build time from pyproject.toml
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const frontendVersion = process.env.NEXT_PUBLIC_APP_VERSION || "dev";
|
||||
|
||||
useEffect(() => {
|
||||
@@ -58,27 +59,18 @@ export function VersionFooter() {
|
||||
fetchAudioSeparatorHealth();
|
||||
}, []);
|
||||
|
||||
// Render encoding worker status indicator
|
||||
const renderEncodingWorkerStatus = () => {
|
||||
if (!encodingWorker) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (encodingWorker.status === "not_configured") {
|
||||
return null; // Don't show if not configured
|
||||
}
|
||||
if (!encodingWorker) return null;
|
||||
if (encodingWorker.status === "not_configured") return null;
|
||||
|
||||
const isHealthy = encodingWorker.available && encodingWorker.status === "ok";
|
||||
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
|
||||
const statusDot = isHealthy ? "●" : "○";
|
||||
const statusDot = isHealthy ? "\u25CF" : "\u25CB";
|
||||
|
||||
// Build status text
|
||||
let statusText = isHealthy ? "Encoder" : "Encoder offline";
|
||||
if (isHealthy && encodingWorker.version) {
|
||||
statusText = `Encoder: v${encodingWorker.version}`;
|
||||
}
|
||||
|
||||
// Add active jobs indicator if there are any
|
||||
if (isHealthy && encodingWorker.active_jobs && encodingWorker.active_jobs > 0) {
|
||||
statusText += ` (${encodingWorker.active_jobs} active)`;
|
||||
}
|
||||
@@ -86,29 +78,19 @@ export function VersionFooter() {
|
||||
return (
|
||||
<>
|
||||
{" | "}
|
||||
<span className={statusColor} title={isHealthy ? "Encoding worker healthy" : encodingWorker.error || "Encoding worker offline"}>
|
||||
{statusDot}
|
||||
</span>{" "}
|
||||
{statusText}
|
||||
<span className={statusColor}>{statusDot}</span> {statusText}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Render flacfetch status indicator
|
||||
const renderFlacfetchStatus = () => {
|
||||
if (!flacfetch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (flacfetch.status === "not_configured") {
|
||||
return null; // Don't show if not configured
|
||||
}
|
||||
if (!flacfetch) return null;
|
||||
if (flacfetch.status === "not_configured") return null;
|
||||
|
||||
const isHealthy = flacfetch.available && flacfetch.status === "ok";
|
||||
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
|
||||
const statusDot = isHealthy ? "●" : "○";
|
||||
const statusDot = isHealthy ? "\u25CF" : "\u25CB";
|
||||
|
||||
// Build status text
|
||||
let statusText = isHealthy ? "Flacfetch" : "Flacfetch offline";
|
||||
if (isHealthy && flacfetch.version) {
|
||||
statusText = `Flacfetch: v${flacfetch.version}`;
|
||||
@@ -117,27 +99,18 @@ export function VersionFooter() {
|
||||
return (
|
||||
<>
|
||||
{" | "}
|
||||
<span className={statusColor} title={isHealthy ? "Flacfetch service healthy" : flacfetch.error || "Flacfetch service offline"}>
|
||||
{statusDot}
|
||||
</span>{" "}
|
||||
{statusText}
|
||||
<span className={statusColor}>{statusDot}</span> {statusText}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Render audio separator status indicator
|
||||
const renderAudioSeparatorStatus = () => {
|
||||
if (!audioSeparator) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (audioSeparator.status === "not_configured") {
|
||||
return null;
|
||||
}
|
||||
if (!audioSeparator) return null;
|
||||
if (audioSeparator.status === "not_configured") return null;
|
||||
|
||||
const isHealthy = audioSeparator.available && audioSeparator.status === "ok";
|
||||
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
|
||||
const statusDot = isHealthy ? "●" : "○";
|
||||
const statusDot = isHealthy ? "\u25CF" : "\u25CB";
|
||||
|
||||
let statusText = isHealthy ? "Separator" : "Separator offline";
|
||||
if (isHealthy && audioSeparator.version) {
|
||||
@@ -147,36 +120,44 @@ export function VersionFooter() {
|
||||
return (
|
||||
<>
|
||||
{" | "}
|
||||
<span className={statusColor} title={isHealthy ? "Audio separator healthy" : audioSeparator.error || "Audio separator offline"}>
|
||||
{statusDot}
|
||||
</span>{" "}
|
||||
{statusText}
|
||||
<span className={statusColor}>{statusDot}</span> {statusText}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<p>
|
||||
Powered by{" "}
|
||||
<a href="https://github.com/nomadkaraoke/karaoke-gen" className="text-amber-500 hover:underline">
|
||||
karaoke-gen
|
||||
</a>
|
||||
</p>
|
||||
<p className="mt-1 text-xs opacity-75">
|
||||
Frontend: v{frontendVersion}
|
||||
{backendVersion && (
|
||||
<>
|
||||
{" | "}
|
||||
Backend: v{backendVersion}
|
||||
</>
|
||||
)}
|
||||
{renderEncodingWorkerStatus()}
|
||||
{renderFlacfetchStatus()}
|
||||
{renderAudioSeparatorStatus()}
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
<>
|
||||
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<p>
|
||||
Powered by{" "}
|
||||
<a href="https://github.com/nomadkaraoke/karaoke-gen" className="text-amber-500 hover:underline">
|
||||
karaoke-gen
|
||||
</a>
|
||||
</p>
|
||||
<p
|
||||
className="mt-1 text-xs opacity-75 cursor-pointer hover:opacity-100 transition-opacity"
|
||||
onClick={() => setModalOpen(true)}
|
||||
title="Click for detailed system status"
|
||||
>
|
||||
Frontend: v{frontendVersion}
|
||||
{backendVersion && (
|
||||
<>
|
||||
{" | "}
|
||||
Backend: v{backendVersion}
|
||||
</>
|
||||
)}
|
||||
{renderEncodingWorkerStatus()}
|
||||
{renderFlacfetchStatus()}
|
||||
{renderAudioSeparatorStatus()}
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<SystemStatusModal
|
||||
open={modalOpen}
|
||||
onClose={() => setModalOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
|
||||
+70
-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
|
||||
@@ -304,6 +304,43 @@ export interface AudioSeparatorHealth {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ServiceStatus {
|
||||
status: string; // 'ok' | 'offline'
|
||||
version?: string | null;
|
||||
deployed_at?: string | null;
|
||||
commit_sha?: string | null;
|
||||
pr_number?: string | null;
|
||||
pr_title?: string | null;
|
||||
active_jobs?: number;
|
||||
admin_details?: {
|
||||
// Encoder blue-green
|
||||
primary_vm?: string;
|
||||
primary_ip?: string;
|
||||
primary_version?: string;
|
||||
primary_deployed_at?: string;
|
||||
secondary_vm?: string;
|
||||
secondary_ip?: string;
|
||||
secondary_version?: string;
|
||||
secondary_deployed_at?: string;
|
||||
last_swap_at?: string;
|
||||
deploy_in_progress?: boolean;
|
||||
active_jobs?: number;
|
||||
queue_length?: number;
|
||||
// Error details for offline services
|
||||
error?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SystemStatus {
|
||||
services: {
|
||||
frontend: ServiceStatus;
|
||||
backend: ServiceStatus;
|
||||
encoder: ServiceStatus;
|
||||
flacfetch: ServiceStatus;
|
||||
separator: ServiceStatus;
|
||||
};
|
||||
}
|
||||
|
||||
// Signed URL upload types
|
||||
export interface SignedUploadUrl {
|
||||
file_type: string;
|
||||
@@ -427,6 +464,7 @@ export const api = {
|
||||
exclude_test?: boolean;
|
||||
fields?: 'summary';
|
||||
hide_completed?: boolean;
|
||||
search?: string;
|
||||
}): Promise<Job[]> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.status) searchParams.set('status', params.status);
|
||||
@@ -434,6 +472,7 @@ export const api = {
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
if (params?.fields) searchParams.set('fields', params.fields);
|
||||
if (params?.hide_completed !== undefined) searchParams.set('hide_completed', String(params.hide_completed));
|
||||
if (params?.search) searchParams.set('search', params.search);
|
||||
|
||||
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
@@ -1320,6 +1359,16 @@ export const api = {
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get aggregated system status for all services
|
||||
*/
|
||||
async getSystemStatus(): Promise<SystemStatus> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/health/system-status`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
// ==========================================================================
|
||||
// Credits/Payment API endpoints
|
||||
// ==========================================================================
|
||||
@@ -2732,6 +2781,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 +2889,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
|
||||
*/
|
||||
|
||||
@@ -294,36 +294,3 @@ export function sortJobsByDate(jobs: Job[]): Job[] {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Select which jobs to display from a sorted list.
|
||||
* When sorted by date, simply applies the display limit and hide-completed filter.
|
||||
*
|
||||
* @param sortedJobs - Jobs already sorted by sortJobsByDate
|
||||
* @param displayLimit - Max jobs to show (-1 = show all)
|
||||
* @returns Object with displayedJobs array and totalFetched count
|
||||
*/
|
||||
export function getDisplayJobs(
|
||||
sortedJobs: Job[],
|
||||
displayLimit: number,
|
||||
hideCompleted: boolean = false
|
||||
): { displayedJobs: Job[]; totalFetched: number } {
|
||||
const totalFetched = sortedJobs.length;
|
||||
|
||||
// Filter out successfully completed jobs when toggle is on (keep failed jobs visible)
|
||||
const filteredJobs = hideCompleted
|
||||
? sortedJobs.filter((job) => {
|
||||
const status = job.status?.toLowerCase() || ""
|
||||
return status !== "complete" && status !== "prep_complete"
|
||||
})
|
||||
: sortedJobs;
|
||||
|
||||
// Show all: -1 or fewer jobs than limit
|
||||
if (displayLimit === -1 || filteredJobs.length <= displayLimit) {
|
||||
return { displayedJobs: filteredJobs, totalFetched };
|
||||
}
|
||||
|
||||
return {
|
||||
displayedJobs: filteredJobs.slice(0, displayLimit),
|
||||
totalFetched,
|
||||
};
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -20,6 +20,10 @@ try {
|
||||
const nextConfig = {
|
||||
env: {
|
||||
NEXT_PUBLIC_APP_VERSION: appVersion,
|
||||
NEXT_PUBLIC_COMMIT_SHA: process.env.NEXT_PUBLIC_COMMIT_SHA || '',
|
||||
NEXT_PUBLIC_PR_NUMBER: process.env.NEXT_PUBLIC_PR_NUMBER || '',
|
||||
NEXT_PUBLIC_PR_TITLE: process.env.NEXT_PUBLIC_PR_TITLE || '',
|
||||
NEXT_PUBLIC_BUILD_TIME: process.env.NEXT_PUBLIC_BUILD_TIME || new Date().toISOString(),
|
||||
},
|
||||
// Only use static export for production builds (not dev)
|
||||
output: process.env.NODE_ENV === 'production' ? 'export' : undefined,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -38,10 +38,11 @@ from config import (
|
||||
)
|
||||
from modules import database, storage as storage_module, artifact_registry, secrets
|
||||
from modules import cloud_tasks, cloud_run, monitoring, networking, runner_manager
|
||||
from modules import divebar_mirror, kn_data_sync, divebar_lookup
|
||||
from modules import divebar_mirror, kn_data_sync, divebar_lookup, backup
|
||||
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 modules.iam import backend_sa, github_actions_sa, claude_automation_sa, claude_readonly_sa, worker_sas
|
||||
from compute import encoding_worker_vm, github_runners, divebar_sync_vm
|
||||
|
||||
# ==================== Core Infrastructure ====================
|
||||
@@ -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",
|
||||
@@ -121,6 +134,26 @@ claude_impersonation = claude_automation_sa.grant_impersonation_permission(
|
||||
claude_automation_service_account
|
||||
)
|
||||
|
||||
# Claude read-only service account (default for Claude Code sessions)
|
||||
claude_readonly_service_account = claude_readonly_sa.create_claude_readonly_service_account()
|
||||
claude_readonly_iam_bindings = claude_readonly_sa.grant_claude_readonly_permissions(
|
||||
claude_readonly_service_account
|
||||
)
|
||||
claude_readonly_impersonation = claude_readonly_sa.grant_impersonation_permission(
|
||||
claude_readonly_service_account
|
||||
)
|
||||
|
||||
# Break-glass service account (excepted from deny policies)
|
||||
break_glass_service_account = claude_readonly_sa.create_break_glass_service_account()
|
||||
|
||||
# IAM deny policies (prevent catastrophic deletes for all principals)
|
||||
# TODO: Deny policy creation fails via Pulumi (v2beta API 404 / IAM permissions issue).
|
||||
# Create manually via gcloud once permissions are sorted:
|
||||
# gcloud iam policies create deny-destructive-operations \
|
||||
# --attachment-point="cloudresourcemanager.googleapis.com/projects/718638054799" \
|
||||
# --kind=denypolicies --policy-file=deny-policy.json
|
||||
# deny_policies = claude_readonly_sa.create_deny_policies(break_glass_service_account)
|
||||
|
||||
# Worker service accounts (VMs)
|
||||
encoding_worker_sa = worker_sas.create_encoding_worker_service_account()
|
||||
encoding_worker_iam_bindings = worker_sas.grant_encoding_worker_permissions(
|
||||
@@ -433,6 +466,9 @@ divebar_sync_compute_admin = gcp.projects.IAMMember(
|
||||
),
|
||||
)
|
||||
|
||||
# ==================== Backup to AWS ====================
|
||||
backup_resources = backup.create_backup_resources(all_secrets)
|
||||
|
||||
# ==================== Audio Separator GPU Service ====================
|
||||
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
|
||||
audio_separator_resources = audio_separator_service.create_all_resources()
|
||||
@@ -526,6 +562,8 @@ pulumi.export("firestore_index_logs_worker_timestamp", db_resources["firestore_i
|
||||
pulumi.export("service_account_email", backend_service_account.email)
|
||||
pulumi.export("github_actions_service_account", github_actions_service_account.email)
|
||||
pulumi.export("claude_automation_service_account", claude_automation_service_account.email)
|
||||
pulumi.export("claude_readonly_service_account", claude_readonly_service_account.email)
|
||||
pulumi.export("break_glass_service_account", break_glass_service_account.email)
|
||||
|
||||
# Artifact Registry
|
||||
pulumi.export("artifact_repo_url", artifact_registry.get_repo_url(artifact_repo))
|
||||
@@ -624,3 +662,9 @@ pulumi.export("audio_separator_service_account", audio_separator_resources["serv
|
||||
# Encoding worker idle shutdown
|
||||
pulumi.export("encoding_worker_idle_function_url", encoding_worker_idle_resources["function"].url)
|
||||
pulumi.export("encoding_worker_idle_scheduler", encoding_worker_idle_resources["scheduler"].name)
|
||||
|
||||
# Backup to AWS
|
||||
pulumi.export("backup_function_url", backup_resources["function"].url)
|
||||
pulumi.export("backup_staging_bucket", backup_resources["staging_bucket"].name)
|
||||
pulumi.export("backup_scheduler_name", backup_resources["scheduler"].name)
|
||||
pulumi.export("backup_service_account", backup_resources["service_account"].email)
|
||||
@@ -52,5 +52,7 @@ export GOOGLE_CLOUD_PROJECT="nomadkaraoke"
|
||||
log "Starting file sync (workers=4)..."
|
||||
python3 "$SCRIPT" --workers 4 2>&1 | tee -a "$LOG_FILE"
|
||||
|
||||
# The script handles shutdown itself after completion
|
||||
log "=== Divebar file sync script exited ==="
|
||||
|
||||
log "Shutting down VM after sync completion..."
|
||||
shutdown -h now
|
||||
Binary file not shown.
@@ -0,0 +1,83 @@
|
||||
"""BigQuery table export to GCS staging bucket as Parquet."""
|
||||
|
||||
import logging
|
||||
from google.cloud import bigquery
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DATASET = "karaoke_decide"
|
||||
|
||||
WEEKLY_TABLES = [
|
||||
"karaokenerds_raw",
|
||||
"karaokenerds_community",
|
||||
"divebar_catalog",
|
||||
"kn_divebar_xref",
|
||||
]
|
||||
|
||||
MONTHLY_TABLES = [
|
||||
"mb_artists",
|
||||
"mb_recordings",
|
||||
"mb_artist_tags",
|
||||
"mb_recording_isrc",
|
||||
"mbid_spotify_mapping",
|
||||
"mb_artists_normalized",
|
||||
"karaoke_recording_links",
|
||||
"mlhd_artist_similarity",
|
||||
]
|
||||
|
||||
|
||||
def export_bigquery_tables(
|
||||
project: str,
|
||||
staging_bucket: str,
|
||||
date_str: str,
|
||||
day_of_week: int,
|
||||
day_of_month: int,
|
||||
) -> str:
|
||||
"""Export BigQuery tables to GCS as Parquet based on schedule.
|
||||
|
||||
Args:
|
||||
project: GCP project ID.
|
||||
staging_bucket: GCS staging bucket name.
|
||||
date_str: ISO date string for folder naming.
|
||||
day_of_week: 0=Monday, 6=Sunday.
|
||||
day_of_month: 1-31.
|
||||
|
||||
Returns:
|
||||
Summary string.
|
||||
"""
|
||||
tables_to_export = []
|
||||
|
||||
if day_of_week == 6: # Sunday
|
||||
tables_to_export.extend((t, "daily-refresh") for t in WEEKLY_TABLES)
|
||||
|
||||
if day_of_month == 1: # 1st of month
|
||||
tables_to_export.extend((t, "musicbrainz") for t in MONTHLY_TABLES)
|
||||
|
||||
if not tables_to_export:
|
||||
logger.info("No BigQuery exports scheduled for today")
|
||||
return "Skipped — no exports scheduled"
|
||||
|
||||
client = bigquery.Client(project=project)
|
||||
exported = []
|
||||
|
||||
for table_name, prefix in tables_to_export:
|
||||
source = f"{project}.{DATASET}.{table_name}"
|
||||
dest_uri = f"gs://{staging_bucket}/bigquery/{prefix}/{date_str}/{table_name}/*.parquet"
|
||||
|
||||
logger.info(f"Exporting {source} to {dest_uri}")
|
||||
|
||||
job_config = bigquery.ExtractJobConfig(
|
||||
destination_format=bigquery.DestinationFormat.PARQUET,
|
||||
)
|
||||
|
||||
job = client.extract_table(
|
||||
source=source,
|
||||
destination_uris=[dest_uri],
|
||||
job_config=job_config,
|
||||
)
|
||||
job.result(timeout=600)
|
||||
|
||||
exported.append(table_name)
|
||||
logger.info(f"Exported {table_name}")
|
||||
|
||||
return f"Exported {len(exported)} tables: {', '.join(exported)}"
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Discord webhook notifications for backup status."""
|
||||
|
||||
import logging
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def send_alert(webhook_url: str, title: str, fields: list[dict], success: bool = True):
|
||||
"""Send a Discord embed notification."""
|
||||
color = 0x00FF00 if success else 0xFF0000
|
||||
embed = {"title": title, "color": color, "fields": fields}
|
||||
|
||||
try:
|
||||
resp = requests.post(webhook_url, json={"embeds": [embed]}, timeout=10)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send Discord alert: {e}")
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Firestore export to GCS staging bucket."""
|
||||
|
||||
import logging
|
||||
from google.cloud import firestore_admin_v1
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
|
||||
"""Export all Firestore collections to GCS.
|
||||
|
||||
Args:
|
||||
project: GCP project ID.
|
||||
staging_bucket: GCS staging bucket name.
|
||||
date_str: ISO date string (YYYY-MM-DD) for the export folder.
|
||||
|
||||
Returns:
|
||||
Summary string of the export.
|
||||
"""
|
||||
client = firestore_admin_v1.FirestoreAdminClient()
|
||||
database_name = f"projects/{project}/databases/(default)"
|
||||
output_uri = f"gs://{staging_bucket}/firestore/{date_str}"
|
||||
|
||||
logger.info(f"Starting Firestore export to {output_uri}")
|
||||
|
||||
operation = client.export_documents(
|
||||
request={
|
||||
"name": database_name,
|
||||
"output_uri_prefix": output_uri,
|
||||
}
|
||||
)
|
||||
|
||||
result = operation.result(timeout=1800) # 30 min timeout
|
||||
|
||||
logger.info(f"Firestore export complete: {output_uri}")
|
||||
return f"Exported to {output_uri} ({date_str})"
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Sync new/changed GCS objects to the staging bucket."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud import storage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SYNC_PREFIXES = ["jobs/", "tenants/", "themes/"]
|
||||
|
||||
|
||||
def sync_gcs_to_staging(
|
||||
source_bucket: str,
|
||||
staging_bucket: str,
|
||||
staging_prefix: str,
|
||||
max_objects: int = 5000,
|
||||
) -> str:
|
||||
"""Copy new/changed objects from source to staging bucket.
|
||||
|
||||
Uses object metadata (updated time) to detect changes since last sync.
|
||||
The staging bucket stores a marker file with the last sync timestamp.
|
||||
|
||||
Args:
|
||||
source_bucket: Source GCS bucket name.
|
||||
staging_bucket: Staging GCS bucket name.
|
||||
staging_prefix: Prefix in staging bucket for synced files.
|
||||
max_objects: Max objects to sync per run (safety limit).
|
||||
|
||||
Returns:
|
||||
Summary string.
|
||||
"""
|
||||
client = storage.Client()
|
||||
src = client.bucket(source_bucket)
|
||||
dst = client.bucket(staging_bucket)
|
||||
|
||||
marker_blob = dst.blob(f"{staging_prefix}.last_sync")
|
||||
last_sync_dt = None
|
||||
if marker_blob.exists():
|
||||
last_sync_str = marker_blob.download_as_text().strip()
|
||||
last_sync_dt = datetime.fromisoformat(last_sync_str)
|
||||
logger.info(f"Last sync: {last_sync_str}")
|
||||
|
||||
copied = 0
|
||||
latest_updated_dt = last_sync_dt
|
||||
|
||||
for prefix in SYNC_PREFIXES:
|
||||
blobs = src.list_blobs(prefix=prefix)
|
||||
for blob in blobs:
|
||||
if not blob.updated:
|
||||
continue
|
||||
|
||||
if last_sync_dt and blob.updated <= last_sync_dt:
|
||||
continue
|
||||
|
||||
dst_path = f"{staging_prefix}{blob.name}"
|
||||
src.copy_blob(blob, dst, dst_path)
|
||||
copied += 1
|
||||
|
||||
if latest_updated_dt is None or blob.updated > latest_updated_dt:
|
||||
latest_updated_dt = blob.updated
|
||||
|
||||
if copied >= max_objects:
|
||||
logger.warning(f"Hit max_objects limit ({max_objects})")
|
||||
break
|
||||
|
||||
if copied >= max_objects:
|
||||
break
|
||||
|
||||
if latest_updated_dt:
|
||||
marker_blob.upload_from_string(latest_updated_dt.isoformat())
|
||||
|
||||
logger.info(f"Synced {copied} objects from {source_bucket}")
|
||||
return f"Synced {copied} objects"
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
Backup to AWS Cloud Function.
|
||||
|
||||
Nightly backup pipeline:
|
||||
1. Firestore export to GCS staging
|
||||
2. BigQuery export to GCS staging (weekly/monthly schedule)
|
||||
3. GCS job files delta sync to staging
|
||||
4. Upload staging files to S3
|
||||
5. Discord alert
|
||||
|
||||
Triggered by Cloud Scheduler at 1:00 AM ET daily.
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
import functions_framework
|
||||
|
||||
from discord_alert import send_alert
|
||||
from firestore_export import export_firestore
|
||||
from bigquery_export import export_bigquery_tables
|
||||
from gcs_sync import sync_gcs_to_staging
|
||||
from s3_upload import upload_staging_to_s3
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STAGING_BUCKET = os.environ.get("STAGING_BUCKET", "nomadkaraoke-backup-staging")
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "nomadkaraoke-backup")
|
||||
GCP_PROJECT = os.environ.get("GCP_PROJECT", "nomadkaraoke")
|
||||
DISCORD_WEBHOOK_URL = os.environ.get("DISCORD_WEBHOOK_URL", "")
|
||||
|
||||
|
||||
@functions_framework.http
|
||||
def backup_to_aws(request):
|
||||
"""Main entry point for the backup Cloud Function."""
|
||||
today = datetime.date.today()
|
||||
date_str = today.isoformat()
|
||||
results = {}
|
||||
errors = []
|
||||
|
||||
logger.info(f"Starting backup for {date_str}")
|
||||
|
||||
# Step 1: Firestore export (nightly)
|
||||
try:
|
||||
results["firestore"] = export_firestore(
|
||||
project=GCP_PROJECT,
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
date_str=date_str,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Firestore export failed: {e}")
|
||||
errors.append(f"Firestore: {e}")
|
||||
|
||||
# Step 2: BigQuery export (weekly on Sundays, monthly on 1st)
|
||||
try:
|
||||
bq_results = export_bigquery_tables(
|
||||
project=GCP_PROJECT,
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
date_str=date_str,
|
||||
day_of_week=today.weekday(),
|
||||
day_of_month=today.day,
|
||||
)
|
||||
results["bigquery"] = bq_results
|
||||
except Exception as e:
|
||||
logger.error(f"BigQuery export failed: {e}")
|
||||
errors.append(f"BigQuery: {e}")
|
||||
|
||||
# Step 3: GCS delta sync (nightly)
|
||||
try:
|
||||
results["gcs_sync"] = sync_gcs_to_staging(
|
||||
source_bucket="karaoke-gen-storage-nomadkaraoke",
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
staging_prefix="gcs/job-files/",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"GCS sync failed: {e}")
|
||||
errors.append(f"GCS sync: {e}")
|
||||
|
||||
# Step 4: Upload to S3
|
||||
try:
|
||||
results["s3_upload"] = upload_staging_to_s3(
|
||||
staging_bucket=STAGING_BUCKET,
|
||||
s3_bucket=S3_BUCKET,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"S3 upload failed: {e}")
|
||||
errors.append(f"S3 upload: {e}")
|
||||
|
||||
# Step 5: Discord alert
|
||||
success = len(errors) == 0
|
||||
fields = [
|
||||
{"name": "Date", "value": date_str, "inline": True},
|
||||
{"name": "Status", "value": "Success" if success else "FAILED", "inline": True},
|
||||
]
|
||||
if errors:
|
||||
fields.append({"name": "Errors", "value": "\n".join(errors), "inline": False})
|
||||
for key, value in results.items():
|
||||
if isinstance(value, str):
|
||||
fields.append({"name": key, "value": value, "inline": True})
|
||||
|
||||
if DISCORD_WEBHOOK_URL:
|
||||
send_alert(
|
||||
webhook_url=DISCORD_WEBHOOK_URL,
|
||||
title="Nightly Backup Report",
|
||||
fields=fields,
|
||||
success=success,
|
||||
)
|
||||
|
||||
status_code = 200 if success else 500
|
||||
return json.dumps({"status": "ok" if success else "failed", "errors": errors}), status_code
|
||||
@@ -0,0 +1,7 @@
|
||||
functions-framework==3.*
|
||||
google-cloud-firestore==2.*
|
||||
google-cloud-bigquery==3.*
|
||||
google-cloud-storage==2.*
|
||||
google-cloud-secret-manager==2.*
|
||||
boto3==1.*
|
||||
requests==2.*
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Upload files from GCS staging bucket to AWS S3."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import boto3
|
||||
from google.cloud import storage, secretmanager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_aws_credentials(project: str) -> dict:
|
||||
"""Retrieve AWS credentials from GCP Secret Manager."""
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
name = f"projects/{project}/secrets/aws-backup-credentials/versions/latest"
|
||||
response = client.access_secret_version(request={"name": name})
|
||||
return json.loads(response.payload.data.decode("utf-8"))
|
||||
|
||||
|
||||
def upload_staging_to_s3(
|
||||
staging_bucket: str,
|
||||
s3_bucket: str,
|
||||
project: str = "nomadkaraoke",
|
||||
) -> str:
|
||||
"""Upload all objects in staging bucket to S3 using streaming.
|
||||
|
||||
Walks the staging bucket and uploads each object to the corresponding
|
||||
S3 key path. Skips marker files (.*).
|
||||
"""
|
||||
aws_creds = get_aws_credentials(project)
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
aws_access_key_id=aws_creds["access_key_id"],
|
||||
aws_secret_access_key=aws_creds["secret_access_key"],
|
||||
region_name=aws_creds.get("region", "us-east-1"),
|
||||
)
|
||||
|
||||
gcs_client = storage.Client()
|
||||
bucket = gcs_client.bucket(staging_bucket)
|
||||
|
||||
uploaded = 0
|
||||
errors = 0
|
||||
|
||||
for blob in bucket.list_blobs():
|
||||
if blob.name.startswith(".") or "/.last_sync" in blob.name:
|
||||
continue
|
||||
|
||||
try:
|
||||
with blob.open("rb") as gcs_file:
|
||||
s3_client.upload_fileobj(
|
||||
Fileobj=gcs_file,
|
||||
Bucket=s3_bucket,
|
||||
Key=blob.name,
|
||||
)
|
||||
uploaded += 1
|
||||
blob.delete()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to upload {blob.name}: {e}")
|
||||
errors += 1
|
||||
|
||||
summary = f"Uploaded {uploaded} files to s3://{s3_bucket}"
|
||||
if errors:
|
||||
summary += f" ({errors} errors)"
|
||||
logger.info(summary)
|
||||
return summary
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Tests for bigquery_export module."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
DAILY_REFRESH_TABLES = [
|
||||
"karaokenerds_raw",
|
||||
"karaokenerds_community",
|
||||
"divebar_catalog",
|
||||
"kn_divebar_xref",
|
||||
]
|
||||
|
||||
MONTHLY_TABLES = [
|
||||
"mb_artists",
|
||||
"mb_recordings",
|
||||
"mb_artist_tags",
|
||||
"mb_recording_isrc",
|
||||
"mbid_spotify_mapping",
|
||||
"mb_artists_normalized",
|
||||
"karaoke_recording_links",
|
||||
"mlhd_artist_similarity",
|
||||
]
|
||||
|
||||
|
||||
class TestBigQueryExport(unittest.TestCase):
|
||||
@patch("bigquery_export.bigquery.Client")
|
||||
def test_weekly_export_on_sunday(self, mock_client_class):
|
||||
from bigquery_export import export_bigquery_tables
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_job = MagicMock()
|
||||
mock_job.result.return_value = None
|
||||
mock_client.extract_table.return_value = mock_job
|
||||
|
||||
result = export_bigquery_tables(
|
||||
project="test",
|
||||
staging_bucket="staging",
|
||||
date_str="2026-03-29",
|
||||
day_of_week=6,
|
||||
day_of_month=29,
|
||||
)
|
||||
|
||||
assert mock_client.extract_table.call_count == len(DAILY_REFRESH_TABLES)
|
||||
|
||||
@patch("bigquery_export.bigquery.Client")
|
||||
def test_monthly_export_on_first(self, mock_client_class):
|
||||
from bigquery_export import export_bigquery_tables
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_job = MagicMock()
|
||||
mock_job.result.return_value = None
|
||||
mock_client.extract_table.return_value = mock_job
|
||||
|
||||
result = export_bigquery_tables(
|
||||
project="test",
|
||||
staging_bucket="staging",
|
||||
date_str="2026-04-01",
|
||||
day_of_week=2,
|
||||
day_of_month=1,
|
||||
)
|
||||
|
||||
assert mock_client.extract_table.call_count == len(MONTHLY_TABLES)
|
||||
|
||||
@patch("bigquery_export.bigquery.Client")
|
||||
def test_no_export_on_regular_day(self, mock_client_class):
|
||||
from bigquery_export import export_bigquery_tables
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
|
||||
result = export_bigquery_tables(
|
||||
project="test",
|
||||
staging_bucket="staging",
|
||||
date_str="2026-03-25",
|
||||
day_of_week=1,
|
||||
day_of_month=25,
|
||||
)
|
||||
|
||||
mock_client.extract_table.assert_not_called()
|
||||
assert "skipped" in result.lower()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Tests for firestore_export module."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
class TestFirestoreExport(unittest.TestCase):
|
||||
@patch("firestore_export.firestore_admin_v1.FirestoreAdminClient")
|
||||
def test_export_firestore_calls_api(self, mock_client_class):
|
||||
from firestore_export import export_firestore
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_operation = MagicMock()
|
||||
mock_operation.result.return_value = MagicMock()
|
||||
mock_client.export_documents.return_value = mock_operation
|
||||
|
||||
result = export_firestore(
|
||||
project="test-project",
|
||||
staging_bucket="test-staging",
|
||||
date_str="2026-03-29",
|
||||
)
|
||||
|
||||
mock_client.export_documents.assert_called_once()
|
||||
call_args = mock_client.export_documents.call_args
|
||||
request = call_args[1]["request"]
|
||||
assert request["name"] == "projects/test-project/databases/(default)"
|
||||
assert "gs://test-staging/firestore/2026-03-29" in request["output_uri_prefix"]
|
||||
|
||||
@patch("firestore_export.firestore_admin_v1.FirestoreAdminClient")
|
||||
def test_export_firestore_returns_summary(self, mock_client_class):
|
||||
from firestore_export import export_firestore
|
||||
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_operation = MagicMock()
|
||||
mock_operation.result.return_value = MagicMock()
|
||||
mock_client.export_documents.return_value = mock_operation
|
||||
|
||||
result = export_firestore("proj", "bucket", "2026-03-29")
|
||||
assert isinstance(result, str)
|
||||
assert "2026-03-29" in result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,6 +3,9 @@ Build and upload the Divebar catalog index to BigQuery.
|
||||
|
||||
Takes the flat file listing from drive_client and the parsed metadata
|
||||
from filename_parser, and loads it into a BigQuery table.
|
||||
|
||||
Uses a staging table + MERGE to preserve gcs_path values set by the
|
||||
file sync script (divebar_file_sync.py).
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -17,8 +20,10 @@ logger = logging.getLogger(__name__)
|
||||
# BigQuery table reference
|
||||
DATASET_ID = "karaoke_decide"
|
||||
TABLE_ID = "divebar_catalog"
|
||||
STAGING_TABLE_ID = "divebar_catalog_staging"
|
||||
|
||||
SCHEMA = [
|
||||
# Schema for the staging table (no gcs_path — that lives only in the main table)
|
||||
STAGING_SCHEMA = [
|
||||
bigquery.SchemaField("file_id", "STRING", mode="REQUIRED"),
|
||||
bigquery.SchemaField("brand", "STRING", mode="REQUIRED"),
|
||||
bigquery.SchemaField("brand_code", "STRING"),
|
||||
@@ -78,31 +83,84 @@ def load_to_bigquery(project_id: str, rows: list[dict]) -> int:
|
||||
"""
|
||||
Load rows into the BigQuery divebar_catalog table.
|
||||
|
||||
Uses WRITE_TRUNCATE to atomically replace the entire table contents.
|
||||
Returns the number of rows loaded.
|
||||
Uses a staging table + MERGE to update the catalog without losing
|
||||
gcs_path values set by the file sync script. Steps:
|
||||
1. WRITE_TRUNCATE the staging table with fresh Drive data
|
||||
2. MERGE staging into main table:
|
||||
- UPDATE existing rows (by file_id) with fresh metadata
|
||||
- INSERT new rows
|
||||
- DELETE rows no longer in Drive
|
||||
gcs_path is preserved on updates and defaults to NULL on inserts.
|
||||
|
||||
Returns the number of rows in the main table after merge.
|
||||
"""
|
||||
if not rows:
|
||||
logger.warning("No rows to load")
|
||||
return 0
|
||||
|
||||
client = bigquery.Client(project=project_id)
|
||||
table_ref = f"{project_id}.{DATASET_ID}.{TABLE_ID}"
|
||||
staging_ref = f"{project_id}.{DATASET_ID}.{STAGING_TABLE_ID}"
|
||||
main_ref = f"{project_id}.{DATASET_ID}.{TABLE_ID}"
|
||||
|
||||
# Step 1: Load fresh data into staging table (TRUNCATE is fine here)
|
||||
job_config = bigquery.LoadJobConfig(
|
||||
schema=SCHEMA,
|
||||
schema=STAGING_SCHEMA,
|
||||
write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
|
||||
source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,
|
||||
)
|
||||
|
||||
# BigQuery load from in-memory rows
|
||||
load_job = client.load_table_from_json(
|
||||
rows,
|
||||
table_ref,
|
||||
job_config=job_config,
|
||||
)
|
||||
|
||||
# Wait for completion
|
||||
load_job = client.load_table_from_json(rows, staging_ref, job_config=job_config)
|
||||
load_job.result()
|
||||
logger.info("Loaded %d rows to staging table", load_job.output_rows)
|
||||
|
||||
logger.info("Loaded %d rows to %s", load_job.output_rows, table_ref)
|
||||
return load_job.output_rows
|
||||
# Step 2: MERGE staging into main table, preserving gcs_path
|
||||
merge_sql = f"""
|
||||
MERGE `{main_ref}` AS main
|
||||
USING `{staging_ref}` AS staging
|
||||
ON main.file_id = staging.file_id
|
||||
|
||||
WHEN MATCHED THEN UPDATE SET
|
||||
brand = staging.brand,
|
||||
brand_code = staging.brand_code,
|
||||
artist = staging.artist,
|
||||
title = staging.title,
|
||||
disc_id = staging.disc_id,
|
||||
filename = staging.filename,
|
||||
format = staging.format,
|
||||
subfolder = staging.subfolder,
|
||||
file_size = staging.file_size,
|
||||
drive_path = staging.drive_path,
|
||||
drive_md5 = staging.drive_md5,
|
||||
artist_normalized = staging.artist_normalized,
|
||||
title_normalized = staging.title_normalized,
|
||||
synced_at = staging.synced_at
|
||||
|
||||
WHEN NOT MATCHED BY TARGET THEN INSERT (
|
||||
file_id, brand, brand_code, artist, title, disc_id,
|
||||
filename, format, subfolder, file_size, drive_path,
|
||||
drive_md5, artist_normalized, title_normalized, synced_at,
|
||||
gcs_path
|
||||
) VALUES (
|
||||
staging.file_id, staging.brand, staging.brand_code,
|
||||
staging.artist, staging.title, staging.disc_id,
|
||||
staging.filename, staging.format, staging.subfolder,
|
||||
staging.file_size, staging.drive_path, staging.drive_md5,
|
||||
staging.artist_normalized, staging.title_normalized,
|
||||
staging.synced_at, NULL
|
||||
)
|
||||
|
||||
WHEN NOT MATCHED BY SOURCE THEN DELETE
|
||||
"""
|
||||
|
||||
logger.info("Merging staging into main table (preserving gcs_path)...")
|
||||
merge_job = client.query(merge_sql)
|
||||
merge_job.result()
|
||||
|
||||
# Get final row count
|
||||
count_result = list(client.query(
|
||||
f"SELECT COUNT(*) as cnt FROM `{main_ref}`"
|
||||
).result())
|
||||
final_count = count_result[0].cnt if count_result else 0
|
||||
|
||||
logger.info("Merge complete. Main table has %d rows", final_count)
|
||||
return final_count
|
||||
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user