mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 01:48:08 +09:00
Compare commits
No files matched your search
@@ -0,0 +1,277 @@
|
||||
name: Build GHA Runner Images
|
||||
|
||||
# Produces three custom GCE images used by the ephemeral GitHub Actions runner
|
||||
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu.
|
||||
#
|
||||
# Flow per variant:
|
||||
# 1. Create a temporary build VM from debian-cloud/debian-12 with
|
||||
# infrastructure/scripts/runner-image-provision.sh as metadata-startup-script.
|
||||
# 2. Poll for /opt/runner-image-ready via gcloud ssh (survives kernel-upgrade reboots).
|
||||
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
|
||||
# image family with name gha-runner-<variant>-<timestamp>.
|
||||
# 4. Delete the build VM (boot disk auto-deletes).
|
||||
# 5. Deprecate older images in the family, keeping the newest 3 ACTIVE.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variants:
|
||||
description: 'Comma-separated variants to build (general,build,gpu) or "all"'
|
||||
required: false
|
||||
default: 'all'
|
||||
skip_prune:
|
||||
description: 'Skip deprecation of old images (debugging)'
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
schedule:
|
||||
# Monthly on the 1st at 02:00 UTC
|
||||
- cron: '0 2 1 * *'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
GCP_PROJECT: nomadkaraoke
|
||||
BUILD_REGION: us-central1
|
||||
BUILD_ZONE: us-central1-a
|
||||
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
|
||||
KEEP_IMAGES_PER_FAMILY: 3
|
||||
|
||||
jobs:
|
||||
resolve-matrix:
|
||||
name: Resolve variant matrix
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
variants: ${{ steps.resolve.outputs.variants }}
|
||||
steps:
|
||||
- id: resolve
|
||||
run: |
|
||||
requested='${{ github.event.inputs.variants || 'all' }}'
|
||||
if [[ "$requested" == "all" || -z "$requested" ]]; then
|
||||
echo 'variants=["general","build","gpu"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
|
||||
echo "variants=$json" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.variant }} image
|
||||
needs: resolve-matrix
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
variant: ${{ fromJSON(needs.resolve-matrix.outputs.variants) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Set up Cloud SDK
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
with:
|
||||
project_id: ${{ env.GCP_PROJECT }}
|
||||
|
||||
- name: Resolve build parameters
|
||||
id: params
|
||||
run: |
|
||||
variant='${{ matrix.variant }}'
|
||||
ts="$(date -u +%Y%m%d-%H%M%S)"
|
||||
name="gha-runner-${variant}-${ts}"
|
||||
family="gha-runner-${variant}"
|
||||
vm="gha-image-build-${variant}-${ts}"
|
||||
|
||||
case "$variant" in
|
||||
general|build)
|
||||
machine="n2-standard-8"
|
||||
disk_size="50"
|
||||
accel=""
|
||||
;;
|
||||
gpu)
|
||||
# Build with a T4 attached so DKMS module is built and validated
|
||||
# against the kernel that ships in the image.
|
||||
machine="n1-standard-4"
|
||||
disk_size="200"
|
||||
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown variant: $variant" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "name=$name"
|
||||
echo "family=$family"
|
||||
echo "vm=$vm"
|
||||
echo "machine=$machine"
|
||||
echo "disk_size=$disk_size"
|
||||
echo "accel=$accel"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create build VM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gcloud compute instances create '${{ steps.params.outputs.vm }}' \
|
||||
--project='${{ env.GCP_PROJECT }}' \
|
||||
--zone='${{ env.BUILD_ZONE }}' \
|
||||
--machine-type='${{ steps.params.outputs.machine }}' \
|
||||
--image='${{ env.BASE_IMAGE }}' \
|
||||
--boot-disk-size='${{ steps.params.outputs.disk_size }}GB' \
|
||||
--boot-disk-type=pd-balanced \
|
||||
--boot-disk-auto-delete \
|
||||
--service-account="${{ secrets.GCP_SERVICE_ACCOUNT }}" \
|
||||
--scopes=https://www.googleapis.com/auth/cloud-platform \
|
||||
--metadata=enable-oslogin=TRUE,image-variant='${{ matrix.variant }}' \
|
||||
--metadata-from-file=startup-script=infrastructure/scripts/runner-image-provision.sh \
|
||||
--labels=purpose=gha-runner-image-builder,variant='${{ matrix.variant }}' \
|
||||
${{ steps.params.outputs.accel }}
|
||||
|
||||
- name: Wait for provisioning to complete
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
# Read the serial console — NOT SSH — to detect completion.
|
||||
#
|
||||
# The provisioner script tees its full output to /dev/ttyS0 (the GCE
|
||||
# serial console). `gcloud compute instances get-serial-port-output`
|
||||
# returns the full console buffer with zero SSH/IAP dependency. This
|
||||
# makes the wait robust against the IAP tunnel issues that previously
|
||||
# caused both false-positive readiness and false-negative timeouts.
|
||||
#
|
||||
# The script writes one of two distinctive marker lines:
|
||||
# "### runner-image: READY: ..." — successful completion
|
||||
# "### runner-image-provision FAILED ..." — fatal error (with line+rc)
|
||||
#
|
||||
# We also stream live progress to the GHA log so the operator can
|
||||
# see what's happening without leaving the run page.
|
||||
deadline=$(( $(date +%s) + 75 * 60 ))
|
||||
last_size=0
|
||||
attempt=0
|
||||
while (( $(date +%s) < deadline )); do
|
||||
attempt=$((attempt+1))
|
||||
console=$(gcloud compute instances get-serial-port-output "$VM" \
|
||||
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null || true)
|
||||
cur_size=${#console}
|
||||
# Stream new provisioner lines (filter syslog noise).
|
||||
if (( cur_size > last_size )); then
|
||||
echo "$console" | tail -c +$((last_size+1)) \
|
||||
| grep -E "runner-image|### |Attempt " || true
|
||||
last_size=$cur_size
|
||||
fi
|
||||
# Success marker
|
||||
if echo "$console" | grep -qE 'runner-image: READY:'; then
|
||||
echo
|
||||
echo "### Image ready (attempt $attempt)"
|
||||
echo "$console" | grep -E 'runner-image: READY:' | tail -1
|
||||
exit 0
|
||||
fi
|
||||
# Failure marker
|
||||
if echo "$console" | grep -qE 'runner-image-provision FAILED'; then
|
||||
echo
|
||||
echo "### Provisioner reported FAILURE — failure block + 40 lines of preceding context:" >&2
|
||||
# -B 40: include 40 lines BEFORE the marker (where the actual
|
||||
# error output of the failing command lives — python tracebacks,
|
||||
# apt errors, curl messages, etc).
|
||||
# -A 5: include the variant/line/cmd metadata lines after the marker.
|
||||
echo "$console" | grep -B 40 -A 5 'runner-image-provision FAILED' \
|
||||
| tail -80 >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 30
|
||||
done
|
||||
echo
|
||||
echo "### Timed out waiting for READY marker after 75 minutes" >&2
|
||||
echo "### Last serial console output (tail):" >&2
|
||||
gcloud compute instances get-serial-port-output "$VM" \
|
||||
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null \
|
||||
| grep -E "runner-image|### " | tail -50 >&2 || true
|
||||
exit 1
|
||||
|
||||
- name: Stop build VM
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gcloud compute instances stop "$VM" --zone="$ZONE" --project="$PROJECT" --quiet
|
||||
# Belt-and-suspenders wait for TERMINATED.
|
||||
for _ in $(seq 1 60); do
|
||||
status=$(gcloud compute instances describe "$VM" --zone="$ZONE" --project="$PROJECT" --format='value(status)')
|
||||
[[ "$status" == "TERMINATED" ]] && break
|
||||
sleep 5
|
||||
done
|
||||
|
||||
- name: Create image
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
IMAGE: ${{ steps.params.outputs.name }}
|
||||
FAMILY: ${{ steps.params.outputs.family }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The "Create build VM" step doesn't pass --device-name or
|
||||
# --boot-disk-name, so GCE auto-names the boot disk after the
|
||||
# instance. We rely on that here instead of extracting the name
|
||||
# via a format expression — the previous
|
||||
# `disks[0].source.scope(disks).segment(1)` selector silently
|
||||
# returned empty and gcloud rejected the call with
|
||||
# "You cannot specify [--source-disk-zone] unless you are
|
||||
# specifying [--source-disk]".
|
||||
DISK="$VM"
|
||||
echo "Creating image $IMAGE in family $FAMILY from disk $DISK in $ZONE..."
|
||||
gcloud compute images create "$IMAGE" \
|
||||
--project="$PROJECT" \
|
||||
--source-disk="$DISK" \
|
||||
--source-disk-zone="$ZONE" \
|
||||
--family="$FAMILY" \
|
||||
--description="GHA ephemeral runner image (${{ matrix.variant }}) built ${{ github.run_id }}" \
|
||||
--labels=purpose=gha-ephemeral-runner,variant=${{ matrix.variant }},built-by=gha
|
||||
echo "Created $IMAGE in family $FAMILY"
|
||||
|
||||
- name: Delete build VM
|
||||
if: always()
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
run: |
|
||||
gcloud compute instances delete "$VM" --zone="$ZONE" --project="$PROJECT" --quiet || true
|
||||
|
||||
- name: Deprecate old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
|
||||
if: ${{ github.event.inputs.skip_prune != 'true' }}
|
||||
env:
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
FAMILY: ${{ steps.params.outputs.family }}
|
||||
KEEP: ${{ env.KEEP_IMAGES_PER_FAMILY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# List ACTIVE images in this family, newest first, skip the top $KEEP.
|
||||
to_deprecate=$(gcloud compute images list \
|
||||
--project="$PROJECT" \
|
||||
--filter="family=$FAMILY AND status=READY AND -deprecated.state:*" \
|
||||
--sort-by='~creationTimestamp' \
|
||||
--format='value(name)' | tail -n +$((KEEP+1)))
|
||||
if [[ -z "$to_deprecate" ]]; then
|
||||
echo "Nothing to deprecate."
|
||||
exit 0
|
||||
fi
|
||||
for img in $to_deprecate; do
|
||||
echo "Deprecating $img"
|
||||
gcloud compute images deprecate "$img" \
|
||||
--project="$PROJECT" \
|
||||
--state=DEPRECATED \
|
||||
--replacement="projects/$PROJECT/global/images/family/$FAMILY"
|
||||
done
|
||||
+85
-32
@@ -268,7 +268,7 @@ jobs:
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
RESPONSE=$(curl -sf --connect-timeout 5 --max-time 30 -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
@@ -516,7 +516,10 @@ jobs:
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
|
||||
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
|
||||
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
|
||||
run: poetry build --format wheel
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
@@ -577,6 +580,15 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
- name: Cache spaCy model
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/spacy
|
||||
key: spacy-en_core_web_sm-${{ runner.os }}
|
||||
|
||||
- name: Install spaCy language models
|
||||
run: poetry run python -m spacy download en_core_web_sm
|
||||
|
||||
- name: Run all backend unit tests
|
||||
env:
|
||||
GOOGLE_CLOUD_PROJECT: test-project
|
||||
@@ -643,7 +655,17 @@ jobs:
|
||||
java-version: "21"
|
||||
|
||||
- name: Install Firestore emulator
|
||||
run: sudo apt-get install -y google-cloud-cli-firestore-emulator
|
||||
run: |
|
||||
# Ensure Google Cloud SDK apt source is present (ephemeral runner images
|
||||
# may not ship it pre-installed). Idempotent.
|
||||
if ! grep -rq "packages.cloud.google.com" /etc/apt/sources.list.d/ 2>/dev/null; then
|
||||
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | \
|
||||
sudo tee /etc/apt/sources.list.d/google-cloud-sdk.list
|
||||
curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | \
|
||||
sudo gpg --dearmor --yes -o /usr/share/keyrings/cloud.google.gpg
|
||||
fi
|
||||
sudo apt-get update -y
|
||||
sudo apt-get install -y google-cloud-cli-firestore-emulator
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
@@ -812,7 +834,12 @@ jobs:
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
|
||||
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
|
||||
# dead weight and pushed the project over PyPI's 10 GB storage cap.
|
||||
# pip always installs from the wheel; nothing builds karaoke-gen from
|
||||
# source (the GCE encoding worker pulls the wheel from GCS).
|
||||
run: poetry build --format wheel
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -906,7 +933,6 @@ jobs:
|
||||
prerelease: false
|
||||
files: |
|
||||
dist/*.whl
|
||||
dist/*.tar.gz
|
||||
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (Cloudflare Pages)"
|
||||
@@ -1228,7 +1254,7 @@ jobs:
|
||||
|
||||
echo "Waiting for service at $HEALTH_URL..."
|
||||
for i in $(seq 1 18); do
|
||||
RESPONSE=$(curl -sf "$HEALTH_URL" 2>/dev/null || echo "")
|
||||
RESPONSE=$(curl -sf --connect-timeout 3 --max-time 5 "$HEALTH_URL" 2>/dev/null || echo "")
|
||||
if [ -n "$RESPONSE" ]; then
|
||||
WHEEL_VERSION=$(echo "$RESPONSE" | jq -r '.wheel_version // empty')
|
||||
echo "Health: version=$WHEEL_VERSION"
|
||||
@@ -1264,7 +1290,8 @@ jobs:
|
||||
"${DEPLOY_TEST_PATH}/test-audio.flac"
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
|
||||
HTTP_CODE=$(curl -s --connect-timeout 5 --max-time 30 \
|
||||
-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" \
|
||||
@@ -1293,7 +1320,7 @@ jobs:
|
||||
|
||||
for i in $(seq 1 12); do
|
||||
sleep 5
|
||||
JOB_STATUS=$(curl -s \
|
||||
JOB_STATUS=$(curl -s --connect-timeout 3 --max-time 10 \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-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)"
|
||||
@@ -1379,29 +1406,47 @@ jobs:
|
||||
run: |
|
||||
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
|
||||
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
# Probe the worker's active_jobs. Echoes a non-negative integer on a
|
||||
# successful /health response, or "unknown" if /health can't be
|
||||
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
|
||||
# encoder running a 4K render pins all 32 cores and can miss the 5s
|
||||
# health window, and treating that as idle previously let us stop the
|
||||
# VM mid-render — orphaning the job and surfacing as "lost contact
|
||||
# with worker ... not found" (incident 2026-06-15).
|
||||
probe_active_jobs() {
|
||||
local body n
|
||||
body=$(curl -sf --connect-timeout 3 --max-time 5 \
|
||||
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
|
||||
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
|
||||
case "$n" in
|
||||
''|*[!0-9]*) echo "unknown" ;;
|
||||
*) echo "$n" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if [ "$ACTIVE_JOBS" -gt 0 ]; then
|
||||
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
|
||||
DRAIN_TIMEOUT=600
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
if [ "$ACTIVE_JOBS" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
|
||||
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
|
||||
# waiting — we only stop on a definitive 0 (or after the timeout, so
|
||||
# a wedged worker can't block the deploy forever). 20 min comfortably
|
||||
# covers a full 4K render; the old primary only drains in-flight work
|
||||
# since new renders already route to the just-swapped new primary.
|
||||
DRAIN_TIMEOUT=1200
|
||||
ELAPSED=0
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "Initial active_jobs: $ACTIVE_JOBS"
|
||||
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
done
|
||||
|
||||
if [ "$ACTIVE_JOBS" = "0" ]; then
|
||||
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
|
||||
else
|
||||
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
@@ -1638,8 +1683,8 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,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"
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
@@ -1656,6 +1701,14 @@ jobs:
|
||||
--quiet
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
|
||||
# ("Invalid secret path ... in annotation") because this job's existing
|
||||
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
|
||||
# re-validates and rejects. Proactive auto-correct env/secret
|
||||
# (AUTO_CORRECT_PROACTIVE_ENABLED + ANTHROPIC_API_KEY) must be wired by a
|
||||
# method that handles the alias format (see proactive-autocorrect plan
|
||||
# doc); until then the proactive flag stays unset and the worker's
|
||||
# _run_proactive_auto_correct() returns early (no-op).
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
@@ -1686,7 +1739,7 @@ jobs:
|
||||
sleep 15
|
||||
|
||||
# Basic health check
|
||||
curl -f "$SERVICE_URL/api/health" || exit 1
|
||||
curl -f --connect-timeout 5 --max-time 30 "$SERVICE_URL/api/health" || exit 1
|
||||
echo "✅ Service is healthy"
|
||||
|
||||
# Version verification with retries (Cloud Run may take time to route to new revision)
|
||||
@@ -1694,7 +1747,7 @@ jobs:
|
||||
RETRY_DELAY=10
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Checking deployed version (attempt $i/$MAX_RETRIES)..."
|
||||
DEPLOYED_VERSION=$(curl -sf "$SERVICE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
DEPLOYED_VERSION=$(curl -sf --connect-timeout 5 --max-time 30 "$SERVICE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
|
||||
if [ "$DEPLOYED_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Version verified: $DEPLOYED_VERSION"
|
||||
|
||||
@@ -54,8 +54,14 @@ jobs:
|
||||
|
||||
BUCKET = os.environ["BUCKET"]
|
||||
# (label, prefix, max_age_hours)
|
||||
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
|
||||
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
|
||||
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
|
||||
# sees the S3 (off-site) copy, so their limits must allow a full week
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
|
||||
# files and secrets DO upload to S3 nightly, so they stay at 36h.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 36),
|
||||
("Firestore", "firestore/", 192),
|
||||
("GCS job files", "gcs/job-files/", 36),
|
||||
("Encrypted secrets", "secrets/", 36),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192),
|
||||
|
||||
@@ -83,6 +83,7 @@ jobs:
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run Credit Purchase Test
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
@@ -102,16 +103,18 @@ jobs:
|
||||
--reporter=list \
|
||||
--timeout=600000 \
|
||||
2>&1 | tee test-output-payment.log
|
||||
# Capture Playwright's real exit code, not tee's (0) — the
|
||||
# authoritative pass/fail signal. See Stage 2 for rationale.
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "CREDIT PURCHASE TEST PASSED" test-output-payment.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Extract session token
|
||||
@@ -209,6 +212,7 @@ jobs:
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Test
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
@@ -234,16 +238,20 @@ jobs:
|
||||
--reporter=list \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-happy-path.log
|
||||
# Capture Playwright's real exit code, not tee's (0). This is the
|
||||
# authoritative pass/fail signal — grepping the log for "failed" is
|
||||
# fragile because benign retry warnings (e.g. "goto attempt 1/3
|
||||
# failed") contain that substring and produce false alarms.
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "passed" test-output-happy-path.log && ! grep -q "failed" test-output-happy-path.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
@@ -317,10 +325,10 @@ jobs:
|
||||
if: github.event_name == 'schedule'
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.sendgrid.net
|
||||
server_address: smtp.postmarkapp.com
|
||||
server_port: 587
|
||||
username: apikey
|
||||
password: ${{ secrets.SENDGRID_API_KEY }}
|
||||
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
name: E2E Daily Test (Tenant Portals)
|
||||
|
||||
# Full production E2E per white-label tenant: submit a job with the tenant's own
|
||||
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
|
||||
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
|
||||
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
|
||||
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
|
||||
# top-of-hour scheduler herd.
|
||||
- cron: '7 0 * * *'
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # for Workload Identity Federation
|
||||
|
||||
jobs:
|
||||
e2e-tenant:
|
||||
name: "Tenant E2E: ${{ matrix.tenant }}"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
|
||||
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
|
||||
max-parallel: 1
|
||||
matrix:
|
||||
tenant: [vocalstar, singa]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Fetch test audio (private GCS)
|
||||
run: bash scripts/e2e/fetch_test_audio.sh frontend/e2e/fixtures
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted (rate limit)
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run tenant E2E (frontend journey)
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
TENANT_ID: ${{ matrix.tenant }}
|
||||
TENANT_PORTAL_URL: https://${{ matrix.tenant }}.nomadkaraoke.com
|
||||
run: |
|
||||
echo "=== Tenant E2E (frontend): ${{ matrix.tenant }} ==="
|
||||
npx playwright test tenant-happy-path.spec.ts \
|
||||
--config=playwright.production.config.ts --project=chromium \
|
||||
--reporter=list --timeout=2400000 2>&1 | tee e2e-output.log
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/e2e-output.log
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
retention-days: 14
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
|
||||
run: |
|
||||
if [ -n "$DISCORD_WEBHOOK" ]; then
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
|
||||
"$DISCORD_WEBHOOK" || true
|
||||
fi
|
||||
|
||||
- name: Fail the job if the test failed
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
run: exit 1
|
||||
|
||||
notify-email:
|
||||
name: "Email summary"
|
||||
runs-on: ubuntu-latest
|
||||
needs: e2e-tenant
|
||||
if: ${{ always() && github.event_name == 'schedule' }}
|
||||
steps:
|
||||
- name: Send email notification
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.postmarkapp.com
|
||||
server_port: 587
|
||||
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
Tenant E2E Daily Test (Vocal Star + Singa)
|
||||
Result: ${{ needs.e2e-tenant.result }}
|
||||
Run: #${{ github.run_number }}
|
||||
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -102,8 +102,10 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
|
||||
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
|
||||
- Components use `useTranslations('namespace')` from next-intl
|
||||
- Pages are under `frontend/src/app/[locale]/` — locale-aware routing
|
||||
- Admin pages (under `/admin/`, `/app/`) use DefaultIntlProvider (English-only, excluded from i18n)
|
||||
- Pages are under `frontend/app/[locale]/` — locale-aware routing (customer-facing: `/`, `/app/*`, `/order/*`, `/auth/*`, `/payment/*`, `/r/*`)
|
||||
- Non-locale routes at those same paths (e.g. `frontend/app/app/jobs/[[...slug]]/page.tsx`) are `<LocaleRedirect />` shims that redirect into `[locale]` — they are NOT English-only surfaces
|
||||
- The `/app/jobs/#/{id}/review`, `/instrumental`, and `/audio-edit` review UIs are fully multilingual (components under `components/lyrics-review/`, `components/instrumental-review/`, `components/audio-editor/` use `useTranslations` heavily)
|
||||
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
|
||||
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
|
||||
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
|
||||
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Makefile for karaoke-gen project
|
||||
# Run `make help` to see available commands
|
||||
|
||||
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
|
||||
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop eval-custom-lyrics
|
||||
|
||||
# Per-stage timeout in seconds (default: 10 minutes)
|
||||
# Prevents hangs from stale dev servers, broken emulators, etc.
|
||||
@@ -133,3 +133,7 @@ clean:
|
||||
rm -rf htmlcov/ .coverage coverage.xml 2>/dev/null || true
|
||||
@echo "Cleaned up temporary files"
|
||||
|
||||
.PHONY: eval-custom-lyrics
|
||||
eval-custom-lyrics:
|
||||
cd backend && poetry run python -m backend.eval.custom_lyrics.run
|
||||
|
||||
@@ -1709,6 +1709,12 @@ async def delete_job_outputs(
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too (prefix-keyed
|
||||
# by brand_code, covers renames). Non-fatal, Nomad-only, no-op otherwise.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
|
||||
# Clean up GCS finals folder - prevents stale files from being picked up during re-encoding
|
||||
try:
|
||||
from backend.services.storage_service import StorageService
|
||||
@@ -2049,6 +2055,7 @@ REGENERATE_SCREENS_ALLOWED_STATES = {
|
||||
"complete",
|
||||
"failed",
|
||||
"awaiting_review",
|
||||
"in_review", # User opened the review UI but hasn't submitted yet
|
||||
"awaiting_instrumental_selection",
|
||||
"instrumental_selected",
|
||||
"prep_complete",
|
||||
@@ -2131,7 +2138,7 @@ async def regenerate_screens(
|
||||
]
|
||||
for path in screen_paths:
|
||||
try:
|
||||
storage.delete_file(path)
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
except Exception:
|
||||
pass # File may not exist
|
||||
screens_deleted = True
|
||||
@@ -2286,16 +2293,16 @@ async def restart_job(
|
||||
for screen_file in ["title.mov", "title.jpg", "title.png", "end.mov", "end.jpg", "end.png"]:
|
||||
try:
|
||||
path = f"jobs/{job_id}/screens/{screen_file}"
|
||||
storage.delete_file(path)
|
||||
deleted_paths.append(path)
|
||||
if storage.delete_file(path, ignore_missing=True):
|
||||
deleted_paths.append(path)
|
||||
except Exception:
|
||||
pass
|
||||
# Delete final outputs
|
||||
for output_file in ["final_4k.mp4", "final_720p.mp4", "with_vocals.mkv", "preview.mp4"]:
|
||||
try:
|
||||
path = f"jobs/{job_id}/output/{output_file}"
|
||||
storage.delete_file(path)
|
||||
deleted_paths.append(path)
|
||||
if storage.delete_file(path, ignore_missing=True):
|
||||
deleted_paths.append(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from pathlib import Path
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
@@ -228,6 +230,9 @@ class AudioSelectRequest(BaseModel):
|
||||
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
|
||||
display_artist: Optional[str] = Field(None, description="Override display artist name")
|
||||
display_title: Optional[str] = Field(None, description="Override display title")
|
||||
# Anti-mismatch guard: client may send the expected credit total it observed.
|
||||
# If the server's computed target_total differs, we return 409 so the UI can refresh.
|
||||
acknowledged_credits: Optional[int] = Field(None, description="Expected total credits after this selection (anti-mismatch guard)")
|
||||
|
||||
|
||||
class AudioSelectResponse(BaseModel):
|
||||
@@ -1174,6 +1179,62 @@ async def select_audio_source(
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results cached for this job")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Duration-based pricing: charge the DELTA before triggering any download.
|
||||
# -------------------------------------------------------------------------
|
||||
# The selected result may carry a duration field (seconds as int).
|
||||
selected_result = search_results[body.selection_index] if 0 <= body.selection_index < len(search_results) else {}
|
||||
duration = selected_result.get('duration') # int seconds, or None
|
||||
|
||||
# Hard ceiling: reject inputs over 60 minutes immediately (before any state change).
|
||||
if duration is not None and is_blocked(duration):
|
||||
raise HTTPException(status_code=422, detail="Inputs over 60 minutes aren't supported")
|
||||
|
||||
# Idempotency guard: if a previous /select call already applied the delta charge,
|
||||
# skip re-charging entirely. This makes double-click / rapid-retry safe.
|
||||
# Residual race: two *truly simultaneous* requests can both read the flag as False
|
||||
# and both charge before either writes it True. The atomic status transition in
|
||||
# _validate_and_prepare_selection() causes the second request to fail with 400,
|
||||
# so the window is tiny; any rare double-charge is recoverable via support refund.
|
||||
select_charge_applied = bool((job.state_data or {}).get('select_charge_applied', False))
|
||||
|
||||
# Compute how many credits this job should total after selecting this result.
|
||||
# If duration is unknown, keep target_total == credits_charged so owed = 0.
|
||||
credits_charged = int((job.state_data or {}).get('credits_charged', 1))
|
||||
target_total = duration_to_credits(duration) if duration is not None else credits_charged
|
||||
owed = max(0, target_total - credits_charged)
|
||||
|
||||
# Anti-mismatch guard: if the client sent an expected total, verify it still matches.
|
||||
if body.acknowledged_credits is not None and body.acknowledged_credits != target_total:
|
||||
raise HTTPException(status_code=409, detail="Credit figure changed; please refresh")
|
||||
|
||||
# Deduct the owed delta (or just persist duration metadata if owed == 0).
|
||||
user_email = job.user_email
|
||||
if not select_charge_applied:
|
||||
if owed > 0:
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=500, detail="Job has no associated user email")
|
||||
ok, _, _ = get_user_service().deduct_credits(
|
||||
user_email,
|
||||
job_id,
|
||||
amount=owed,
|
||||
reason="job_creation",
|
||||
count_as_job_creation=False, # job was already counted at create_job()
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=402, detail="Insufficient credits")
|
||||
|
||||
# Persist updated credit total, duration estimate, and idempotency flag.
|
||||
state_update: dict = {
|
||||
"state_data.credits_charged": target_total,
|
||||
"state_data.select_charge_applied": True,
|
||||
}
|
||||
if duration is not None:
|
||||
state_update["state_data.duration_estimate_seconds"] = duration
|
||||
state_update["state_data.duration_estimate_source"] = "search_metadata"
|
||||
job_manager.update_job(job_id, state_update)
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
|
||||
selection_info = _validate_and_prepare_selection(
|
||||
job_id=job_id,
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
"""Bulk Mode API routes.
|
||||
|
||||
Lets a user submit up to 100 karaoke jobs at once, by text (artist/title rows)
|
||||
or by album (MusicBrainz release lookup). Album tracklists and text rows are
|
||||
enriched with KaraokeNerds community-version availability so the user can skip
|
||||
tracks that already exist.
|
||||
|
||||
Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
|
||||
(added in later phases).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/bulk", tags=["bulk"])
|
||||
|
||||
MAX_BULK_SONGS = 100
|
||||
|
||||
|
||||
# --- Models -----------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkArtist(BaseModel):
|
||||
mbid: Optional[str] = None
|
||||
name: str
|
||||
disambiguation: str = ""
|
||||
type: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
|
||||
|
||||
class BulkAlbum(BaseModel):
|
||||
release_group_mbid: str
|
||||
title: str
|
||||
primary_type: Optional[str] = None
|
||||
secondary_types: list[str] = []
|
||||
first_release_date: str = ""
|
||||
is_studio: bool = True
|
||||
|
||||
|
||||
class BulkEdition(BaseModel):
|
||||
release_mbid: str
|
||||
title: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
date: str = ""
|
||||
country: Optional[str] = None
|
||||
track_count: int = 0
|
||||
|
||||
|
||||
class BulkEditionVariant(BaseModel):
|
||||
"""A distinct tracklist variant (country pressings collapsed by track count)."""
|
||||
|
||||
representative_release_mbid: str
|
||||
label: Literal["Original", "Reissue"] = "Original"
|
||||
track_count: int = 0
|
||||
year: str = ""
|
||||
pressing_count: int = 0
|
||||
delta_vs_original: int = 0
|
||||
|
||||
|
||||
class CommunityVersion(BaseModel):
|
||||
"""An existing community karaoke version the user can preview on YouTube."""
|
||||
|
||||
brand: str
|
||||
url: str
|
||||
|
||||
|
||||
class BulkTrack(BaseModel):
|
||||
position: Optional[int] = None
|
||||
title: str
|
||||
recording_mbid: Optional[str] = None
|
||||
length_ms: Optional[int] = None
|
||||
is_extra: bool = False
|
||||
extra_reason: str = ""
|
||||
# Availability (filled from KaraokeNerds); available=True => already exists
|
||||
available: bool = False
|
||||
brands: list[str] = []
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
class BulkTracklistResponse(BaseModel):
|
||||
release_mbid: Optional[str] = None
|
||||
canonical_release_mbid: Optional[str] = None
|
||||
selected_variant_mbid: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
date: str = ""
|
||||
tracks: list[BulkTrack] = []
|
||||
editions: list[BulkEdition] = []
|
||||
variants: list[BulkEditionVariant] = []
|
||||
|
||||
|
||||
class AvailabilityItem(BaseModel):
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class AvailabilityRequest(BaseModel):
|
||||
tracks: list[AvailabilityItem]
|
||||
|
||||
|
||||
class AvailabilityResult(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
available: bool
|
||||
brands: list[str] = []
|
||||
brand_count: int = 0
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
class AvailabilityResponse(BaseModel):
|
||||
results: list[AvailabilityResult]
|
||||
|
||||
|
||||
# --- Album lookup routes ----------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/album/artists", response_model=list[BulkArtist])
|
||||
async def album_artists(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Artist name search"),
|
||||
limit: int = Query(8, ge=1, le=25),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Search MusicBrainz for artists (album-mode step 1)."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
|
||||
try:
|
||||
results = await get_musicbrainz_service().search_artists(q, limit=limit)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz artist search failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Artist lookup is temporarily unavailable")
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/album/albums", response_model=list[BulkAlbum])
|
||||
async def album_albums(
|
||||
request: Request,
|
||||
artist_mbid: str = Query(..., min_length=1),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""List an artist's albums (release-groups) for the album picker."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
|
||||
try:
|
||||
return await get_musicbrainz_service().get_albums(artist_mbid)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz album list failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Album lookup is temporarily unavailable")
|
||||
|
||||
|
||||
@router.get("/album/tracklist", response_model=BulkTracklistResponse)
|
||||
async def album_tracklist(
|
||||
request: Request,
|
||||
artist: str = Query(..., min_length=1, description="Artist name for availability checks"),
|
||||
release_group_mbid: Optional[str] = Query(None),
|
||||
release_mbid: Optional[str] = Query(None, description="Specific edition to load"),
|
||||
locale: Optional[str] = Query(None, description="UI locale → biases representative-pressing choice"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Resolve an album's canonical tracklist (or a specific edition) and enrich
|
||||
each track with KaraokeNerds community-version availability.
|
||||
|
||||
Response shape note: ``variants`` is only populated on the ``release_group_mbid``
|
||||
path (the initial album load). When loading a specific edition via
|
||||
``release_mbid`` it is intentionally ``[]`` — the client already holds the
|
||||
variant list from the initial load and only needs the chosen edition's tracks.
|
||||
"""
|
||||
from backend.services.musicbrainz_service import (
|
||||
get_musicbrainz_service,
|
||||
country_prefs_for_locale,
|
||||
)
|
||||
from backend.services.karaokenerds_service import check_community_versions_batch
|
||||
|
||||
if not release_group_mbid and not release_mbid:
|
||||
raise HTTPException(status_code=422, detail="release_group_mbid or release_mbid required")
|
||||
|
||||
mb = get_musicbrainz_service()
|
||||
try:
|
||||
if release_mbid:
|
||||
# Loading a specific variant — variants already known to the client.
|
||||
tracklist = await mb.get_release_tracklist(release_mbid)
|
||||
tracklist.setdefault("editions", [])
|
||||
tracklist.setdefault("canonical_release_mbid", release_mbid)
|
||||
tracklist.setdefault("variants", [])
|
||||
tracklist.setdefault("selected_variant_mbid", release_mbid)
|
||||
else:
|
||||
tracklist = await mb.get_album_tracklist(
|
||||
release_group_mbid, preferred_countries=country_prefs_for_locale(locale)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz tracklist failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Tracklist lookup is temporarily unavailable")
|
||||
|
||||
tracks = tracklist.get("tracks", [])
|
||||
# Availability enrichment — never fatal.
|
||||
try:
|
||||
avail = await check_community_versions_batch(
|
||||
[{"artist": artist, "title": t["title"]} for t in tracks]
|
||||
)
|
||||
for t, a in zip(tracks, avail):
|
||||
t["available"] = a["available"]
|
||||
t["brands"] = a["brands"]
|
||||
t["versions"] = a.get("versions", [])
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Availability enrichment failed (non-fatal): %s", e)
|
||||
|
||||
return BulkTracklistResponse(
|
||||
release_mbid=tracklist.get("release_mbid"),
|
||||
canonical_release_mbid=tracklist.get("canonical_release_mbid"),
|
||||
selected_variant_mbid=tracklist.get("selected_variant_mbid"),
|
||||
title=tracklist.get("title"),
|
||||
date=tracklist.get("date", ""),
|
||||
tracks=[BulkTrack(**t) for t in tracks],
|
||||
editions=[BulkEdition(**e) for e in tracklist.get("editions", [])],
|
||||
variants=[BulkEditionVariant(**v) for v in tracklist.get("variants", [])],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/availability", response_model=AvailabilityResponse)
|
||||
async def bulk_availability(
|
||||
request: Request,
|
||||
body: AvailabilityRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Batch KaraokeNerds availability check for text-mode rows."""
|
||||
from backend.services.karaokenerds_service import check_community_versions_batch
|
||||
|
||||
if len(body.tracks) > MAX_BULK_SONGS:
|
||||
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} tracks per request")
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": t.artist, "title": t.title} for t in body.tracks]
|
||||
)
|
||||
return AvailabilityResponse(results=[AvailabilityResult(**r) for r in results])
|
||||
|
||||
|
||||
# --- Submission -------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkSong(BaseModel):
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
display_artist: Optional[str] = None
|
||||
display_title: Optional[str] = None
|
||||
|
||||
|
||||
class BulkSettings(BaseModel):
|
||||
auto_select_if_lossless: bool = True
|
||||
is_private: bool = False
|
||||
skip_audio_edit: bool = True
|
||||
skip_customization: bool = True
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
songs: list[BulkSong]
|
||||
settings: BulkSettings = Field(default_factory=BulkSettings)
|
||||
|
||||
|
||||
class BulkSubmitResponse(BaseModel):
|
||||
batch_id: str
|
||||
job_ids: list[str]
|
||||
total: int
|
||||
|
||||
|
||||
@router.post("/submit", response_model=BulkSubmitResponse)
|
||||
async def bulk_submit(
|
||||
request: Request,
|
||||
body: BulkSubmitRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Create one job per song, gate on credits upfront, and dispatch the batch
|
||||
search worker. Jobs start parked (auto_download=False) and the worker either
|
||||
auto-selects a confident lossless match or leaves them awaiting selection."""
|
||||
from backend.config import get_settings
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.models.job import JobCreate
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
n = len(body.songs)
|
||||
if n == 0:
|
||||
raise HTTPException(status_code=422, detail="At least one song is required")
|
||||
if n > MAX_BULK_SONGS:
|
||||
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} songs per batch")
|
||||
|
||||
user_email = auth_result.user_email
|
||||
is_admin = bool(auth_result.is_admin)
|
||||
|
||||
# Upfront credit gate (1 credit/song minimum). Admins bypass.
|
||||
if not is_admin and user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
available = get_user_service().check_credits(user_email)
|
||||
if available < n:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"error": "insufficient_credits",
|
||||
"message": "You don't have enough credits for this batch.",
|
||||
"credits_available": available,
|
||||
"credits_required": n,
|
||||
},
|
||||
)
|
||||
|
||||
settings = get_settings()
|
||||
theme_service = get_theme_service()
|
||||
theme_id = theme_service.get_default_theme_id()
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
|
||||
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
bulk_settings = body.settings.model_dump()
|
||||
job_manager = JobManager()
|
||||
job_ids: list[str] = []
|
||||
|
||||
for song in body.songs:
|
||||
display_artist = (song.display_artist or song.artist).strip()
|
||||
display_title = (song.display_title or song.title).strip()
|
||||
request_metadata = {
|
||||
"created_from": "bulk",
|
||||
"batch_id": batch_id,
|
||||
"user_email": user_email,
|
||||
}
|
||||
job_create = JobCreate(
|
||||
artist=display_artist,
|
||||
title=display_title,
|
||||
theme_id=theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
user_email=user_email,
|
||||
audio_search_artist=song.artist.strip(),
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
discord_webhook_url=settings.default_discord_webhook_url,
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
request_metadata=request_metadata,
|
||||
)
|
||||
try:
|
||||
job = job_manager.create_job(job_create, is_admin=is_admin)
|
||||
except InsufficientCreditsError:
|
||||
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
|
||||
# already-created jobs are valid and will proceed.
|
||||
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
|
||||
break
|
||||
|
||||
job_manager.update_job(
|
||||
job.job_id,
|
||||
{
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
},
|
||||
)
|
||||
job_ids.append(job.job_id)
|
||||
|
||||
if not job_ids:
|
||||
raise HTTPException(status_code=402, detail="No jobs could be created")
|
||||
|
||||
# Dispatch the batch search worker. Retry once on transient failure. If it
|
||||
# still fails the jobs exist (and are charged) but won't process, so surface
|
||||
# an explicit error with the batch_id — and tell the user NOT to resubmit
|
||||
# (that would create+charge a second batch); the batch can be re-dispatched.
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
logger.critical(
|
||||
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
|
||||
batch_id, len(job_ids),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={
|
||||
"error": "dispatch_failed",
|
||||
"message": "Your batch was created but processing couldn't start. "
|
||||
"Please don't resubmit — contact support with this batch ID and we'll start it.",
|
||||
"batch_id": batch_id,
|
||||
"job_ids": job_ids,
|
||||
},
|
||||
)
|
||||
logger.info("[batch:%s] created %d jobs, dispatched bulk-search worker", batch_id, len(job_ids))
|
||||
|
||||
return BulkSubmitResponse(batch_id=batch_id, job_ids=job_ids, total=len(job_ids))
|
||||
|
||||
|
||||
# --- Progress ---------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkJobStatus(BaseModel):
|
||||
job_id: str
|
||||
artist: str
|
||||
title: str
|
||||
status: str
|
||||
auto_selected: bool = False
|
||||
|
||||
|
||||
class BulkBatchResponse(BaseModel):
|
||||
batch_id: str
|
||||
total: int
|
||||
counts: dict
|
||||
jobs: list[BulkJobStatus]
|
||||
|
||||
|
||||
# Status -> progress bucket for the batch summary.
|
||||
_AWAITING = "awaiting_audio_selection"
|
||||
_TERMINAL_OK = "complete"
|
||||
_TERMINAL_FAIL = "failed"
|
||||
_SEARCHING = {"pending", "searching_audio"}
|
||||
|
||||
|
||||
def _bucket(status: str, pending_search: bool) -> str:
|
||||
if pending_search or status in _SEARCHING:
|
||||
return "searching"
|
||||
if status == _AWAITING:
|
||||
return "awaiting_selection"
|
||||
if status == _TERMINAL_OK:
|
||||
return "complete"
|
||||
if status == _TERMINAL_FAIL:
|
||||
return "failed"
|
||||
return "processing"
|
||||
|
||||
|
||||
@router.get("/{batch_id}", response_model=BulkBatchResponse)
|
||||
async def bulk_batch(
|
||||
request: Request,
|
||||
batch_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Progress summary for a batch: counts by bucket + per-job status."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job_manager = JobManager()
|
||||
jobs = job_manager.list_jobs_by_batch_id(batch_id)
|
||||
|
||||
if not bool(auth_result.is_admin):
|
||||
email = (auth_result.user_email or "").lower()
|
||||
jobs = [j for j in jobs if (j.user_email or "").lower() == email]
|
||||
|
||||
if not jobs:
|
||||
raise HTTPException(status_code=404, detail="Batch not found")
|
||||
|
||||
counts = {"searching": 0, "awaiting_selection": 0, "processing": 0, "complete": 0, "failed": 0}
|
||||
job_statuses: list[BulkJobStatus] = []
|
||||
for j in jobs:
|
||||
status = j.status.value if hasattr(j.status, "value") else str(j.status)
|
||||
sd = j.state_data or {}
|
||||
bucket = _bucket(status, bool(sd.get("bulk_pending_search")))
|
||||
counts[bucket] += 1
|
||||
job_statuses.append(
|
||||
BulkJobStatus(
|
||||
job_id=j.job_id,
|
||||
artist=j.audio_search_artist or j.artist or "",
|
||||
title=j.audio_search_title or j.title or "",
|
||||
status=status,
|
||||
auto_selected=bool(sd.get("bulk_auto_selected")),
|
||||
)
|
||||
)
|
||||
|
||||
return BulkBatchResponse(
|
||||
batch_id=batch_id, total=len(jobs), counts=counts, jobs=job_statuses
|
||||
)
|
||||
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -103,6 +103,38 @@ class CommunityCheckResponse(BaseModel):
|
||||
best_youtube_url: Optional[str] = None
|
||||
|
||||
|
||||
class MatchJudgeRequest(BaseModel):
|
||||
"""Request body for the artist/title match judge."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
# The audio search's confidence tier (1=strong..3=weak), so the judge can
|
||||
# tell whether weak results hint at a typo. Optional.
|
||||
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
|
||||
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
|
||||
# parallel with the audio search; "full" = complete pipeline once the tier is
|
||||
# known. Defaults to "full" so a single legacy call still works.
|
||||
stage: Literal["fast", "full"] = "full"
|
||||
|
||||
|
||||
class MatchJudgeAlternative(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
class MatchJudgeResponse(BaseModel):
|
||||
"""Verdict on a typed artist/title — formatting + match acceptance."""
|
||||
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[MatchJudgeAlternative] = []
|
||||
engine: str # "deterministic" | "catalog" | "ai"
|
||||
reason: str = ""
|
||||
# Set by a "fast" pass that couldn't decide — the client should follow up with
|
||||
# a "full" call once the audio tier is known.
|
||||
needs_ai: bool = False
|
||||
|
||||
|
||||
# --- Routes ---
|
||||
|
||||
|
||||
@@ -161,3 +193,31 @@ async def check_community_versions(
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/match-judge", response_model=MatchJudgeResponse)
|
||||
async def match_judge(
|
||||
request: Request,
|
||||
body: MatchJudgeRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Judge a typed artist/title: decide official formatting + whether it matches a
|
||||
real song. Deterministic + catalog layers run first; a light AI model fires
|
||||
only when those aren't confident. Never blocks the submission flow — failures
|
||||
degrade to a "none" verdict.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.match_judge.service import judge_match
|
||||
verdict = await judge_match(
|
||||
body.artist, body.title,
|
||||
audio_tier=body.audio_confidence_tier,
|
||||
stage=body.stage,
|
||||
)
|
||||
logger.info(
|
||||
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
|
||||
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
|
||||
)
|
||||
return verdict.to_dict()
|
||||
@@ -2,14 +2,23 @@
|
||||
Encoding worker lifecycle endpoints.
|
||||
|
||||
Provides warmup and heartbeat endpoints for the blue-green
|
||||
encoding worker VMs. Called by the frontend to ensure the
|
||||
primary VM is running before encoding requests.
|
||||
encoding worker VMs. Called by the lyrics-review frontend to ensure the
|
||||
primary VM is running before the reviewer previews a render.
|
||||
|
||||
Auth: these are gated on ``require_review_auth`` (review access to a specific
|
||||
job), NOT ``require_admin``. The callers are ordinary customers on the
|
||||
lyrics-review page — gating on admin makes every non-admin caller 403, which
|
||||
silently defeats the JIT pre-warm. Scoping to the job being reviewed keeps the
|
||||
abuse posture identical to the rest of the review surface: you can only warm
|
||||
the shared encoding VM if you already have review access to a real job.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Tuple
|
||||
from fastapi import APIRouter, Depends
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.dependencies import require_review_auth
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,28 +44,50 @@ def get_worker_manager():
|
||||
return _manager
|
||||
|
||||
|
||||
@router.post("/warmup")
|
||||
@router.post("/warmup/{job_id}")
|
||||
async def warmup_encoding_worker(
|
||||
_admin=Depends(require_admin),
|
||||
job_id: str,
|
||||
_auth: Tuple[str, str] = Depends(require_review_auth),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Start the primary encoding worker VM if it's stopped."""
|
||||
"""Start the primary encoding worker VM if it's stopped.
|
||||
|
||||
Called on lyrics-review page load so the VM is warm by the time the
|
||||
reviewer previews a render. ``job_id`` scopes auth to the job under review.
|
||||
"""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.info(f"Started encoding worker VM: {result['vm_name']}")
|
||||
return result
|
||||
except EncodingWorkerStartError as e:
|
||||
# The primary VM couldn't start (capacity exhaustion or a transient
|
||||
# 503 SERVICE_UNAVAILABLE from the GCE backend). This is NOT fatal:
|
||||
# the encoding flow's own warmup (ensure_any_running) falls back to
|
||||
# the alternate-zone workers, so the job still completes. Log at
|
||||
# WARNING so it doesn't trip the production error monitor and page us
|
||||
# for self-healing capacity events.
|
||||
logger.warning(
|
||||
f"Primary encoding worker warmup failed ({e}); "
|
||||
f"encoding will fall back to an alternate-zone worker"
|
||||
)
|
||||
return {"started": False, "error": str(e)}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to warm up encoding worker: {e}")
|
||||
return {"started": False, "error": str(e)}
|
||||
|
||||
|
||||
@router.post("/heartbeat")
|
||||
@router.post("/heartbeat/{job_id}")
|
||||
async def heartbeat_encoding_worker(
|
||||
_admin=Depends(require_admin),
|
||||
job_id: str,
|
||||
_auth: Tuple[str, str] = Depends(require_review_auth),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Update activity timestamp to prevent idle shutdown."""
|
||||
"""Update activity timestamp to prevent idle shutdown.
|
||||
|
||||
Called periodically while the reviewer works. ``job_id`` scopes auth to the
|
||||
job under review.
|
||||
"""
|
||||
try:
|
||||
manager.update_activity()
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -10,12 +10,11 @@ Supports two upload flows:
|
||||
- Client uploads files directly to GCS using signed URLs (no size limit)
|
||||
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import os
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
|
||||
@@ -58,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _select_mixed_audio_files(files):
|
||||
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
|
||||
|
||||
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
|
||||
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
|
||||
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
|
||||
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
|
||||
the instrumental — so transcription would run on the backing track instead of the
|
||||
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
|
||||
"""
|
||||
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
@@ -68,12 +80,20 @@ def _apply_tenant_overrides(
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
|
||||
distribution settings, so tenant outputs never inherit the global consumer defaults
|
||||
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
|
||||
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
|
||||
tenant job would land in the shared consumer Dropbox folder and upload to the global
|
||||
Google Drive, regardless of the tenant's own config.
|
||||
|
||||
For tenant jobs:
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
|
||||
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
|
||||
otherwise disables that channel entirely (no global-default leak)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload
|
||||
- Disables YouTube upload (tenants never publish to YouTube)
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
@@ -82,14 +102,12 @@ def _apply_tenant_overrides(
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
features = tenant_config.features
|
||||
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
# Authoritative distribution routing (overrides any global defaults in `dist`).
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
@@ -338,16 +356,6 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
|
||||
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
|
||||
|
||||
|
||||
async def _trigger_audio_worker_only(job_id: str) -> None:
|
||||
"""
|
||||
Trigger only the audio worker.
|
||||
|
||||
Used for URL jobs where audio needs to be downloaded first.
|
||||
The audio worker will trigger the lyrics worker after download completes.
|
||||
"""
|
||||
await worker_service.trigger_audio_worker(job_id)
|
||||
|
||||
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
@@ -1393,12 +1401,14 @@ async def mark_uploads_complete(
|
||||
|
||||
# List files with this prefix to find the actual uploaded file
|
||||
files = storage_service.list_files(prefix)
|
||||
if file_type == 'audio':
|
||||
files = _select_mixed_audio_files(files)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
|
||||
)
|
||||
|
||||
|
||||
# Use the first (and should be only) file found
|
||||
gcs_path = files[0]
|
||||
|
||||
@@ -1571,11 +1581,140 @@ def _validate_url(url: Optional[str]) -> bool:
|
||||
for supported in supported_domains:
|
||||
if domain == supported or domain.endswith('.' + supported):
|
||||
return True
|
||||
|
||||
|
||||
# For other URLs, let yt-dlp try (it supports many more sites)
|
||||
return True
|
||||
|
||||
|
||||
# Streaming services whose catalogue is DRM-protected and therefore cannot be
|
||||
# downloaded by yt-dlp / flacfetch. Submitting one of these only creates a job
|
||||
# that fails deep in the download stage with a cryptic "Unsupported URL" error
|
||||
# (and lets the user trigger a futile retry), so we reject them at submission
|
||||
# time with a clear, actionable message. Maps host -> friendly platform name;
|
||||
# matching is suffix-based, so e.g. "spotify.com" also covers open./play.
|
||||
_UNSUPPORTED_DRM_HOSTS = {
|
||||
'music.apple.com': 'Apple Music',
|
||||
'itunes.apple.com': 'Apple Music',
|
||||
'spotify.com': 'Spotify',
|
||||
'tidal.com': 'Tidal',
|
||||
'deezer.com': 'Deezer',
|
||||
'pandora.com': 'Pandora',
|
||||
}
|
||||
|
||||
# Third-party tools that can download audio from a DRM platform, which the user
|
||||
# can then upload to us. Listed where we know of working options; platforms
|
||||
# without an entry fall back to a web-search link for "<platform> downloader".
|
||||
_DRM_DOWNLOADER_SUGGESTIONS = {
|
||||
'Apple Music': ['https://am-dl.pages.dev', 'https://aplmate.com'],
|
||||
'Spotify': ['https://spotdown.org', 'https://spotmate.online'],
|
||||
}
|
||||
|
||||
|
||||
def _drm_unsupported_detail(locale: str, platform: str) -> str:
|
||||
"""
|
||||
Build the user-facing 400 message for a rejected DRM streaming URL.
|
||||
|
||||
Platforms with known downloader tools get a "download from {tools}, then
|
||||
upload" message linking each tool; everything else gets a "search the web
|
||||
for a '<platform> downloader'" message linking a Google search. Either way
|
||||
the goal is to guide the user to obtain the audio and upload it themselves.
|
||||
"""
|
||||
downloaders = _DRM_DOWNLOADER_SUGGESTIONS.get(platform)
|
||||
if downloaders:
|
||||
# Join with commas (locale-neutral) rather than an English "or"; the
|
||||
# message wording frames them as options and LinkifiedText makes each
|
||||
# URL clickable in the frontend.
|
||||
return t(
|
||||
locale, "audioSearch.drmUrlUnsupportedWithLink",
|
||||
platform=platform, downloader=", ".join(downloaders),
|
||||
)
|
||||
|
||||
from urllib.parse import quote_plus
|
||||
search_url = "https://www.google.com/search?q=" + quote_plus(f"{platform} downloader")
|
||||
return t(
|
||||
locale, "audioSearch.drmUrlUnsupportedSearch",
|
||||
platform=platform, searchUrl=search_url,
|
||||
)
|
||||
|
||||
|
||||
def _unsupported_url_platform(url: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
Return a friendly platform name if the URL belongs to a known DRM-protected
|
||||
streaming service that cannot be downloaded, else None.
|
||||
|
||||
These links (Apple Music, Spotify, Tidal, Amazon Music, Deezer, Pandora) are
|
||||
rejected at submission time instead of being allowed to create a job that
|
||||
always fails deep in the download stage. Note: YouTube Music
|
||||
(music.youtube.com) is downloadable and is deliberately NOT included.
|
||||
"""
|
||||
if not url or not isinstance(url, str):
|
||||
return None
|
||||
|
||||
from urllib.parse import urlparse
|
||||
try:
|
||||
# .hostname is already lowercased and strips userinfo, port, and IPv6
|
||||
# brackets, so it's safer than parsing .netloc by hand.
|
||||
domain = (urlparse(url).hostname or "").lower()
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
if not domain:
|
||||
return None
|
||||
# Normalise leading www.
|
||||
if domain.startswith('www.'):
|
||||
domain = domain[4:]
|
||||
|
||||
for host, platform in _UNSUPPORTED_DRM_HOSTS.items():
|
||||
if domain == host or domain.endswith('.' + host):
|
||||
return platform
|
||||
|
||||
# Amazon Music spans many country domains (music.amazon.com, .co.uk, .co.jp,
|
||||
# .fr, .de, ...), so match the music.amazon.* prefix generically.
|
||||
if domain == 'music.amazon' or domain.startswith('music.amazon.'):
|
||||
return 'Amazon Music'
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class ValidateUrlRequest(BaseModel):
|
||||
"""Request to pre-validate a URL before submitting a job."""
|
||||
url: str = Field(..., description="The URL the user intends to submit")
|
||||
|
||||
|
||||
class ValidateUrlResponse(BaseModel):
|
||||
"""Whether a URL can be used for a job, with a friendly reason if not."""
|
||||
supported: bool
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
|
||||
async def validate_job_url(
|
||||
request: Request,
|
||||
body: ValidateUrlRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
) -> ValidateUrlResponse:
|
||||
"""
|
||||
Lightweight pre-flight check for a job URL, used by the guided submission
|
||||
flow so unsupported links are caught at the "Use this URL" step instead of
|
||||
only at final submit. Mirrors the URL validation in create_job_from_url.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
platform = _unsupported_url_platform(body.url)
|
||||
if platform:
|
||||
return ValidateUrlResponse(
|
||||
supported=False, detail=_drm_unsupported_detail(locale, platform)
|
||||
)
|
||||
|
||||
if not _validate_url(body.url):
|
||||
return ValidateUrlResponse(
|
||||
supported=False,
|
||||
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL.",
|
||||
)
|
||||
|
||||
return ValidateUrlResponse(supported=True)
|
||||
|
||||
|
||||
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
|
||||
async def create_job_from_url(
|
||||
request: Request,
|
||||
@@ -1609,6 +1748,17 @@ async def create_job_from_url(
|
||||
)
|
||||
|
||||
try:
|
||||
# Reject DRM-protected streaming links upfront (Apple Music, Spotify,
|
||||
# Tidal, etc.). These can never be downloaded, so creating a job would
|
||||
# only fail deep in the pipeline with a cryptic error and tempt the user
|
||||
# into a futile retry storm.
|
||||
unsupported_platform = _unsupported_url_platform(body.url)
|
||||
if unsupported_platform:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=_drm_unsupported_detail(locale, unsupported_platform),
|
||||
)
|
||||
|
||||
# Validate URL
|
||||
if not _validate_url(body.url):
|
||||
raise HTTPException(
|
||||
@@ -1635,6 +1785,13 @@ async def create_job_from_url(
|
||||
detail = "This YouTube video is private and cannot be downloaded."
|
||||
elif availability.get("is_removed"):
|
||||
detail = "This YouTube video has been removed and cannot be downloaded."
|
||||
elif availability.get("is_bot_blocked"):
|
||||
detail = (
|
||||
"We're temporarily unable to access YouTube to download this video — "
|
||||
"YouTube is asking our server to verify it's not a bot. "
|
||||
"Please try again in a few minutes, or use Audio Search to find this song "
|
||||
"from another source."
|
||||
)
|
||||
elif availability.get("is_age_restricted"):
|
||||
detail = "This YouTube video is age-restricted and cannot be downloaded."
|
||||
else:
|
||||
@@ -1777,55 +1934,47 @@ async def create_job_from_url(
|
||||
if title:
|
||||
logger.info(f" Title: {title}")
|
||||
|
||||
# For YouTube URLs, download audio NOW using YouTubeDownloadService
|
||||
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
|
||||
if _is_youtube_url(body.url):
|
||||
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
|
||||
try:
|
||||
youtube_service = get_youtube_download_service()
|
||||
audio_gcs_path = await youtube_service.download(
|
||||
url=body.url,
|
||||
job_id=job_id,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
# Update job with the downloaded audio path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
10, # progress
|
||||
"Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
except YouTubeDownloadError as e:
|
||||
logger.error(f"YouTube download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
|
||||
)
|
||||
else:
|
||||
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
|
||||
# The audio worker will download the URL and trigger lyrics worker after
|
||||
job_manager.transition_to_state(
|
||||
# Download audio NOW via the flacfetch service for ALL URLs (YouTube and
|
||||
# any other yt-dlp-supported site, e.g. Facebook/SoundCloud/TikTok).
|
||||
# flacfetch is the sole downloader — no yt-dlp ever runs on Cloud Run.
|
||||
# Downloading up front (before the GPU worker starts) also keeps the GPU
|
||||
# idle until the audio is in GCS.
|
||||
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
|
||||
try:
|
||||
download_service = get_youtube_download_service()
|
||||
audio_gcs_path = await download_service.download(
|
||||
url=body.url,
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Starting audio download from URL"
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
# Update job with the downloaded audio path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
logger.info(f"Audio downloaded to GCS: {audio_gcs_path}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
10, # progress
|
||||
"Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
except YouTubeDownloadError as e:
|
||||
logger.error(f"URL download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"Download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
|
||||
)
|
||||
background_tasks.add_task(_trigger_audio_worker_only, job_id)
|
||||
|
||||
return CreateJobFromUrlResponse(
|
||||
status="success",
|
||||
|
||||
+229
-15
@@ -20,6 +20,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.workers.audio_worker import process_audio_separation
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
from backend.workers.lyrics_worker import process_lyrics_transcription
|
||||
from backend.workers.screens_worker import generate_screens
|
||||
from backend.workers.video_worker import generate_video
|
||||
@@ -227,6 +228,48 @@ async def trigger_lyrics_worker(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/auto-correct", response_model=WorkerResponse)
|
||||
async def trigger_auto_correct_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Proactively pre-generate + cache AI auto-correct suggestions for a job.
|
||||
|
||||
Called by the lyrics worker once transcription + references are ready, so
|
||||
the suggestions are cached before the reviewer opens the lyrics UI. Runs
|
||||
HERE (the API service) because the service has the working Anthropic key /
|
||||
compare-models config; the lyrics job does not.
|
||||
|
||||
Best-effort and runs synchronously within the request (the caller awaits
|
||||
with its own timeout): the work never fails the karaoke job, and the
|
||||
response just reports what happened. Gated by AUTO_CORRECT_PROACTIVE_ENABLED.
|
||||
"""
|
||||
job_id = request.job_id
|
||||
|
||||
# Extract trace context from incoming request (propagated via the trigger).
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_TRIGGER worker=auto-correct")
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("worker", "auto-correct")
|
||||
|
||||
# process_proactive_auto_correct already swallows its own errors; the extra
|
||||
# guard keeps the endpoint itself best-effort no matter what.
|
||||
try:
|
||||
result = await process_proactive_auto_correct(job_id)
|
||||
add_span_event("auto_correct_proactive", {"result": result.get("status", "unknown")})
|
||||
return WorkerResponse(
|
||||
status=result.get("status", "unknown"),
|
||||
job_id=job_id,
|
||||
message=f"Proactive auto-correct: {result.get('status', 'unknown')}",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fail the caller
|
||||
logger.warning(f"[job:{job_id}] auto-correct endpoint error (non-fatal): {e}")
|
||||
add_span_event("auto_correct_proactive", {"result": "error"})
|
||||
return WorkerResponse(status="error", job_id=job_id, message=f"error: {e}")
|
||||
|
||||
|
||||
@router.post("/workers/screens", response_model=WorkerResponse)
|
||||
async def trigger_screens_worker(
|
||||
request: WorkerRequest,
|
||||
@@ -362,8 +405,9 @@ async def check_idle_reminder(
|
||||
"""
|
||||
Check if a job needs an idle reminder email.
|
||||
|
||||
This endpoint is called by a Cloud Tasks scheduled task 5 minutes after
|
||||
a job enters AWAITING_REVIEW state.
|
||||
This endpoint is called by a Cloud Tasks scheduled task after a job enters
|
||||
a blocking state (AWAITING_REVIEW, AWAITING_AUDIO_EDIT, AWAITING_DURATION_CONFIRM,
|
||||
or the legacy AWAITING_INSTRUMENTAL_SELECTION).
|
||||
|
||||
If the job is still in the blocking state and no reminder has been sent yet,
|
||||
sends a reminder email to the user.
|
||||
@@ -390,7 +434,11 @@ async def check_idle_reminder(
|
||||
|
||||
# Check if job is still in a blocking state
|
||||
# Note: AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs only
|
||||
blocking_states = [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]
|
||||
blocking_states = [
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
|
||||
JobStatus.AWAITING_DURATION_CONFIRM,
|
||||
]
|
||||
if job.status not in [s.value for s in blocking_states]:
|
||||
logger.info(f"[job:{job_id}] Job no longer in blocking state ({job.status}), skipping reminder")
|
||||
add_span_event("not_blocking", {"current_status": job.status})
|
||||
@@ -424,23 +472,32 @@ async def check_idle_reminder(
|
||||
# Determine action type
|
||||
action_type = state_data.get('blocking_action_type')
|
||||
if not action_type:
|
||||
action_type = "lyrics" if job.status == JobStatus.AWAITING_REVIEW.value else "instrumental"
|
||||
if job.status == JobStatus.AWAITING_REVIEW.value:
|
||||
action_type = "lyrics"
|
||||
elif job.status == JobStatus.AWAITING_DURATION_CONFIRM.value:
|
||||
action_type = "duration_confirm"
|
||||
else:
|
||||
action_type = "instrumental"
|
||||
|
||||
# Send the reminder email
|
||||
try:
|
||||
notification_service = get_job_notification_service()
|
||||
|
||||
success = await notification_service.send_action_reminder_email(
|
||||
job_id=job.job_id,
|
||||
user_email=job.user_email,
|
||||
action_type=action_type,
|
||||
user_name=None, # Could fetch from user service if needed
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
audio_hash=job.audio_hash,
|
||||
review_token=job.review_token,
|
||||
instrumental_token=job.instrumental_token,
|
||||
)
|
||||
if action_type == "duration_confirm":
|
||||
# Duration-confirm has its own dedicated reminder method
|
||||
success = await notification_service.send_duration_confirm_reminder(job)
|
||||
else:
|
||||
success = await notification_service.send_action_reminder_email(
|
||||
job_id=job.job_id,
|
||||
user_email=job.user_email,
|
||||
action_type=action_type,
|
||||
user_name=None, # Could fetch from user service if needed
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
audio_hash=job.audio_hash,
|
||||
review_token=job.review_token,
|
||||
instrumental_token=job.instrumental_token,
|
||||
)
|
||||
|
||||
if success:
|
||||
# Mark reminder as sent (prevents duplicate sends)
|
||||
@@ -576,6 +633,163 @@ async def trigger_gdrive_validation_endpoint(
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/retry-pending-render-jobs")
|
||||
async def retry_pending_render_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
|
||||
|
||||
Called every 5 minutes by Cloud Scheduler. When the GCE encoding worker
|
||||
can't be started because the zone is exhausted, the render worker parks
|
||||
the job in this state instead of failing it. This endpoint re-attempts
|
||||
the render — when GCE has capacity, the start succeeds and the job
|
||||
completes normally.
|
||||
|
||||
Strategy:
|
||||
- Process up to MAX_PER_TICK jobs (the GCE worker is single-tenant per
|
||||
render, so spinning up many in parallel just collides on the same VM)
|
||||
- Pick the oldest first (longest waiter gets fairness)
|
||||
- Time out jobs that have been waiting longer than MAX_WAIT_SECONDS;
|
||||
transition them to FAILED with a clear permanent-failure message
|
||||
- For each remaining job: clear error state, reset to REVIEW_COMPLETE,
|
||||
kick off the render worker again
|
||||
"""
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
# Long enough to ride out a sustained capacity outage but short enough
|
||||
# that an op gets paged about it before the user sees a "still pending"
|
||||
# job >24h old.
|
||||
MAX_WAIT_SECONDS = 24 * 60 * 60 # 24h
|
||||
MAX_PER_TICK = 1 # one render at a time on the GCE worker
|
||||
|
||||
extract_trace_context(dict(http_request.headers))
|
||||
add_span_attribute("operation", "retry_pending_render_jobs")
|
||||
logger.info("RETRY_PENDING_RENDER_JOBS starting")
|
||||
|
||||
job_manager = JobManager()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
# Filter by status only — sorting by updated_at server-side would require
|
||||
# a composite Firestore index that we don't have. The pending-capacity
|
||||
# population is small (handful of jobs at most), so streaming and
|
||||
# sorting in Python is cheap and avoids the index ceremony.
|
||||
pending_query = (
|
||||
jobs_ref
|
||||
.where(filter=FieldFilter("status", "==", JobStatus.RENDER_PENDING_CAPACITY.value))
|
||||
.limit(50) # cap defensively in case the queue ever grows
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
timed_out = []
|
||||
retried = []
|
||||
skipped = 0
|
||||
|
||||
# Materialize and sort by first_seen_at (oldest waiter first). Falls back
|
||||
# to updated_at, then doc id, when meta is missing.
|
||||
pending_docs = list(pending_query.stream())
|
||||
|
||||
def _sort_key(doc):
|
||||
data = doc.to_dict() or {}
|
||||
meta = (data.get("state_data") or {}).get("render_pending_capacity") or {}
|
||||
first_seen = meta.get("first_seen_at") or ""
|
||||
updated = data.get("updated_at")
|
||||
# Firestore returns a datetime; isoformat sorts correctly within the same TZ.
|
||||
updated_str = updated.isoformat() if hasattr(updated, "isoformat") else str(updated or "")
|
||||
return (first_seen, updated_str, doc.id)
|
||||
|
||||
pending_docs.sort(key=_sort_key)
|
||||
|
||||
for doc in pending_docs:
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
sd = job_data.get("state_data") or {}
|
||||
pending_meta = sd.get("render_pending_capacity") or {}
|
||||
first_seen = pending_meta.get("first_seen_at")
|
||||
|
||||
# Permanent-failure timeout
|
||||
if first_seen:
|
||||
try:
|
||||
first_seen_dt = datetime.fromisoformat(first_seen)
|
||||
age = now - first_seen_dt
|
||||
except (ValueError, TypeError):
|
||||
age = timedelta(0)
|
||||
if age.total_seconds() > MAX_WAIT_SECONDS:
|
||||
permanent_msg = (
|
||||
"Encoding capacity remained unavailable after "
|
||||
f"{int(age.total_seconds() // 3600)}h of automatic retries. "
|
||||
"Please retry manually or contact support."
|
||||
)
|
||||
logger.error(
|
||||
f"[job:{job_id}] Capacity wait exceeded {MAX_WAIT_SECONDS}s — failing permanently"
|
||||
)
|
||||
job_manager.fail_job(job_id, permanent_msg, error_details={
|
||||
"stage": "render_video",
|
||||
"permanent_capacity_timeout": True,
|
||||
"first_seen_at": first_seen,
|
||||
"attempts": pending_meta.get("attempt_count", 0),
|
||||
})
|
||||
timed_out.append(job_id)
|
||||
continue
|
||||
|
||||
if len(retried) >= MAX_PER_TICK:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Clear error state and reset render progress for idempotency.
|
||||
# render_pending_capacity meta is preserved so the next failure (if any)
|
||||
# increments the existing attempt counter.
|
||||
job_manager.update_job(job_id, {
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
})
|
||||
job_manager.update_state_data(job_id, "render_progress", {"stage": "pending"})
|
||||
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.REVIEW_COMPLETE,
|
||||
progress=70,
|
||||
message="Auto-retrying video render — encoding capacity check",
|
||||
raise_on_invalid=False,
|
||||
):
|
||||
logger.warning(f"[job:{job_id}] Could not transition to REVIEW_COMPLETE for retry")
|
||||
continue
|
||||
|
||||
try:
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
retried.append(job_id)
|
||||
logger.info(f"[job:{job_id}] Auto-retry triggered")
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Failed to trigger render worker: {e}")
|
||||
# Job remains in REVIEW_COMPLETE — next tick will pick it up if it
|
||||
# falls back to RENDER_PENDING_CAPACITY again.
|
||||
|
||||
add_span_event("retry_complete", {
|
||||
"retried": len(retried),
|
||||
"timed_out": len(timed_out),
|
||||
"skipped": skipped,
|
||||
})
|
||||
logger.info(
|
||||
f"RETRY_PENDING_RENDER_JOBS complete: retried={len(retried)} "
|
||||
f"timed_out={len(timed_out)} skipped={skipped}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"retried_jobs": retried,
|
||||
"retried_count": len(retried),
|
||||
"timed_out_jobs": timed_out,
|
||||
"timed_out_count": len(timed_out),
|
||||
"skipped_for_next_tick": skipped,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/recover-stuck-jobs")
|
||||
async def recover_stuck_jobs(
|
||||
http_request: Request,
|
||||
|
||||
+376
-23
@@ -17,7 +17,7 @@ from pathlib import Path
|
||||
from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
@@ -44,7 +44,10 @@ from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.firestore_service import FirestoreService, log_to_job
|
||||
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.youtube_download_service import get_youtube_download_service
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from pydantic import BaseModel, Field, HttpUrl, validator
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -120,6 +123,32 @@ async def create_job(
|
||||
)
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Duration-based pricing: derive credit cost from known audio duration.
|
||||
# Reject inputs that are too long before any job is created.
|
||||
duration_seconds = request.duration_seconds
|
||||
if duration_seconds is not None and is_blocked(duration_seconds):
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="Inputs over 60 minutes aren't supported"
|
||||
)
|
||||
credits = duration_to_credits(duration_seconds) if duration_seconds is not None else 1
|
||||
|
||||
# Anti-mismatch guard: if the client told us how many credits it expects,
|
||||
# reject early if the server's computation disagrees (avoids surprise charges).
|
||||
if request.acknowledged_credits is not None and request.acknowledged_credits != credits:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Credit figure changed; please refresh"
|
||||
)
|
||||
|
||||
# Build initial state_data with duration estimate for observability.
|
||||
initial_state_data: Dict[str, Any] = {}
|
||||
if duration_seconds is not None:
|
||||
initial_state_data["duration_estimate_seconds"] = duration_seconds
|
||||
initial_state_data["duration_estimate_source"] = "youtube_metadata"
|
||||
else:
|
||||
initial_state_data["duration_estimate_source"] = "unknown"
|
||||
|
||||
# Create job with all preferences
|
||||
job_create = JobCreate(
|
||||
url=str(request.url),
|
||||
@@ -133,13 +162,18 @@ async def create_job(
|
||||
webhook_url=request.webhook_url,
|
||||
user_email=user_email,
|
||||
is_private=request.is_private or False,
|
||||
credits=credits,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
# Store client IP on job for anti-abuse correlation
|
||||
# Persist duration estimate fields and creation_ip in a single Firestore write.
|
||||
update_payload = {
|
||||
f"state_data.{k}": v for k, v in initial_state_data.items()
|
||||
}
|
||||
creation_ip = get_client_ip(http_request)
|
||||
if creation_ip:
|
||||
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
|
||||
update_payload["creation_ip"] = creation_ip
|
||||
FirestoreService().update_job(job.job_id, update_payload)
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job.job_id)
|
||||
@@ -160,7 +194,7 @@ async def create_job(
|
||||
job_id=job.job_id,
|
||||
message=t(locale, "jobs.created")
|
||||
)
|
||||
except InsufficientCreditsError:
|
||||
except (InsufficientCreditsError, HTTPException):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job: {e}", exc_info=True)
|
||||
@@ -362,6 +396,11 @@ async def edit_completed_track(
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
# Also remove the Nomad 720p master from the GCS fast-sync mirror
|
||||
# (prefix-keyed by brand_code, so it covers renames). Non-fatal,
|
||||
# Nomad-brand only, no-op otherwise.
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
except Exception as e:
|
||||
@@ -536,11 +575,58 @@ _SUMMARY_STATE_DATA_KEYS = {
|
||||
'audio_progress', 'lyrics_progress',
|
||||
'audio_complete', 'lyrics_complete',
|
||||
'backing_vocals_analysis', 'visibility_change_in_progress',
|
||||
'render_pending_capacity',
|
||||
'cloud_run_retry_pending',
|
||||
'credits_charged',
|
||||
'pending_additional_credits',
|
||||
'duration_actual_seconds',
|
||||
'duration_confirm_reason',
|
||||
'batch_id',
|
||||
'bulk_auto_selected',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
|
||||
|
||||
|
||||
def _is_auto_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
|
||||
"""Return True if a Cloud Run Job auto-retry is currently expected.
|
||||
|
||||
The audio-download worker records `state_data.cloud_run_retry_pending`
|
||||
with an `expires_at` when it fails and another task attempt is coming.
|
||||
The /retry endpoint uses this to refuse starting a parallel execution,
|
||||
and the UI uses the projected field to show a "Retrying automatically..."
|
||||
indicator instead of a Retry button.
|
||||
"""
|
||||
pending = (state_data or {}).get('cloud_run_retry_pending')
|
||||
if not isinstance(pending, dict):
|
||||
return False
|
||||
expires_at_str = pending.get('expires_at')
|
||||
if not expires_at_str:
|
||||
return False
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(str(expires_at_str).replace('Z', '+00:00'))
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
return expires_at > datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _has_title_screen(file_urls: Dict[str, Any]) -> bool:
|
||||
"""Return True if a title screen image (jpg or png) was generated.
|
||||
|
||||
Used by the /retry endpoint to decide whether to resume from the render
|
||||
stage or rewind further. The actual screen URLs live under format-specific
|
||||
keys (`title_jpg`, `title_png`) rather than a bare `title` key, so a
|
||||
naive `screens.get('title')` check produced false-negatives and forced
|
||||
completed-review jobs back to AWAITING_REVIEW.
|
||||
"""
|
||||
screens = file_urls.get('screens') or {}
|
||||
if not isinstance(screens, dict):
|
||||
return False
|
||||
return any(k == 'title' or k.startswith('title_') for k in screens)
|
||||
|
||||
|
||||
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Strip state_data down to dashboard-required keys."""
|
||||
sd = data.get('state_data')
|
||||
@@ -995,14 +1081,23 @@ async def submit_corrections(
|
||||
)
|
||||
|
||||
try:
|
||||
# Strip reference_lyrics from Firestore save to avoid exceeding 1MB document
|
||||
# limit. reference_lyrics can be very large (e.g. Genius fetching non-lyrics
|
||||
# content like screenplays). The full data is preserved in the GCS upload below.
|
||||
corrections_for_firestore = {
|
||||
k: v for k, v in submission.corrections.items()
|
||||
if k != 'reference_lyrics'
|
||||
# Persist ONLY a lightweight summary of the corrections to Firestore —
|
||||
# never the full segment arrays. The complete corrections JSON
|
||||
# (corrected_segments, original_segments, resized_segments, etc.) can be
|
||||
# several MB for long songs (e.g. a 30+ minute mashup with hundreds of
|
||||
# segments) and would blow past Firestore's 1MB per-document hard limit,
|
||||
# failing the save with a 400. (An earlier fix stripped only
|
||||
# reference_lyrics, but the segment arrays are the real bulk.) The full
|
||||
# data is preserved in the GCS upload below (corrections_updated.json),
|
||||
# which the render worker reads. The only in-Firestore consumer is the
|
||||
# complete-review 0-segment guard, which just needs the segment count.
|
||||
corrected_segments = submission.corrections.get('corrected_segments')
|
||||
corrected_lyrics_summary = {
|
||||
'corrected_segment_count': (
|
||||
len(corrected_segments) if isinstance(corrected_segments, list) else 0
|
||||
),
|
||||
}
|
||||
job_manager.update_state_data(job_id, 'corrected_lyrics', corrections_for_firestore)
|
||||
job_manager.update_state_data(job_id, 'corrected_lyrics', corrected_lyrics_summary)
|
||||
if submission.user_notes:
|
||||
job_manager.update_state_data(job_id, 'review_notes', submission.user_notes)
|
||||
|
||||
@@ -1024,6 +1119,18 @@ async def submit_corrections(
|
||||
from backend.services.storage_service import StorageService
|
||||
storage = StorageService()
|
||||
|
||||
# Safety net: never persist word timings that fall outside their segment.
|
||||
# Frontend should already prevent this; this guarantees clean stored data
|
||||
# (the render worker reads corrections_updated.json verbatim).
|
||||
from backend.services.timing_sanitizer import sanitize_corrections
|
||||
sanitized, clamp_count = sanitize_corrections(submission.corrections)
|
||||
if clamp_count:
|
||||
logger.warning(
|
||||
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
|
||||
f"in submitted corrections before persisting"
|
||||
)
|
||||
submission.corrections = sanitized
|
||||
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, submission.corrections)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
@@ -1358,10 +1465,15 @@ async def complete_review(
|
||||
lyrics_metadata = state_data.get('lyrics_metadata')
|
||||
if lyrics_metadata is not None:
|
||||
segment_count = lyrics_metadata.get('segment_count', 0)
|
||||
corrected_lyrics = state_data.get('corrected_lyrics', {})
|
||||
corrected_segments = corrected_lyrics.get('corrected_segments', [])
|
||||
corrected_lyrics = state_data.get('corrected_lyrics') or {}
|
||||
# corrected_lyrics now stores a lightweight summary
|
||||
# ({'corrected_segment_count': N}). Fall back to the legacy shape (full
|
||||
# dict with a corrected_segments list) for jobs saved before that change.
|
||||
corrected_segment_count = corrected_lyrics.get('corrected_segment_count')
|
||||
if corrected_segment_count is None:
|
||||
corrected_segment_count = len(corrected_lyrics.get('corrected_segments') or [])
|
||||
|
||||
if segment_count == 0 and len(corrected_segments) == 0:
|
||||
if segment_count == 0 and corrected_segment_count == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t(locale, "jobs.noLyricsDetected")
|
||||
@@ -1370,6 +1482,13 @@ async def complete_review(
|
||||
try:
|
||||
# Store instrumental selection if provided (combined review flow)
|
||||
instrumental_selection = body.instrumental_selection if body else None
|
||||
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
|
||||
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
|
||||
# render uses the provided instrumental instead of a separated stem that was never
|
||||
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
|
||||
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
instrumental_selection = 'custom'
|
||||
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
|
||||
if instrumental_selection:
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
|
||||
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
|
||||
@@ -1707,6 +1826,15 @@ async def retry_job(
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
# Refuse if a Cloud Run Job auto-retry is already coming for this job.
|
||||
# Otherwise the manual retry races with the automatic one and produces
|
||||
# duplicate downloads and downstream worker triggers (see job 8a9c74ff).
|
||||
if _is_auto_retry_pending(job.state_data):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="An automatic retry is already in progress. Please wait a few minutes."
|
||||
)
|
||||
|
||||
try:
|
||||
# Determine retry point based on what's already complete
|
||||
error_details = job.error_details or {}
|
||||
@@ -1758,7 +1886,7 @@ async def retry_job(
|
||||
# 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
|
||||
_has_title_screen(file_urls) and
|
||||
state_data.get('instrumental_selection')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
|
||||
@@ -1795,7 +1923,7 @@ async def retry_job(
|
||||
# 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')):
|
||||
_has_title_screen(file_urls)):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
|
||||
|
||||
@@ -1859,9 +1987,18 @@ async def retry_job(
|
||||
"retry_stage": "screens_generation"
|
||||
}
|
||||
|
||||
# If we have input audio (uploaded or from URL), restart from beginning
|
||||
elif job.input_media_gcs_path or job.url:
|
||||
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
|
||||
# If the input audio is already in GCS (an uploaded file, or a URL whose
|
||||
# download succeeded), restart from beginning — the audio/lyrics workers
|
||||
# re-fetch it from GCS.
|
||||
#
|
||||
# A URL job whose download never succeeded has only `job.url` and NO
|
||||
# audio in GCS, so it must NOT take this branch: triggering the workers
|
||||
# would just fail with "Failed to download audio file" and Cloud Run
|
||||
# would retry them repeatedly (see job 7f36304a — an Apple Music link).
|
||||
# Such jobs fall through to the "resubmit" refusal below, since there is
|
||||
# no worker that re-downloads a generic URL.
|
||||
elif job.input_media_gcs_path:
|
||||
logger.info(f"Job {job_id}: Has input audio in GCS, restarting from beginning")
|
||||
|
||||
# Clear error state and any partial progress
|
||||
job_manager.update_job(job_id, {
|
||||
@@ -2150,6 +2287,14 @@ async def cleanup_distribution(
|
||||
"status": "skipped",
|
||||
"reason": "no files found to delete",
|
||||
}
|
||||
|
||||
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too, so a
|
||||
# re-finalise (incl. artist/title rename) doesn't leave the old cut on
|
||||
# kjbox. Prefix-keyed by brand_code (covers renames); the subsequent
|
||||
# re-run's push re-adds the new master. Non-fatal, Nomad-only.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
else:
|
||||
results["gdrive"] = {
|
||||
"status": "failed",
|
||||
@@ -2320,11 +2465,21 @@ async def create_job_from_search(
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
|
||||
|
||||
# Determine display values
|
||||
# Determine display values.
|
||||
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
|
||||
# body.title carry whatever is currently in the wizard's artist/title fields,
|
||||
# which reflect a "Use official formatting" correction the user may have applied
|
||||
# after searching. The displayed job name must honour that correction, so prefer
|
||||
# the request body over the stored query. An explicit display override wins above all.
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
# body.artist/body.title are required but unvalidated for whitespace, so strip
|
||||
# them and fall back to the stored query if blank (display_* is pre-stripped to
|
||||
# None by its validator). This keeps a stray " " from becoming the job name.
|
||||
body_artist = (body.artist or "").strip()
|
||||
body_title = (body.title or "").strip()
|
||||
effective_display_artist = body.display_artist or body_artist or session_artist
|
||||
effective_display_title = body.display_title or body_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id') or ""
|
||||
|
||||
@@ -2497,3 +2652,201 @@ async def change_visibility(
|
||||
except Exception as e:
|
||||
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Duration Confirmation Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class ConfirmDurationRequest(BaseModel):
|
||||
"""Request body for POST /jobs/{job_id}/confirm-duration."""
|
||||
acknowledged_credits: int
|
||||
|
||||
|
||||
# Keep a set of background tasks alive to prevent GC (mirrors complete_review pattern)
|
||||
_duration_confirm_tasks: set = set()
|
||||
|
||||
|
||||
@router.post("/{job_id}/confirm-duration")
|
||||
async def confirm_duration(
|
||||
job_id: str,
|
||||
body: ConfirmDurationRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Confirm duration-based credit charge and resume job processing.
|
||||
|
||||
Called when a job is paused in AWAITING_DURATION_CONFIRM state.
|
||||
|
||||
The only pause reason currently used is ``reconcile``: the actual measured
|
||||
duration costs more than was already charged; ``state_data.pending_additional_credits``
|
||||
holds the delta owed. This applies to URL, upload, and audio-search jobs alike.
|
||||
|
||||
The caller must pass ``acknowledged_credits`` equal to the total credit cost
|
||||
the user has agreed to pay. If the figure has changed (race condition) a 409
|
||||
is returned so the frontend can refresh and re-show the dialog.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
# 1. Load job — 404 if not found or not owned by this user.
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
# Return 404 (not 403) to avoid leaking job existence to non-owners.
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# 2. Status guard.
|
||||
if job.status != JobStatus.AWAITING_DURATION_CONFIRM:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"Job is not awaiting duration confirmation (status: {job.status})",
|
||||
)
|
||||
|
||||
# 3. Compute owed credits and expected total.
|
||||
#
|
||||
# - credits_charged: total already deducted from the user's account
|
||||
# - pending_additional_credits: exactly how many MORE credits are owed to clear the pause
|
||||
#
|
||||
# The reconcile engine is responsible for computing and storing pending_additional_credits.
|
||||
# confirm_duration never needs to call duration_to_credits.
|
||||
state_data = job.state_data or {}
|
||||
reason = state_data.get("duration_confirm_reason", "reconcile")
|
||||
credits_charged = int(state_data.get("credits_charged", 0))
|
||||
owed = int(state_data.get("pending_additional_credits", 0))
|
||||
expected_total = credits_charged + owed
|
||||
|
||||
# 4. Acknowledged-credits mismatch guard (figure may have changed; client refreshes).
|
||||
if body.acknowledged_credits != expected_total:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=(
|
||||
f"acknowledged_credits ({body.acknowledged_credits}) does not match "
|
||||
f"expected total ({expected_total}). Please refresh and confirm again."
|
||||
),
|
||||
)
|
||||
|
||||
# 5. Deduct credits if any are owed.
|
||||
if owed > 0:
|
||||
user_email = job.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=500, detail="Job has no associated user email")
|
||||
|
||||
user_svc = get_user_service()
|
||||
success, _remaining, _msg = user_svc.deduct_credits(
|
||||
user_email,
|
||||
job_id,
|
||||
amount=owed,
|
||||
reason="duration_confirm",
|
||||
count_as_job_creation=False, # job was already counted at create_job()
|
||||
)
|
||||
if not success:
|
||||
raise InsufficientCreditsError(
|
||||
message=f"Insufficient credits to confirm processing ({owed} credit(s) required).",
|
||||
credits_available=_remaining,
|
||||
credits_required=owed,
|
||||
)
|
||||
|
||||
# Update credits_charged in state_data to reflect the new total.
|
||||
job_manager.update_job(
|
||||
job_id,
|
||||
{
|
||||
"state_data.credits_charged": credits_charged + owed,
|
||||
"state_data.duration_confirmed": True,
|
||||
"state_data.pending_additional_credits": 0,
|
||||
},
|
||||
)
|
||||
else:
|
||||
# owed == 0: nothing to charge, just mark confirmed.
|
||||
job_manager.update_job(
|
||||
job_id,
|
||||
{
|
||||
"state_data.duration_confirmed": True,
|
||||
"state_data.pending_additional_credits": 0,
|
||||
},
|
||||
)
|
||||
|
||||
# 6. Transition job OUT of AWAITING_DURATION_CONFIRM before triggering workers.
|
||||
#
|
||||
# This is the idempotency guard: if a duplicate confirm POST arrives (e.g. a
|
||||
# double-click) the status guard at step 2 will now 409 immediately, preventing
|
||||
# a second pair of worker launches. We transition to SEPARATING_STAGE1 —
|
||||
# the normal next state for both the audio and lyrics parallel tracks — which is
|
||||
# a valid transition from AWAITING_DURATION_CONFIRM per STATE_TRANSITIONS.
|
||||
# The audio and lyrics workers update their own track states from here on, the
|
||||
# same as the normal convergence path.
|
||||
job_manager.transition_to_state(
|
||||
job_id,
|
||||
new_status=JobStatus.SEPARATING_STAGE1,
|
||||
progress=20,
|
||||
message="Cost confirmed, processing",
|
||||
)
|
||||
|
||||
# 7. Resume processing: trigger both parallel workers in background.
|
||||
# Use asyncio.create_task (mirrors complete_review in review.py) so the HTTP
|
||||
# response returns immediately without waiting for Cloud Run job submission.
|
||||
ws = get_worker_service()
|
||||
|
||||
async def _trigger_workers_after_confirm():
|
||||
try:
|
||||
await asyncio.gather(
|
||||
ws.trigger_audio_worker(job_id),
|
||||
ws.trigger_lyrics_worker(job_id),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"Job {job_id}: Failed to trigger workers after duration confirm: {exc}")
|
||||
|
||||
task = asyncio.create_task(_trigger_workers_after_confirm())
|
||||
_duration_confirm_tasks.add(task)
|
||||
task.add_done_callback(_duration_confirm_tasks.discard)
|
||||
|
||||
logger.info(
|
||||
f"Job {job_id}: duration confirmed (reason={reason}, owed={owed}); workers triggered"
|
||||
)
|
||||
|
||||
# 8. Return the updated job.
|
||||
updated_job = job_manager.get_job(job_id)
|
||||
if updated_job is None:
|
||||
# Should not happen, but be safe.
|
||||
return {"job_id": job_id, "status": "confirmed"}
|
||||
return updated_job
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /jobs/estimate — URL duration probe
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class EstimateRequest(BaseModel):
|
||||
url: HttpUrl
|
||||
|
||||
|
||||
@router.post("/estimate")
|
||||
async def estimate_duration(
|
||||
body: EstimateRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Probe a URL to estimate its duration and compute the credit cost,
|
||||
WITHOUT creating a job or downloading any audio.
|
||||
|
||||
Returns duration_seconds (or None if unknown), source, credits, and
|
||||
whether the duration exceeds the supported ceiling (blocked).
|
||||
"""
|
||||
info = await get_youtube_download_service().check_availability(str(body.url))
|
||||
seconds = (info or {}).get("duration")
|
||||
if seconds is None:
|
||||
return {
|
||||
"duration_seconds": None,
|
||||
"source": "unknown",
|
||||
"credits": 1,
|
||||
"blocked": False,
|
||||
}
|
||||
return {
|
||||
"duration_seconds": seconds,
|
||||
"source": "youtube_metadata",
|
||||
"credits": duration_to_credits(seconds),
|
||||
"blocked": is_blocked(seconds),
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"""POST /api/parse-karaoke-titles — batch karaoke-filename → artist/title.
|
||||
|
||||
Internal admin endpoint used by kjbox to canonicalise downloaded-file names.
|
||||
Reuses the Vertex Gemini parser; never blocks the caller (kjbox degrades to a
|
||||
deterministic guess when this is unavailable).
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.parse_titles import parse_titles
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["parse-titles"])
|
||||
|
||||
|
||||
class ParseItem(BaseModel):
|
||||
id: str
|
||||
filename: str
|
||||
channel: Optional[str] = None
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
class ParseRequest(BaseModel):
|
||||
items: list[ParseItem]
|
||||
|
||||
|
||||
class ParseResult(BaseModel):
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
confidence: float
|
||||
|
||||
|
||||
class ParseResponse(BaseModel):
|
||||
results: list[ParseResult]
|
||||
|
||||
|
||||
@router.post("/parse-karaoke-titles", response_model=ParseResponse)
|
||||
async def parse_karaoke_titles(
|
||||
body: ParseRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
items = [i.model_dump() for i in body.items]
|
||||
results = await parse_titles(items)
|
||||
logger.info("parse-karaoke-titles: %d items", len(items))
|
||||
return {"results": results}
|
||||
+386
-29
@@ -21,9 +21,8 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Optional, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends
|
||||
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
@@ -37,11 +36,156 @@ from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
|
||||
from pydantic import BaseModel as _PydBaseModel
|
||||
from backend.services.custom_lyrics_service import (
|
||||
CustomLyricsService,
|
||||
CustomLyricsServiceError,
|
||||
get_custom_lyrics_service,
|
||||
)
|
||||
from backend.services.auto_correct import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
|
||||
class LineMetadataResponse(_PydBaseModel):
|
||||
line_index: int
|
||||
target_text: str
|
||||
candidate_text: str
|
||||
target_syllables: list[int]
|
||||
candidate_syllables: list[int]
|
||||
min_delta: int
|
||||
passes: bool
|
||||
severity: str # "ok" | "minor" | "major"
|
||||
time_budget_seconds: float
|
||||
|
||||
|
||||
class CustomLyricsResponse(_PydBaseModel):
|
||||
lines: list[str]
|
||||
line_metadata: list[LineMetadataResponse]
|
||||
iterations_used: int
|
||||
stop_reason: str # "success" | "plateau" | "max_iters_reached" | "line_count_mismatch" | "verbatim_skip"
|
||||
settings_applied: dict
|
||||
new_segment_timing: Optional[list[tuple[float, float]]] = None
|
||||
line_count_mismatch: bool
|
||||
warnings: list[str]
|
||||
model: str
|
||||
|
||||
|
||||
class AutoCorrectRequest(_PydBaseModel):
|
||||
segments: list[dict] # client's current working corrected_segments
|
||||
reference_lyrics: dict # client's reference sources (incl. user-added)
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
settings: Optional[dict] = None # AutoCorrectSettings knobs
|
||||
|
||||
|
||||
class AutoCorrectSuggestionResponse(_PydBaseModel):
|
||||
id: str
|
||||
op: str # "replace" | "delete" | "insert_after"
|
||||
word_ids: list[str]
|
||||
segment_ids: list[str]
|
||||
original_text: str
|
||||
new_text: str
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
models: list[str]
|
||||
consensus: int
|
||||
total_models: int
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
class AutoCorrectResponse(_PydBaseModel):
|
||||
suggestions: list[AutoCorrectSuggestionResponse]
|
||||
model: str
|
||||
elapsed_seconds: float
|
||||
settings_applied: dict
|
||||
warnings: list[str]
|
||||
cached: bool = False
|
||||
|
||||
|
||||
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_custom_lyrics_service()
|
||||
|
||||
|
||||
def _get_auto_correct_service_dep() -> AutoCorrectService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_auto_correct_service()
|
||||
|
||||
|
||||
async def _load_target_segments_for_custom_lyrics(
|
||||
job_id: str,
|
||||
target_lines: list[str],
|
||||
) -> list[dict]:
|
||||
"""Load segments with timing for the custom-lyrics endpoint.
|
||||
|
||||
Tries to fetch corrections.json from GCS for accurate per-segment timing
|
||||
(start_time, end_time). Falls back to synthesized timing (2s per line)
|
||||
if corrections.json is unavailable or has a mismatched line count.
|
||||
|
||||
Returns a list of dicts with at least start_time, end_time, text, words keys.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
return _synthesized_segments(target_lines)
|
||||
|
||||
# Try corrections_updated first (latest review session edits), then corrections (original)
|
||||
corrections_path = (
|
||||
job.file_urls.get("lyrics", {}).get("corrections_updated")
|
||||
or f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
)
|
||||
if not (corrections_path and storage.file_exists(corrections_path)):
|
||||
corrections_path = (
|
||||
job.file_urls.get("lyrics", {}).get("corrections")
|
||||
or f"jobs/{job_id}/lyrics/corrections.json"
|
||||
)
|
||||
|
||||
try:
|
||||
if corrections_path and storage.file_exists(corrections_path):
|
||||
data = storage.download_json(corrections_path)
|
||||
segments = data.get("corrected_segments") or data.get("segments") or []
|
||||
if len(segments) == len(target_lines):
|
||||
return segments
|
||||
logger.warning(
|
||||
f"Job {job_id}: corrections.json has {len(segments)} segments but "
|
||||
f"{len(target_lines)} target_lines provided; using synthesized timing"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - degrade gracefully
|
||||
logger.warning(
|
||||
f"Job {job_id}: could not load segments from {corrections_path}: {e}; "
|
||||
f"using synthesized timing"
|
||||
)
|
||||
|
||||
return _synthesized_segments(target_lines)
|
||||
|
||||
|
||||
def _synthesized_segments(target_lines: list[str]) -> list[dict]:
|
||||
"""Fallback when real timing is unavailable: 2s per line."""
|
||||
return [
|
||||
{
|
||||
"id": f"synth-{i}",
|
||||
"start_time": float(i * 2.0),
|
||||
"end_time": float((i + 1) * 2.0),
|
||||
"text": line,
|
||||
"words": [],
|
||||
}
|
||||
for i, line in enumerate(target_lines)
|
||||
]
|
||||
|
||||
|
||||
# LyricsTranscriber imports for preview generation
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.output.timing_validation import LyricsTimingError
|
||||
|
||||
# Import from the unified style loader
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
@@ -419,6 +563,196 @@ async def complete_review(
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.reviewCompletedError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/custom-lyrics/generate", response_model=CustomLyricsResponse)
|
||||
async def generate_custom_lyrics(
|
||||
job_id: str,
|
||||
existing_lines: str = Form(..., description="JSON-encoded array of segment lines"),
|
||||
custom_text: Optional[str] = Form(None),
|
||||
notes: Optional[str] = Form(None),
|
||||
artist: Optional[str] = Form(None),
|
||||
title: Optional[str] = Form(None),
|
||||
settings_json: Optional[str] = Form(None, description="JSON-encoded GenerationSettings"),
|
||||
file: Optional[UploadFile] = File(None),
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
service: CustomLyricsService = Depends(_get_custom_lyrics_service_dep),
|
||||
) -> CustomLyricsResponse:
|
||||
"""Generate syllable-aware custom lyrics for a job using Gemini 3.1 Pro.
|
||||
|
||||
Stateless: returns generated lines + per-line metadata for the frontend
|
||||
to render in an annotated preview. Persistence happens via the existing
|
||||
/complete path after the user reviews and saves.
|
||||
"""
|
||||
from backend.services.custom_lyrics.settings import (
|
||||
GenerationSettings,
|
||||
settings_from_dict,
|
||||
)
|
||||
|
||||
# Parse existing_lines JSON
|
||||
try:
|
||||
parsed_lines = json.loads(existing_lines)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"existing_lines is not valid JSON: {exc}"
|
||||
) from exc
|
||||
if not isinstance(parsed_lines, list) or not all(
|
||||
isinstance(x, str) for x in parsed_lines
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="existing_lines must be a JSON array of strings",
|
||||
)
|
||||
if not parsed_lines:
|
||||
raise HTTPException(status_code=400, detail="existing_lines is empty")
|
||||
|
||||
# Parse settings (default to GenerationSettings() if missing)
|
||||
if settings_json:
|
||||
try:
|
||||
settings_dict = json.loads(settings_json)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"settings_json is not valid JSON: {exc}"
|
||||
) from exc
|
||||
try:
|
||||
settings = settings_from_dict(settings_dict)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
|
||||
else:
|
||||
settings = GenerationSettings()
|
||||
|
||||
# Read file body
|
||||
file_bytes: Optional[bytes] = None
|
||||
file_mime: Optional[str] = None
|
||||
file_name: Optional[str] = None
|
||||
if file is not None:
|
||||
file_bytes = await file.read()
|
||||
file_mime = file.content_type
|
||||
file_name = file.filename
|
||||
|
||||
if not custom_text and not file_bytes:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="must provide either custom_text or a file upload",
|
||||
)
|
||||
|
||||
# Load segments for timing context
|
||||
target_segments = await _load_target_segments_for_custom_lyrics(job_id, parsed_lines)
|
||||
|
||||
try:
|
||||
result = service.generate(
|
||||
job_id=job_id,
|
||||
target_lines=parsed_lines,
|
||||
target_segments=target_segments,
|
||||
artist=artist,
|
||||
title=title,
|
||||
custom_text=custom_text,
|
||||
file_bytes=file_bytes,
|
||||
file_mime=file_mime,
|
||||
file_name=file_name,
|
||||
notes=notes,
|
||||
settings=settings,
|
||||
)
|
||||
except CustomLyricsServiceError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
|
||||
return CustomLyricsResponse(
|
||||
lines=result.lines,
|
||||
line_metadata=[
|
||||
LineMetadataResponse(
|
||||
line_index=v.line_index,
|
||||
target_text=v.target_text,
|
||||
candidate_text=v.candidate_text,
|
||||
target_syllables=v.target_syllables,
|
||||
candidate_syllables=v.candidate_syllables,
|
||||
min_delta=v.min_delta,
|
||||
passes=v.passes,
|
||||
severity=v.severity.value,
|
||||
time_budget_seconds=v.time_budget_seconds,
|
||||
)
|
||||
for v in result.line_metadata
|
||||
],
|
||||
iterations_used=result.iterations_used,
|
||||
stop_reason=result.stop_reason.value,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
new_segment_timing=result.new_segment_timing,
|
||||
line_count_mismatch=result.line_count_mismatch,
|
||||
warnings=result.warnings,
|
||||
model=result.model,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/auto-correct", response_model=AutoCorrectResponse)
|
||||
async def auto_correct_suggestions(
|
||||
job_id: str,
|
||||
body: AutoCorrectRequest,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
service: AutoCorrectService = Depends(_get_auto_correct_service_dep),
|
||||
) -> AutoCorrectResponse:
|
||||
"""Generate AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless and strictly opt-in: one whole-song LLM call comparing the
|
||||
client's current working transcription against the reference lyrics.
|
||||
Returns word-id-keyed suggestions; nothing is applied server-side —
|
||||
the reviewer accepts or rejects each suggestion individually and
|
||||
persistence happens via the existing corrections/complete paths.
|
||||
"""
|
||||
from backend.services.auto_correct.settings import settings_from_dict
|
||||
|
||||
try:
|
||||
settings = settings_from_dict(body.settings or {})
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
|
||||
|
||||
with job_log_context(job_id), create_span("auto_correct_suggestions"):
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("segment_count", len(body.segments))
|
||||
logger.info(
|
||||
"auto-correct requested job=%s segments=%d sources=%d",
|
||||
job_id, len(body.segments), len(body.reference_lyrics),
|
||||
)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=body.segments,
|
||||
reference_lyrics=body.reference_lyrics,
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
settings=settings,
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
logger.info(
|
||||
"auto-correct completed job=%s suggestions=%d model=%s elapsed=%.1fs",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
|
||||
return AutoCorrectResponse(
|
||||
suggestions=[
|
||||
AutoCorrectSuggestionResponse(
|
||||
id=s.id,
|
||||
op=s.op,
|
||||
word_ids=s.word_ids,
|
||||
segment_ids=s.segment_ids,
|
||||
original_text=s.original_text,
|
||||
new_text=s.new_text,
|
||||
reason=s.reason,
|
||||
category=s.category,
|
||||
confidence=s.confidence,
|
||||
models=s.models,
|
||||
consensus=s.consensus,
|
||||
total_models=s.total_models,
|
||||
conflict_group=s.conflict_group,
|
||||
)
|
||||
for s in result.suggestions
|
||||
],
|
||||
model=result.model,
|
||||
elapsed_seconds=result.elapsed_seconds,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
warnings=result.warnings,
|
||||
cached=result.cached,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(
|
||||
job_id: str,
|
||||
@@ -893,6 +1227,13 @@ async def generate_preview_video(
|
||||
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError as timing_err:
|
||||
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
|
||||
# user-fixable input problem, not a server fault. Return 422 with an
|
||||
# actionable message instead of a cryptic 500.
|
||||
logger.warning(f"Job {job_id}: Preview blocked — lyrics not synchronized: {timing_err}")
|
||||
span.set_attribute("error", "lyrics_not_synchronized")
|
||||
raise HTTPException(status_code=422, detail=str(timing_err)) from timing_err
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to generate preview video: {e}", exc_info=True)
|
||||
span.set_attribute("error", str(e))
|
||||
@@ -908,9 +1249,19 @@ async def get_preview_video(
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the generated preview video."""
|
||||
"""Serve the generated preview video via a signed GCS URL redirect.
|
||||
|
||||
We redirect to a signed URL rather than proxying the bytes through Cloud
|
||||
Run because Cloud Run caps response bodies at 32 MiB. Long songs (e.g. a
|
||||
30+ minute mashup) produce a 360p preview larger than that, which the proxy
|
||||
path truncated mid-stream — the response started as 206 but the client
|
||||
received a 500, so the browser reported "no supported format". The signed
|
||||
URL lets the browser fetch the mp4 directly from GCS (with byte-range
|
||||
support intact), bypassing the limit entirely. Mirrors the audio-review
|
||||
endpoint above.
|
||||
"""
|
||||
storage = StorageService()
|
||||
|
||||
|
||||
# Check in-memory cache first
|
||||
preview_gcs_path = None
|
||||
if job_id in _preview_videos and preview_hash in _preview_videos[job_id]:
|
||||
@@ -920,30 +1271,14 @@ async def get_preview_video(
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
if not storage.file_exists(preview_gcs_path):
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
|
||||
|
||||
|
||||
try:
|
||||
# Download to temp file and stream
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
storage.download_file(preview_gcs_path, tmp_path)
|
||||
|
||||
logger.info(f"Job {job_id}: Streaming preview video {preview_hash}")
|
||||
|
||||
return FileResponse(
|
||||
tmp_path,
|
||||
media_type="video/mp4",
|
||||
filename=f"preview_{preview_hash}.mp4",
|
||||
headers={
|
||||
"Accept-Ranges": "bytes",
|
||||
"Content-Disposition": "inline",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
background=BackgroundTask(os.unlink, tmp_path),
|
||||
)
|
||||
|
||||
signed_url = storage.generate_signed_url(preview_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for preview video {preview_hash}")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
|
||||
logger.error(f"Job {job_id}: Error serving preview video: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
|
||||
|
||||
|
||||
@@ -1606,7 +1941,8 @@ async def apply_audio_edit(
|
||||
"""
|
||||
Apply an edit operation to the input audio.
|
||||
|
||||
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
|
||||
Supported operations: trim_start, trim_end, cut, mute, fade_in, fade_out,
|
||||
join_start, join_end.
|
||||
Returns updated waveform data and playback URL.
|
||||
"""
|
||||
import uuid
|
||||
@@ -1620,7 +1956,7 @@ async def apply_audio_edit(
|
||||
if not operation:
|
||||
raise HTTPException(status_code=400, detail="Missing 'operation' field")
|
||||
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "fade_in", "fade_out", "join_start", "join_end"}
|
||||
if operation not in valid_operations:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
|
||||
|
||||
@@ -1965,6 +2301,27 @@ async def submit_audio_edit(
|
||||
message="Audio edit complete, starting processing"
|
||||
)
|
||||
|
||||
# Reconcile credit charge against the (possibly-edited) audio before triggering workers.
|
||||
# reconcile_and_maybe_pause probes job.input_media_gcs_path — which was just updated above
|
||||
# to point to the edited audio (jobs/{job_id}/input/edited.flac) if edits were applied.
|
||||
if await reconcile_and_maybe_pause(job_id):
|
||||
# Job paused (AWAITING_DURATION_CONFIRM) or cancelled — do not start processing.
|
||||
# Reload to distinguish the two outcomes so the caller can surface the right message.
|
||||
reloaded = job_manager.get_job(job_id)
|
||||
if reloaded and reloaded.status in (JobStatus.CANCELLED, JobStatus.FAILED):
|
||||
return {
|
||||
"status": "cancelled",
|
||||
"message": "Audio edit saved. Job was cancelled — audio exceeds the supported limit.",
|
||||
"job_id": job_id,
|
||||
"edits_applied": len(edit_stack),
|
||||
}
|
||||
return {
|
||||
"status": "paused",
|
||||
"message": "Audio edit saved. Additional credits are required to continue processing.",
|
||||
"job_id": job_id,
|
||||
"edits_applied": len(edit_stack),
|
||||
}
|
||||
|
||||
# Trigger parallel workers in background so the HTTP response returns immediately.
|
||||
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
|
||||
# waiting synchronously causes the browser request to time out.
|
||||
|
||||
+175
-1
@@ -43,6 +43,8 @@ from backend.models.user import (
|
||||
SendMagicLinkRequest,
|
||||
SendMagicLinkResponse,
|
||||
VerifyMagicLinkResponse,
|
||||
ResendFromTokenRequest,
|
||||
ResendFromTokenResponse,
|
||||
AddCreditsRequest,
|
||||
AddCreditsResponse,
|
||||
UserListResponse,
|
||||
@@ -217,7 +219,7 @@ async def send_magic_link(
|
||||
Send a magic link email for passwordless authentication.
|
||||
|
||||
The user will receive an email with a link that logs them in.
|
||||
Links expire after 15 minutes and can only be used once.
|
||||
Links expire after 24 hours and can only be used once.
|
||||
|
||||
For white-label tenants, validates email domain against tenant config.
|
||||
"""
|
||||
@@ -479,6 +481,178 @@ async def verify_magic_link(
|
||||
)
|
||||
|
||||
|
||||
class MagicLinkStatusResponse(BaseModel):
|
||||
status: str # "valid" | "used" | "expired" | "invalid"
|
||||
|
||||
|
||||
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
|
||||
async def magic_link_status(
|
||||
token: str,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Read-only status of a magic link — does NOT consume it.
|
||||
|
||||
The verify page calls this on load so it can show the correct UI upfront:
|
||||
the "Complete Sign-In" gate for a valid link, or an "already used / expired"
|
||||
message for a dead one — without making the user click only to then fail.
|
||||
|
||||
This endpoint is intentionally non-mutating so that an email link-scanner
|
||||
which renders the verify page (and triggers this read) cannot burn a still-
|
||||
valid token before the real user clicks. Token consumption happens only in
|
||||
the separate GET /auth/verify, which requires an explicit user click.
|
||||
"""
|
||||
if not token or not token.strip():
|
||||
return MagicLinkStatusResponse(status="invalid")
|
||||
return MagicLinkStatusResponse(status=user_service.get_magic_link_status(token))
|
||||
|
||||
|
||||
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
|
||||
async def resend_magic_link_from_token(
|
||||
request: ResendFromTokenRequest,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
email_service: EmailService = Depends(get_email_service),
|
||||
):
|
||||
"""
|
||||
Resend a magic link to the email associated with a previously-issued token.
|
||||
|
||||
Used by the verify failure UI to give users a one-click recovery when their
|
||||
sign-in link has expired or already been used. The original token is a 32-byte
|
||||
cryptographic secret — only the email recipient could possess it — so resending
|
||||
to the email recorded in the token doc adds no new attack surface.
|
||||
|
||||
Behaviour:
|
||||
- Token doc found → mint a fresh magic link, send it, return masked email.
|
||||
- Token doc missing → return status="no_token" so the UI can fall back to
|
||||
the standard sign-in form.
|
||||
"""
|
||||
from backend.services.user_service import MAGIC_LINKS_COLLECTION
|
||||
from backend.middleware.tenant import get_tenant_from_request, get_tenant_config_from_request
|
||||
|
||||
locale = get_locale_from_request(http_request)
|
||||
token = (request.token or "").strip()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(status_code=422, detail=t(locale, "users.invalidToken"))
|
||||
|
||||
magic_link_doc = user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
|
||||
if not magic_link_doc.exists:
|
||||
return ResendFromTokenResponse(
|
||||
status="no_token",
|
||||
masked_email=None,
|
||||
message=t(locale, "users.resendNoToken"),
|
||||
)
|
||||
|
||||
magic_link_data = magic_link_doc.to_dict() or {}
|
||||
email = (magic_link_data.get("email") or "").lower()
|
||||
if not email:
|
||||
return ResendFromTokenResponse(
|
||||
status="no_token",
|
||||
masked_email=None,
|
||||
message=t(locale, "users.resendNoToken"),
|
||||
)
|
||||
|
||||
if not email_service.is_configured():
|
||||
logger.error("Email service not configured - cannot resend magic links")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=t(locale, "users.emailServiceNotConfigured"),
|
||||
)
|
||||
|
||||
# Per-token cooldown: ignore repeat clicks of the resend button (or
|
||||
# email-scanner pre-fetches) within a short window. We still report
|
||||
# "sent" so the UI doesn't degrade — the user already got an email.
|
||||
RESEND_COOLDOWN_SECONDS = 60
|
||||
last_resend_at = magic_link_data.get("last_resend_at")
|
||||
if last_resend_at is not None:
|
||||
last_resend_dt = last_resend_at
|
||||
if isinstance(last_resend_at, str):
|
||||
try:
|
||||
last_resend_dt = datetime.fromisoformat(last_resend_at.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
last_resend_dt = None
|
||||
if last_resend_dt is not None:
|
||||
now = datetime.utcnow()
|
||||
if last_resend_dt.tzinfo is not None:
|
||||
from datetime import timezone as _tz
|
||||
now = now.replace(tzinfo=_tz.utc)
|
||||
elapsed = (now - last_resend_dt).total_seconds()
|
||||
if 0 <= elapsed < RESEND_COOLDOWN_SECONDS:
|
||||
logger.info(
|
||||
f"Resend cooldown active for {_mask_email(email)} ({elapsed:.0f}s elapsed)"
|
||||
)
|
||||
return ResendFromTokenResponse(
|
||||
status="sent",
|
||||
masked_email=_mask_email(email),
|
||||
message=t(locale, "users.magicLinkSent"),
|
||||
)
|
||||
|
||||
ip_address = get_client_ip(http_request)
|
||||
user_agent = http_request.headers.get("user-agent")
|
||||
|
||||
# Carry forward tenant context: prefer the original token's tenant so the
|
||||
# resent link goes to the same portal the user originally signed up on.
|
||||
original_tenant_id = magic_link_data.get("tenant_id")
|
||||
request_tenant_id = get_tenant_from_request(http_request)
|
||||
request_tenant_config = get_tenant_config_from_request(http_request)
|
||||
tenant_id = original_tenant_id or request_tenant_id
|
||||
|
||||
tenant_config = request_tenant_config
|
||||
if original_tenant_id and original_tenant_id != request_tenant_id:
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
tenant_config = get_tenant_service().get_tenant_config(original_tenant_id)
|
||||
|
||||
referral_code = magic_link_data.get("referral_code")
|
||||
device_fingerprint = magic_link_data.get("device_fingerprint")
|
||||
|
||||
new_link = user_service.create_magic_link(
|
||||
email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
|
||||
sender_email = None
|
||||
tenant_frontend_url = None
|
||||
tenant_name = None
|
||||
if tenant_config:
|
||||
sender_email = tenant_config.get_sender_email()
|
||||
tenant_frontend_url = tenant_config.get_frontend_url()
|
||||
tenant_name = tenant_config.name
|
||||
|
||||
sent = email_service.send_magic_link(
|
||||
email,
|
||||
new_link.token,
|
||||
sender_email=sender_email,
|
||||
tenant_frontend_url=tenant_frontend_url,
|
||||
tenant_name=tenant_name,
|
||||
locale=locale,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to resend magic link email to {_mask_email(email)}")
|
||||
|
||||
# Stamp the original token so the cooldown applies to subsequent clicks.
|
||||
try:
|
||||
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
"last_resend_at": datetime.utcnow(),
|
||||
})
|
||||
except Exception:
|
||||
logger.exception("Failed to stamp last_resend_at on magic link doc")
|
||||
|
||||
logger.info(f"Resent magic link to {_mask_email(email)} from expired/used token")
|
||||
|
||||
return ResendFromTokenResponse(
|
||||
status="sent",
|
||||
masked_email=_mask_email(email),
|
||||
message=t(locale, "users.magicLinkSent"),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/auth/logout", response_model=LogoutResponse)
|
||||
async def logout(
|
||||
request: Request,
|
||||
|
||||
@@ -20,6 +20,17 @@ class Settings(BaseSettings):
|
||||
gcs_temp_bucket: str = os.getenv("GCS_TEMP_BUCKET", "karaoke-gen-temp")
|
||||
gcs_output_bucket: str = os.getenv("GCS_OUTPUT_BUCKET", "karaoke-gen-outputs")
|
||||
firestore_collection: str = os.getenv("FIRESTORE_COLLECTION", "jobs")
|
||||
|
||||
# Nomad master fast-sync: push freshly-published Nomad 720p masters straight to the
|
||||
# Divebar GCS mirror so kjbox (which mirrors that folder every 5 min) picks them up
|
||||
# within minutes instead of waiting for the nightly Drive->GCS VM. Nomad-brand only.
|
||||
divebar_files_bucket: str = os.getenv("DIVEBAR_FILES_BUCKET", "nomadkaraoke-divebar-files")
|
||||
nomad_master_gcs_prefix: str = os.getenv("NOMAD_MASTER_GCS_PREFIX", "files/Nomad Karaoke/MP4-720p")
|
||||
nomad_master_fast_sync_enabled: bool = os.getenv("NOMAD_MASTER_FAST_SYNC_ENABLED", "true").lower() == "true"
|
||||
# Original-vocals guide: a padded isolated-vocals file (silence[intro] + vocals) pushed to
|
||||
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
|
||||
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
|
||||
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
@@ -61,12 +72,75 @@ class Settings(BaseSettings):
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
|
||||
# Lyrics transcription outer (safety-net) timeout, scaled by audio duration.
|
||||
# Long inputs (e.g. 30+ minute mashups) legitimately take longer to transcribe,
|
||||
# so the timeout = clamp(floor, duration * per_audio_second, cap). The cap must
|
||||
# stay under the Cloud Run Job task timeout so we surface a clean RuntimeError
|
||||
# before the platform hard-kills the task. The lyrics-transcription-job sets the
|
||||
# task timeout to 3000s and overrides this cap to 2700s via env; the 1700s
|
||||
# default here is the safe value if that env is ever unset (under an 1800s task).
|
||||
transcription_timeout_floor_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_FLOOR_SECONDS", "1200"))
|
||||
transcription_timeout_cap_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_CAP_SECONDS", "1700"))
|
||||
transcription_timeout_per_audio_second: float = float(os.getenv("TRANSCRIPTION_TIMEOUT_PER_AUDIO_SECOND", "1.0"))
|
||||
|
||||
# AI Credit Evaluation (anti-abuse gating for free credits)
|
||||
# When enabled, welcome and feedback credit grants are evaluated by Gemini
|
||||
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
|
||||
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
|
||||
|
||||
# Custom Lyrics (LLM-powered) — used by the Custom Lyrics mode in the
|
||||
# Edit All Lyrics modal. Stateless service: takes operator-provided
|
||||
# custom-lyrics text/file and returns transformed lyric lines.
|
||||
custom_lyrics_model: str = os.getenv("CUSTOM_LYRICS_MODEL", "gemini-3.1-pro-preview")
|
||||
custom_lyrics_max_file_mb: int = int(os.getenv("CUSTOM_LYRICS_MAX_FILE_MB", "5"))
|
||||
custom_lyrics_max_input_lines: int = int(os.getenv("CUSTOM_LYRICS_MAX_INPUT_LINES", "500"))
|
||||
custom_lyrics_max_iterations: int = int(os.getenv("CUSTOM_LYRICS_MAX_ITERATIONS", "4"))
|
||||
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
|
||||
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
|
||||
|
||||
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
|
||||
# review UI. Stateless: one whole-song LLM call returning word-level
|
||||
# suggestions the reviewer accepts/rejects individually.
|
||||
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
|
||||
# Models used by the multi-model "compare" mode (semicolon-separated —
|
||||
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
|
||||
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
|
||||
# Proactively generate (and cache) auto-correct suggestions in the lyrics
|
||||
# worker once transcription + references are ready, so the review UI has
|
||||
# them instantly. Best-effort: failures never block or fail the job. Only
|
||||
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
|
||||
# (the lyrics-transcription-job, via ci.yml). Default off.
|
||||
auto_correct_proactive_enabled: bool = os.getenv(
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Match judge — artist/title formatting + match-acceptance for the job
|
||||
# submission flow. Deterministic + catalog layers always run; the light AI
|
||||
# layer (Vertex Gemini Flash) fires only when those aren't confident.
|
||||
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
|
||||
"true", "1", "yes",
|
||||
)
|
||||
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
|
||||
# Bounds the AI call so a hung model never strands the submission UI. Kept
|
||||
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
|
||||
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
|
||||
# call still runs off the critical path and degrades to "none" on timeout.
|
||||
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
|
||||
|
||||
# Batch karaoke-filename parser (kjbox download-naming). Reuses the Vertex
|
||||
# Gemini stack. Larger timeout than match_judge because it batches ~200 items.
|
||||
parse_titles_enabled: bool = os.getenv("PARSE_TITLES_ENABLED", "true").lower() in (
|
||||
"1", "true", "yes",
|
||||
)
|
||||
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.5-flash")
|
||||
parse_titles_timeout_ms: int = int(os.getenv("PARSE_TITLES_TIMEOUT_MS", "20000"))
|
||||
parse_titles_max_items: int = int(os.getenv("PARSE_TITLES_MAX_ITEMS", "200"))
|
||||
# Items per Gemini call: large client batches are split into concurrent
|
||||
# chunks of this size so one call never outgrows parse_titles_timeout_ms
|
||||
# (a 100-item single call did, blanking the whole batch).
|
||||
parse_titles_chunk_size: int = int(os.getenv("PARSE_TITLES_CHUNK_SIZE", "10"))
|
||||
|
||||
# Cloud Tasks (for scalable worker coordination)
|
||||
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
@@ -87,6 +161,13 @@ class Settings(BaseSettings):
|
||||
encoding_worker_url: Optional[str] = os.getenv("ENCODING_WORKER_URL") # e.g., http://136.119.50.148:8080
|
||||
encoding_worker_api_key: Optional[str] = os.getenv("ENCODING_WORKER_API_KEY")
|
||||
|
||||
# Optional capacity-fallback VMs in alternate zones. JSON list of objects:
|
||||
# '[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"34.x.x.x"}]'
|
||||
# Empty by default. After `pulumi up` provisions the fallback VMs (Phase 3
|
||||
# of the capacity-resilience plan), populate this var with their public
|
||||
# IPs to enable multi-zone failover when us-central1-c is exhausted.
|
||||
encoding_worker_fallback_vms: Optional[str] = os.getenv("ENCODING_WORKER_FALLBACK_VMS")
|
||||
|
||||
# GCE Preview Encoding (for faster preview video generation)
|
||||
# When enabled, preview video encoding during lyrics review is offloaded to the GCE worker.
|
||||
# This reduces preview generation time from 60+ seconds to ~15-20 seconds.
|
||||
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,81 @@
|
||||
"""One-shot script to populate the year-5-stars fixture from a real production job.
|
||||
|
||||
Run once:
|
||||
poetry run python -m backend.eval.custom_lyrics._bootstrap_year5
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
|
||||
JOB_ID = "2cb49a45"
|
||||
FIXTURE_DIR = Path(__file__).parent / "fixtures" / "year-5-stars-shake-it-off"
|
||||
CLIENT_INPUT_SRC = Path("/Users/andrew/Projects/nomadkaraoke/year-5-stars-client-custom-lyrics.txt")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
FIXTURE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
fs = firestore.Client(project="nomadkaraoke")
|
||||
job_doc = fs.collection("jobs").document(JOB_ID).get()
|
||||
if not job_doc.exists:
|
||||
raise SystemExit(f"Job {JOB_ID} not found")
|
||||
job = job_doc.to_dict()
|
||||
|
||||
# Corrected lyrics are stored inline in state_data (not in GCS for this job)
|
||||
corrected = (
|
||||
job.get("state_data", {}).get("corrected_lyrics")
|
||||
or job.get("corrected_lyrics")
|
||||
or {}
|
||||
)
|
||||
if not corrected:
|
||||
# Fallback: try GCS path if present
|
||||
corrected_path = job.get("corrected_json_gcs_path") or job.get("lyrics", {}).get("corrected_path")
|
||||
if corrected_path:
|
||||
from google.cloud import storage # noqa: PLC0415
|
||||
storage_client = storage.Client(project="nomadkaraoke")
|
||||
bucket_name, *blob_parts = corrected_path.replace("gs://", "").split("/", 1)
|
||||
blob = storage_client.bucket(bucket_name).blob(blob_parts[0])
|
||||
corrected = json.loads(blob.download_as_bytes())
|
||||
else:
|
||||
raise SystemExit(f"Job {JOB_ID} has no corrected lyrics (checked state_data and GCS path fields)")
|
||||
|
||||
segments = corrected.get("corrected_segments") or corrected.get("segments") or []
|
||||
if not segments:
|
||||
raise SystemExit("No segments found in corrected.json")
|
||||
|
||||
(FIXTURE_DIR / "original_segments.json").write_text(json.dumps(segments, indent=2))
|
||||
(FIXTURE_DIR / "original_lyrics.txt").write_text(
|
||||
"\n".join(seg.get("text", "").strip() for seg in segments) + "\n"
|
||||
)
|
||||
|
||||
if CLIENT_INPUT_SRC.exists():
|
||||
shutil.copy(CLIENT_INPUT_SRC, FIXTURE_DIR / "client_input.txt")
|
||||
else:
|
||||
print(f"WARNING: {CLIENT_INPUT_SRC} not found; populate client_input.txt manually")
|
||||
|
||||
metadata = {
|
||||
"id": "year-5-stars-shake-it-off",
|
||||
"artist": job.get("artist") or "Taylor Swift",
|
||||
"title": job.get("title") or "Shake It Off",
|
||||
"source_job_id": JOB_ID,
|
||||
"difficulty": "hard",
|
||||
"input_style": "long substantive lines, name-heavy, mismatched syllable budget",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": True, "allow_omit": True, "fixed_line_count": True, "strictness": "balanced"},
|
||||
{"name": "verbatim", "allow_reword": True, "allow_omit": True, "fixed_line_count": True, "strictness": "verbatim"},
|
||||
{"name": "strict", "allow_reword": True, "allow_omit": True, "fixed_line_count": True, "strictness": "strict"},
|
||||
],
|
||||
}
|
||||
(FIXTURE_DIR / "metadata.json").write_text(json.dumps(metadata, indent=2))
|
||||
|
||||
print(f"Fixture populated at {FIXTURE_DIR}")
|
||||
print(f" - {len(segments)} segments")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Disk-backed cache for LLM responses, keyed by (system, user, model, settings)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
class LlmCallCache:
|
||||
def __init__(self, cache_dir: Path, replay_only: bool = False) -> None:
|
||||
self.cache_dir = cache_dir
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.replay_only = replay_only
|
||||
|
||||
def _key(
|
||||
self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
*,
|
||||
model: str,
|
||||
settings_dict: dict[str, Any],
|
||||
) -> str:
|
||||
h = hashlib.sha256()
|
||||
h.update(system_prompt.encode())
|
||||
h.update(b"\x00")
|
||||
h.update(user_prompt.encode())
|
||||
h.update(b"\x00")
|
||||
h.update(model.encode())
|
||||
h.update(b"\x00")
|
||||
h.update(json.dumps(settings_dict, sort_keys=True).encode())
|
||||
return h.hexdigest()
|
||||
|
||||
def _path(self, key: str) -> Path:
|
||||
return self.cache_dir / f"{key}.json"
|
||||
|
||||
def get(
|
||||
self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
*,
|
||||
model: str,
|
||||
settings_dict: dict[str, Any],
|
||||
) -> Optional[list[str]]:
|
||||
path = self._path(self._key(system_prompt, user_prompt, model=model, settings_dict=settings_dict))
|
||||
if not path.exists():
|
||||
if self.replay_only:
|
||||
raise RuntimeError(f"cache miss in replay-only mode: {path.name}")
|
||||
return None
|
||||
return json.loads(path.read_text())["lines"]
|
||||
|
||||
def set(
|
||||
self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
*,
|
||||
model: str,
|
||||
settings_dict: dict[str, Any],
|
||||
response_lines: list[str],
|
||||
) -> None:
|
||||
if self.replay_only:
|
||||
return
|
||||
path = self._path(self._key(system_prompt, user_prompt, model=model, settings_dict=settings_dict))
|
||||
path.write_text(json.dumps({"lines": response_lines}, indent=2))
|
||||
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
@@ -0,0 +1 @@
|
||||
We're singing this for Alex's birthday! Can you change the lyrics so it says Alex's name instead of "he"? Like "For she's a jolly good fellow" or however it makes sense with Alex. Just make it clear it's for Alex. It's a birthday celebration for our friend Alex.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"id": "jolly-good-fellow-name-replace",
|
||||
"artist": "Traditional",
|
||||
"title": "For He's a Jolly Good Fellow",
|
||||
"difficulty": "easy",
|
||||
"input_style": "explicit name replacement instruction",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "balanced"},
|
||||
{"name": "strict", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "strict"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
For he's a jolly good fellow
|
||||
For he's a jolly good fellow
|
||||
For he's a jolly good fellow
|
||||
Which nobody can deny
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
[
|
||||
{
|
||||
"id": "seg-00",
|
||||
"start_time": 0.0,
|
||||
"end_time": 2.5,
|
||||
"text": "For he's a jolly good fellow",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-01",
|
||||
"start_time": 2.5,
|
||||
"end_time": 5.0,
|
||||
"text": "For he's a jolly good fellow",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-02",
|
||||
"start_time": 5.0,
|
||||
"end_time": 7.5,
|
||||
"text": "For he's a jolly good fellow",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-03",
|
||||
"start_time": 7.5,
|
||||
"end_time": 10.0,
|
||||
"text": "Which nobody can deny",
|
||||
"words": []
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
We need this song to be about Mike and Sarah's wedding. Mike is a software engineer who loves climbing mountains, hiking on Saturdays with his border collie Max, and brewing his own beer in the basement. Sarah is a pediatric nurse with three sisters — Jenny, Tara, and Rachel — and she runs marathons every fall in the city park near her apartment. They met five years ago at a friend's birthday party in Brooklyn and bought their first house together last summer in Queens. Make the song celebrate their journey together. Highlight Max the dog if you can, and mention the marathons and the brewing.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"id": "row-row-line-surplus",
|
||||
"artist": "Traditional",
|
||||
"title": "Row, Row, Row Your Boat",
|
||||
"difficulty": "medium",
|
||||
"input_style": "client input far exceeds song's structural capacity (line surplus)",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "balanced"},
|
||||
{"name": "strict", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "strict"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
Row, row, row your boat,
|
||||
Gently down the stream,
|
||||
Merrily, merrily, merrily, merrily,
|
||||
Life is but a dream.
|
||||
@@ -0,0 +1,30 @@
|
||||
[
|
||||
{
|
||||
"text": "Row, row, row your boat,",
|
||||
"start_time": 0.0,
|
||||
"end_time": 1.5,
|
||||
"id": "rr-0",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"text": "Gently down the stream,",
|
||||
"start_time": 1.5,
|
||||
"end_time": 3.0,
|
||||
"id": "rr-1",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"text": "Merrily, merrily, merrily, merrily,",
|
||||
"start_time": 3.0,
|
||||
"end_time": 4.5,
|
||||
"id": "rr-2",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"text": "Life is but a dream.",
|
||||
"start_time": 4.5,
|
||||
"end_time": 6.0,
|
||||
"id": "rr-3",
|
||||
"words": []
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
Hi! Can you change the word "star" to "Sam" throughout the song? Every time "star" appears, I want it to say "Sam" instead. It's for my son Sam's birthday party. Thanks!
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"id": "twinkle-name-swap",
|
||||
"artist": "Traditional",
|
||||
"title": "Twinkle Twinkle Little Star",
|
||||
"difficulty": "easy",
|
||||
"input_style": "simple word substitution, well-defined target",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "balanced"},
|
||||
{"name": "strict", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "strict"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
Twinkle, twinkle, little star
|
||||
How I wonder what you are
|
||||
Up above the world so high
|
||||
Like a diamond in the sky
|
||||
Twinkle, twinkle, little star
|
||||
How I wonder what you are
|
||||
@@ -0,0 +1,44 @@
|
||||
[
|
||||
{
|
||||
"id": "seg-00",
|
||||
"start_time": 0.0,
|
||||
"end_time": 2.0,
|
||||
"text": "Twinkle, twinkle, little star",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-01",
|
||||
"start_time": 2.0,
|
||||
"end_time": 4.0,
|
||||
"text": "How I wonder what you are",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-02",
|
||||
"start_time": 4.0,
|
||||
"end_time": 6.0,
|
||||
"text": "Up above the world so high",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-03",
|
||||
"start_time": 6.0,
|
||||
"end_time": 8.0,
|
||||
"text": "Like a diamond in the sky",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-04",
|
||||
"start_time": 8.0,
|
||||
"end_time": 10.0,
|
||||
"text": "Twinkle, twinkle, little star",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-05",
|
||||
"start_time": 10.0,
|
||||
"end_time": 12.0,
|
||||
"text": "How I wonder what you are",
|
||||
"words": []
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,68 @@
|
||||
We walk in the room, yeah we own this place
|
||||
Anna hits the floor, watch her lead the way
|
||||
Grace brings the rhythm, dancing every day
|
||||
Oona on guitar, getting in the groove
|
||||
Savannah steps forward, watch her make her move
|
||||
Eirini singing, Frankie right there
|
||||
Voices together, filling the air
|
||||
Step aside now, nobody stands a chance
|
||||
|
||||
|
||||
Mr Moulton jokes, we try not to laugh
|
||||
But we’re ready now, we’ve done the graft
|
||||
|
||||
|
||||
We’re gonna win, win, win, hear the crowd go loud
|
||||
Singing all together, yeah we’re making you proud
|
||||
Clap your hands, feel the beat, come and take a glance
|
||||
We’re Year 5 strong, nobody stands a chance
|
||||
Oh oh, here we go
|
||||
Oh oh, steal the show
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
|
||||
|
||||
Mr Bunney listening, nodding to the beat
|
||||
Mr Woodward watching, tapping his feet
|
||||
We’ll impress him with every note we play
|
||||
Best performance of the whole school day
|
||||
Mrs Woodbridge smiling, watching from the side
|
||||
Thinking “Year 6 will be full of pride”
|
||||
We’re stepping up, this is our dance
|
||||
Better step back, nobody stands a chance
|
||||
|
||||
|
||||
If we feel nervous, we just smile
|
||||
We’ve been ready for a while
|
||||
|
||||
|
||||
We’re gonna win, win, win, hear the crowd go loud
|
||||
Singing all together, yeah we’re making you proud
|
||||
Clap your hands, feel the beat, come and take a glance
|
||||
We’re Year 5 strong, nobody stands a chance
|
||||
Oh oh, here we go
|
||||
Oh oh, steal the show
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
|
||||
|
||||
Savannah solo
|
||||
I step to the front, now it’s my time
|
||||
Hear my voice, watch me shine
|
||||
All eyes on me, feel that vibe
|
||||
This is my moment, I come alive
|
||||
|
||||
Strum it strong, feel the sound
|
||||
Let the music spin around
|
||||
Keep the rhythm, don’t slow down
|
||||
Now we bring it back around
|
||||
|
||||
|
||||
We’re gonna win, win, win, loud and clear
|
||||
Best group performance of the year
|
||||
Sing it out, give it all, take a chance
|
||||
We’re Year 5 stars, nobody stands a chance
|
||||
Oh oh, this is it
|
||||
Oh oh, we won’t quit
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"id": "year-5-stars-shake-it-off",
|
||||
"artist": "Taylor Swift",
|
||||
"title": "Year 5 Stars",
|
||||
"source_job_id": "2cb49a45",
|
||||
"difficulty": "hard",
|
||||
"input_style": "long substantive lines, name-heavy, mismatched syllable budget",
|
||||
"settings_to_test": [
|
||||
{
|
||||
"name": "default",
|
||||
"allow_reword": true,
|
||||
"allow_omit": true,
|
||||
"fixed_line_count": true,
|
||||
"strictness": "balanced"
|
||||
},
|
||||
{
|
||||
"name": "verbatim",
|
||||
"allow_reword": true,
|
||||
"allow_omit": true,
|
||||
"fixed_line_count": true,
|
||||
"strictness": "verbatim"
|
||||
},
|
||||
{
|
||||
"name": "strict",
|
||||
"allow_reword": true,
|
||||
"allow_omit": true,
|
||||
"fixed_line_count": true,
|
||||
"strictness": "strict"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
We walk in the room
|
||||
Yeah we own this place
|
||||
Anna hits the floor, mm- mm
|
||||
Watch her lead the way, mm- mm
|
||||
Grace brings the rhythm
|
||||
Dancing every day
|
||||
Oona on guitar, mm- mm
|
||||
Getting in the groove, mm- mm
|
||||
Eirini singing, Frankie right there
|
||||
Voices together, filling the air
|
||||
Nobody stands a chance
|
||||
'Cause the players gonna play, play, play, play, play
|
||||
And the haters gonna hate, hate, hate, hate, hate
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Heartbreakers gonna break, break, break, break, break
|
||||
And the fakers gonna fake, fake, fake, fake, fake
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Mr Moulton jokes
|
||||
We try not to laugh
|
||||
But we’re ready now, mm- mm
|
||||
We’ve done the graft, mm- mm
|
||||
We’re gonna win (hear the crowd go loud)
|
||||
Singing all together (yeah we’re making you proud)
|
||||
Clap your hands, feel the beat, mm- mm
|
||||
Come and take a glance, mm- mm
|
||||
We’re Year 5 strong
|
||||
Here we go, steal the show
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
'Cause the players gonna play, play, play, play, play
|
||||
And the haters gonna hate, hate, hate, hate, hate
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Heartbreakers gonna break, break, break, break, break
|
||||
And the fakers gonna fake, fake, fake, fake, fake
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
Hey, hey, hey
|
||||
Just think, while you've been gettin' down and out about the liars
|
||||
And the dirty, dirty cheats of the world
|
||||
You could've been gettin' down to this sick beat
|
||||
My ex- man brought his new girlfriend
|
||||
She's like, "Oh my God"
|
||||
But I'm just gonna shake
|
||||
And to the fella over there with the hella good hair
|
||||
Won't you come on over, baby? We can shake, shake, shake
|
||||
Yeah, oh
|
||||
'Cause the players gonna play, play, play, play, play
|
||||
And the haters gonna hate, hate, hate, hate, hate
|
||||
I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Heartbreakers gonna break, break, break, break, break
|
||||
And the fakers gonna fake, fake, fake, fake
|
||||
I'm just gonna shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
Shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
(You got to)
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
+4153
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,109 @@
|
||||
"""Markdown report generation for eval runs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from backend.eval.custom_lyrics.runner import FixtureRunResult
|
||||
from backend.eval.custom_lyrics.scorer import aggregate_corpus
|
||||
|
||||
|
||||
def write_run_reports(
|
||||
results: list[FixtureRunResult],
|
||||
out_dir: Path,
|
||||
baseline: Optional[dict] = None,
|
||||
) -> None:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "per_fixture").mkdir(exist_ok=True)
|
||||
|
||||
summary_lines = ["# Custom Lyrics Eval Run", ""]
|
||||
summary_lines.append(f"_Generated: {datetime.now(timezone.utc).isoformat()}_")
|
||||
summary_lines.append("")
|
||||
summary_lines.append("## Per-fixture summary")
|
||||
summary_lines.append("")
|
||||
summary_lines.append("| Fixture | Settings | pass@±2 | Δ | mean_Δ | iters | stop |")
|
||||
summary_lines.append("|---------|----------|---------|---|--------|-------|------|")
|
||||
for r in results:
|
||||
s = r.score
|
||||
delta_str = ""
|
||||
if baseline:
|
||||
prev = baseline.get(r.fixture_id, {}).get(r.settings_name, {})
|
||||
if "pct_pass_at_2" in prev:
|
||||
d = s.pct_pass_at_2 - prev["pct_pass_at_2"]
|
||||
delta_str = f"{d:+.2f}"
|
||||
summary_lines.append(
|
||||
f"| {r.fixture_id} | {r.settings_name} | {s.pct_pass_at_2:.2f} | "
|
||||
f"{delta_str} | {s.mean_delta:.2f} | {s.iterations_used} | {s.stop_reason} |"
|
||||
)
|
||||
|
||||
summary_lines.append("")
|
||||
corpus = aggregate_corpus([r.score for r in results])
|
||||
summary_lines.append("## Corpus aggregate")
|
||||
summary_lines.append("")
|
||||
summary_lines.append(f"- Macro pass@±2: {corpus.get('macro_pct_pass_at_2', 0):.2f}")
|
||||
summary_lines.append(f"- Macro pass@±1: {corpus.get('macro_pct_pass_at_1', 0):.2f}")
|
||||
summary_lines.append(f"- Macro pass@±0: {corpus.get('macro_pct_pass_at_0', 0):.2f}")
|
||||
summary_lines.append(f"- Total Gemini calls: {corpus.get('total_gemini_calls', 0)}")
|
||||
|
||||
(out_dir / "summary.md").write_text("\n".join(summary_lines))
|
||||
|
||||
for r in results:
|
||||
per_dir = out_dir / "per_fixture" / f"{r.fixture_id}__{r.settings_name}"
|
||||
per_dir.mkdir(parents=True, exist_ok=True)
|
||||
(per_dir / "output.json").write_text(json.dumps({
|
||||
"fixture_id": r.fixture_id,
|
||||
"settings_name": r.settings_name,
|
||||
"score": r.score.__dict__,
|
||||
"lines": r.output_lines,
|
||||
"line_metadata": r.line_metadata,
|
||||
}, indent=2))
|
||||
_write_per_fixture_md(per_dir, r)
|
||||
|
||||
|
||||
def _write_per_fixture_md(out_dir: Path, r: FixtureRunResult) -> None:
|
||||
lines = [
|
||||
f"# {r.fixture_id} — {r.settings_name}",
|
||||
"",
|
||||
f"Stop reason: **{r.score.stop_reason}** after {r.score.iterations_used} iterations.",
|
||||
f"Pass@±2: **{r.score.pct_pass_at_2:.0%}** ({sum(1 for v in r.line_metadata if v['min_delta']<=2)}/{r.score.line_count})",
|
||||
"",
|
||||
"| # | Original target | Candidate | Δ | Severity |",
|
||||
"|---|------------------|-----------|---|----------|",
|
||||
]
|
||||
for v in r.line_metadata:
|
||||
lines.append(
|
||||
f"| {v['line_index']+1} | {_escape(v['target_text'])} | "
|
||||
f"{_escape(v['candidate_text'])} | {v['min_delta']} | {v['severity']} |"
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"## Your rating",
|
||||
"",
|
||||
"Add your qualitative notes here:",
|
||||
"- [ ] Singable end-to-end",
|
||||
"- [ ] Names placed naturally",
|
||||
"- [ ] Stress patterns reasonable",
|
||||
"- Notes:",
|
||||
"",
|
||||
]
|
||||
(out_dir / "output.md").write_text("\n".join(lines))
|
||||
|
||||
|
||||
def _escape(s: str) -> str:
|
||||
return s.replace("|", "\\|").replace("\n", " ")
|
||||
|
||||
|
||||
def write_baseline(results: list[FixtureRunResult], path: Path) -> None:
|
||||
out: dict = {}
|
||||
for r in results:
|
||||
bucket = out.setdefault(r.fixture_id, {})
|
||||
bucket[r.settings_name] = {
|
||||
"pct_pass_at_2": r.score.pct_pass_at_2,
|
||||
"pct_pass_at_0": r.score.pct_pass_at_0,
|
||||
"mean_delta": r.score.mean_delta,
|
||||
"iterations_used": r.score.iterations_used,
|
||||
"captured_at": datetime.now(timezone.utc).date().isoformat(),
|
||||
}
|
||||
path.write_text(json.dumps(out, indent=2))
|
||||
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
@@ -0,0 +1,86 @@
|
||||
"""CLI: python -m backend.eval.custom_lyrics.run"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from backend.eval.custom_lyrics.cache import LlmCallCache
|
||||
from backend.eval.custom_lyrics.report import write_baseline, write_run_reports
|
||||
from backend.eval.custom_lyrics.runner import run_fixture
|
||||
from backend.services.custom_lyrics.service import CustomLyricsService
|
||||
|
||||
EVAL_ROOT = Path(__file__).parent
|
||||
FIXTURES_DIR = EVAL_ROOT / "fixtures"
|
||||
RESULTS_DIR = EVAL_ROOT / "results"
|
||||
CACHE_DIR = EVAL_ROOT / "cache"
|
||||
BASELINE_PATH = EVAL_ROOT / "baseline.json"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--fixtures", default="all", help="fixture id, or comma-separated, or 'all'")
|
||||
parser.add_argument("--settings", default=None, help="settings name from metadata.settings_to_test")
|
||||
parser.add_argument("--no-cache", action="store_true")
|
||||
parser.add_argument("--replay-only", action="store_true")
|
||||
parser.add_argument("--save-as-baseline", default=None,
|
||||
help="path to write baseline JSON (e.g., baseline-post.json)")
|
||||
args = parser.parse_args()
|
||||
|
||||
cache = LlmCallCache(
|
||||
CACHE_DIR,
|
||||
replay_only=args.replay_only,
|
||||
) if not args.no_cache else _NullCache()
|
||||
|
||||
fixture_dirs = _select_fixtures(args.fixtures)
|
||||
service = CustomLyricsService()
|
||||
|
||||
results = []
|
||||
for fdir in fixture_dirs:
|
||||
meta = json.loads((fdir / "metadata.json").read_text())
|
||||
candidate_settings = meta.get("settings_to_test", [{
|
||||
"name": "default",
|
||||
"allow_reword": True,
|
||||
"allow_omit": True,
|
||||
"fixed_line_count": True,
|
||||
"strictness": "balanced",
|
||||
}])
|
||||
for s in candidate_settings:
|
||||
if args.settings and s["name"] != args.settings:
|
||||
continue
|
||||
settings_dict = {k: v for k, v in s.items() if k != "name"}
|
||||
print(f"Running {fdir.name} / {s['name']}...", file=sys.stderr)
|
||||
results.append(run_fixture(
|
||||
fdir, s["name"], settings_dict,
|
||||
cache=cache, service=service,
|
||||
))
|
||||
|
||||
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H%M")
|
||||
out_dir = RESULTS_DIR / ts
|
||||
baseline = json.loads(BASELINE_PATH.read_text()) if BASELINE_PATH.exists() else None
|
||||
write_run_reports(results, out_dir, baseline=baseline)
|
||||
|
||||
if args.save_as_baseline:
|
||||
write_baseline(results, EVAL_ROOT / args.save_as_baseline)
|
||||
print(f"Baseline saved to {args.save_as_baseline}", file=sys.stderr)
|
||||
|
||||
print(f"\nReport: {out_dir / 'summary.md'}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def _select_fixtures(spec: str) -> list[Path]:
|
||||
if spec == "all":
|
||||
return sorted(p for p in FIXTURES_DIR.iterdir() if p.is_dir() and (p / "metadata.json").exists())
|
||||
ids = [s.strip() for s in spec.split(",")]
|
||||
return [FIXTURES_DIR / i for i in ids]
|
||||
|
||||
|
||||
class _NullCache:
|
||||
def get(self, *args, **kwargs): return None
|
||||
def set(self, *args, **kwargs): pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Eval runner: load fixture → call service (cached) → score → return result."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.eval.custom_lyrics.cache import LlmCallCache
|
||||
from backend.eval.custom_lyrics.scorer import FixtureScore, aggregate_fixture
|
||||
from backend.services.custom_lyrics.service import CustomLyricsService
|
||||
from backend.services.custom_lyrics.settings import (
|
||||
GenerationSettings,
|
||||
settings_from_dict,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FixtureRunResult:
|
||||
fixture_id: str
|
||||
settings_name: str
|
||||
score: FixtureScore
|
||||
output_lines: list[str]
|
||||
line_metadata: list[dict[str, Any]]
|
||||
fixture_dir: Path
|
||||
|
||||
|
||||
def load_fixture(fixture_dir: Path) -> dict:
|
||||
metadata = json.loads((fixture_dir / "metadata.json").read_text())
|
||||
metadata["original_lyrics"] = (fixture_dir / "original_lyrics.txt").read_text().strip().splitlines()
|
||||
metadata["original_segments"] = json.loads((fixture_dir / "original_segments.json").read_text())
|
||||
metadata["client_input"] = (fixture_dir / "client_input.txt").read_text()
|
||||
notes_path = fixture_dir / "notes.txt"
|
||||
metadata["notes"] = notes_path.read_text() if notes_path.exists() else None
|
||||
return metadata
|
||||
|
||||
|
||||
def run_fixture(
|
||||
fixture_dir: Path,
|
||||
settings_name: str,
|
||||
settings_dict: dict[str, Any],
|
||||
*,
|
||||
cache: LlmCallCache,
|
||||
service: CustomLyricsService,
|
||||
) -> FixtureRunResult:
|
||||
fixture = load_fixture(fixture_dir)
|
||||
settings = settings_from_dict(settings_dict)
|
||||
gemini_call_count = 0
|
||||
|
||||
real_call = service._call_gemini
|
||||
|
||||
def cached_call(*, system_prompt: str, user_prompt: str, pdf_bytes, settings: GenerationSettings):
|
||||
nonlocal gemini_call_count
|
||||
cached = cache.get(
|
||||
system_prompt, user_prompt,
|
||||
model=service.settings.custom_lyrics_model,
|
||||
settings_dict=settings.to_dict(),
|
||||
)
|
||||
if cached is not None:
|
||||
return cached
|
||||
gemini_call_count += 1
|
||||
result = real_call(
|
||||
system_prompt=system_prompt, user_prompt=user_prompt,
|
||||
pdf_bytes=pdf_bytes, settings=settings,
|
||||
)
|
||||
cache.set(
|
||||
system_prompt, user_prompt,
|
||||
model=service.settings.custom_lyrics_model,
|
||||
settings_dict=settings.to_dict(),
|
||||
response_lines=result,
|
||||
)
|
||||
return result
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=cached_call):
|
||||
result = service.generate(
|
||||
job_id=fixture["id"],
|
||||
target_lines=fixture["original_lyrics"],
|
||||
target_segments=fixture["original_segments"],
|
||||
artist=fixture.get("artist"),
|
||||
title=fixture.get("title"),
|
||||
custom_text=fixture["client_input"],
|
||||
file_bytes=None, file_mime=None, file_name=None,
|
||||
notes=fixture.get("notes"),
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
score = aggregate_fixture(
|
||||
fixture_id=fixture["id"],
|
||||
settings_name=settings_name,
|
||||
metadata=result.line_metadata,
|
||||
iterations_used=result.iterations_used,
|
||||
stop_reason=result.stop_reason.value,
|
||||
duration_ms=result.duration_ms,
|
||||
gemini_calls=gemini_call_count,
|
||||
line_count_match=not result.line_count_mismatch,
|
||||
)
|
||||
|
||||
return FixtureRunResult(
|
||||
fixture_id=fixture["id"],
|
||||
settings_name=settings_name,
|
||||
score=score,
|
||||
output_lines=result.lines,
|
||||
line_metadata=[{
|
||||
"line_index": v.line_index,
|
||||
"target_text": v.target_text,
|
||||
"candidate_text": v.candidate_text,
|
||||
"min_delta": v.min_delta,
|
||||
"severity": v.severity.value,
|
||||
} for v in result.line_metadata],
|
||||
fixture_dir=fixture_dir,
|
||||
)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Pure scoring functions for custom-lyrics eval."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
from backend.services.custom_lyrics.validator import LineValidation
|
||||
|
||||
|
||||
@dataclass
|
||||
class PerLineScore:
|
||||
line_index: int
|
||||
min_delta: int
|
||||
pass_at_0: bool
|
||||
pass_at_1: bool
|
||||
pass_at_2: bool
|
||||
pass_at_4: bool
|
||||
severity: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class FixtureScore:
|
||||
fixture_id: str
|
||||
settings_name: str
|
||||
line_count: int
|
||||
pct_pass_at_2: float
|
||||
pct_pass_at_1: float
|
||||
pct_pass_at_0: float
|
||||
pct_pass_at_4: float
|
||||
mean_delta: float
|
||||
median_delta: float
|
||||
max_delta: int
|
||||
iterations_used: int
|
||||
stop_reason: str
|
||||
duration_ms: int
|
||||
gemini_calls: int
|
||||
line_count_match: bool
|
||||
severity_breakdown: dict[str, int]
|
||||
|
||||
|
||||
def score_per_line(val: LineValidation) -> PerLineScore:
|
||||
return PerLineScore(
|
||||
line_index=val.line_index,
|
||||
min_delta=val.min_delta,
|
||||
pass_at_0=val.min_delta <= 0,
|
||||
pass_at_1=val.min_delta <= 1,
|
||||
pass_at_2=val.min_delta <= 2,
|
||||
pass_at_4=val.min_delta <= 4,
|
||||
severity=val.severity.value,
|
||||
)
|
||||
|
||||
|
||||
def aggregate_fixture(
|
||||
*,
|
||||
fixture_id: str,
|
||||
settings_name: str,
|
||||
metadata: list[LineValidation],
|
||||
iterations_used: int,
|
||||
stop_reason: str,
|
||||
duration_ms: int,
|
||||
gemini_calls: int,
|
||||
line_count_match: bool,
|
||||
) -> FixtureScore:
|
||||
n = len(metadata)
|
||||
if n == 0:
|
||||
return FixtureScore(
|
||||
fixture_id=fixture_id, settings_name=settings_name,
|
||||
line_count=0,
|
||||
pct_pass_at_2=0, pct_pass_at_1=0, pct_pass_at_0=0, pct_pass_at_4=0,
|
||||
mean_delta=0, median_delta=0, max_delta=0,
|
||||
iterations_used=iterations_used, stop_reason=stop_reason,
|
||||
duration_ms=duration_ms, gemini_calls=gemini_calls,
|
||||
line_count_match=line_count_match,
|
||||
severity_breakdown={"ok": 0, "minor": 0, "major": 0},
|
||||
)
|
||||
deltas = sorted(v.min_delta for v in metadata)
|
||||
severity_breakdown = {"ok": 0, "minor": 0, "major": 0}
|
||||
for v in metadata:
|
||||
severity_breakdown[v.severity.value] += 1
|
||||
return FixtureScore(
|
||||
fixture_id=fixture_id,
|
||||
settings_name=settings_name,
|
||||
line_count=n,
|
||||
pct_pass_at_2=sum(1 for d in deltas if d <= 2) / n,
|
||||
pct_pass_at_1=sum(1 for d in deltas if d <= 1) / n,
|
||||
pct_pass_at_0=sum(1 for d in deltas if d <= 0) / n,
|
||||
pct_pass_at_4=sum(1 for d in deltas if d <= 4) / n,
|
||||
mean_delta=sum(deltas) / n,
|
||||
median_delta=deltas[n // 2],
|
||||
max_delta=deltas[-1],
|
||||
iterations_used=iterations_used,
|
||||
stop_reason=stop_reason,
|
||||
duration_ms=duration_ms,
|
||||
gemini_calls=gemini_calls,
|
||||
line_count_match=line_count_match,
|
||||
severity_breakdown=severity_breakdown,
|
||||
)
|
||||
|
||||
|
||||
def aggregate_corpus(per_fixture: Iterable[FixtureScore]) -> dict:
|
||||
"""Macro-averaged corpus aggregate."""
|
||||
fixtures = list(per_fixture)
|
||||
if not fixtures:
|
||||
return {}
|
||||
return {
|
||||
"fixture_count": len(fixtures),
|
||||
"macro_pct_pass_at_2": sum(f.pct_pass_at_2 for f in fixtures) / len(fixtures),
|
||||
"macro_pct_pass_at_1": sum(f.pct_pass_at_1 for f in fixtures) / len(fixtures),
|
||||
"macro_pct_pass_at_0": sum(f.pct_pass_at_0 for f in fixtures) / len(fixtures),
|
||||
"macro_pct_pass_at_4": sum(f.pct_pass_at_4 for f in fixtures) / len(fixtures),
|
||||
"macro_mean_delta": sum(f.mean_delta for f in fixtures) / len(fixtures),
|
||||
"total_gemini_calls": sum(f.gemini_calls for f in fixtures),
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,38 @@
|
||||
"""Tests for the LLM-call disk cache."""
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from backend.eval.custom_lyrics.cache import LlmCallCache
|
||||
|
||||
|
||||
def test_miss_returns_none() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp))
|
||||
assert c.get("system", "user", model="m1", settings_dict={"x": 1}) is None
|
||||
|
||||
|
||||
def test_set_then_get_hits() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp))
|
||||
c.set("system", "user", model="m1", settings_dict={"x": 1}, response_lines=["a", "b"])
|
||||
assert c.get("system", "user", model="m1", settings_dict={"x": 1}) == ["a", "b"]
|
||||
|
||||
|
||||
def test_different_settings_different_keys() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp))
|
||||
c.set("system", "user", model="m1", settings_dict={"x": 1}, response_lines=["a"])
|
||||
assert c.get("system", "user", model="m1", settings_dict={"x": 2}) is None
|
||||
|
||||
|
||||
def test_replay_only_raises_on_miss() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp), replay_only=True)
|
||||
try:
|
||||
c.get("system", "user", model="m1", settings_dict={"x": 1})
|
||||
except RuntimeError as e:
|
||||
assert "cache miss" in str(e).lower()
|
||||
else:
|
||||
raise AssertionError("expected RuntimeError")
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Tests for eval scorer."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.eval.custom_lyrics.scorer import (
|
||||
PerLineScore,
|
||||
FixtureScore,
|
||||
score_per_line,
|
||||
aggregate_fixture,
|
||||
)
|
||||
from backend.services.custom_lyrics.validator import LineValidation, Severity
|
||||
|
||||
|
||||
def _line_val(idx: int, target: list[int], cand: list[int], passes: bool, severity: Severity, delta: int) -> LineValidation:
|
||||
return LineValidation(
|
||||
line_index=idx,
|
||||
target_text=f"t{idx}",
|
||||
candidate_text=f"c{idx}",
|
||||
target_syllables=target,
|
||||
candidate_syllables=cand,
|
||||
min_delta=delta,
|
||||
passes=passes,
|
||||
severity=severity,
|
||||
time_budget_seconds=1.0,
|
||||
)
|
||||
|
||||
|
||||
def test_score_per_line_pass_fail_thresholds() -> None:
|
||||
val = _line_val(0, [5, 5, 5, 5], [6, 6, 6, 6], passes=False, severity=Severity.MINOR, delta=1)
|
||||
s = score_per_line(val)
|
||||
assert s.pass_at_0 is False
|
||||
assert s.pass_at_1 is True
|
||||
assert s.pass_at_2 is True
|
||||
assert s.pass_at_4 is True
|
||||
assert s.min_delta == 1
|
||||
|
||||
|
||||
def test_score_per_line_major_violation() -> None:
|
||||
val = _line_val(0, [5, 5, 5, 5], [12, 12, 12, 12], passes=False, severity=Severity.MAJOR, delta=7)
|
||||
s = score_per_line(val)
|
||||
assert s.pass_at_0 is False
|
||||
assert s.pass_at_4 is False
|
||||
assert s.severity == "major"
|
||||
|
||||
|
||||
def test_aggregate_fixture_basic() -> None:
|
||||
metadata = [
|
||||
_line_val(0, [5]*4, [5]*4, passes=True, severity=Severity.OK, delta=0),
|
||||
_line_val(1, [5]*4, [6]*4, passes=False, severity=Severity.MINOR, delta=1),
|
||||
_line_val(2, [5]*4, [9]*4, passes=False, severity=Severity.MAJOR, delta=4),
|
||||
]
|
||||
fixture = aggregate_fixture(
|
||||
fixture_id="x",
|
||||
settings_name="default",
|
||||
metadata=metadata,
|
||||
iterations_used=2,
|
||||
stop_reason="max_iters_reached",
|
||||
duration_ms=1500,
|
||||
gemini_calls=3,
|
||||
line_count_match=True,
|
||||
)
|
||||
assert fixture.pct_pass_at_2 == pytest.approx(2 / 3)
|
||||
assert fixture.pct_pass_at_0 == pytest.approx(1 / 3)
|
||||
assert fixture.mean_delta == pytest.approx((0 + 1 + 4) / 3)
|
||||
assert fixture.max_delta == 4
|
||||
+28
-4
@@ -1,5 +1,8 @@
|
||||
"""
|
||||
FastAPI application entry point for karaoke generation backend.
|
||||
|
||||
(Trivial comment touch to trigger backend CI on ephemeral runners after
|
||||
the 2026-05-17 dispatcher e2 fix; safe to remove on next backend edit.)
|
||||
"""
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -7,7 +10,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -103,18 +106,37 @@ async def lifespan(app: FastAPI):
|
||||
yield
|
||||
|
||||
# Shutdown - wait for any active workers to complete before terminating
|
||||
# This prevents Cloud Run from killing workers mid-processing
|
||||
# This prevents Cloud Run from killing workers mid-processing.
|
||||
#
|
||||
# Cloud Run gen2 default termination grace period is 600s. We wait up to
|
||||
# 480s, leaving ~120s for the cleanup pass below to write Firestore state
|
||||
# before SIGKILL. Without that headroom, render jobs that miss the wait
|
||||
# would sit in `rendering_video` forever waiting for an operator.
|
||||
logger.info("Shutdown requested, checking for active workers...")
|
||||
if worker_registry.has_active_workers():
|
||||
active = worker_registry.get_active_workers()
|
||||
logger.info(f"Active workers found: {active}")
|
||||
logger.info("Waiting for workers to complete (timeout: 600s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=600) # 10 min max
|
||||
logger.info("Waiting for workers to complete (timeout: 480s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=480)
|
||||
if not completed:
|
||||
logger.error(
|
||||
"Shutdown timeout - some workers may not have completed cleanly. "
|
||||
f"Remaining workers: {worker_registry.get_active_workers()}"
|
||||
)
|
||||
|
||||
# Park any still-active render jobs so the auto-retry scheduler can
|
||||
# recover them. Safe to call unconditionally — it's a no-op if nothing
|
||||
# render-related is in flight.
|
||||
try:
|
||||
from backend.workers.render_video_worker import park_active_render_jobs_for_shutdown
|
||||
parked = park_active_render_jobs_for_shutdown()
|
||||
if parked:
|
||||
logger.warning(
|
||||
f"Parked {parked} in-flight render job(s) for auto-retry "
|
||||
f"due to shutdown"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"Render-job shutdown park failed: {exc!r}")
|
||||
else:
|
||||
logger.info("No active workers, proceeding with shutdown")
|
||||
|
||||
@@ -165,6 +187,8 @@ app.include_router(admin.router, prefix="/api") # Admin dashboard and managemen
|
||||
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
|
||||
app.include_router(push.router, prefix="/api") # Push notification subscription management
|
||||
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
|
||||
app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename parser
|
||||
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
|
||||
|
||||
+39
-5
@@ -45,6 +45,9 @@ class JobStatus(str, Enum):
|
||||
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
|
||||
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
|
||||
|
||||
# Optional: duration cost confirmation (BLOCKING) - confirm credits before heavy processing
|
||||
AWAITING_DURATION_CONFIRM = "awaiting_duration_confirm" # ⚠️ WAITING FOR USER - confirm duration-based cost
|
||||
|
||||
# Stage 2a: Audio separation (parallel track 1)
|
||||
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
|
||||
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
|
||||
@@ -68,6 +71,7 @@ class JobStatus(str, Enum):
|
||||
|
||||
# Stage 5.5: Render video with corrected lyrics (post-review)
|
||||
RENDERING_VIDEO = "rendering_video" # Using OutputGenerator to create with_vocals.mkv
|
||||
RENDER_PENDING_CAPACITY = "render_pending_capacity" # Waiting for GCE encoding capacity (auto-retry)
|
||||
|
||||
# Stage 6: Instrumental already selected (during combined review)
|
||||
# Note: AWAITING_INSTRUMENTAL_SELECTION kept for DB compatibility with historical jobs only
|
||||
@@ -106,16 +110,23 @@ STATE_TRANSITIONS = {
|
||||
# Audio search flow (for artist+title search mode)
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
|
||||
|
||||
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
|
||||
# Can also enter optional audio edit phase if requires_audio_edit flag is set
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
|
||||
|
||||
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
|
||||
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
|
||||
|
||||
# Duration cost confirmation (BLOCKING) - user confirms before heavy processing begins
|
||||
JobStatus.AWAITING_DURATION_CONFIRM: [
|
||||
JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING,
|
||||
JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT,
|
||||
JobStatus.FAILED, JobStatus.CANCELLED,
|
||||
],
|
||||
|
||||
# Audio separation flow
|
||||
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
|
||||
@@ -135,10 +146,27 @@ STATE_TRANSITIONS = {
|
||||
# AWAITING_REVIEW can go directly to REVIEW_COMPLETE (quick review) or to IN_REVIEW (editing)
|
||||
JobStatus.AWAITING_REVIEW: [JobStatus.IN_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_REVIEW: [JobStatus.REVIEW_COMPLETE, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
JobStatus.REVIEW_COMPLETE: [JobStatus.RENDERING_VIDEO, JobStatus.PREP_COMPLETE, JobStatus.FAILED], # PREP_COMPLETE for prep-only jobs
|
||||
JobStatus.REVIEW_COMPLETE: [
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.PREP_COMPLETE, # for prep-only jobs
|
||||
JobStatus.RENDER_PENDING_CAPACITY, # GCE capacity exhausted before render started
|
||||
JobStatus.FAILED,
|
||||
],
|
||||
|
||||
# Video rendering (post-review) - instrumental was already selected during combined review
|
||||
JobStatus.RENDERING_VIDEO: [JobStatus.INSTRUMENTAL_SELECTED, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
|
||||
# RENDER_PENDING_CAPACITY = parked when GCE encoding capacity is exhausted; auto-retried by scheduler.
|
||||
JobStatus.RENDERING_VIDEO: [
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.PREP_COMPLETE,
|
||||
JobStatus.RENDER_PENDING_CAPACITY,
|
||||
JobStatus.FAILED,
|
||||
],
|
||||
JobStatus.RENDER_PENDING_CAPACITY: [
|
||||
JobStatus.RENDERING_VIDEO, # auto-retry succeeded, picked up again
|
||||
JobStatus.REVIEW_COMPLETE, # admin / scheduler resets to re-trigger render
|
||||
JobStatus.FAILED, # exceeded max wait or operator gave up
|
||||
JobStatus.CANCELLED, # user cancelled while waiting
|
||||
],
|
||||
|
||||
# AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs in DB
|
||||
# New jobs never enter this state; they go directly to INSTRUMENTAL_SELECTED after render
|
||||
@@ -166,6 +194,7 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
JobStatus.AWAITING_REVIEW, # Retry from combined review
|
||||
JobStatus.RENDER_PENDING_CAPACITY, # Operator parks a stale-failed job for auto-retry
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
@@ -577,6 +606,11 @@ class JobCreate(BaseModel):
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Credit pricing: how many credits to charge for this job at creation time.
|
||||
# Search and upload jobs pass the default (1) and may top up later.
|
||||
# URL jobs with a known duration pass ceil(duration/600) credits.
|
||||
credits: int = 1
|
||||
|
||||
# Request metadata (set by API endpoint from request headers)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
|
||||
@@ -20,6 +20,10 @@ class URLSubmissionRequest(BaseModel):
|
||||
user_email: Optional[str] = None
|
||||
is_private: Optional[bool] = None # Private (non-published) track mode
|
||||
|
||||
# Duration-based pricing: supplied by the client from YouTube metadata
|
||||
duration_seconds: Optional[float] = None # Known audio duration in seconds
|
||||
acknowledged_credits: Optional[int] = None # Client's expected credit cost (anti-mismatch guard)
|
||||
|
||||
|
||||
class UploadSubmissionRequest(BaseModel):
|
||||
"""Request to submit a job from an uploaded file."""
|
||||
|
||||
@@ -191,6 +191,18 @@ class VerifyMagicLinkRequest(BaseModel):
|
||||
token: str
|
||||
|
||||
|
||||
class ResendFromTokenRequest(BaseModel):
|
||||
"""Request to resend a magic link based on a previously-issued (expired/used) token."""
|
||||
token: str
|
||||
|
||||
|
||||
class ResendFromTokenResponse(BaseModel):
|
||||
"""Response after attempting to resend a magic link from a known token."""
|
||||
status: str # "sent" | "no_token"
|
||||
masked_email: Optional[str] = None
|
||||
message: str
|
||||
|
||||
|
||||
class VerifyMagicLinkResponse(BaseModel):
|
||||
"""Response after verifying magic link."""
|
||||
status: str
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Operational and maintenance scripts for the karaoke-gen backend."""
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill original input audio into past jobs' Dropbox folders.
|
||||
|
||||
Restores files like ``<artist> - <title> (flacfetch).flac`` / ``(uploaded).mp3`` to
|
||||
the organised Dropbox track folders for completed jobs that predate the pipeline fix
|
||||
(the distributed pipeline stopped copying the source audio into the output folder).
|
||||
|
||||
Dry-run by default; pass ``--live`` to actually upload. NOTE: this cannot backfill the
|
||||
screen ``.mov`` files — those require re-encoding the job.
|
||||
|
||||
Usage:
|
||||
python -m backend.scripts.backfill_original_audio # dry-run, since 2026-03-01
|
||||
python -m backend.scripts.backfill_original_audio --live # actually upload
|
||||
python -m backend.scripts.backfill_original_audio --since 2026-02-01 --limit 50 -v
|
||||
"""
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.original_audio import (
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("backfill_original_audio")
|
||||
|
||||
# The regression window: screen/audio files stopped reaching Dropbox once the
|
||||
# distributed pipeline took over (last known-good folder ~Feb; PR #647/#650 Mar 31).
|
||||
DEFAULT_SINCE = "2026-03-01"
|
||||
|
||||
|
||||
def plan_job_backfill(job, *, storage, dropbox):
|
||||
"""Decide what to do for one job (existence checks only — no uploads).
|
||||
|
||||
Returns ``(action, detail)`` where action is one of:
|
||||
- ``"skip-no-dropbox"`` — job was never uploaded to Dropbox
|
||||
- ``"skip-no-audio-record"`` — no original-audio reference on the job
|
||||
- ``"skip-audio-missing-gcs"`` — original audio no longer in GCS (detail=gcs_path)
|
||||
- ``"skip-folder-missing"`` — the track's Dropbox folder doesn't exist (detail=folder)
|
||||
- ``"skip-already-present"`` — file already in the Dropbox folder (detail=remote_path)
|
||||
- ``"upload"`` — detail={gcs_path, remote_path, filename}
|
||||
"""
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
state = getattr(job, "state_data", None) or {}
|
||||
brand_code = state.get("brand_code")
|
||||
# Use the EFFECTIVE dropbox path — private (NOMADNP) tracks upload to the
|
||||
# NonPublished path, not the job's stored (public) dropbox_path. This mirrors
|
||||
# what the orchestrator does at distribution time.
|
||||
dropbox_path = get_effective_distribution_for_job(job).dropbox_path
|
||||
if not brand_code or not dropbox_path:
|
||||
return ("skip-no-dropbox", None)
|
||||
|
||||
gcs_path = original_audio_gcs_path(job)
|
||||
if not gcs_path:
|
||||
return ("skip-no-audio-record", None)
|
||||
if not storage.file_exists(gcs_path):
|
||||
return ("skip-audio-missing-gcs", gcs_path)
|
||||
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
filename = original_audio_output_filename(job, base_name)
|
||||
folder = f"{dropbox_path.rstrip('/')}/{brand_code} - {base_name}"
|
||||
remote_path = f"{folder}/{filename}"
|
||||
|
||||
# Only backfill into a track folder that already exists — never create a new
|
||||
# folder (guards against drifted brand/artist/title naming producing an orphan).
|
||||
if not dropbox.file_exists(folder):
|
||||
return ("skip-folder-missing", folder)
|
||||
|
||||
if dropbox.file_exists(remote_path):
|
||||
return ("skip-already-present", remote_path)
|
||||
|
||||
return ("upload", {"gcs_path": gcs_path, "remote_path": remote_path, "filename": filename})
|
||||
|
||||
|
||||
def _execute_upload(detail, *, storage, dropbox):
|
||||
"""Download the original audio from GCS and upload it to the Dropbox folder."""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
local = os.path.join(td, detail["filename"])
|
||||
storage.download_file(detail["gcs_path"], local)
|
||||
dropbox.upload_file(local, detail["remote_path"])
|
||||
|
||||
|
||||
def run_backfill(*, since, until=None, limit, environment, live):
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
jm = JobManager()
|
||||
storage = StorageService()
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
logger.error("Dropbox not configured; aborting.")
|
||||
return
|
||||
|
||||
# NOTE: created_at is stored as an ISO string in Firestore, so server-side
|
||||
# created_after/created_before datetime filters match nothing. We fetch the most
|
||||
# recent completed jobs (ordered by created_at desc) and filter dates in Python.
|
||||
# `limit` therefore bounds how far back we look — set it high enough to cover the
|
||||
# window since `since`.
|
||||
jobs = jm.list_jobs(status=JobStatus.COMPLETE, limit=limit)
|
||||
|
||||
def _created(j):
|
||||
c = getattr(j, "created_at", None)
|
||||
if c is None:
|
||||
return None
|
||||
return c.replace(tzinfo=None) if getattr(c, "tzinfo", None) else c
|
||||
|
||||
since_naive = since.replace(tzinfo=None)
|
||||
until_naive = until.replace(tzinfo=None) if until else None
|
||||
|
||||
def _in_window(j):
|
||||
c = _created(j)
|
||||
if c is None:
|
||||
return False
|
||||
if c < since_naive:
|
||||
return False
|
||||
if until_naive and c >= until_naive:
|
||||
return False
|
||||
return True
|
||||
|
||||
jobs = [j for j in jobs if _in_window(j)]
|
||||
|
||||
if environment:
|
||||
def _env(j):
|
||||
rm = getattr(j, "request_metadata", None)
|
||||
if rm is None:
|
||||
return None
|
||||
return rm.get("environment") if isinstance(rm, dict) else getattr(rm, "environment", None)
|
||||
jobs = [j for j in jobs if _env(j) == environment]
|
||||
|
||||
logger.info(
|
||||
"Considering %d completed jobs since %s (env=%s, fetch limit=%d)",
|
||||
len(jobs), since.date(), environment or "all", limit,
|
||||
)
|
||||
|
||||
tally = {}
|
||||
for job in jobs:
|
||||
try:
|
||||
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
|
||||
except Exception as e:
|
||||
# A transient GCS/Dropbox error while planning shouldn't abort the whole run.
|
||||
logger.error(" planning failed for %s: %s", getattr(job, "job_id", "?"), e)
|
||||
tally["error"] = tally.get("error", 0) + 1
|
||||
continue
|
||||
tally[action] = tally.get(action, 0) + 1
|
||||
if action == "upload":
|
||||
verb = "uploading" if live else "[DRY-RUN] would upload"
|
||||
logger.info("%s: %s -> %s", verb, job.job_id, detail["remote_path"])
|
||||
if live:
|
||||
try:
|
||||
_execute_upload(detail, storage=storage, dropbox=dropbox)
|
||||
except Exception as e:
|
||||
logger.error(" upload failed for %s: %s", job.job_id, e)
|
||||
tally["upload"] -= 1
|
||||
tally["error"] = tally.get("error", 0) + 1
|
||||
else:
|
||||
logger.debug("%s: %s (%s)", action, job.job_id, detail)
|
||||
|
||||
logger.info("=== Backfill summary (%s) ===", "LIVE" if live else "DRY-RUN")
|
||||
for k in sorted(tally):
|
||||
logger.info(" %-24s %d", k, tally[k])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--since", default=DEFAULT_SINCE, help="Only jobs created on/after YYYY-MM-DD")
|
||||
parser.add_argument("--until", default=None, help="Only jobs created before YYYY-MM-DD")
|
||||
parser.add_argument("--limit", type=int, default=5000,
|
||||
help="Max completed jobs to fetch (most-recent first). Bounds how far "
|
||||
"back the date window can reach.")
|
||||
parser.add_argument("--env", default=None, dest="environment",
|
||||
help="Filter to a request environment (e.g. production). Default: all "
|
||||
"(test jobs are skipped anyway — no brand code / Dropbox folder).")
|
||||
parser.add_argument("--live", action="store_true", help="Actually upload (default: dry-run)")
|
||||
parser.add_argument("-v", "--verbose", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(message)s",
|
||||
)
|
||||
|
||||
since = datetime.strptime(args.since, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
until = (
|
||||
datetime.strptime(args.until, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
if args.until else None
|
||||
)
|
||||
run_backfill(since=since, until=until, limit=args.limit, environment=args.environment, live=args.live)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -106,6 +106,54 @@ class AudioEditService:
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
# Fades must be anchored to a clip edge — FFmpeg's afade silences audio outside
|
||||
# the ramp, so a mid-clip fade would unexpectedly mute the rest of the track.
|
||||
# The tolerance matches the editor UI's edge gating (start < 1s / end within 1s).
|
||||
FADE_ANCHOR_TOLERANCE_SECONDS = 1.0
|
||||
|
||||
def fade_region(
|
||||
self, input_path: str, start: float, end: float, direction: str, output_path: str
|
||||
) -> AudioMetadata:
|
||||
"""Apply a fade in or out anchored to a clip edge (preserves duration).
|
||||
|
||||
direction='in' ramps the volume from silence to full over [0, end];
|
||||
direction='out' ramps from full to silence over [start, clip_end].
|
||||
|
||||
Anchoring is enforced server-side (not just in the UI) because FFmpeg's
|
||||
afade filter silences audio outside the ramp window: a fade-in is forced
|
||||
to begin at the clip start, and a fade-out to finish at the clip end, so a
|
||||
non-anchored request can never silently mute the rest of the track.
|
||||
"""
|
||||
if direction not in ("in", "out"):
|
||||
raise ValueError(f"Invalid fade direction: {direction}")
|
||||
if start < 0 or end <= start:
|
||||
raise ValueError(f"Invalid fade region: start={start}, end={end}")
|
||||
|
||||
total = self.get_metadata(input_path).duration_seconds
|
||||
tol = self.FADE_ANCHOR_TOLERANCE_SECONDS
|
||||
if end > total + tol:
|
||||
raise ValueError(f"Fade region exceeds clip duration ({end} > {total})")
|
||||
|
||||
if direction == "in":
|
||||
if start > tol:
|
||||
raise ValueError(f"fade_in must be anchored to the clip start (got start={start})")
|
||||
fade_start, fade_duration = 0.0, end
|
||||
else:
|
||||
if end < total - tol:
|
||||
raise ValueError(f"fade_out must be anchored to the clip end (got end={end}, duration={total})")
|
||||
fade_start, fade_duration = start, total - start
|
||||
|
||||
if fade_duration <= 0:
|
||||
raise ValueError(f"Fade region must have positive duration (got {fade_duration})")
|
||||
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-af", f"afade=t={direction}:st={fade_start}:d={fade_duration}",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
|
||||
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
|
||||
if position == "start":
|
||||
@@ -156,6 +204,11 @@ class AudioEditService:
|
||||
metadata = self.mute_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], local_output
|
||||
)
|
||||
elif operation in ("fade_in", "fade_out"):
|
||||
direction = "in" if operation == "fade_in" else "out"
|
||||
metadata = self.fade_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], direction, local_output
|
||||
)
|
||||
elif operation in ("join_start", "join_end"):
|
||||
# Download the upload file
|
||||
upload_gcs_path = params["upload_gcs_path"]
|
||||
|
||||
@@ -18,7 +18,8 @@ downloads since Cloud Run doesn't support BitTorrent peer connections.
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Optional
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import nest_asyncio
|
||||
|
||||
@@ -47,6 +48,151 @@ AudioSearchError = AudioFetcherError
|
||||
AudioDownloadResult = AudioFetchResult
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bulk Mode: tier-1 auto-selection.
|
||||
#
|
||||
# This is a faithful port of the frontend confidence-tier logic in
|
||||
# frontend/lib/audio-search-utils.ts (categorizeResult / getBestResult /
|
||||
# checkFilenameMismatch / getSearchConfidence). It operates on the dicts
|
||||
# produced by AudioSearchResult.to_dict() (keys: is_lossless, quality_data,
|
||||
# seeders, provider, release_type, target_file, title, index).
|
||||
#
|
||||
# MAINTENANCE SEAM: if the frontend tier rule changes, update both. The
|
||||
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_BEST_RESULT_PRIORITY = [
|
||||
"BEST CHOICE",
|
||||
"STUDIO ALBUMS",
|
||||
"HI-RES 24-BIT",
|
||||
"SINGLES",
|
||||
"COMPILATIONS",
|
||||
"SPOTIFY",
|
||||
"YOUTUBE",
|
||||
"OTHER",
|
||||
]
|
||||
|
||||
|
||||
def _categorize_result(result: Dict[str, Any]) -> str:
|
||||
"""Port of categorizeResult() from audio-search-utils.ts."""
|
||||
is_lossless = result.get("is_lossless") is True
|
||||
quality_data = result.get("quality_data") or {}
|
||||
is_24bit = quality_data.get("bit_depth") == 24
|
||||
seeders = result.get("seeders") or 0
|
||||
provider = (result.get("provider") or "").lower()
|
||||
release_type = (result.get("release_type") or "").lower()
|
||||
media = (quality_data.get("media") or "").lower()
|
||||
|
||||
if provider == "spotify":
|
||||
return "SPOTIFY"
|
||||
if provider == "youtube" or not is_lossless:
|
||||
return "YOUTUBE"
|
||||
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
|
||||
if is_lossless and media == "vinyl":
|
||||
return "VINYL RIPS"
|
||||
if is_lossless and seeders >= 50:
|
||||
return "BEST CHOICE"
|
||||
if is_lossless and is_24bit:
|
||||
return "HI-RES 24-BIT"
|
||||
if is_lossless and (
|
||||
release_type == "live album" or release_type == "bootleg" or "live" in release_type
|
||||
):
|
||||
return "LIVE VERSIONS"
|
||||
if is_lossless and release_type in ("compilation", "soundtrack", "anthology"):
|
||||
return "COMPILATIONS"
|
||||
if is_lossless and release_type in ("single", "ep"):
|
||||
return "SINGLES"
|
||||
if is_lossless and (release_type == "album" or not release_type):
|
||||
return "STUDIO ALBUMS"
|
||||
return "OTHER"
|
||||
|
||||
|
||||
def _get_best_result(results: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""Port of getBestResult() — highest-priority category, skipping vinyl."""
|
||||
if not results:
|
||||
return None
|
||||
best: Optional[Dict[str, Any]] = None
|
||||
best_priority = float("inf")
|
||||
for result in results:
|
||||
category = _categorize_result(result)
|
||||
if category == "VINYL RIPS":
|
||||
continue
|
||||
try:
|
||||
priority = _BEST_RESULT_PRIORITY.index(category)
|
||||
except ValueError:
|
||||
priority = float("inf")
|
||||
if priority < best_priority:
|
||||
best = result
|
||||
best_priority = priority
|
||||
elif priority == best_priority and best is not None:
|
||||
if (result.get("seeders") or 0) > (best.get("seeders") or 0):
|
||||
best = result
|
||||
return best if best is not None else results[0]
|
||||
|
||||
|
||||
def _check_filename_mismatch(search_title: str, result: Dict[str, Any]) -> bool:
|
||||
"""Port of checkFilenameMismatch() — True if the file is clearly another track."""
|
||||
if len(search_title) < 3:
|
||||
return False
|
||||
|
||||
target_file = result.get("target_file")
|
||||
if target_file:
|
||||
raw_filename = target_file.split("/")[-1] or target_file
|
||||
without_ext = re.sub(r"\.[^.]+$", "", raw_filename)
|
||||
filename = re.sub(r"^\d{1,3}\s*[-.\s]\s*", "", without_ext)
|
||||
elif result.get("title"):
|
||||
filename = result["title"]
|
||||
else:
|
||||
return False
|
||||
|
||||
def normalize(s: str) -> str:
|
||||
s = s.lower()
|
||||
s = re.sub(r"[_\-.]+", " ", s)
|
||||
s = re.sub(r"[^a-z0-9\s]", "", s)
|
||||
s = re.sub(r"\s+", " ", s)
|
||||
return s.strip()
|
||||
|
||||
norm_title = normalize(search_title)
|
||||
norm_file = normalize(filename)
|
||||
if not norm_file or not norm_title:
|
||||
return False
|
||||
|
||||
# Stricter than the frontend's substring check (intentional — for the bulk
|
||||
# AUTO-select path we'd rather park an uncertain match than auto-pick the
|
||||
# wrong track). A match requires every title word to appear as a whole word
|
||||
# in the filename, so "One" no longer matches "Someone".
|
||||
title_tokens = [t for t in norm_title.split() if t]
|
||||
file_tokens = set(norm_file.split())
|
||||
if not title_tokens:
|
||||
return False
|
||||
matches = all(tok in file_tokens for tok in title_tokens)
|
||||
return not matches
|
||||
|
||||
|
||||
def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -> Optional[int]:
|
||||
"""Return the index to auto-select, or None if no confident lossless pick.
|
||||
|
||||
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
|
||||
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
|
||||
must match ``search_title`` (the song the user searched for). Otherwise we
|
||||
defer to human selection.
|
||||
"""
|
||||
if not results:
|
||||
return None
|
||||
# Require a usable title before auto-selecting: a blank/too-short title can't
|
||||
# be verified against the filename, so defer to human selection.
|
||||
if len((search_title or "").strip()) < 3:
|
||||
return None
|
||||
best = _get_best_result(results)
|
||||
if best is None:
|
||||
return None
|
||||
if _categorize_result(best) != "BEST CHOICE":
|
||||
return None
|
||||
if _check_filename_mismatch(search_title, best):
|
||||
return None
|
||||
return best.get("index")
|
||||
|
||||
|
||||
class AudioSearchService:
|
||||
"""
|
||||
Service for searching and downloading audio files.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless suggestion generation: the client posts its current working
|
||||
segments, the service returns word-level suggestions (replace / delete /
|
||||
insert_after) referencing word ids. Nothing is applied server-side — the
|
||||
reviewer accepts or rejects each suggestion in the UI.
|
||||
"""
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AutoCorrectService",
|
||||
"AutoCorrectServiceError",
|
||||
"get_auto_correct_service",
|
||||
]
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Token pricing for auto-correct model calls.
|
||||
|
||||
Used to turn the per-call token usage we capture from each provider into an
|
||||
estimated USD cost, for both the production usage logs and the offline
|
||||
measurement script (``scripts/measure_autocorrect_cost.py``).
|
||||
|
||||
Prices are USD per 1,000,000 tokens.
|
||||
|
||||
- **Anthropic** prices are authoritative (published Claude API pricing).
|
||||
``output`` is the billed output rate, which already includes adaptive
|
||||
*thinking* tokens — they are billed as output and are not separable from
|
||||
the final answer in the Anthropic usage object.
|
||||
- **Gemini** prices are a best-known ESTIMATE for the Vertex preview tier and
|
||||
are clearly marked below. Verify against current Vertex pricing before
|
||||
relying on the dollar figure. Gemini thinking tokens ARE separable
|
||||
(``thoughts_token_count``) and are billed at the output rate, so we fold
|
||||
them into the output total.
|
||||
|
||||
The raw token counts are always logged alongside the dollar figure, so the
|
||||
cost here is a derived convenience — if a rate is stale, recompute from the
|
||||
logged tokens rather than trusting the historical USD value.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
class TokenUsage(TypedDict):
|
||||
"""Normalized, provider-agnostic usage for one model call.
|
||||
|
||||
``output_tokens`` is the total billed output (final answer + thinking).
|
||||
``thinking_tokens`` is informational only (None when the provider does
|
||||
not report it separately) — it is already counted inside ``output_tokens``.
|
||||
"""
|
||||
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
cache_read_tokens: int
|
||||
thinking_tokens: Optional[int]
|
||||
|
||||
|
||||
class _Rate(TypedDict):
|
||||
input: float
|
||||
output: float
|
||||
cache_read: float
|
||||
|
||||
|
||||
# USD per 1,000,000 tokens.
|
||||
MODEL_PRICING: dict[str, _Rate] = {
|
||||
# --- Anthropic (authoritative) ---
|
||||
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
|
||||
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
|
||||
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
|
||||
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
|
||||
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
|
||||
# tier; confirm against current Google pricing before trusting USD) ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
}
|
||||
|
||||
|
||||
def get_rate(model: str) -> Optional[_Rate]:
|
||||
"""Return the rate card for ``model``, or None if we have no pricing.
|
||||
|
||||
Falls back to a prefix match on the model family (e.g. a dated
|
||||
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
|
||||
so a minor model-id change doesn't silently drop cost tracking.
|
||||
"""
|
||||
if model in MODEL_PRICING:
|
||||
return MODEL_PRICING[model]
|
||||
for known, rate in MODEL_PRICING.items():
|
||||
if model.startswith(known):
|
||||
return rate
|
||||
return None
|
||||
|
||||
|
||||
def estimate_cost_usd(model: str, usage: Optional[TokenUsage]) -> Optional[float]:
|
||||
"""Estimate the USD cost of one model call from its token usage.
|
||||
|
||||
Returns None when usage is unavailable or the model has no known pricing,
|
||||
so callers can distinguish "free/zero" from "unknown".
|
||||
"""
|
||||
if not usage:
|
||||
return None
|
||||
rate = get_rate(model)
|
||||
if rate is None:
|
||||
return None
|
||||
input_tokens = usage.get("input_tokens") or 0
|
||||
output_tokens = usage.get("output_tokens") or 0
|
||||
cache_read = usage.get("cache_read_tokens") or 0
|
||||
return (
|
||||
input_tokens * rate["input"]
|
||||
+ output_tokens * rate["output"]
|
||||
+ cache_read * rate["cache_read"]
|
||||
) / 1_000_000.0
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Prompt construction for AI auto-correction suggestions.
|
||||
|
||||
Kept in sync with the offline eval harness
|
||||
(lyrics-alignment-eval-dataset/auto-correct-eval/harness.py) — changes here
|
||||
should be re-scored against the 30-job ground-truth dataset.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"suggestions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"op": {
|
||||
"type": "string",
|
||||
"enum": ["replace", "delete", "insert_after"],
|
||||
},
|
||||
"start_idx": {"type": "integer"},
|
||||
"end_idx": {"type": "integer"},
|
||||
"new_text": {"type": "string"},
|
||||
"reason": {"type": "string"},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
],
|
||||
},
|
||||
"confidence": {"type": "number"},
|
||||
},
|
||||
"required": [
|
||||
"op",
|
||||
"start_idx",
|
||||
"end_idx",
|
||||
"new_text",
|
||||
"reason",
|
||||
"category",
|
||||
"confidence",
|
||||
],
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["suggestions"],
|
||||
}
|
||||
|
||||
_BASE_SYSTEM_PROMPT = """\
|
||||
You are an expert lyrics transcription reviewer for a karaoke video company. \
|
||||
You are given an automatic speech transcription of a song's vocals (already \
|
||||
segmented into lines, each word tagged with a numeric index) plus lyrics for \
|
||||
the same song from internet sources. Internet sources are usually (not always) \
|
||||
closer to the true lyrics, but lack the transcription's timing and line layout.
|
||||
|
||||
Propose word-level corrections to the TRANSCRIPTION so its words match what is \
|
||||
actually sung. A human reviewer who has listened to the song will accept or \
|
||||
reject each suggestion individually, so precision matters far more than \
|
||||
recall: only suggest a change when you are confident a careful human reviewer \
|
||||
would make it. If reference sources disagree and you have no other evidence, \
|
||||
make no suggestion.
|
||||
|
||||
Guidelines:
|
||||
- Transcription errors are usually sound-alike mishearings: the wrong words \
|
||||
sound similar to the true lyric (e.g. "glory" vs "chlorine", "ladder" vs \
|
||||
"matter"). Prefer corrections that are phonetically plausible.
|
||||
- The same mishearing often repeats in every chorus; correct every occurrence.
|
||||
- Keep the transcription's line structure. NEVER suggest timing changes.
|
||||
- Match the casing and punctuation style of the surrounding transcription.
|
||||
- Do not censor or bowdlerise explicit lyrics.
|
||||
- Do not rewrite lines wholesale unless the transcription is clearly garbled \
|
||||
and a reference line is unambiguously what is sung at that point.
|
||||
- new_text may contain multiple words, or differ in word count from the span \
|
||||
it replaces.
|
||||
"""
|
||||
|
||||
_ADLIB_ALLOWED = """\
|
||||
- Parenthesised backing vocals / adlibs that the transcription contains but \
|
||||
references omit may be real (references often drop them). Only suggest \
|
||||
deleting them when they look like transcription hallucinations or the \
|
||||
references make clear they are not sung lead lines; use category \
|
||||
"adlib_removal" and lower confidence.
|
||||
"""
|
||||
|
||||
_ADLIB_FORBIDDEN = """\
|
||||
- NEVER suggest deleting backing vocals or adlibs solely because the \
|
||||
references omit them; references often drop adlibs that are really sung.
|
||||
"""
|
||||
|
||||
_INSERTIONS_FORBIDDEN = """\
|
||||
- NEVER use the "insert_after" operation; only suggest "replace" and \
|
||||
"delete" operations.
|
||||
"""
|
||||
|
||||
_OUTPUT_SPEC = """\
|
||||
Output JSON only, matching this shape exactly:
|
||||
{"suggestions": [{"op": "replace"|"delete"|"insert_after",
|
||||
"start_idx": <int>, "end_idx": <int>,
|
||||
"new_text": "<replacement, empty for delete>",
|
||||
"reason": "<short justification>",
|
||||
"category": "mishearing"|"grammar"|"adlib_removal"|"repeated_chorus_fix"|"formatting"|"other",
|
||||
"confidence": <0.0-1.0>}]}
|
||||
start_idx and end_idx are inclusive word indices. For "insert_after", \
|
||||
start_idx == end_idx == the index of the word the new text should follow. \
|
||||
If nothing needs changing, return {"suggestions": []}.
|
||||
"""
|
||||
|
||||
|
||||
def build_system_prompt(settings: AutoCorrectSettings) -> str:
|
||||
parts = [_BASE_SYSTEM_PROMPT]
|
||||
parts.append(_ADLIB_ALLOWED if settings.suggest_adlib_removal else _ADLIB_FORBIDDEN)
|
||||
if not settings.allow_insertions:
|
||||
parts.append(_INSERTIONS_FORBIDDEN)
|
||||
parts.append(_OUTPUT_SPEC)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def build_user_prompt(
|
||||
*,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: str | None,
|
||||
title: str | None,
|
||||
) -> str:
|
||||
"""Render segments (with global word indices) + reference sources."""
|
||||
lines = [f"ARTIST: {artist or 'unknown'}", f"TITLE: {title or 'unknown'}", "", "TRANSCRIPTION:"]
|
||||
idx = 0
|
||||
for li, seg in enumerate(segments):
|
||||
toks = []
|
||||
for w in seg.get("words") or []:
|
||||
toks.append(f"{idx}:{w.get('text', '')}")
|
||||
idx += 1
|
||||
lines.append(f"[L{li:03d}] " + " ".join(toks))
|
||||
for source, ref in (reference_lyrics or {}).items():
|
||||
lines.append("")
|
||||
lines.append(f"REFERENCE LYRICS ({source}):")
|
||||
for seg in ref.get("segments") or []:
|
||||
lines.append(seg.get("text", ""))
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,717 @@
|
||||
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
|
||||
from backend.services.auto_correct.prompts import (
|
||||
RESPONSE_SCHEMA,
|
||||
build_system_prompt,
|
||||
build_user_prompt,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_OPS = {"replace", "delete", "insert_after"}
|
||||
VALID_CATEGORIES = {
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
}
|
||||
|
||||
|
||||
class AutoCorrectServiceError(Exception):
|
||||
def __init__(
|
||||
self, message: str, *, status_code: int = 400, retryable: bool = False
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
# True for transient provider conditions (rate limits, overload) the
|
||||
# caller may safely retry; drives backoff in _call_model.
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
# Retry knobs for a single model call. Vertex 429 RESOURCE_EXHAUSTED is a
|
||||
# recurring, transient condition; a short app-level backoff lets quota recover
|
||||
# where the SDK's fast internal retry cannot. Kept small so a request never
|
||||
# stalls the review UI for long. Parsed defensively: a malformed env override
|
||||
# clamps to a safe value with a warning rather than crashing the backend at
|
||||
# import or breaking the retry loop.
|
||||
def _env_number(name: str, default: float, *, minimum: float, is_int: bool) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
val: float = int(raw) if is_int else float(raw)
|
||||
except ValueError:
|
||||
logger.warning("invalid %s=%r; using default %s", name, raw, default)
|
||||
return default
|
||||
import math as _math
|
||||
|
||||
if not _math.isfinite(val) or val < minimum:
|
||||
logger.warning(
|
||||
"%s=%s out of range (min %s); clamping to %s", name, val, minimum, minimum
|
||||
)
|
||||
return minimum
|
||||
return val
|
||||
|
||||
|
||||
_MODEL_CALL_MAX_ATTEMPTS = int(
|
||||
_env_number("AUTO_CORRECT_MODEL_MAX_ATTEMPTS", 3, minimum=1, is_int=True)
|
||||
)
|
||||
_MODEL_CALL_BACKOFF_SECONDS = float(
|
||||
_env_number("AUTO_CORRECT_MODEL_BACKOFF_SECONDS", 2.0, minimum=0.0, is_int=False)
|
||||
)
|
||||
|
||||
|
||||
def _is_transient_model_error(exc: BaseException) -> bool:
|
||||
"""True when a provider exception is a retryable rate-limit/overload.
|
||||
|
||||
Matches both structured status codes (google-genai ClientError/ServerError
|
||||
expose ``code``; Anthropic errors expose ``status_code``) and, as a
|
||||
fallback, the textual markers Vertex/Anthropic use — so detection survives
|
||||
SDK exception-class churn.
|
||||
"""
|
||||
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
|
||||
if isinstance(code, int) and code in {429, 500, 502, 503, 529}:
|
||||
return True
|
||||
text = str(exc).upper()
|
||||
markers = ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "OVERLOADED", "429", "503", "529")
|
||||
return any(m in text for m in markers)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Suggestion:
|
||||
id: str
|
||||
op: str # replace | delete | insert_after
|
||||
word_ids: list[str] # targeted words (replace/delete); [anchor] for insert_after
|
||||
segment_ids: list[str] # segments containing the targeted words
|
||||
original_text: str # current text of the targeted span ("" for insert_after)
|
||||
new_text: str # replacement text ("" for delete)
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
# Multi-model compare metadata. In single-model mode models has one
|
||||
# entry and consensus == total_models == 1.
|
||||
models: list[str] = field(default_factory=list)
|
||||
consensus: int = 1
|
||||
total_models: int = 1
|
||||
# Set when other suggestions target overlapping words with a different
|
||||
# outcome — the UI lets the reviewer pick at most one per group.
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoCorrectResult:
|
||||
suggestions: list[Suggestion]
|
||||
model: str # comma-joined when compare mode queried several models
|
||||
elapsed_seconds: float
|
||||
settings_applied: AutoCorrectSettings
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
# True when served from the per-job GCS cache (no LLM call was made).
|
||||
cached: bool = False
|
||||
|
||||
|
||||
class AutoCorrectService:
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
|
||||
def suggest(
|
||||
self,
|
||||
*,
|
||||
job_id: str,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> AutoCorrectResult:
|
||||
if not segments:
|
||||
raise AutoCorrectServiceError("segments is empty")
|
||||
if not reference_lyrics:
|
||||
raise AutoCorrectServiceError(
|
||||
"no reference lyrics available — auto-correction needs at least "
|
||||
"one internet/reference source to compare against",
|
||||
status_code=422,
|
||||
)
|
||||
|
||||
# Flat word list mirrors the prompt's global indices.
|
||||
flat: list[tuple[str, str, str]] = [] # (word_id, word_text, segment_id)
|
||||
for seg in segments:
|
||||
if not seg.get("id"):
|
||||
raise AutoCorrectServiceError("all segments must have ids")
|
||||
for w in seg.get("words") or []:
|
||||
if not w.get("id"):
|
||||
raise AutoCorrectServiceError("all words must have ids")
|
||||
flat.append((w["id"], w.get("text", ""), seg["id"]))
|
||||
|
||||
system_prompt = build_system_prompt(settings)
|
||||
user_prompt = build_user_prompt(
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
models = self._models_for(settings)
|
||||
|
||||
# Re-running on byte-identical input (lyrics, references, settings,
|
||||
# models) returns the previous result instead of paying for another
|
||||
# LLM call. Word ids are part of the key, so cached suggestions
|
||||
# always reference words that still exist.
|
||||
cache_path = self._cache_path(
|
||||
job_id, models, settings, flat, reference_lyrics, artist, title
|
||||
)
|
||||
cached = self._cache_get(cache_path)
|
||||
if cached is not None:
|
||||
logger.info(
|
||||
"auto-correct cache hit job=%s suggestions=%d", job_id,
|
||||
len(cached.suggestions),
|
||||
)
|
||||
return cached
|
||||
|
||||
t0 = time.time()
|
||||
per_model: dict[str, list[Suggestion]] = {}
|
||||
# Token usage per successful model call (None when the provider's
|
||||
# usage object couldn't be read). Drives the cost log below.
|
||||
per_model_usage: dict[str, Optional[TokenUsage]] = {}
|
||||
warnings: list[str] = []
|
||||
if len(models) == 1:
|
||||
raw, usage = self._call_model(
|
||||
models[0], system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
per_model[models[0]] = suggestions
|
||||
per_model_usage[models[0]] = usage
|
||||
warnings.extend(vw)
|
||||
else:
|
||||
import concurrent.futures as cf
|
||||
|
||||
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
|
||||
futures = {
|
||||
ex.submit(
|
||||
self._call_model, m, system_prompt, user_prompt, job_id=job_id
|
||||
): m
|
||||
for m in models
|
||||
}
|
||||
for fut, m in futures.items():
|
||||
try:
|
||||
raw, usage = fut.result()
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
except AutoCorrectServiceError as exc:
|
||||
# One model failing (call OR malformed output) must not
|
||||
# abort compare mode; the rest still return results.
|
||||
warnings.append(f"model {m} failed: {exc}")
|
||||
continue
|
||||
per_model[m] = suggestions
|
||||
per_model_usage[m] = usage
|
||||
warnings.extend(f"[{m}] {w}" for w in vw)
|
||||
if not per_model:
|
||||
raise AutoCorrectServiceError(
|
||||
"all AI models failed", status_code=502
|
||||
)
|
||||
|
||||
merged = self._merge(per_model, flat)
|
||||
elapsed = time.time() - t0
|
||||
model_label = ", ".join(per_model.keys())
|
||||
logger.info(
|
||||
"auto-correct job=%s models=%s words=%d suggestions=%d dropped_warnings=%d elapsed=%.1fs",
|
||||
job_id, model_label, len(flat), len(merged), len(warnings), elapsed,
|
||||
)
|
||||
self._log_usage(job_id, per_model_usage)
|
||||
result = AutoCorrectResult(
|
||||
suggestions=merged,
|
||||
model=model_label,
|
||||
elapsed_seconds=round(elapsed, 1),
|
||||
settings_applied=settings,
|
||||
warnings=warnings,
|
||||
)
|
||||
self._cache_put(cache_path, result)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _log_usage(
|
||||
job_id: str, per_model_usage: dict[str, Optional[TokenUsage]]
|
||||
) -> None:
|
||||
"""Emit greppable per-model and total cost lines for one suggest() call.
|
||||
|
||||
Token counts are ground truth; the USD figures are derived from
|
||||
``pricing.MODEL_PRICING`` and use ESTIMATED Gemini rates (see that
|
||||
module). Query in Cloud Logging via ``auto-correct usage`` /
|
||||
``auto-correct cost``. Observability only — never raises.
|
||||
"""
|
||||
total_cost = 0.0
|
||||
any_cost = False
|
||||
for model, usage in per_model_usage.items():
|
||||
cost = estimate_cost_usd(model, usage)
|
||||
if cost is not None:
|
||||
total_cost += cost
|
||||
any_cost = True
|
||||
if usage is None:
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s tokens=unavailable",
|
||||
job_id, model,
|
||||
)
|
||||
continue
|
||||
thinking = usage.get("thinking_tokens")
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s input_tokens=%d "
|
||||
"output_tokens=%d thinking_tokens=%s cache_read_tokens=%d "
|
||||
"est_cost_usd=%s",
|
||||
job_id,
|
||||
model,
|
||||
usage.get("input_tokens", 0),
|
||||
usage.get("output_tokens", 0),
|
||||
"na" if thinking is None else thinking,
|
||||
usage.get("cache_read_tokens", 0),
|
||||
"unknown" if cost is None else f"{cost:.4f}",
|
||||
)
|
||||
logger.info(
|
||||
"auto-correct cost job=%s models=%s total_est_cost_usd=%s",
|
||||
job_id,
|
||||
", ".join(per_model_usage.keys()),
|
||||
f"{total_cost:.4f}" if any_cost else "unknown",
|
||||
)
|
||||
|
||||
# ---- suggestion cache (GCS, best-effort) ----
|
||||
|
||||
def _get_storage(self):
|
||||
if not hasattr(self, "_storage"):
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._storage = StorageService()
|
||||
return self._storage
|
||||
|
||||
@staticmethod
|
||||
def _cache_path(
|
||||
job_id: str,
|
||||
models: list[str],
|
||||
settings: AutoCorrectSettings,
|
||||
flat: list[tuple[str, str, str]],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> str:
|
||||
payload = {
|
||||
"v": 1,
|
||||
"models": models,
|
||||
"settings": settings.to_dict(),
|
||||
"words": [[word_id, text] for word_id, text, _seg in flat],
|
||||
"references": {
|
||||
source: [seg.get("text", "") for seg in (ref.get("segments") or [])]
|
||||
for source, ref in sorted((reference_lyrics or {}).items())
|
||||
},
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
|
||||
).hexdigest()[:24]
|
||||
return f"jobs/{job_id}/lyrics/auto_correct_cache/{digest}.json"
|
||||
|
||||
def _cache_get(self, path: str) -> Optional[AutoCorrectResult]:
|
||||
"""Best-effort: any storage/shape problem is a cache miss, never an error."""
|
||||
try:
|
||||
storage = self._get_storage()
|
||||
if not storage.bucket.blob(path).exists():
|
||||
return None
|
||||
data = storage.download_json(path)
|
||||
return AutoCorrectResult(
|
||||
suggestions=[Suggestion(**s) for s in data["suggestions"]],
|
||||
model=data["model"],
|
||||
elapsed_seconds=0.0,
|
||||
settings_applied=AutoCorrectSettings(**data["settings_applied"]),
|
||||
warnings=list(data.get("warnings") or []),
|
||||
cached=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache read failed for %s", path, exc_info=True)
|
||||
return None
|
||||
|
||||
def _cache_put(self, path: str, result: AutoCorrectResult) -> None:
|
||||
"""Best-effort: a failed cache write never fails the request."""
|
||||
try:
|
||||
self._get_storage().upload_json(
|
||||
path,
|
||||
{
|
||||
"suggestions": [asdict(s) for s in result.suggestions],
|
||||
"model": result.model,
|
||||
"settings_applied": result.settings_applied.to_dict(),
|
||||
"warnings": result.warnings,
|
||||
"elapsed_seconds": result.elapsed_seconds,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache write failed for %s", path, exc_info=True)
|
||||
|
||||
def _models_for(self, settings: AutoCorrectSettings) -> list[str]:
|
||||
if settings.compare_models:
|
||||
configured = [
|
||||
m.strip()
|
||||
for m in self.settings.auto_correct_compare_models.replace(",", ";").split(";")
|
||||
if m.strip()
|
||||
]
|
||||
# De-dupe while preserving order.
|
||||
seen: set[str] = set()
|
||||
models = [m for m in configured if not (m in seen or seen.add(m))]
|
||||
if len(models) >= 2:
|
||||
return models
|
||||
logger.warning(
|
||||
"compare_models requested but AUTO_CORRECT_COMPARE_MODELS has "
|
||||
"%d usable entries; falling back to single model", len(models),
|
||||
)
|
||||
return [self.settings.auto_correct_model]
|
||||
|
||||
@staticmethod
|
||||
def _merge(
|
||||
per_model: dict[str, list[Suggestion]],
|
||||
flat: list[tuple[str, str, str]],
|
||||
) -> list[Suggestion]:
|
||||
"""Deduplicate identical suggestions across models, tag consensus,
|
||||
assign conflict groups to overlapping non-identical suggestions, and
|
||||
sort by document position."""
|
||||
total = len(per_model)
|
||||
merged: dict[tuple, Suggestion] = {}
|
||||
for model, suggestions in per_model.items():
|
||||
for s in suggestions:
|
||||
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
|
||||
existing = merged.get(key)
|
||||
if existing is None:
|
||||
s.models = [model]
|
||||
s.consensus = 1
|
||||
s.total_models = total
|
||||
merged[key] = s
|
||||
else:
|
||||
existing.models.append(model)
|
||||
existing.consensus += 1
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
|
||||
result = list(merged.values())
|
||||
|
||||
# Conflict groups: suggestions sharing any target word but not merged
|
||||
# above disagree about the same span — reviewer picks at most one.
|
||||
# (insert_after anchors are excluded: inserting after a word does not
|
||||
# conflict with editing that word.)
|
||||
by_word: dict[str, list[int]] = {}
|
||||
for i, s in enumerate(result):
|
||||
if s.op == "insert_after":
|
||||
continue
|
||||
for wid in s.word_ids:
|
||||
by_word.setdefault(wid, []).append(i)
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
parent[find(other)] = find(overlapping[0])
|
||||
roots: dict[int, list[int]] = {}
|
||||
for i in range(len(result)):
|
||||
roots.setdefault(find(i), []).append(i)
|
||||
for members in roots.values():
|
||||
if len(members) < 2:
|
||||
continue
|
||||
group = str(uuid.uuid4())
|
||||
for i in members:
|
||||
result[i].conflict_group = group
|
||||
|
||||
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
|
||||
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
|
||||
return result
|
||||
|
||||
# ---- internals ----
|
||||
|
||||
def _call_model(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable.
|
||||
|
||||
Transient provider errors (rate limits / overload, flagged
|
||||
``retryable``) are retried with exponential backoff. Permanent errors
|
||||
(misconfig, malformed output) fail fast.
|
||||
"""
|
||||
for attempt in range(1, _MODEL_CALL_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
if model.startswith("claude"):
|
||||
return self._call_anthropic(
|
||||
model, system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
return self._call_gemini(
|
||||
model, system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
if not exc.retryable or attempt == _MODEL_CALL_MAX_ATTEMPTS:
|
||||
raise
|
||||
backoff = _MODEL_CALL_BACKOFF_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
"auto-correct model call transient failure job=%s model=%s "
|
||||
"attempt=%d/%d; retrying in %.1fs (%s)",
|
||||
job_id, model, attempt, _MODEL_CALL_MAX_ATTEMPTS, backoff, exc,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
# Unreachable: the loop either returns or raises on the final attempt.
|
||||
raise AssertionError("retry loop exited without returning or raising")
|
||||
|
||||
@staticmethod
|
||||
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from an Anthropic response.
|
||||
|
||||
``output_tokens`` already includes adaptive thinking tokens (billed as
|
||||
output); they are not separable here, so thinking_tokens is None.
|
||||
Returns None on any shape problem — usage must never break the call.
|
||||
"""
|
||||
try:
|
||||
u = response.usage
|
||||
return TokenUsage(
|
||||
input_tokens=int(getattr(u, "input_tokens", 0) or 0),
|
||||
output_tokens=int(getattr(u, "output_tokens", 0) or 0),
|
||||
cache_read_tokens=int(getattr(u, "cache_read_input_tokens", 0) or 0),
|
||||
thinking_tokens=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Anthropic usage", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _gemini_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from a Gemini (Vertex) response.
|
||||
|
||||
Gemini reports thinking separately (``thoughts_token_count``); it is
|
||||
billed at the output rate, so it's folded into output_tokens and also
|
||||
reported separately for visibility. Returns None on any shape problem.
|
||||
"""
|
||||
try:
|
||||
u = response.usage_metadata
|
||||
prompt = int(getattr(u, "prompt_token_count", 0) or 0)
|
||||
candidates = int(getattr(u, "candidates_token_count", 0) or 0)
|
||||
thoughts = int(getattr(u, "thoughts_token_count", 0) or 0)
|
||||
cached = int(getattr(u, "cached_content_token_count", 0) or 0)
|
||||
return TokenUsage(
|
||||
input_tokens=prompt,
|
||||
output_tokens=candidates + thoughts,
|
||||
cache_read_tokens=cached,
|
||||
thinking_tokens=thoughts,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Gemini usage", exc_info=True)
|
||||
return None
|
||||
|
||||
def _call_anthropic(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
import anthropic
|
||||
|
||||
if not os.environ.get("ANTHROPIC_API_KEY"):
|
||||
# No silent fallback to another provider — surface the
|
||||
# misconfiguration so it gets fixed, not masked.
|
||||
logger.error(
|
||||
"auto-correct model %s requires ANTHROPIC_API_KEY which is not set "
|
||||
"(job=%s)", model, job_id,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is not configured", status_code=502
|
||||
)
|
||||
|
||||
# Structured outputs require additionalProperties: false on objects;
|
||||
# the Vertex variant of the schema omits it, so inject here. Deep-copy
|
||||
# because the google-genai SDK mutates schema dicts in place (it adds
|
||||
# 'property_ordering', which the Anthropic API rejects).
|
||||
import copy
|
||||
|
||||
base = copy.deepcopy(RESPONSE_SCHEMA)
|
||||
for obj in (base, base["properties"]["suggestions"]["items"]):
|
||||
obj.pop("property_ordering", None)
|
||||
obj.pop("propertyOrdering", None)
|
||||
obj["additionalProperties"] = False
|
||||
strict_schema = base
|
||||
client = anthropic.Anthropic(timeout=120.0)
|
||||
try:
|
||||
response = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=16000,
|
||||
system=system_prompt,
|
||||
messages=[{"role": "user", "content": user_prompt}],
|
||||
thinking={"type": "adaptive"},
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
)
|
||||
except Exception as exc:
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._anthropic_usage(response)
|
||||
try:
|
||||
text = next(b.text for b in response.content if b.type == "text")
|
||||
return json.loads(text), usage
|
||||
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
# Milliseconds; bounds the call so a hung model never strands the UI.
|
||||
http_options=types.HttpOptions(timeout=120_000),
|
||||
)
|
||||
# Deep-copy: the google-genai SDK mutates the schema dict in place,
|
||||
# which would poison the shared module-level constant for other
|
||||
# providers running in the same process.
|
||||
import copy
|
||||
|
||||
try:
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._gemini_usage(response)
|
||||
try:
|
||||
return json.loads(response.text), usage
|
||||
except (json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _validate(
|
||||
self,
|
||||
raw: Any,
|
||||
flat: list[tuple[str, str, str]],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> tuple[list[Suggestion], list[str]]:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("suggestions"), list):
|
||||
raise AutoCorrectServiceError(
|
||||
"AI response missing 'suggestions' list", status_code=502
|
||||
)
|
||||
n = len(flat)
|
||||
out: list[Suggestion] = []
|
||||
warnings: list[str] = []
|
||||
for i, s in enumerate(raw["suggestions"]):
|
||||
problem = self._check(s, n, settings)
|
||||
if problem:
|
||||
warnings.append(f"dropped suggestion {i}: {problem}")
|
||||
continue
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
if s["op"] == "insert_after":
|
||||
word_ids = [flat[start][0]]
|
||||
segment_ids = [flat[start][2]]
|
||||
original_text = ""
|
||||
else:
|
||||
span = flat[start : end + 1]
|
||||
word_ids = [w[0] for w in span]
|
||||
segment_ids = sorted({w[2] for w in span})
|
||||
original_text = " ".join(w[1] for w in span)
|
||||
out.append(
|
||||
Suggestion(
|
||||
id=str(uuid.uuid4()),
|
||||
op=s["op"],
|
||||
word_ids=word_ids,
|
||||
segment_ids=segment_ids,
|
||||
original_text=original_text,
|
||||
new_text="" if s["op"] == "delete" else str(s["new_text"]).strip(),
|
||||
reason=str(s.get("reason", "")),
|
||||
category=s["category"] if s.get("category") in VALID_CATEGORIES else "other",
|
||||
confidence=max(0.0, min(1.0, float(s["confidence"]))),
|
||||
)
|
||||
)
|
||||
return out, warnings
|
||||
|
||||
@staticmethod
|
||||
def _check(s: Any, n_words: int, settings: AutoCorrectSettings) -> Optional[str]:
|
||||
if not isinstance(s, dict):
|
||||
return "not an object"
|
||||
op = s.get("op")
|
||||
if op not in VALID_OPS:
|
||||
return f"invalid op {op!r}"
|
||||
try:
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
confidence = float(s["confidence"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return "missing/invalid indices or confidence"
|
||||
if not (0 <= start <= end < n_words):
|
||||
return f"indices out of range ({start}..{end} of {n_words})"
|
||||
if op == "insert_after" and not settings.allow_insertions:
|
||||
return "insertions disabled by settings"
|
||||
if op == "insert_after" and start != end:
|
||||
return "insert_after requires start_idx == end_idx"
|
||||
new_text = str(s.get("new_text", "")).strip()
|
||||
if op in ("replace", "insert_after") and not new_text:
|
||||
return f"{op} with empty new_text"
|
||||
if op == "delete" and new_text:
|
||||
return "delete with non-empty new_text"
|
||||
if confidence < settings.min_confidence:
|
||||
return f"confidence {confidence:.2f} below threshold"
|
||||
if (
|
||||
s.get("category") == "adlib_removal"
|
||||
and not settings.suggest_adlib_removal
|
||||
):
|
||||
return "adlib removal disabled by settings"
|
||||
return None
|
||||
|
||||
|
||||
_service_instance: Optional[AutoCorrectService] = None
|
||||
|
||||
|
||||
def get_auto_correct_service() -> AutoCorrectService:
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = AutoCorrectService()
|
||||
return _service_instance
|
||||
@@ -0,0 +1,47 @@
|
||||
"""User-facing knobs for AI auto-correction suggestions."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoCorrectSettings:
|
||||
"""Reviewer-tunable behaviour for a suggestion run.
|
||||
|
||||
suggest_adlib_removal: allow suggestions that delete transcribed
|
||||
backing-vocal / adlib phrases absent from the references.
|
||||
allow_insertions: allow suggestions that insert words the
|
||||
transcription missed entirely.
|
||||
min_confidence: drop suggestions below this confidence server-side
|
||||
(the UI can filter further client-side).
|
||||
compare_models: query every configured compare model in parallel,
|
||||
deduplicate identical suggestions and report per-suggestion
|
||||
model consensus (slower, costs one call per model).
|
||||
"""
|
||||
|
||||
suggest_adlib_removal: bool = True
|
||||
allow_insertions: bool = True
|
||||
min_confidence: float = 0.0
|
||||
compare_models: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def settings_from_dict(data: dict) -> AutoCorrectSettings:
|
||||
known = {f for f in AutoCorrectSettings.__dataclass_fields__}
|
||||
unknown = set(data) - known
|
||||
if unknown:
|
||||
raise ValueError(f"unknown settings: {sorted(unknown)}")
|
||||
merged = {**AutoCorrectSettings().to_dict(), **data}
|
||||
if not isinstance(merged["suggest_adlib_removal"], bool):
|
||||
raise ValueError("suggest_adlib_removal must be a boolean")
|
||||
if not isinstance(merged["allow_insertions"], bool):
|
||||
raise ValueError("allow_insertions must be a boolean")
|
||||
if not isinstance(merged["compare_models"], bool):
|
||||
raise ValueError("compare_models must be a boolean")
|
||||
mc = merged["min_confidence"]
|
||||
if isinstance(mc, bool) or not isinstance(mc, (int, float)) or not 0.0 <= float(mc) <= 1.0:
|
||||
raise ValueError("min_confidence must be a number between 0 and 1")
|
||||
merged["min_confidence"] = float(mc)
|
||||
return AutoCorrectSettings(**merged)
|
||||
@@ -22,6 +22,30 @@ from backend.config import get_settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _destroy_old_secret_versions(client, secret_path: str, keep: int = 5) -> None:
|
||||
"""Destroy ENABLED secret versions beyond the newest `keep`.
|
||||
|
||||
OAuth credential secrets are rewritten on every refresh, which would
|
||||
otherwise accumulate hundreds of versions and cost ~$0.06/version/month
|
||||
in replica storage. Only the newest version is read (`versions/latest`),
|
||||
so older versions are dead weight.
|
||||
"""
|
||||
try:
|
||||
versions = list(client.list_secret_versions(request={"parent": secret_path}))
|
||||
enabled = [
|
||||
v for v in versions
|
||||
if v.state == v.State.ENABLED # type: ignore[attr-defined]
|
||||
]
|
||||
enabled.sort(key=lambda v: v.create_time, reverse=True)
|
||||
for v in enabled[keep:]:
|
||||
try:
|
||||
client.destroy_secret_version(request={"name": v.name})
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to destroy {v.name}: {e}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prune old secret versions for {secret_path}: {e}")
|
||||
|
||||
|
||||
class CredentialStatus(str, Enum):
|
||||
"""Status of OAuth credentials."""
|
||||
VALID = "valid"
|
||||
@@ -329,7 +353,9 @@ class CredentialManager:
|
||||
parent=secret_path,
|
||||
payload={"data": json.dumps(updated_data).encode("utf-8")}
|
||||
)
|
||||
|
||||
|
||||
_destroy_old_secret_versions(client, secret_path, keep=5)
|
||||
|
||||
logger.info(f"Updated {secret_name} with refreshed token")
|
||||
return True
|
||||
|
||||
@@ -421,19 +447,21 @@ class CredentialManager:
|
||||
"""Update stored Dropbox credentials."""
|
||||
try:
|
||||
from google.cloud import secretmanager
|
||||
|
||||
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
project_id = self.settings.google_cloud_project
|
||||
secret_path = f"projects/{project_id}/secrets/{self.DROPBOX_SECRET}"
|
||||
|
||||
|
||||
client.add_secret_version(
|
||||
parent=secret_path,
|
||||
payload={"data": json.dumps(creds).encode("utf-8")}
|
||||
)
|
||||
|
||||
|
||||
_destroy_old_secret_versions(client, secret_path, keep=5)
|
||||
|
||||
logger.info("Updated Dropbox credentials with refreshed token")
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update Dropbox credentials: {e}")
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Custom lyrics generation package.
|
||||
|
||||
Stateless helpers that take transcribed lyrics + client custom-lyrics input
|
||||
and return syllable-aware customised lyrics via Gemini 3.1 Pro.
|
||||
"""
|
||||
@@ -0,0 +1,129 @@
|
||||
"""System and user prompt builders for custom-lyrics generation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings, params_for
|
||||
from backend.services.custom_lyrics.validator import LineValidation
|
||||
|
||||
|
||||
_BASE_SYSTEM = """You are a professional karaoke lyricist. Your task is to produce custom karaoke lyrics for a song, applying customisations the client has requested while making the result singable.
|
||||
|
||||
RULES:
|
||||
1. Each output line corresponds positionally to the same input line (line 1 -> line 1, etc.). Do not reorder.
|
||||
2. Preserve each line's role (verse/chorus/repeat). If the original repeats a chorus three times, the customised version should also repeat its corresponding chorus three times.
|
||||
3. Apply the client's customisations as faithfully as possible. If the client gave explicit "replace X with Y" instructions, follow them. If they gave a free-form theme or names without explicit mapping, use your best judgement to weave them in where they fit naturally.
|
||||
4. Where the client gave no clear customisation for a line, keep the original lyric unchanged.
|
||||
5. Output JSON only, matching the schema. No commentary, no surrounding prose."""
|
||||
|
||||
|
||||
_RULE_FIXED_COUNT = "6. The output MUST contain exactly the same number of lines as the input transcribed lyrics."
|
||||
_RULE_FLEXIBLE_COUNT = "6. You may output any number of lines that flows naturally; do not pad to match the input length."
|
||||
_RULE_NO_REWORD = "7. Do NOT paraphrase or reword the client's text. Use it verbatim wherever it appears in the input."
|
||||
_RULE_USE_ALL = "8. All client-provided content MUST appear in the output. Do not skip any of the client's words."
|
||||
|
||||
|
||||
def build_system_prompt(settings: GenerationSettings) -> str:
|
||||
parts = [_BASE_SYSTEM]
|
||||
parts.append(_RULE_FIXED_COUNT if settings.fixed_line_count else _RULE_FLEXIBLE_COUNT)
|
||||
if not settings.allow_reword:
|
||||
parts.append(_RULE_NO_REWORD)
|
||||
if not settings.allow_omit:
|
||||
parts.append(_RULE_USE_ALL)
|
||||
parts.append("")
|
||||
parts.append(f"GUIDANCE: {params_for(settings.strictness).prompt_phrase}")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _format_target_count(counts: list[int]) -> str:
|
||||
"""Render the 4-method target as a single ≈ approximate value (median for stability)."""
|
||||
if not counts:
|
||||
return "≈0 syl"
|
||||
sorted_c = sorted(counts)
|
||||
mid = sorted_c[len(sorted_c) // 2]
|
||||
return f"≈{mid} syl"
|
||||
|
||||
|
||||
def build_initial_user_prompt(
|
||||
*,
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
target_lines: list[str],
|
||||
target_syllables: list[list[int]],
|
||||
time_budgets: list[float],
|
||||
observed_rates: list[float],
|
||||
custom_text_block: str,
|
||||
notes: Optional[str],
|
||||
settings: GenerationSettings,
|
||||
) -> str:
|
||||
n = len(target_lines)
|
||||
annotated = []
|
||||
for i, line in enumerate(target_lines):
|
||||
meta = (
|
||||
f"[{_format_target_count(target_syllables[i])}, "
|
||||
f"{time_budgets[i]:.1f}s @ {observed_rates[i]:.1f} syl/s]"
|
||||
)
|
||||
annotated.append(f"{i + 1}. {meta} {line}")
|
||||
numbered = "\n".join(annotated)
|
||||
notes_block = notes.strip() if notes else "(none)"
|
||||
custom_block = custom_text_block if custom_text_block else "(see attached PDF)"
|
||||
line_count_clause = (
|
||||
f"exactly {n} lines" if settings.fixed_line_count else "an appropriate number of lines"
|
||||
)
|
||||
return (
|
||||
f"SONG: {artist or '(unknown artist)'} - {title or '(unknown title)'}\n\n"
|
||||
f"ORIGINAL TRANSCRIBED LYRICS ({n} lines, with per-line syllable target and time budget):\n"
|
||||
f"{numbered}\n\n"
|
||||
f"CLIENT CUSTOM LYRICS / INSTRUCTIONS:\n{custom_block}\n\n"
|
||||
f"ADDITIONAL NOTES FROM OPERATOR:\n{notes_block}\n\n"
|
||||
f"Produce the customised lyrics in JSON format with {line_count_clause}, "
|
||||
f"honouring the per-line syllable targets and time budgets where possible."
|
||||
)
|
||||
|
||||
|
||||
def build_repair_user_prompt(
|
||||
*,
|
||||
previous_output: list[str],
|
||||
violations: list[LineValidation],
|
||||
target_lines: list[str],
|
||||
target_syllables: list[list[int]],
|
||||
time_budgets: list[float],
|
||||
observed_rates: list[float],
|
||||
settings: GenerationSettings,
|
||||
) -> str:
|
||||
if not violations:
|
||||
return "no violations to fix; return previous output unchanged"
|
||||
|
||||
n = len(previous_output)
|
||||
violating_indices = {v.line_index for v in violations}
|
||||
keep_indices = sorted(i + 1 for i in range(n) if i not in violating_indices)
|
||||
keep_clause = (
|
||||
", ".join(str(i) for i in keep_indices) if keep_indices else "(none)"
|
||||
)
|
||||
|
||||
fix_blocks: list[str] = []
|
||||
for v in violations:
|
||||
i = v.line_index
|
||||
target_meta = _format_target_count(target_syllables[i])
|
||||
delta_sign = "+" if (v.candidate_syllables and v.target_syllables and
|
||||
max(v.candidate_syllables) > max(v.target_syllables)) else "-"
|
||||
actual = max(v.candidate_syllables) if v.candidate_syllables else 0
|
||||
fix_blocks.append(
|
||||
f"- Line {i + 1}: target {target_meta}, time budget {time_budgets[i]:.1f}s, "
|
||||
f"sung at ~{observed_rates[i]:.1f} syl/s.\n"
|
||||
f" Original transcribed line (for inspiration on how the budget can be filled): "
|
||||
f"\"{target_lines[i]}\"\n"
|
||||
f" You wrote: \"{v.candidate_text}\" "
|
||||
f"({actual} syl, {delta_sign}{v.min_delta} {'over' if delta_sign == '+' else 'under'}).\n"
|
||||
f" Trim or paraphrase to fit while preserving the client's intent."
|
||||
)
|
||||
|
||||
return (
|
||||
f"Your previous output had {len(violations)} lines that exceeded the syllable budget too far.\n"
|
||||
f"Please fix ONLY those lines. Keep every other line exactly the same as before.\n\n"
|
||||
f"Lines to fix:\n\n"
|
||||
f"{chr(10).join(fix_blocks)}\n\n"
|
||||
f"Lines to keep unchanged: {keep_clause}\n\n"
|
||||
f"Return JSON with all {n} lines, in original order, with the listed lines fixed "
|
||||
f"and all other lines unchanged."
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Result types for the custom-lyrics service."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings
|
||||
from backend.services.custom_lyrics.validator import LineValidation
|
||||
|
||||
|
||||
class StopReason(str, Enum):
|
||||
SUCCESS = "success"
|
||||
PLATEAU = "plateau"
|
||||
MAX_ITERS_REACHED = "max_iters_reached"
|
||||
LINE_COUNT_MISMATCH = "line_count_mismatch"
|
||||
VERBATIM_SKIP = "verbatim_skip"
|
||||
# A repair iteration failed (e.g. the model returned an empty/blocked
|
||||
# response); we keep the best result found so far instead of failing.
|
||||
REPAIR_FAILED = "repair_failed"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CustomLyricsResult:
|
||||
lines: list[str]
|
||||
line_metadata: list[LineValidation]
|
||||
iterations_used: int
|
||||
stop_reason: StopReason
|
||||
settings_applied: GenerationSettings
|
||||
model: str
|
||||
duration_ms: int
|
||||
new_segment_timing: Optional[list[tuple[float, float]]] = None
|
||||
line_count_mismatch: bool = False
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
@@ -0,0 +1,638 @@
|
||||
"""Custom lyrics service: validate-and-repair loop orchestrator."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.custom_lyrics.prompts import (
|
||||
build_initial_user_prompt,
|
||||
build_repair_user_prompt,
|
||||
build_system_prompt,
|
||||
)
|
||||
from backend.services.custom_lyrics.result import CustomLyricsResult, StopReason
|
||||
from backend.services.custom_lyrics.settings import (
|
||||
GenerationSettings,
|
||||
StrictnessLevel,
|
||||
params_for,
|
||||
)
|
||||
from backend.services.custom_lyrics.timing import redistribute_timing_proportional
|
||||
from backend.services.custom_lyrics.validator import (
|
||||
LineValidation,
|
||||
Severity,
|
||||
validate,
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.utils.syllable_counter import SyllableCounter
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
SUPPORTED_MIMES = {
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
||||
"application/pdf": "pdf",
|
||||
"text/plain": "txt",
|
||||
"text/markdown": "md",
|
||||
}
|
||||
|
||||
|
||||
def _format_worst_lines(validations: list[LineValidation], n: int = 3) -> list[dict]:
|
||||
"""Top-N failing lines for log breadcrumbs. Cuts text at 80 chars."""
|
||||
failing = sorted(
|
||||
(v for v in validations if not v.passes),
|
||||
key=lambda v: v.min_delta,
|
||||
reverse=True,
|
||||
)[:n]
|
||||
return [
|
||||
{
|
||||
"line_index": v.line_index,
|
||||
"min_delta": v.min_delta,
|
||||
"severity": v.severity.value,
|
||||
"target": v.target_text[:80],
|
||||
"candidate": v.candidate_text[:80],
|
||||
"target_syllables": v.target_syllables,
|
||||
"candidate_syllables": v.candidate_syllables,
|
||||
}
|
||||
for v in failing
|
||||
]
|
||||
|
||||
|
||||
class CustomLyricsServiceError(Exception):
|
||||
def __init__(self, message: str, *, status_code: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class CustomLyricsService:
|
||||
def __init__(self, counter: Optional[SyllableCounter] = None) -> None:
|
||||
self.settings = get_settings()
|
||||
self._counter = counter or SyllableCounter()
|
||||
|
||||
# ---- public ----
|
||||
|
||||
def generate(
|
||||
self,
|
||||
*,
|
||||
job_id: str,
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
custom_text: Optional[str],
|
||||
file_bytes: Optional[bytes],
|
||||
file_mime: Optional[str],
|
||||
file_name: Optional[str],
|
||||
notes: Optional[str],
|
||||
settings: GenerationSettings,
|
||||
) -> CustomLyricsResult:
|
||||
start = time.monotonic()
|
||||
n = len(target_lines)
|
||||
if n == 0:
|
||||
raise CustomLyricsServiceError(
|
||||
"target_lines must not be empty", status_code=400
|
||||
)
|
||||
if n > self.settings.custom_lyrics_max_input_lines:
|
||||
raise CustomLyricsServiceError(
|
||||
f"target_lines exceeds max ({self.settings.custom_lyrics_max_input_lines})",
|
||||
status_code=400,
|
||||
)
|
||||
if not custom_text and not file_bytes:
|
||||
raise CustomLyricsServiceError(
|
||||
"must provide custom_text or file_bytes", status_code=400
|
||||
)
|
||||
|
||||
custom_text_block, pdf_bytes = self._prepare_inputs(
|
||||
custom_text=custom_text,
|
||||
file_bytes=file_bytes,
|
||||
file_mime=file_mime,
|
||||
file_name=file_name,
|
||||
)
|
||||
|
||||
# Pre-compute per-line metadata (used for prompts AND for validator)
|
||||
target_syllables = [self._counter.count_per_line(line) for line in target_lines]
|
||||
time_budgets = [self._segment_duration(seg) for seg in target_segments]
|
||||
observed_rates = [
|
||||
(sum(s) / 4 / dur) if dur > 0 else 0.0
|
||||
for s, dur in zip(target_syllables, time_budgets)
|
||||
]
|
||||
|
||||
params = params_for(settings.strictness)
|
||||
sys_prompt = build_system_prompt(settings)
|
||||
initial_user_prompt = build_initial_user_prompt(
|
||||
artist=artist, title=title,
|
||||
target_lines=target_lines,
|
||||
target_syllables=target_syllables,
|
||||
time_budgets=time_budgets,
|
||||
observed_rates=observed_rates,
|
||||
custom_text_block=custom_text_block,
|
||||
notes=notes,
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_initial_call_start",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"model": self.settings.custom_lyrics_model,
|
||||
"input_lines": n,
|
||||
"settings": settings.to_dict(),
|
||||
"tolerance": params.tolerance,
|
||||
"max_iterations": params.max_iterations,
|
||||
"system_prompt_chars": len(sys_prompt),
|
||||
"user_prompt_chars": len(initial_user_prompt),
|
||||
"pdf_bytes": len(pdf_bytes) if pdf_bytes else 0,
|
||||
"input_lines_total_syllables": sum(sum(s) / 4 for s in target_syllables),
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
candidate_lines = self._call_gemini(
|
||||
system_prompt=sys_prompt,
|
||||
user_prompt=initial_user_prompt,
|
||||
pdf_bytes=pdf_bytes,
|
||||
settings=settings,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"custom_lyrics_initial_call_failed",
|
||||
extra={"job_id": job_id, "stage": "initial"},
|
||||
)
|
||||
raise
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_initial_call_complete",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"candidate_lines": len(candidate_lines),
|
||||
"expected_lines": n,
|
||||
"line_count_match": len(candidate_lines) == n,
|
||||
},
|
||||
)
|
||||
|
||||
# Verbatim path: skip the repair loop entirely
|
||||
if settings.strictness is StrictnessLevel.VERBATIM:
|
||||
metadata = self._validate_for_metadata_only(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
)
|
||||
return self._finalise(
|
||||
lines=candidate_lines,
|
||||
metadata=metadata,
|
||||
iterations_used=0,
|
||||
stop_reason=StopReason.VERBATIM_SKIP,
|
||||
settings=settings,
|
||||
target_lines=target_lines,
|
||||
target_segments=target_segments,
|
||||
start=start,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
# Validate-and-repair loop
|
||||
validations = self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=params.tolerance, fixed=settings.fixed_line_count,
|
||||
)
|
||||
best = (candidate_lines, validations)
|
||||
prev_score = self._score(validations)
|
||||
iteration = 0
|
||||
violation_count = sum(1 for v in validations if not v.passes)
|
||||
stop_reason = StopReason.SUCCESS if violation_count == 0 else StopReason.MAX_ITERS_REACHED
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_initial_validation",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"violations": prev_score[0],
|
||||
"total_min_delta": prev_score[1],
|
||||
"worst_lines": _format_worst_lines(validations),
|
||||
},
|
||||
)
|
||||
|
||||
while iteration < params.max_iterations:
|
||||
violations = [v for v in validations if not v.passes]
|
||||
if not violations:
|
||||
stop_reason = StopReason.SUCCESS
|
||||
break
|
||||
|
||||
repair_prompt = build_repair_user_prompt(
|
||||
previous_output=candidate_lines,
|
||||
violations=violations,
|
||||
target_lines=target_lines,
|
||||
target_syllables=target_syllables,
|
||||
time_budgets=time_budgets,
|
||||
observed_rates=observed_rates,
|
||||
settings=settings,
|
||||
)
|
||||
iter_num = iteration + 1
|
||||
logger.info(
|
||||
"custom_lyrics_repair_call_start",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"iteration": iter_num,
|
||||
"max_iterations": params.max_iterations,
|
||||
"violations_to_repair": len(violations),
|
||||
"repair_prompt_chars": len(repair_prompt),
|
||||
},
|
||||
)
|
||||
try:
|
||||
candidate_lines = self._call_gemini(
|
||||
system_prompt=sys_prompt,
|
||||
user_prompt=repair_prompt,
|
||||
pdf_bytes=pdf_bytes,
|
||||
settings=settings,
|
||||
)
|
||||
except Exception:
|
||||
# Repair is a best-effort *improvement* step. If a repair call
|
||||
# fails (e.g. the model returned an empty/blocked response, or a
|
||||
# transient Vertex error), we must NOT throw away the successful
|
||||
# initial result — that turned a working generation into a 500 and
|
||||
# a browser "NetworkError". Keep the best candidate found so far.
|
||||
# WARNING (not exception/ERROR): this is now a handled, non-fatal
|
||||
# degradation, so it should not trip the production error monitor.
|
||||
logger.warning(
|
||||
"custom_lyrics_repair_call_failed",
|
||||
exc_info=True,
|
||||
extra={"job_id": job_id, "iteration": iter_num, "stage": "repair"},
|
||||
)
|
||||
stop_reason = StopReason.REPAIR_FAILED
|
||||
break
|
||||
validations = self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=params.tolerance, fixed=settings.fixed_line_count,
|
||||
)
|
||||
|
||||
new_score = self._score(validations)
|
||||
improved = new_score < prev_score
|
||||
if improved:
|
||||
best = (candidate_lines, validations)
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_repair_iter_complete",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"iteration": iter_num,
|
||||
"violations_before": prev_score[0],
|
||||
"violations_after": new_score[0],
|
||||
"delta_total_before": prev_score[1],
|
||||
"delta_total_after": new_score[1],
|
||||
"improved": improved,
|
||||
"candidate_line_count": len(candidate_lines),
|
||||
"worst_lines": _format_worst_lines(validations),
|
||||
},
|
||||
)
|
||||
|
||||
# Plateau when score did not strictly improve
|
||||
if new_score >= prev_score:
|
||||
stop_reason = StopReason.PLATEAU
|
||||
iteration += 1
|
||||
break
|
||||
prev_score = new_score
|
||||
iteration += 1
|
||||
if new_score[0] == 0:
|
||||
stop_reason = StopReason.SUCCESS
|
||||
break
|
||||
|
||||
return self._finalise(
|
||||
lines=best[0],
|
||||
metadata=best[1],
|
||||
iterations_used=iteration,
|
||||
stop_reason=stop_reason,
|
||||
settings=settings,
|
||||
target_lines=target_lines,
|
||||
target_segments=target_segments,
|
||||
start=start,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
# ---- helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _segment_duration(seg: Any) -> float:
|
||||
if isinstance(seg, dict):
|
||||
start = seg.get("start_time")
|
||||
end = seg.get("end_time")
|
||||
else:
|
||||
start = getattr(seg, "start_time", None)
|
||||
end = getattr(seg, "end_time", None)
|
||||
if start is None or end is None:
|
||||
return 0.0
|
||||
try:
|
||||
return max(0.0, float(end) - float(start))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
@staticmethod
|
||||
def _score(validations: list[LineValidation]) -> tuple[int, int]:
|
||||
"""Lower is better. Sort by (violation_count, total_min_delta)."""
|
||||
violations = sum(1 for v in validations if not v.passes)
|
||||
total = sum(v.min_delta for v in validations)
|
||||
return (violations, total)
|
||||
|
||||
def _validate_for_metadata_only(
|
||||
self,
|
||||
candidate_lines: list[str],
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
) -> list[LineValidation]:
|
||||
"""Validator run with infinite tolerance (everything passes); used for Verbatim."""
|
||||
if len(candidate_lines) != len(target_lines):
|
||||
return self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=10**9, fixed=False,
|
||||
)
|
||||
return validate(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
self._counter, tolerance=10**9,
|
||||
)
|
||||
|
||||
def _validate_with_length_handling(
|
||||
self,
|
||||
candidate_lines: list[str],
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
*,
|
||||
tolerance: int,
|
||||
fixed: bool,
|
||||
) -> list[LineValidation]:
|
||||
"""Handle length mismatches without raising:
|
||||
- If fixed=True and lengths differ, all positions count as violations
|
||||
beyond the overlap.
|
||||
- If fixed=False, only validate the overlap (variable line count is OK).
|
||||
"""
|
||||
if len(candidate_lines) == len(target_lines):
|
||||
return validate(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
self._counter, tolerance=tolerance,
|
||||
)
|
||||
overlap = min(len(candidate_lines), len(target_lines))
|
||||
partial = validate(
|
||||
candidate_lines[:overlap], target_lines[:overlap],
|
||||
target_segments[:overlap], self._counter, tolerance=tolerance,
|
||||
)
|
||||
if fixed and len(candidate_lines) != len(target_lines):
|
||||
extra = abs(len(candidate_lines) - len(target_lines))
|
||||
for i in range(overlap, overlap + extra):
|
||||
idx = i
|
||||
tgt_text = target_lines[idx] if idx < len(target_lines) else ""
|
||||
cand_text = candidate_lines[idx] if idx < len(candidate_lines) else ""
|
||||
partial.append(LineValidation(
|
||||
line_index=idx,
|
||||
target_text=tgt_text,
|
||||
candidate_text=cand_text,
|
||||
target_syllables=[0, 0, 0, 0],
|
||||
candidate_syllables=[0, 0, 0, 0],
|
||||
min_delta=99,
|
||||
passes=False,
|
||||
severity=Severity.MAJOR,
|
||||
time_budget_seconds=0.0,
|
||||
))
|
||||
return partial
|
||||
|
||||
def _finalise(
|
||||
self,
|
||||
*,
|
||||
lines: list[str],
|
||||
metadata: list[LineValidation],
|
||||
iterations_used: int,
|
||||
stop_reason: StopReason,
|
||||
settings: GenerationSettings,
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
start: float,
|
||||
job_id: str,
|
||||
) -> CustomLyricsResult:
|
||||
n = len(target_lines)
|
||||
m = len(lines)
|
||||
line_count_mismatch = (m != n)
|
||||
|
||||
new_timing: Optional[list[tuple[float, float]]] = None
|
||||
if line_count_mismatch and not settings.fixed_line_count and target_segments:
|
||||
window_start = self._segment_start(target_segments[0])
|
||||
window_end = self._segment_end(target_segments[-1])
|
||||
new_timing = redistribute_timing_proportional(
|
||||
new_lines=lines,
|
||||
total_window=(window_start, window_end),
|
||||
counter=self._counter,
|
||||
)
|
||||
|
||||
warnings: list[str] = []
|
||||
if line_count_mismatch and settings.fixed_line_count:
|
||||
stop_reason = StopReason.LINE_COUNT_MISMATCH
|
||||
warnings.append(
|
||||
f"AI returned {m} lines but {n} were expected. "
|
||||
f"Manually adjust the textarea or click Regenerate."
|
||||
)
|
||||
|
||||
duration_ms = int((time.monotonic() - start) * 1000)
|
||||
result = CustomLyricsResult(
|
||||
lines=lines,
|
||||
line_metadata=metadata,
|
||||
iterations_used=iterations_used,
|
||||
stop_reason=stop_reason,
|
||||
settings_applied=settings,
|
||||
model=self.settings.custom_lyrics_model,
|
||||
duration_ms=duration_ms,
|
||||
new_segment_timing=new_timing,
|
||||
line_count_mismatch=line_count_mismatch,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_generated",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"model": result.model,
|
||||
"input_lines": n,
|
||||
"output_lines": m,
|
||||
"iterations_used": iterations_used,
|
||||
"stop_reason": stop_reason.value,
|
||||
"settings": settings.to_dict(),
|
||||
"final_violation_count": sum(1 for v in metadata if not v.passes),
|
||||
"line_count_mismatch": line_count_mismatch,
|
||||
"duration_ms": duration_ms,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _segment_start(seg: Any) -> float:
|
||||
v = seg["start_time"] if isinstance(seg, dict) else seg.start_time
|
||||
return float(v or 0.0)
|
||||
|
||||
@staticmethod
|
||||
def _segment_end(seg: Any) -> float:
|
||||
v = seg["end_time"] if isinstance(seg, dict) else seg.end_time
|
||||
return float(v or 0.0)
|
||||
|
||||
def _prepare_inputs(
|
||||
self,
|
||||
*,
|
||||
custom_text: Optional[str],
|
||||
file_bytes: Optional[bytes],
|
||||
file_mime: Optional[str],
|
||||
file_name: Optional[str],
|
||||
) -> tuple[str, Optional[bytes]]:
|
||||
text_chunks: list[str] = []
|
||||
if custom_text and custom_text.strip():
|
||||
text_chunks.append(custom_text.strip())
|
||||
|
||||
pdf_bytes: Optional[bytes] = None
|
||||
if file_bytes is not None:
|
||||
self._validate_file(file_bytes=file_bytes, file_mime=file_mime, file_name=file_name)
|
||||
kind = SUPPORTED_MIMES[file_mime]
|
||||
if kind == "pdf":
|
||||
pdf_bytes = file_bytes
|
||||
elif kind == "docx":
|
||||
text_chunks.append(self._extract_docx_text(file_bytes))
|
||||
elif kind in ("txt", "md"):
|
||||
text_chunks.append(file_bytes.decode("utf-8", errors="replace"))
|
||||
else:
|
||||
raise CustomLyricsServiceError(
|
||||
f"unsupported file kind: {kind}", status_code=400
|
||||
)
|
||||
|
||||
combined = "\n\n".join(chunk for chunk in text_chunks if chunk.strip())
|
||||
return combined, pdf_bytes
|
||||
|
||||
def _validate_file(
|
||||
self,
|
||||
*,
|
||||
file_bytes: bytes,
|
||||
file_mime: Optional[str],
|
||||
file_name: Optional[str],
|
||||
) -> None:
|
||||
max_bytes = self.settings.custom_lyrics_max_file_mb * 1024 * 1024
|
||||
if len(file_bytes) > max_bytes:
|
||||
raise CustomLyricsServiceError(
|
||||
f"file exceeds {self.settings.custom_lyrics_max_file_mb} MB limit",
|
||||
status_code=400,
|
||||
)
|
||||
if file_mime not in SUPPORTED_MIMES:
|
||||
raise CustomLyricsServiceError(
|
||||
f"unsupported file mime: {file_mime!r}; expected one of "
|
||||
f"{sorted(SUPPORTED_MIMES.keys())}",
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _extract_docx_text(file_bytes: bytes) -> str:
|
||||
try:
|
||||
import docx as docx_mod
|
||||
except ImportError as exc:
|
||||
raise CustomLyricsServiceError(
|
||||
"python-docx is not installed", status_code=500
|
||||
) from exc
|
||||
|
||||
try:
|
||||
doc = docx_mod.Document(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise CustomLyricsServiceError(
|
||||
f"could not parse .docx: {exc}", status_code=400
|
||||
) from exc
|
||||
|
||||
paragraphs = [p.text for p in doc.paragraphs if p.text and p.text.strip()]
|
||||
return "\n".join(paragraphs)
|
||||
|
||||
def _call_gemini(
|
||||
self,
|
||||
*,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
pdf_bytes: Optional[bytes],
|
||||
settings: GenerationSettings,
|
||||
) -> list[str]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
contents: list = [user_prompt]
|
||||
if pdf_bytes is not None:
|
||||
contents.append(
|
||||
types.Part.from_bytes(mime_type="application/pdf", data=pdf_bytes)
|
||||
)
|
||||
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.custom_lyrics_model,
|
||||
contents=contents,
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=0.4,
|
||||
response_mime_type="application/json",
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lines": {"type": "array", "items": {"type": "string"}}
|
||||
},
|
||||
"required": ["lines"],
|
||||
},
|
||||
),
|
||||
)
|
||||
# The model can return no text (safety block, MAX_TOKENS with no content,
|
||||
# empty candidate). `response.text` is then None and json.loads(None) would
|
||||
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
|
||||
# reports a confusing "NetworkError". Surface a clean, diagnosable error.
|
||||
text = response.text
|
||||
if text is None:
|
||||
raise CustomLyricsServiceError(
|
||||
f"The AI returned an empty response ({self._describe_empty_response(response)}). "
|
||||
f"Please try again.",
|
||||
status_code=502,
|
||||
)
|
||||
return self._parse_lines(text)
|
||||
|
||||
@staticmethod
|
||||
def _describe_empty_response(response: Any) -> str:
|
||||
"""Best-effort reason for an empty model response, for logs and messages."""
|
||||
parts: list[str] = []
|
||||
try:
|
||||
block_reason = getattr(getattr(response, "prompt_feedback", None), "block_reason", None)
|
||||
if block_reason:
|
||||
parts.append(f"prompt_block={getattr(block_reason, 'name', block_reason)}")
|
||||
except Exception: # pragma: no cover - defensive
|
||||
pass
|
||||
try:
|
||||
candidates = getattr(response, "candidates", None) or []
|
||||
if candidates:
|
||||
finish = getattr(candidates[0], "finish_reason", None)
|
||||
if finish is not None:
|
||||
parts.append(f"finish_reason={getattr(finish, 'name', finish)}")
|
||||
else:
|
||||
parts.append("no_candidates")
|
||||
except Exception: # pragma: no cover - defensive
|
||||
pass
|
||||
return ", ".join(parts) if parts else "unknown"
|
||||
|
||||
@staticmethod
|
||||
def _parse_lines(text: str) -> list[str]:
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise CustomLyricsServiceError(
|
||||
f"AI returned non-JSON output: {exc}", status_code=502
|
||||
) from exc
|
||||
if not isinstance(data, dict) or "lines" not in data:
|
||||
raise CustomLyricsServiceError(
|
||||
"AI response missing 'lines' field", status_code=502
|
||||
)
|
||||
lines = data["lines"]
|
||||
if not isinstance(lines, list) or not all(isinstance(x, str) for x in lines):
|
||||
raise CustomLyricsServiceError(
|
||||
"AI response 'lines' is not a list of strings", status_code=502
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
_service_instance: Optional[CustomLyricsService] = None
|
||||
|
||||
|
||||
def get_custom_lyrics_service() -> CustomLyricsService:
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = CustomLyricsService()
|
||||
return _service_instance
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Operator-facing generation settings and strictness→params mapping."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, asdict
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
class StrictnessLevel(str, Enum):
|
||||
VERBATIM = "verbatim"
|
||||
LOOSE = "loose"
|
||||
BALANCED = "balanced"
|
||||
TIGHT = "tight"
|
||||
STRICT = "strict"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StrictnessParams:
|
||||
tolerance: int
|
||||
max_iterations: int
|
||||
prompt_phrase: str
|
||||
|
||||
|
||||
_STRICTNESS_TABLE: dict[StrictnessLevel, StrictnessParams] = {
|
||||
StrictnessLevel.VERBATIM: StrictnessParams(
|
||||
tolerance=10**6,
|
||||
max_iterations=0,
|
||||
prompt_phrase="Use the client's text as-is. Rhythm matching is not a goal.",
|
||||
),
|
||||
StrictnessLevel.LOOSE: StrictnessParams(
|
||||
tolerance=4,
|
||||
max_iterations=1,
|
||||
prompt_phrase="Aim to roughly match the original syllable count where convenient.",
|
||||
),
|
||||
StrictnessLevel.BALANCED: StrictnessParams(
|
||||
tolerance=2,
|
||||
max_iterations=2,
|
||||
prompt_phrase="Match each line's syllable count within 2 where possible.",
|
||||
),
|
||||
StrictnessLevel.TIGHT: StrictnessParams(
|
||||
tolerance=1,
|
||||
max_iterations=3,
|
||||
prompt_phrase="Closely match each line's syllable count. Aim for ±1 syllable.",
|
||||
),
|
||||
StrictnessLevel.STRICT: StrictnessParams(
|
||||
tolerance=0,
|
||||
max_iterations=4,
|
||||
prompt_phrase="Match each line's syllable count exactly. Rhythm precision is the priority.",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def params_for(level: StrictnessLevel) -> StrictnessParams:
|
||||
return _STRICTNESS_TABLE[level]
|
||||
|
||||
|
||||
@dataclass
|
||||
class GenerationSettings:
|
||||
allow_reword: bool = True
|
||||
allow_omit: bool = True
|
||||
fixed_line_count: bool = True
|
||||
strictness: StrictnessLevel = StrictnessLevel.BALANCED
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
d = asdict(self)
|
||||
d["strictness"] = self.strictness.value
|
||||
return d
|
||||
|
||||
|
||||
def settings_from_dict(data: dict[str, Any]) -> GenerationSettings:
|
||||
"""Construct GenerationSettings from a partial dict (used by the API layer)."""
|
||||
kwargs: dict[str, Any] = {}
|
||||
if "allow_reword" in data:
|
||||
kwargs["allow_reword"] = bool(data["allow_reword"])
|
||||
if "allow_omit" in data:
|
||||
kwargs["allow_omit"] = bool(data["allow_omit"])
|
||||
if "fixed_line_count" in data:
|
||||
kwargs["fixed_line_count"] = bool(data["fixed_line_count"])
|
||||
if "strictness" in data:
|
||||
kwargs["strictness"] = StrictnessLevel(data["strictness"]) # raises ValueError if invalid
|
||||
return GenerationSettings(**kwargs)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Proportional timing redistribution for variable line count."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class _CounterProtocol(Protocol):
|
||||
def count_per_line(self, line: str) -> list[int]: ...
|
||||
|
||||
|
||||
def _median_count(counts: list[int]) -> int:
|
||||
if not counts:
|
||||
return 0
|
||||
sorted_c = sorted(counts)
|
||||
n = len(sorted_c)
|
||||
if n % 2 == 1:
|
||||
return sorted_c[n // 2]
|
||||
# Even-length: integer-rounded average of the two middle values
|
||||
return (sorted_c[n // 2 - 1] + sorted_c[n // 2]) // 2
|
||||
|
||||
|
||||
def redistribute_timing_proportional(
|
||||
*,
|
||||
new_lines: list[str],
|
||||
total_window: tuple[float, float],
|
||||
counter: _CounterProtocol,
|
||||
) -> list[tuple[float, float]]:
|
||||
"""Distribute `total_window` across `new_lines` proportional to per-line syllable count.
|
||||
|
||||
Falls back to even distribution if all lines have 0 syllables.
|
||||
"""
|
||||
if not new_lines:
|
||||
raise ValueError("new_lines must not be empty")
|
||||
start, end = total_window
|
||||
if end <= start:
|
||||
raise ValueError(f"window invalid: ({start}, {end})")
|
||||
|
||||
syllables = [_median_count(counter.count_per_line(line)) for line in new_lines]
|
||||
total_syl = sum(syllables)
|
||||
|
||||
if total_syl == 0:
|
||||
# Even split fallback
|
||||
per_line = (end - start) / len(new_lines)
|
||||
return [
|
||||
(start + i * per_line, start + (i + 1) * per_line)
|
||||
for i in range(len(new_lines))
|
||||
]
|
||||
|
||||
# Treat zero-syllable lines as weight-1 so they get a non-zero slice.
|
||||
# Otherwise an empty/whitespace line in a mostly-non-empty set yields a
|
||||
# zero-length segment that the timing pipeline downstream may reject.
|
||||
weights = [s if s > 0 else 1 for s in syllables]
|
||||
total_weight = sum(weights)
|
||||
|
||||
out: list[tuple[float, float]] = []
|
||||
cursor = start
|
||||
duration = end - start
|
||||
for i, w in enumerate(weights):
|
||||
if i == len(weights) - 1:
|
||||
out.append((cursor, end)) # last slice goes to exact end (avoid float drift)
|
||||
else:
|
||||
slice_dur = duration * w / total_weight
|
||||
out.append((cursor, cursor + slice_dur))
|
||||
cursor += slice_dur
|
||||
return out
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Pure validator over LLM-generated candidate lines vs. target lines."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
class Severity(str, Enum):
|
||||
OK = "ok"
|
||||
MINOR = "minor"
|
||||
MAJOR = "major"
|
||||
|
||||
|
||||
@dataclass
|
||||
class LineValidation:
|
||||
line_index: int
|
||||
target_text: str
|
||||
candidate_text: str
|
||||
target_syllables: list[int]
|
||||
candidate_syllables: list[int]
|
||||
min_delta: int
|
||||
passes: bool
|
||||
severity: Severity
|
||||
time_budget_seconds: float
|
||||
|
||||
|
||||
class _CounterProtocol(Protocol):
|
||||
def count_per_line(self, line: str) -> list[int]: ...
|
||||
def any_method_within(
|
||||
self, candidate_counts: list[int], target_counts: list[int], tolerance: int
|
||||
) -> bool: ...
|
||||
def min_delta(
|
||||
self, candidate_counts: list[int], target_counts: list[int]
|
||||
) -> int: ...
|
||||
|
||||
|
||||
def _segment_duration(seg: Any) -> float:
|
||||
"""Accepts dict or object with start_time/end_time; returns end - start (>= 0)."""
|
||||
if isinstance(seg, dict):
|
||||
start = seg.get("start_time")
|
||||
end = seg.get("end_time")
|
||||
else:
|
||||
start = getattr(seg, "start_time", None)
|
||||
end = getattr(seg, "end_time", None)
|
||||
if start is None or end is None:
|
||||
return 0.0
|
||||
try:
|
||||
return max(0.0, float(end) - float(start))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def validate(
|
||||
candidate_lines: list[str],
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
counter: _CounterProtocol,
|
||||
tolerance: int,
|
||||
) -> list[LineValidation]:
|
||||
"""Score each candidate line against its target. Pure; no I/O."""
|
||||
if not (len(candidate_lines) == len(target_lines) == len(target_segments)):
|
||||
raise ValueError(
|
||||
f"length mismatch: candidates={len(candidate_lines)} targets={len(target_lines)} "
|
||||
f"segments={len(target_segments)}"
|
||||
)
|
||||
|
||||
out: list[LineValidation] = []
|
||||
for i, (cand, tgt, seg) in enumerate(zip(candidate_lines, target_lines, target_segments)):
|
||||
target_counts = counter.count_per_line(tgt)
|
||||
candidate_counts = counter.count_per_line(cand)
|
||||
delta = counter.min_delta(candidate_counts, target_counts)
|
||||
passes = counter.any_method_within(candidate_counts, target_counts, tolerance)
|
||||
if passes:
|
||||
severity = Severity.OK
|
||||
elif delta <= tolerance + 2:
|
||||
severity = Severity.MINOR
|
||||
else:
|
||||
severity = Severity.MAJOR
|
||||
out.append(
|
||||
LineValidation(
|
||||
line_index=i,
|
||||
target_text=tgt,
|
||||
candidate_text=cand,
|
||||
target_syllables=target_counts,
|
||||
candidate_syllables=candidate_counts,
|
||||
min_delta=delta,
|
||||
passes=passes,
|
||||
severity=severity,
|
||||
time_budget_seconds=_segment_duration(seg),
|
||||
)
|
||||
)
|
||||
return out
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Backward-compat shim. Real implementation lives in backend.services.custom_lyrics."""
|
||||
from backend.services.custom_lyrics.service import (
|
||||
CustomLyricsService,
|
||||
CustomLyricsServiceError,
|
||||
get_custom_lyrics_service,
|
||||
)
|
||||
from backend.services.custom_lyrics.result import CustomLyricsResult, StopReason
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings, StrictnessLevel
|
||||
|
||||
__all__ = [
|
||||
"CustomLyricsService",
|
||||
"CustomLyricsServiceError",
|
||||
"CustomLyricsResult",
|
||||
"GenerationSettings",
|
||||
"StopReason",
|
||||
"StrictnessLevel",
|
||||
"get_custom_lyrics_service",
|
||||
]
|
||||
@@ -151,6 +151,37 @@ class DropboxService:
|
||||
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
|
||||
return next_code
|
||||
|
||||
def file_exists(self, remote_path: str) -> bool:
|
||||
"""
|
||||
Check whether a file exists at the given Dropbox path.
|
||||
|
||||
Args:
|
||||
remote_path: Dropbox path (must start with /)
|
||||
|
||||
Returns:
|
||||
True if a file exists at the path, False otherwise.
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
if not remote_path.startswith("/"):
|
||||
remote_path = f"/{remote_path}"
|
||||
|
||||
try:
|
||||
self.client.files_get_metadata(remote_path)
|
||||
return True
|
||||
except ApiError as e:
|
||||
# Only a genuine "not found" means the file is absent. Re-raise other
|
||||
# API errors (auth, network, rate limit) so callers don't mistake a
|
||||
# transient failure for "missing" (e.g. the backfill uploading a dup).
|
||||
err = e.error
|
||||
if (
|
||||
hasattr(err, "is_path")
|
||||
and err.is_path()
|
||||
and err.get_path().is_not_found()
|
||||
):
|
||||
return False
|
||||
raise
|
||||
|
||||
def upload_file(self, local_path: str, remote_path: str) -> None:
|
||||
"""
|
||||
Upload a single file to Dropbox.
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Reconcile a job's credit charge against the actual audio about to be processed.
|
||||
|
||||
Called at the convergence point immediately before the separation+transcription
|
||||
workers are triggered (post-edit if an edit occurred). The probe callable returns
|
||||
the duration in seconds of `job.input_media_gcs_path` (the to-be-processed audio).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Optional
|
||||
import logging
|
||||
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReconcileResult:
|
||||
action: str # "proceed" | "pause" | "cancel"
|
||||
pending_additional_credits: int = 0
|
||||
actual_seconds: Optional[float] = None
|
||||
|
||||
|
||||
def reconcile_duration(
|
||||
job_id: str,
|
||||
job_manager,
|
||||
user_service,
|
||||
probe_duration: Callable[[object], Optional[float]],
|
||||
email_service=None,
|
||||
) -> ReconcileResult:
|
||||
job = job_manager.get_job(job_id)
|
||||
actual = probe_duration(job)
|
||||
state = dict(job.state_data or {})
|
||||
credits_charged = int(state.get("credits_charged", 1))
|
||||
|
||||
# Short-circuit for admin / payment-bypassed jobs: measure duration for
|
||||
# observability but do NOT pause, charge, refund, or cancel regardless of
|
||||
# how long the audio turns out to be.
|
||||
if state.get("payment_bypassed"):
|
||||
if actual is not None:
|
||||
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
|
||||
logger.info("Job %s: payment_bypassed=True, skipping reconcile (actual=%s s)", job_id, actual)
|
||||
return ReconcileResult(action="proceed", actual_seconds=actual)
|
||||
|
||||
if actual is None:
|
||||
logger.warning("Job %s: duration probe returned None; proceeding without reconcile", job_id)
|
||||
return ReconcileResult(action="proceed", actual_seconds=None)
|
||||
|
||||
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
|
||||
|
||||
if is_blocked(actual):
|
||||
if credits_charged > 0:
|
||||
user_service.add_credits(job.user_email, amount=credits_charged,
|
||||
reason="duration_over_limit_refund", job_id=job_id)
|
||||
job_manager.update_job(job_id, {"credit_refunded": True}) # suppress cancel_job's built-in 1-credit refund (we already refunded the full charge)
|
||||
job_manager.cancel_job(job_id, reason="Input audio exceeds the 60-minute limit")
|
||||
if email_service:
|
||||
email_service.send_duration_confirm_expired(
|
||||
to_email=job.user_email,
|
||||
artist=getattr(job, "artist", None),
|
||||
title=getattr(job, "title", None),
|
||||
credits_refunded=credits_charged,
|
||||
reason="over_limit",
|
||||
)
|
||||
return ReconcileResult(action="cancel", actual_seconds=actual)
|
||||
|
||||
required = duration_to_credits(actual)
|
||||
delta = required - credits_charged
|
||||
|
||||
if delta == 0:
|
||||
return ReconcileResult(action="proceed", actual_seconds=actual)
|
||||
|
||||
if delta < 0:
|
||||
user_service.add_credits(job.user_email, amount=abs(delta),
|
||||
reason="duration_refund", job_id=job_id)
|
||||
job_manager.update_job(job_id, {"state_data.credits_charged": required})
|
||||
return ReconcileResult(action="proceed", actual_seconds=actual)
|
||||
|
||||
# delta > 0 : owe more credits — pause for explicit re-confirmation.
|
||||
job_manager.update_job(job_id, {
|
||||
"state_data.duration_confirm_reason": "reconcile",
|
||||
"state_data.pending_additional_credits": delta,
|
||||
})
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_DURATION_CONFIRM,
|
||||
progress=16,
|
||||
message=f"This turned out longer than estimated — {delta} more credit(s) needed",
|
||||
)
|
||||
return ReconcileResult(action="pause", pending_additional_credits=delta, actual_seconds=actual)
|
||||
|
||||
|
||||
# --- Pipeline wiring (impure: uses singletons + ffprobe) ---
|
||||
|
||||
def _ffprobe_seconds(job, storage) -> Optional[float]:
|
||||
"""Header-only ffprobe of job.input_media_gcs_path via a signed URL.
|
||||
|
||||
Mirrors the async _get_audio_duration_ffprobe_signed helper in
|
||||
backend/api/routes/jobs.py, but as a sync function suitable for use
|
||||
in run_in_executor.
|
||||
"""
|
||||
gcs_path = getattr(job, "input_media_gcs_path", None)
|
||||
if not gcs_path:
|
||||
return None
|
||||
try:
|
||||
signed_url = storage.generate_signed_url(gcs_path, expiration_minutes=5)
|
||||
result = subprocess.run(
|
||||
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", signed_url],
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return float(json.loads(result.stdout)["format"]["duration"])
|
||||
except Exception as e:
|
||||
logger.warning("Job %s: ffprobe duration failed: %s", getattr(job, "id", "?"), e)
|
||||
return None
|
||||
|
||||
|
||||
async def reconcile_and_maybe_pause(job_id: str) -> bool:
|
||||
"""Resolve real singletons, probe duration, run reconcile_duration, return True if blocked.
|
||||
|
||||
Returns True when the job has been paused (AWAITING_DURATION_CONFIRM) or cancelled,
|
||||
meaning the caller must NOT trigger downstream workers.
|
||||
Returns False when the job should proceed normally.
|
||||
|
||||
Designed for the no-edit convergence point in audio_download_worker.py.
|
||||
"""
|
||||
# Import at function scope to avoid circular imports.
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
job_manager = JobManager()
|
||||
user_service = get_user_service()
|
||||
storage = StorageService()
|
||||
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
|
||||
email_service = get_email_service()
|
||||
|
||||
result = await asyncio.get_running_loop().run_in_executor(
|
||||
None,
|
||||
lambda: reconcile_duration(
|
||||
job_id,
|
||||
job_manager,
|
||||
user_service,
|
||||
lambda job: _ffprobe_seconds(job, storage),
|
||||
email_service,
|
||||
),
|
||||
)
|
||||
return result.action in ("pause", "cancel")
|
||||
@@ -2,13 +2,10 @@
|
||||
Email service for sending transactional emails.
|
||||
|
||||
Supports multiple providers:
|
||||
- SendGrid (recommended for production)
|
||||
- Postmark (production)
|
||||
- Console logging (for development/testing)
|
||||
|
||||
Future providers can be added:
|
||||
- Mailgun
|
||||
- AWS SES
|
||||
- Postmark
|
||||
Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
|
||||
"""
|
||||
import html
|
||||
import logging
|
||||
@@ -18,6 +15,8 @@ from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, List
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_prefix
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
@@ -120,15 +119,18 @@ class PreviewEmailProvider(EmailProvider):
|
||||
return self.last_html
|
||||
|
||||
|
||||
class SendGridEmailProvider(EmailProvider):
|
||||
class PostmarkEmailProvider(EmailProvider):
|
||||
"""
|
||||
SendGrid email provider for production.
|
||||
Postmark email provider for production.
|
||||
|
||||
Requires SENDGRID_API_KEY environment variable.
|
||||
Requires POSTMARK_SERVER_TOKEN environment variable. Sends via the
|
||||
Postmark REST API directly (no SDK dependency).
|
||||
"""
|
||||
|
||||
def __init__(self, api_key: str, from_email: str, from_name: str = "Nomad Karaoke"):
|
||||
self.api_key = api_key
|
||||
API_URL = "https://api.postmarkapp.com/email"
|
||||
|
||||
def __init__(self, server_token: str, from_email: str, from_name: str = "Nomad Karaoke"):
|
||||
self.server_token = server_token
|
||||
self.from_email = from_email
|
||||
self.from_name = from_name
|
||||
|
||||
@@ -143,67 +145,66 @@ class SendGridEmailProvider(EmailProvider):
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> bool:
|
||||
try:
|
||||
# Import here to avoid requiring sendgrid in all environments
|
||||
from sendgrid import SendGridAPIClient
|
||||
from sendgrid.helpers.mail import Mail, Email, To, Content, Cc, Bcc
|
||||
|
||||
sg = SendGridAPIClient(api_key=self.api_key)
|
||||
|
||||
# Use override sender if provided (for multi-tenant)
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
"From": f'"{self.from_name}" <{sender_email}>',
|
||||
"To": to_email,
|
||||
"Subject": subject,
|
||||
"HtmlBody": html_content,
|
||||
"MessageStream": "outbound",
|
||||
}
|
||||
if text_content:
|
||||
payload["TextBody"] = text_content
|
||||
|
||||
message = Mail(
|
||||
from_email=Email(sender_email, self.from_name),
|
||||
to_emails=To(to_email),
|
||||
subject=subject,
|
||||
html_content=Content("text/html", html_content)
|
||||
if cc_emails:
|
||||
payload["Cc"] = ", ".join(_dedupe_emails(cc_emails))
|
||||
if bcc_emails:
|
||||
payload["Bcc"] = ", ".join(_dedupe_emails(bcc_emails))
|
||||
|
||||
response = requests.post(
|
||||
self.API_URL,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-Postmark-Server-Token": self.server_token,
|
||||
},
|
||||
json=payload,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
# Add CC recipients if provided (deduplicated and normalized)
|
||||
if cc_emails:
|
||||
# Normalize emails (lowercase, strip whitespace) and deduplicate
|
||||
seen = set()
|
||||
unique_cc_emails = []
|
||||
for cc_email in cc_emails:
|
||||
normalized = cc_email.strip().lower()
|
||||
if normalized and normalized not in seen:
|
||||
seen.add(normalized)
|
||||
unique_cc_emails.append(cc_email.strip())
|
||||
|
||||
for cc_email in unique_cc_emails:
|
||||
message.add_cc(Cc(cc_email))
|
||||
|
||||
# Add BCC recipients if provided (deduplicated and normalized)
|
||||
if bcc_emails:
|
||||
seen = set()
|
||||
unique_bcc_emails = []
|
||||
for bcc_email in bcc_emails:
|
||||
normalized = bcc_email.strip().lower()
|
||||
if normalized and normalized not in seen:
|
||||
seen.add(normalized)
|
||||
unique_bcc_emails.append(bcc_email.strip())
|
||||
|
||||
for bcc_email in unique_bcc_emails:
|
||||
message.add_bcc(Bcc(bcc_email))
|
||||
|
||||
if text_content:
|
||||
message.add_content(Content("text/plain", text_content))
|
||||
|
||||
response = sg.send(message)
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
if 200 <= response.status_code < 300:
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
bcc_info = f" (BCC: {', '.join(bcc_emails)})" if bcc_emails else ""
|
||||
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via SendGrid")
|
||||
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via Postmark")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"SendGrid returned status {response.status_code}")
|
||||
return False
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to send email via SendGrid")
|
||||
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
|
||||
try:
|
||||
err = response.json()
|
||||
logger.error(
|
||||
f"Postmark returned status {response.status_code}: "
|
||||
f"ErrorCode={err.get('ErrorCode')} Message={err.get('Message')}"
|
||||
)
|
||||
except ValueError:
|
||||
logger.error(f"Postmark returned status {response.status_code}: {response.text[:200]}")
|
||||
return False
|
||||
|
||||
except requests.RequestException:
|
||||
logger.exception("Failed to send email via Postmark")
|
||||
return False
|
||||
|
||||
|
||||
def _dedupe_emails(emails: List[str]) -> List[str]:
|
||||
"""Lowercase-normalize and deduplicate a list of email addresses, preserving order."""
|
||||
seen = set()
|
||||
out = []
|
||||
for em in emails:
|
||||
normalized = em.strip().lower()
|
||||
if normalized and normalized not in seen:
|
||||
seen.add(normalized)
|
||||
out.append(em.strip())
|
||||
return out
|
||||
|
||||
|
||||
class EmailService:
|
||||
"""
|
||||
@@ -227,21 +228,25 @@ class EmailService:
|
||||
self.buy_url = os.getenv("BUY_URL", self.frontend_url)
|
||||
|
||||
def _get_provider(self) -> EmailProvider:
|
||||
"""Get the configured email provider."""
|
||||
sendgrid_api_key = os.getenv("SENDGRID_API_KEY")
|
||||
"""Get the configured email provider.
|
||||
|
||||
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
|
||||
back to console logging (dev/test).
|
||||
"""
|
||||
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
|
||||
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
from_name = os.getenv("EMAIL_FROM_NAME", "Nomad Karaoke")
|
||||
|
||||
if sendgrid_api_key:
|
||||
logger.info("Using SendGrid email provider")
|
||||
return SendGridEmailProvider(sendgrid_api_key, from_email, from_name)
|
||||
else:
|
||||
logger.warning("No email provider configured, using console logging")
|
||||
return ConsoleEmailProvider()
|
||||
if postmark_token:
|
||||
logger.info("Using Postmark email provider")
|
||||
return PostmarkEmailProvider(postmark_token, from_email, from_name)
|
||||
|
||||
logger.warning("No email provider configured, using console logging")
|
||||
return ConsoleEmailProvider()
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
"""Check if a real email provider is configured (not just console logging)."""
|
||||
return isinstance(self.provider, SendGridEmailProvider)
|
||||
return isinstance(self.provider, PostmarkEmailProvider)
|
||||
|
||||
def send_magic_link(
|
||||
self,
|
||||
@@ -1115,6 +1120,148 @@ class EmailService:
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_duration_confirm_reminder(
|
||||
self,
|
||||
to_email: str,
|
||||
job_id: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
pending_credits: Optional[int] = None,
|
||||
duration_seconds: Optional[int] = None,
|
||||
confirm_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
|
||||
|
||||
Sent when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes without
|
||||
the user confirming the extra cost.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
job_id: Job ID (used to build the confirm URL if not provided)
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
pending_credits: Number of additional credits required
|
||||
duration_seconds: Actual duration of the song in seconds
|
||||
confirm_url: Direct URL to the confirmation page
|
||||
locale: User's locale (future: translated; currently English)
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
if artist and title:
|
||||
subject = f"Your karaoke job needs you to confirm the cost — {artist} - {title}"
|
||||
else:
|
||||
subject = "Your karaoke job needs you to confirm the cost"
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
background-color: #fef3c7;
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.confirm-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.cost-box {
|
||||
background-color: #f0f9ff;
|
||||
border: 1px solid #93c5fd;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = (
|
||||
f" for <strong>{html.escape(artist)} — {html.escape(title)}</strong>"
|
||||
if artist and title
|
||||
else ""
|
||||
)
|
||||
song_name_text = f" for {artist} — {title}" if artist and title else ""
|
||||
|
||||
# Build cost detail line (best-effort — fields may be absent for older jobs)
|
||||
if pending_credits is not None and duration_seconds is not None:
|
||||
duration_mins = duration_seconds // 60
|
||||
duration_secs = duration_seconds % 60
|
||||
duration_str = f"{duration_mins}:{duration_secs:02d}"
|
||||
cost_detail_html = (
|
||||
f"<p>The song{song_name} turned out to be "
|
||||
f"<strong>{duration_str}</strong> long and requires "
|
||||
f"<strong>{pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''}</strong> to process.</p>"
|
||||
)
|
||||
cost_detail_text = (
|
||||
f"The song{song_name_text} turned out to be {duration_str} long and "
|
||||
f"requires {pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''} to process.\n"
|
||||
)
|
||||
elif pending_credits is not None:
|
||||
cost_detail_html = (
|
||||
f"<p>Processing{song_name} requires "
|
||||
f"<strong>{pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''}</strong>.</p>"
|
||||
)
|
||||
cost_detail_text = (
|
||||
f"Processing{song_name_text} requires {pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''}.\n"
|
||||
)
|
||||
else:
|
||||
cost_detail_html = f"<p>Your karaoke job{song_name} requires a few extra credits to continue.</p>"
|
||||
cost_detail_text = f"Your karaoke job{song_name_text} requires a few extra credits to continue.\n"
|
||||
|
||||
# TODO(i18n): translate subject/body once duration-confirm keys are added to
|
||||
# backend/translations/{locale}.json. URL already uses the locale prefix.
|
||||
locale_prefix = get_locale_prefix(locale)
|
||||
url_to_use = confirm_url or (
|
||||
f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review"
|
||||
if job_id
|
||||
else f"{self.frontend_url}{locale_prefix}/app"
|
||||
)
|
||||
|
||||
content = f"""
|
||||
<div class="alert">
|
||||
⏰ Your job is waiting for your confirmation
|
||||
</div>
|
||||
|
||||
{cost_detail_html}
|
||||
|
||||
<p>Please visit your job to review the cost and confirm whether to continue processing.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(url_to_use)}" class="confirm-btn">Confirm cost & continue</a>
|
||||
</p>
|
||||
|
||||
<p>If you have any questions, just reply to this email — we're happy to help.</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = (
|
||||
f"Your karaoke job is waiting for your confirmation.\n\n"
|
||||
f"{cost_detail_text}\n"
|
||||
f"Please visit your job to confirm: {url_to_use}\n\n"
|
||||
f"If you have any questions, just reply to this email — we're happy to help."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_review_expired(
|
||||
self,
|
||||
to_email: str,
|
||||
@@ -1208,6 +1355,148 @@ class EmailService:
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_duration_confirm_expired(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
credits_refunded: int = 0,
|
||||
locale: str = "en",
|
||||
reason: str = "timeout",
|
||||
) -> bool:
|
||||
"""
|
||||
Send duration-confirm cancellation notification email.
|
||||
|
||||
Two cancellation reasons are supported via the ``reason`` parameter:
|
||||
|
||||
- ``"timeout"`` (default): job was auto-cancelled after 48 hours in
|
||||
AWAITING_DURATION_CONFIRM because the user never confirmed the extra cost.
|
||||
- ``"over_limit"`` : job was immediately cancelled because the audio
|
||||
duration exceeds the supported 60-minute ceiling.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
credits_refunded: Number of credits that were refunded
|
||||
locale: User locale (reserved for future i18n; currently English)
|
||||
reason: "timeout" or "over_limit" — controls the cancellation message
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
if reason == "over_limit":
|
||||
if artist and title:
|
||||
subject = f"Your karaoke job was cancelled — audio exceeds 60 minutes ({artist} - {title})"
|
||||
else:
|
||||
subject = "Your karaoke job was cancelled — audio exceeds 60 minutes"
|
||||
else:
|
||||
if artist and title:
|
||||
subject = f"Your karaoke job was cancelled — cost not confirmed in time ({artist} - {title})"
|
||||
else:
|
||||
subject = "Your karaoke job was cancelled — cost not confirmed in time"
|
||||
|
||||
extra_styles = """
|
||||
.info-box {
|
||||
background-color: #f0f9ff;
|
||||
border: 1px solid #93c5fd;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.credit-badge {
|
||||
display: inline-block;
|
||||
background-color: #22c55e;
|
||||
color: #ffffff;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.create-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
song_name_text = f" for {artist} - {title}" if artist and title else ""
|
||||
credits_word = "credit" if credits_refunded == 1 else "credits"
|
||||
|
||||
refund_notice_html = (
|
||||
f"<p>We've refunded <span class=\"credit-badge\">{credits_refunded} {credits_word}</span> "
|
||||
f"to your account.</p>"
|
||||
if credits_refunded > 0
|
||||
else "<p>Your account has been updated.</p>"
|
||||
)
|
||||
refund_notice_text = (
|
||||
f"We've refunded {credits_refunded} {credits_word} to your account."
|
||||
if credits_refunded > 0
|
||||
else "Your account has been updated."
|
||||
)
|
||||
|
||||
if reason == "over_limit":
|
||||
cancel_reason_html = (
|
||||
f"Your karaoke job{song_name} was automatically cancelled because the audio "
|
||||
f"exceeds the supported 60-minute limit."
|
||||
)
|
||||
cancel_reason_text = (
|
||||
f"Your karaoke job{song_name_text} was automatically cancelled because the "
|
||||
f"audio exceeds the supported 60-minute limit."
|
||||
)
|
||||
else:
|
||||
cancel_reason_html = (
|
||||
f"Your karaoke job{song_name} was automatically cancelled because the extra cost "
|
||||
f"was not confirmed within 48 hours."
|
||||
)
|
||||
cancel_reason_text = (
|
||||
f"Your karaoke job{song_name_text} was automatically cancelled because the extra "
|
||||
f"cost was not confirmed within 48 hours."
|
||||
)
|
||||
|
||||
# TODO(i18n): translate subject/body once duration-confirm keys are added to
|
||||
# backend/translations/{locale}.json. URL already uses the locale prefix.
|
||||
locale_prefix = get_locale_prefix(locale)
|
||||
app_url = f"{self.frontend_url}{locale_prefix}/app"
|
||||
|
||||
content = f"""
|
||||
<div class="info-box">
|
||||
{cancel_reason_html}
|
||||
</div>
|
||||
|
||||
{refund_notice_html}
|
||||
|
||||
<p>You can start a new job at any time — your credits are ready to use.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(app_url)}" class="create-btn">Create a new job</a>
|
||||
</p>
|
||||
|
||||
<p>If you have any questions, just reply to this email — we're happy to help.</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = (
|
||||
f"{cancel_reason_text}\n\n"
|
||||
f"{refund_notice_text}\n\n"
|
||||
f"You can start a new job at any time: {app_url}\n\n"
|
||||
f"If you have any questions, just reply to this email — we're happy to help."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_youtube_upload_complete(
|
||||
self,
|
||||
to_email: str,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Typed exceptions for encoding worker lifecycle failures.
|
||||
|
||||
These let callers distinguish between transient capacity issues (retry will
|
||||
likely help) and unexpected start failures (something is actually broken).
|
||||
"""
|
||||
|
||||
from typing import FrozenSet
|
||||
|
||||
|
||||
CAPACITY_ERROR_CODES: FrozenSet[str] = frozenset({
|
||||
"ZONE_RESOURCE_POOL_EXHAUSTED",
|
||||
"ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS",
|
||||
"STOCKOUT",
|
||||
"QUOTA_EXCEEDED",
|
||||
})
|
||||
|
||||
|
||||
class EncodingWorkerStartError(Exception):
|
||||
"""Raised when an attempt to start an encoding worker VM fails.
|
||||
|
||||
Carries the GCE error code so callers can react to specific failure modes.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
vm_name: str = "",
|
||||
zone: str = "",
|
||||
code: str = "",
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.vm_name = vm_name
|
||||
self.zone = zone
|
||||
self.code = code
|
||||
|
||||
|
||||
class EncodingWorkerCapacityError(EncodingWorkerStartError):
|
||||
"""A capacity-related GCE failure (e.g. ZONE_RESOURCE_POOL_EXHAUSTED).
|
||||
|
||||
The zone temporarily cannot allocate the requested machine type. Callers
|
||||
should treat this as recoverable — retrying after a wait, or trying an
|
||||
alternate zone, is likely to succeed.
|
||||
"""
|
||||
|
||||
|
||||
def classify_gce_error(code: str, message: str, *, vm_name: str, zone: str) -> EncodingWorkerStartError:
|
||||
"""Wrap a GCE error code/message in the appropriate typed exception."""
|
||||
if code in CAPACITY_ERROR_CODES:
|
||||
return EncodingWorkerCapacityError(
|
||||
f"VM {vm_name} could not be started in {zone}: {code} — {message}",
|
||||
vm_name=vm_name,
|
||||
zone=zone,
|
||||
code=code,
|
||||
)
|
||||
return EncodingWorkerStartError(
|
||||
f"VM {vm_name} start failed in {zone}: {code or 'unknown error'} — {message or 'no message'}",
|
||||
vm_name=vm_name,
|
||||
zone=zone,
|
||||
code=code,
|
||||
)
|
||||
@@ -65,6 +65,12 @@ class EncodingOutput:
|
||||
lossless_mkv_path: Optional[str] = None # MKV with FLAC (for YouTube)
|
||||
lossy_720p_mp4_path: Optional[str] = None # 720p web version
|
||||
|
||||
# Standalone 5-second screen videos generated from the title/end images.
|
||||
# Kept so they land in the Dropbox folder (regression after #647/#650 moved
|
||||
# screen generation to the encoder). Not used downstream.
|
||||
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
|
||||
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
|
||||
|
||||
# All output files as a dict for convenience
|
||||
output_files: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@@ -385,6 +391,10 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
elif filename_lower.endswith("(title).mov"):
|
||||
output_files["title_mov"] = path
|
||||
elif filename_lower.endswith("(end).mov"):
|
||||
output_files["end_mov"] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
@@ -396,6 +406,8 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
lossless_mkv_path=output_files.get("mkv_4k"),
|
||||
lossy_720p_mp4_path=output_files.get("mp4_720p"),
|
||||
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
|
||||
title_mov_path=output_files.get("title_mov"),
|
||||
end_mov_path=output_files.get("end_mov"),
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name
|
||||
|
||||
@@ -17,15 +17,36 @@ Usage:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Optional, Dict, Any
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional, Dict, Any, AsyncIterator
|
||||
|
||||
import aiohttp
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.encoding_errors import (
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Per-URL submission throttle. The encoding worker has a ThreadPoolExecutor
|
||||
# of 4 workers (gce_encoding/main.py). Submitting more concurrent jobs than
|
||||
# that to a single VM caused `Connection reset by peer` errors on the 5th+
|
||||
# job during the May 6 fallback storm — 7 jobs simultaneously hammered
|
||||
# fallback-a after the primary failed.
|
||||
#
|
||||
# Limit to 3 concurrent renders per URL per Cloud Run instance, leaving 1
|
||||
# worker thread for status polls / preview / health checks. With multiple
|
||||
# Cloud Run instances this is not a global cap (would require a distributed
|
||||
# lock) but it caps each instance's contribution to the storm — empirically
|
||||
# enough to prevent the failure mode.
|
||||
_DEFAULT_SUBMISSION_CONCURRENCY = int(
|
||||
os.environ.get("ENCODING_SUBMISSION_CONCURRENCY", "3")
|
||||
)
|
||||
|
||||
# Retry configuration for handling transient failures (e.g., worker restarts during deployments).
|
||||
#
|
||||
# During a CI deployment, the encoding worker is restarted via systemctl. The restart
|
||||
@@ -45,6 +66,18 @@ MAX_BACKOFF_SECONDS = 15.0
|
||||
MAX_CONSECUTIVE_POLL_FAILURES = 5
|
||||
|
||||
|
||||
def _format_exception(e: BaseException) -> str:
|
||||
"""Render an exception with type info.
|
||||
|
||||
Some aiohttp connection errors have empty str(e), which made the original
|
||||
"GCE worker connection failed after 8 attempts: " log line useless during
|
||||
the 2026-04-24 cold-start incident (job 2c577535). Always include the
|
||||
type name so operators can tell what failure class hit them.
|
||||
"""
|
||||
msg = str(e)
|
||||
return f"{type(e).__name__}: {msg}" if msg else type(e).__name__
|
||||
|
||||
|
||||
class EncodingService:
|
||||
"""Service for dispatching encoding jobs to GCE worker."""
|
||||
|
||||
@@ -58,12 +91,24 @@ class EncodingService:
|
||||
self._url_cached_at = 0
|
||||
self._URL_CACHE_TTL = 30 # seconds
|
||||
|
||||
# Per-URL submission semaphores. Lazily created on first use so we
|
||||
# don't bind to the wrong event loop at import time. Bound at
|
||||
# _DEFAULT_SUBMISSION_CONCURRENCY to keep concurrent renders per
|
||||
# worker VM under the worker's own ThreadPool capacity.
|
||||
self._url_semaphores: Dict[str, asyncio.Semaphore] = {}
|
||||
self._url_semaphores_lock: Optional[asyncio.Lock] = None
|
||||
self._submission_concurrency = _DEFAULT_SUBMISSION_CONCURRENCY
|
||||
|
||||
def set_worker_manager(self, manager):
|
||||
"""Set the worker manager for dynamic URL resolution from Firestore."""
|
||||
self._worker_manager = manager
|
||||
|
||||
def _get_worker_url(self) -> str:
|
||||
"""Get the current primary worker URL from Firestore (with TTL cache).
|
||||
"""Get the current worker URL from Firestore (with TTL cache).
|
||||
|
||||
Returns config.active_url, which is normally the primary URL but
|
||||
switches to the capacity-fallback override when a primary-zone
|
||||
outage caused us to start a fallback VM in another zone.
|
||||
|
||||
Falls back to static URL from config if worker_manager is not set.
|
||||
"""
|
||||
@@ -73,7 +118,7 @@ class EncodingService:
|
||||
|
||||
if self._worker_manager:
|
||||
config = self._worker_manager.get_config()
|
||||
self._cached_url = config.primary_url
|
||||
self._cached_url = config.active_url
|
||||
self._url_cached_at = now
|
||||
return self._cached_url
|
||||
|
||||
@@ -82,6 +127,105 @@ class EncodingService:
|
||||
self._load_credentials()
|
||||
return self._url
|
||||
|
||||
def _invalidate_cached_url(self) -> None:
|
||||
"""Force the next _get_worker_url() to re-read from Firestore.
|
||||
|
||||
Called after the worker manager updates active_override (e.g. on
|
||||
capacity fallback) so the in-flight request loop picks up the new URL.
|
||||
"""
|
||||
self._cached_url = None
|
||||
self._url_cached_at = 0.0
|
||||
|
||||
@asynccontextmanager
|
||||
async def _submission_slot(self, url: str, job_id: str) -> AsyncIterator[None]:
|
||||
"""Bound the number of concurrent renders/encodes per worker URL.
|
||||
|
||||
The encoding worker has 4 thread-pool workers; submitting 7+ at once
|
||||
causes `Connection reset by peer` mid-encode (observed during the
|
||||
May 6 fallback storm). This semaphore caps each Cloud Run instance's
|
||||
concurrent submissions per URL at `_submission_concurrency`,
|
||||
leaving headroom for status polls and previews.
|
||||
|
||||
Captures the URL at entry — if the worker manager swaps active_url
|
||||
mid-operation (capacity fallback) we keep the original slot. The
|
||||
slot count for the new URL will be slightly understated until the
|
||||
next submission, which is acceptable: the fallback path is rare,
|
||||
and the goal is preventing the orchestrator-side thundering herd.
|
||||
"""
|
||||
# Lazily create the per-loop lock so we bind to the right event loop
|
||||
if self._url_semaphores_lock is None:
|
||||
self._url_semaphores_lock = asyncio.Lock()
|
||||
|
||||
async with self._url_semaphores_lock:
|
||||
sem = self._url_semaphores.get(url)
|
||||
if sem is None:
|
||||
sem = asyncio.Semaphore(self._submission_concurrency)
|
||||
self._url_semaphores[url] = sem
|
||||
|
||||
# Brief log only when we actually have to wait — keeps the happy
|
||||
# path quiet but surfaces contention during a fallback storm.
|
||||
if sem.locked():
|
||||
logger.info(
|
||||
f"[job:{job_id}] Waiting for encoding submission slot "
|
||||
f"(url={url}, in_flight>={self._submission_concurrency})"
|
||||
)
|
||||
async with sem:
|
||||
yield
|
||||
|
||||
def _build_worker_candidates(self) -> list:
|
||||
"""Build the ordered candidate list for ensure_any_running.
|
||||
|
||||
Reads optional fallback VMs from settings (env var
|
||||
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip}). Returns
|
||||
an empty list when no worker manager / no configured fallbacks —
|
||||
caller falls back to the single-VM ensure_primary_running path.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return []
|
||||
try:
|
||||
config = self._worker_manager.get_config()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Could not read worker config for candidates: {_format_exception(e)}")
|
||||
return []
|
||||
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerCandidate
|
||||
|
||||
# Primary always goes first. Single-zone deployments stop here.
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(
|
||||
vm_name=config.primary_vm,
|
||||
zone=self._worker_manager._zone,
|
||||
ip=config.primary_ip,
|
||||
)
|
||||
]
|
||||
|
||||
# Optional capacity-fallback VMs in alternate zones, configured via
|
||||
# env var. Schema: '[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"34.x.x.x"}, ...]'
|
||||
# The list is empty by default; user populates after `pulumi up`
|
||||
# provisions the fallback VMs.
|
||||
import json as _json
|
||||
raw = self.settings.encoding_worker_fallback_vms
|
||||
if not raw:
|
||||
return candidates
|
||||
try:
|
||||
parsed = _json.loads(raw)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
|
||||
return candidates
|
||||
|
||||
for item in parsed:
|
||||
try:
|
||||
candidates.append(EncodingWorkerCandidate(
|
||||
vm_name=item["vm"],
|
||||
zone=item["zone"],
|
||||
ip=item["ip"],
|
||||
))
|
||||
except (KeyError, TypeError) as e:
|
||||
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
|
||||
continue
|
||||
|
||||
return candidates
|
||||
|
||||
def _load_credentials(self):
|
||||
"""Load encoding worker URL and API key from config/secrets."""
|
||||
if self._initialized:
|
||||
@@ -115,27 +259,87 @@ 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:
|
||||
async 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.
|
||||
Two paths:
|
||||
- VM already RUNNING/STAGING (deploy restart): return after the start
|
||||
attempt; the existing 90s retry loop covers the systemctl restart window.
|
||||
- VM was TERMINATED (cold start): block on wait_for_worker_ready until
|
||||
the VM is up and /health returns 200. The next retry attempt will
|
||||
then succeed immediately. If the readiness wait times out, log and
|
||||
return — the retry loop will surface the failure with a clear error.
|
||||
|
||||
If the worker_manager is not set (e.g. dev mode with static URL), this
|
||||
is a no-op.
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: GCE could not allocate capacity (e.g.
|
||||
ZONE_RESOURCE_POOL_EXHAUSTED). Caller should bail out of any
|
||||
retry loop — no point hammering an HTTP endpoint that will
|
||||
never come up — and surface the error to the job.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return
|
||||
|
||||
candidates = self._build_worker_candidates()
|
||||
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"
|
||||
)
|
||||
if candidates and len(candidates) > 1:
|
||||
# Multi-zone path: try primary, then fallbacks in alt zones.
|
||||
result = self._worker_manager.ensure_any_running(candidates)
|
||||
# If we fell back, the worker manager just persisted the
|
||||
# active_override URL — invalidate our cache so the next
|
||||
# request hits the right VM.
|
||||
if result.get("fell_back"):
|
||||
self._invalidate_cached_url()
|
||||
else:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
|
||||
)
|
||||
result = self._worker_manager.ensure_primary_running()
|
||||
except EncodingWorkerStartError:
|
||||
# Every candidate exhausted (or single-zone primary failed) — both
|
||||
# capacity errors and other start failures (e.g. 503
|
||||
# SERVICE_UNAVAILABLE from the GCE backend) are transient and the
|
||||
# render worker should park the job for retry rather than hard-fail
|
||||
# with a misleading "connection timeout" message. EncodingWorker
|
||||
# CapacityError subclasses StartError, so this catches both.
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): "
|
||||
f"{_format_exception(e)}"
|
||||
)
|
||||
return
|
||||
|
||||
if result["started"]:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
|
||||
)
|
||||
try:
|
||||
await self._worker_manager.wait_for_worker_ready(
|
||||
result["vm_name"],
|
||||
f"{result['primary_url']}/health",
|
||||
# Pass the candidate's zone — without this, multi-zone
|
||||
# fallback successfully starts a VM in (e.g.) us-central1-a
|
||||
# but readiness wait looks for it in the manager's default
|
||||
# zone (us-central1-c), gets 404, gives up, and the next
|
||||
# request hits a still-booting VM and times out.
|
||||
zone=result.get("zone"),
|
||||
)
|
||||
logger.info(
|
||||
f"[job:{job_id}] Cold-started VM {result['vm_name']} is now ready"
|
||||
)
|
||||
except TimeoutError as e:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Cold-start readiness wait timed out: {e}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Cold-start readiness wait failed (non-fatal): "
|
||||
f"{_format_exception(e)}"
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
|
||||
)
|
||||
|
||||
async def _request_with_retry(
|
||||
self,
|
||||
@@ -145,6 +349,8 @@ class EncodingService:
|
||||
json_payload: Optional[Dict[str, Any]] = None,
|
||||
timeout: float = 30.0,
|
||||
job_id: str = "unknown",
|
||||
path: Optional[str] = None,
|
||||
allow_failover: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Make an HTTP request with retry logic for transient failures.
|
||||
@@ -154,11 +360,25 @@ class EncodingService:
|
||||
|
||||
Args:
|
||||
method: HTTP method (GET, POST)
|
||||
url: Request URL
|
||||
url: Initial request URL (used for the first attempt)
|
||||
headers: Request headers
|
||||
json_payload: JSON body for POST requests
|
||||
timeout: Request timeout in seconds
|
||||
job_id: Job ID for logging
|
||||
path: Endpoint path (e.g. "/render-video"). When set, retry attempts
|
||||
AFTER the warmup runs re-resolve the URL via _get_worker_url() +
|
||||
path. This is what lets multi-zone fallback take effect mid-loop:
|
||||
the warmup may set a new active_override (e.g. switching to a
|
||||
fallback VM in another zone) and invalidate the URL cache; the
|
||||
next retry then targets the freshly-routed URL instead of the
|
||||
original primary which is dead.
|
||||
allow_failover: When True (default), a connection error fires the
|
||||
fallback-VM warmup and lets retries re-resolve the URL. Set False
|
||||
for requests pinned to a specific worker (in-flight status polls):
|
||||
a pinned poll must never re-route to active_url nor spin up a
|
||||
fallback VM, because a different/fresh VM cannot have the job — it
|
||||
would only return "not found" and orphan a render that is actually
|
||||
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
|
||||
|
||||
Returns:
|
||||
Dict with keys:
|
||||
@@ -173,8 +393,22 @@ class EncodingService:
|
||||
"""
|
||||
last_exception = None
|
||||
backoff = INITIAL_BACKOFF_SECONDS
|
||||
warmup_ran = False
|
||||
|
||||
for attempt in range(MAX_RETRIES + 1):
|
||||
# Re-resolve URL on retries after the warmup has fired, so that any
|
||||
# active_override change made by the warmup actually takes effect.
|
||||
# Without this, all 8 retry attempts hammer the original (dead)
|
||||
# URL even though the warmup successfully routed to a fallback VM.
|
||||
if allow_failover and path and warmup_ran and self._worker_manager is not None:
|
||||
resolved = f"{self._get_worker_url()}{path}"
|
||||
if resolved != url:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Re-resolved encoding URL after warmup: "
|
||||
f"{url} -> {resolved}"
|
||||
)
|
||||
url = resolved
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if method.upper() == "POST":
|
||||
@@ -198,18 +432,33 @@ 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 allow_failover and attempt == 0:
|
||||
try:
|
||||
await self._warmup_encoding_worker_fallback(job_id)
|
||||
warmup_ran = True
|
||||
except EncodingWorkerStartError as start_err:
|
||||
# No VM could be started — capacity exhaustion or
|
||||
# transient backend errors (e.g. 503). Hammering the
|
||||
# HTTP endpoint 7 more times won't help; surface the
|
||||
# typed error so the render worker can park the job
|
||||
# for auto-retry rather than fail hard.
|
||||
logger.error(
|
||||
f"[job:{job_id}] Encoding worker start failed, "
|
||||
f"aborting retries: {start_err}"
|
||||
)
|
||||
raise start_err from e
|
||||
if attempt < MAX_RETRIES:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
|
||||
f"[job:{job_id}] GCE worker connection failed "
|
||||
f"(attempt {attempt + 1}/{MAX_RETRIES + 1}): {_format_exception(e)}. "
|
||||
f"Retrying in {backoff:.1f}s..."
|
||||
)
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 2, MAX_BACKOFF_SECONDS)
|
||||
else:
|
||||
logger.error(
|
||||
f"[job:{job_id}] GCE worker connection failed after {MAX_RETRIES + 1} attempts: {e}"
|
||||
f"[job:{job_id}] GCE worker connection failed "
|
||||
f"after {MAX_RETRIES + 1} attempts: {_format_exception(e)}"
|
||||
)
|
||||
|
||||
raise last_exception
|
||||
@@ -241,7 +490,8 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._get_worker_url()}/encode"
|
||||
path = "/encode"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {
|
||||
"job_id": job_id,
|
||||
@@ -259,6 +509,7 @@ class EncodingService:
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -287,12 +538,23 @@ class EncodingService:
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
|
||||
async def get_job_status(
|
||||
self, job_id: str, worker_url: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the status of an encoding job.
|
||||
|
||||
Args:
|
||||
job_id: Job identifier
|
||||
worker_url: When set, pin the request to this worker base URL instead
|
||||
of resolving the current active_url. In-flight polls must stay on
|
||||
the worker that accepted the job: a blue-green deploy can swap the
|
||||
active_url primary pointer mid-render, and an unpinned poll would
|
||||
migrate to the new primary — which never received the job and 404s
|
||||
"not found", orphaning a render that is succeeding on the original
|
||||
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
|
||||
disables failover (allow_failover=False) so it never re-routes nor
|
||||
starts a fallback VM.
|
||||
|
||||
Returns:
|
||||
Job status including: status, progress, error, output_files
|
||||
@@ -302,7 +564,11 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._get_worker_url()}/status/{job_id}"
|
||||
path = f"/status/{job_id}"
|
||||
if worker_url:
|
||||
url = f"{worker_url}{path}"
|
||||
else:
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
@@ -311,6 +577,10 @@ class EncodingService:
|
||||
headers=headers,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
# When pinned, never re-resolve or fail over — the job lives on this
|
||||
# exact worker; do not pass `path` (which drives re-resolution).
|
||||
path=None if worker_url else path,
|
||||
allow_failover=not worker_url,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -328,6 +598,7 @@ class EncodingService:
|
||||
poll_interval: float = 10.0,
|
||||
timeout: float = 3600.0,
|
||||
progress_callback=None,
|
||||
worker_url: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Poll for encoding job completion with tolerance for transient failures.
|
||||
@@ -342,6 +613,11 @@ class EncodingService:
|
||||
poll_interval: Seconds between status checks
|
||||
timeout: Maximum time to wait (default 1 hour)
|
||||
progress_callback: Optional callback(progress: int) for progress updates
|
||||
worker_url: Worker base URL the job was submitted to. When set, every
|
||||
poll is pinned to this worker (see get_job_status) so a mid-render
|
||||
blue-green primary swap can't migrate the poll to a worker that
|
||||
never received the job. When None, polls resolve active_url (legacy
|
||||
behaviour, e.g. direct callers/tests).
|
||||
|
||||
Returns:
|
||||
Final job status with output files
|
||||
@@ -362,7 +638,7 @@ class EncodingService:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
status = await self.get_job_status(job_id, worker_url=worker_url)
|
||||
# Reset failure counter on successful poll
|
||||
consecutive_failures = 0
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
|
||||
@@ -425,7 +701,10 @@ class EncodingService:
|
||||
"""
|
||||
Submit encoding job and wait for completion.
|
||||
|
||||
This is a convenience method that combines submit + wait.
|
||||
This is a convenience method that combines submit + wait. The
|
||||
submission is bounded by a per-URL semaphore so concurrent renders
|
||||
from the same Cloud Run instance can't overwhelm a single worker
|
||||
VM (see `_submission_slot`).
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
@@ -439,23 +718,36 @@ class EncodingService:
|
||||
"""
|
||||
config = encoding_config or {"formats": ["mp4_4k", "mp4_720p"]}
|
||||
|
||||
# Submit the job
|
||||
submit_result = await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
# Resolve URL up front so the semaphore is keyed by the actual
|
||||
# target VM (matters when capacity fallback is active — see
|
||||
# _submission_slot for the URL-change semantics).
|
||||
target_url = self._get_worker_url()
|
||||
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
async with self._submission_slot(target_url, job_id):
|
||||
# Submit the job
|
||||
submit_result = await self.submit_encoding_job(
|
||||
job_id, input_gcs_path, output_gcs_path, config,
|
||||
)
|
||||
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actually doing CPU work for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
|
||||
async def submit_preview_encoding_job(
|
||||
self,
|
||||
@@ -490,7 +782,8 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._get_worker_url()}/encode-preview"
|
||||
path = "/encode-preview"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {
|
||||
"job_id": job_id,
|
||||
@@ -513,6 +806,7 @@ class EncodingService:
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -577,11 +871,15 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion with shorter timeout
|
||||
return await self.wait_for_completion(
|
||||
job_id=job_id,
|
||||
poll_interval=poll_interval,
|
||||
timeout=timeout,
|
||||
worker_url=pinned_url,
|
||||
)
|
||||
|
||||
async def submit_render_video_job(
|
||||
@@ -608,7 +906,8 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._get_worker_url()}/render-video"
|
||||
path = "/render-video"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {"job_id": job_id, **render_config}
|
||||
|
||||
@@ -621,6 +920,7 @@ class EncodingService:
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -662,7 +962,10 @@ class EncodingService:
|
||||
"""
|
||||
Submit render-video job and wait for completion.
|
||||
|
||||
This is a convenience method that combines submit + wait.
|
||||
This is a convenience method that combines submit + wait. The
|
||||
submission is bounded by a per-URL semaphore so concurrent renders
|
||||
from the same Cloud Run instance can't overwhelm a single worker
|
||||
VM (see `_submission_slot`).
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
@@ -672,27 +975,43 @@ class EncodingService:
|
||||
Returns:
|
||||
Final job status with output files and metadata
|
||||
"""
|
||||
# Submit the job
|
||||
submit_result = await self.submit_render_video_job(job_id, render_config)
|
||||
# Resolve URL up front so the semaphore is keyed by the actual
|
||||
# target VM. If capacity fallback later swaps active_url, the slot
|
||||
# accounting is slightly off for that operation but the new
|
||||
# submissions land on the right counter.
|
||||
target_url = self._get_worker_url()
|
||||
|
||||
# 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"),
|
||||
}
|
||||
async with self._submission_slot(target_url, job_id):
|
||||
# Submit the job
|
||||
submit_result = await self.submit_render_video_job(job_id, render_config)
|
||||
|
||||
# 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")
|
||||
# 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"),
|
||||
}
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
# 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")
|
||||
|
||||
# Pin status polls to the worker the job actually landed on. Resolving
|
||||
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
|
||||
# the URL cache) while being BEFORE any later blue-green deploy swap —
|
||||
# so the poll follows the job, not the floating active_url primary
|
||||
# pointer (incident 2026-06-16, job d3af33ae).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actively rendering for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -25,15 +25,29 @@ Usage:
|
||||
result = manager.ensure_primary_running()
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, UTC
|
||||
from typing import Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
import aiohttp
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.services.encoding_errors import (
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
classify_gce_error,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# How long to wait for a compute.instances.start operation to settle. The GCE
|
||||
# operation itself is fast (1-2s) — we just need to know whether it succeeded
|
||||
# or returned an immediate error like ZONE_RESOURCE_POOL_EXHAUSTED.
|
||||
START_OPERATION_TIMEOUT_SECONDS = 30.0
|
||||
|
||||
CONFIG_COLLECTION = "config"
|
||||
CONFIG_DOCUMENT = "encoding-worker"
|
||||
ENCODING_WORKER_PORT = 8080
|
||||
@@ -55,6 +69,14 @@ class EncodingWorkerConfig:
|
||||
last_activity_at: Optional[str]
|
||||
deploy_in_progress: bool
|
||||
deploy_in_progress_since: Optional[str]
|
||||
# Optional capacity-fallback override: when ensure_any_running falls back
|
||||
# to a non-primary VM (e.g. due to ZONE_RESOURCE_POOL_EXHAUSTED), these
|
||||
# fields point at the active fallback so requests target the right VM.
|
||||
# Cleared when the primary becomes healthy again.
|
||||
active_override_vm: Optional[str] = None
|
||||
active_override_ip: Optional[str] = None
|
||||
active_override_zone: Optional[str] = None
|
||||
active_override_set_at: Optional[str] = None
|
||||
|
||||
@property
|
||||
def primary_url(self) -> str:
|
||||
@@ -64,6 +86,37 @@ class EncodingWorkerConfig:
|
||||
def secondary_url(self) -> str:
|
||||
return f"http://{self.secondary_ip}:{ENCODING_WORKER_PORT}"
|
||||
|
||||
@property
|
||||
def active_url(self) -> str:
|
||||
"""URL the encoding service should target right now.
|
||||
|
||||
Returns the capacity-fallback override if set, otherwise the primary
|
||||
URL. The override mechanism lets us route around a zone that's
|
||||
temporarily out of c4d-highcpu-32 capacity without rewriting the
|
||||
blue-green primary/secondary tracking.
|
||||
"""
|
||||
if self.active_override_ip:
|
||||
return f"http://{self.active_override_ip}:{ENCODING_WORKER_PORT}"
|
||||
return self.primary_url
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncodingWorkerCandidate:
|
||||
"""A VM that ensure_any_running may try to start.
|
||||
|
||||
Carries everything needed to talk to the worker: VM name + zone (so the
|
||||
GCE compute client targets the right zone) and external IP (so successful
|
||||
starts can be persisted as the active URL override).
|
||||
"""
|
||||
|
||||
vm_name: str
|
||||
zone: str
|
||||
ip: str
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return f"http://{self.ip}:{ENCODING_WORKER_PORT}"
|
||||
|
||||
|
||||
class EncodingWorkerManager:
|
||||
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
|
||||
@@ -104,6 +157,10 @@ class EncodingWorkerManager:
|
||||
last_activity_at=data.get("last_activity_at"),
|
||||
deploy_in_progress=data.get("deploy_in_progress", False),
|
||||
deploy_in_progress_since=data.get("deploy_in_progress_since"),
|
||||
active_override_vm=data.get("active_override_vm"),
|
||||
active_override_ip=data.get("active_override_ip"),
|
||||
active_override_zone=data.get("active_override_zone"),
|
||||
active_override_set_at=data.get("active_override_set_at"),
|
||||
)
|
||||
|
||||
def update_activity(self) -> None:
|
||||
@@ -161,55 +218,81 @@ class EncodingWorkerManager:
|
||||
# VM lifecycle operations (Task 2)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_vm_status(self, vm_name: str) -> str:
|
||||
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING)."""
|
||||
def get_vm_status(self, vm_name: str, zone: Optional[str] = None) -> str:
|
||||
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING).
|
||||
|
||||
Pass `zone` for fallback VMs that live in alternate zones.
|
||||
"""
|
||||
instance = self._compute.get(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
zone=zone or self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
return instance.status
|
||||
|
||||
def start_vm(self, vm_name: str) -> None:
|
||||
def start_vm(self, vm_name: str, zone: Optional[str] = None) -> None:
|
||||
"""Start a VM if it is not already running or starting.
|
||||
|
||||
Fire-and-forget: returns immediately. Caller should poll get_vm_status
|
||||
if they need to wait for the VM to be fully RUNNING.
|
||||
Waits for the start operation to complete and raises a typed error if
|
||||
GCE rejects the request (e.g. ZONE_RESOURCE_POOL_EXHAUSTED). Caller
|
||||
should still poll get_vm_status / wait_for_worker_ready before
|
||||
dispatching work — operation success only means GCE accepted the start,
|
||||
not that the VM has finished booting.
|
||||
|
||||
Args:
|
||||
vm_name: VM to start.
|
||||
zone: Override the manager's default zone. Required when starting
|
||||
capacity-fallback VMs in alternate zones.
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: zone is out of capacity for the
|
||||
machine type. Retry from a different zone or after a wait.
|
||||
EncodingWorkerStartError: any other start failure.
|
||||
"""
|
||||
status = self.get_vm_status(vm_name)
|
||||
target_zone = zone or self._zone
|
||||
status = self.get_vm_status(vm_name, zone=target_zone)
|
||||
if status in ("RUNNING", "STAGING"):
|
||||
logger.info("VM %s is already %s, skipping start", vm_name, status)
|
||||
return
|
||||
logger.info("Starting VM %s (current status: %s)", vm_name, status)
|
||||
self._compute.start(
|
||||
logger.info("Starting VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
|
||||
operation = self._compute.start(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
zone=target_zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
self._wait_for_compute_operation(operation, vm_name=vm_name, zone=target_zone)
|
||||
|
||||
def stop_vm(self, vm_name: str) -> None:
|
||||
def stop_vm(self, vm_name: str, zone: Optional[str] = None) -> None:
|
||||
"""Stop a VM if it is not already stopped or stopping."""
|
||||
status = self.get_vm_status(vm_name)
|
||||
target_zone = zone or self._zone
|
||||
status = self.get_vm_status(vm_name, zone=target_zone)
|
||||
if status in ("TERMINATED", "STOPPING"):
|
||||
logger.info("VM %s is already %s, skipping stop", vm_name, status)
|
||||
return
|
||||
logger.info("Stopping VM %s (current status: %s)", vm_name, status)
|
||||
logger.info("Stopping VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
|
||||
self._compute.stop(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
zone=target_zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
|
||||
def ensure_primary_running(self) -> dict:
|
||||
"""Ensure the primary encoding worker VM is running.
|
||||
|
||||
Reads config, starts primary VM if stopped, and updates activity timestamp.
|
||||
Reads config, starts primary VM if stopped, and updates activity
|
||||
timestamp. Waits for the start operation to settle so that capacity
|
||||
errors surface immediately instead of being hidden behind a 120s
|
||||
readiness wait.
|
||||
|
||||
Returns:
|
||||
dict with keys:
|
||||
- started (bool): True if VM was started, False if already running
|
||||
- vm_name (str): Name of the primary VM
|
||||
- primary_url (str): URL of the primary encoding worker
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: zone is exhausted for the machine type.
|
||||
EncodingWorkerStartError: any other start failure.
|
||||
"""
|
||||
config = self.get_config()
|
||||
vm_name = config.primary_vm
|
||||
@@ -219,11 +302,12 @@ class EncodingWorkerManager:
|
||||
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info("Primary VM %s is %s, starting it", vm_name, status)
|
||||
self._compute.start(
|
||||
operation = self._compute.start(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
self._wait_for_compute_operation(operation, vm_name=vm_name, zone=self._zone)
|
||||
started = True
|
||||
else:
|
||||
logger.info("Primary VM %s is already %s", vm_name, status)
|
||||
@@ -233,7 +317,267 @@ class EncodingWorkerManager:
|
||||
return {
|
||||
"started": started,
|
||||
"vm_name": vm_name,
|
||||
"zone": self._zone,
|
||||
"primary_url": config.primary_url,
|
||||
}
|
||||
|
||||
def ensure_any_running(self, candidates: list) -> dict:
|
||||
"""Start the first candidate VM that GCE accepts; raise if all are exhausted.
|
||||
|
||||
Iterates `candidates` in order, attempting to start each one. A
|
||||
capacity error (ZONE_RESOURCE_POOL_EXHAUSTED, etc.) on candidate N
|
||||
triggers a try of candidate N+1. Other start failures abort the
|
||||
whole call.
|
||||
|
||||
On fallback success (a non-first candidate started), persists the
|
||||
fallback's URL as `active_override_*` in Firestore so subsequent
|
||||
encoding requests target the right VM. The first candidate (the
|
||||
primary) succeeding clears any stale override.
|
||||
|
||||
Args:
|
||||
candidates: List of EncodingWorkerCandidate, ordered by preference.
|
||||
Typically [primary, secondary, *fallbacks_in_alt_zones].
|
||||
|
||||
Returns:
|
||||
dict {started, vm_name, zone, primary_url, fell_back}
|
||||
fell_back is True iff the chosen VM is not the first candidate.
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: all candidates rejected with
|
||||
capacity errors.
|
||||
EncodingWorkerStartError: any non-capacity start failure.
|
||||
ValueError: empty candidate list.
|
||||
"""
|
||||
if not candidates:
|
||||
raise ValueError("ensure_any_running requires at least one candidate")
|
||||
|
||||
# Track the last error so we can raise something representative if
|
||||
# every candidate fails. Capacity errors are preferred (they're more
|
||||
# actionable for the user-facing message) but generic start errors
|
||||
# also trigger fallback — observed failure modes include 503
|
||||
# SERVICE_UNAVAILABLE from the GCE backend, which behaves like
|
||||
# capacity exhaustion (transient, retry on a different VM/zone helps).
|
||||
last_capacity_error: Optional[EncodingWorkerCapacityError] = None
|
||||
last_start_error: Optional[EncodingWorkerStartError] = None
|
||||
for index, candidate in enumerate(candidates):
|
||||
try:
|
||||
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
|
||||
started = False
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info(
|
||||
"Trying candidate %d/%d: VM %s in %s (status %s)",
|
||||
index + 1, len(candidates), candidate.vm_name,
|
||||
candidate.zone, status,
|
||||
)
|
||||
self.start_vm(candidate.vm_name, zone=candidate.zone)
|
||||
started = True
|
||||
|
||||
self.update_activity()
|
||||
fell_back = index > 0
|
||||
if fell_back:
|
||||
self._set_active_override(candidate)
|
||||
else:
|
||||
self._clear_active_override()
|
||||
|
||||
return {
|
||||
"started": started,
|
||||
"vm_name": candidate.vm_name,
|
||||
"zone": candidate.zone,
|
||||
"primary_url": candidate.url,
|
||||
"fell_back": fell_back,
|
||||
}
|
||||
except EncodingWorkerCapacityError as cap_err:
|
||||
logger.warning(
|
||||
"Candidate %s in %s exhausted (%s), trying next candidate",
|
||||
candidate.vm_name, candidate.zone, cap_err.code,
|
||||
)
|
||||
last_capacity_error = cap_err
|
||||
last_start_error = cap_err
|
||||
continue
|
||||
except EncodingWorkerStartError as start_err:
|
||||
# Other start failures (e.g. 503 SERVICE_UNAVAILABLE from the
|
||||
# GCE backend) are also transient — try the next candidate
|
||||
# rather than giving up. If all candidates fail with these
|
||||
# generic errors and no candidate hit a capacity error, we
|
||||
# surface the last generic error.
|
||||
logger.warning(
|
||||
"Candidate %s in %s start failed (%s), trying next candidate",
|
||||
candidate.vm_name, candidate.zone, start_err.code or "no-code",
|
||||
)
|
||||
last_start_error = start_err
|
||||
continue
|
||||
|
||||
# Every candidate failed. Prefer raising the capacity error if any
|
||||
# candidate hit one (more actionable for the caller / user message).
|
||||
if last_capacity_error is not None:
|
||||
raise last_capacity_error
|
||||
assert last_start_error is not None
|
||||
raise last_start_error
|
||||
|
||||
def _set_active_override(self, candidate) -> None:
|
||||
"""Record a fallback VM as the active worker URL in Firestore."""
|
||||
now = datetime.now(UTC).isoformat()
|
||||
self._doc_ref().update({
|
||||
"active_override_vm": candidate.vm_name,
|
||||
"active_override_ip": candidate.ip,
|
||||
"active_override_zone": candidate.zone,
|
||||
"active_override_set_at": now,
|
||||
})
|
||||
logger.info(
|
||||
"Set active_override to %s in %s (capacity fallback)",
|
||||
candidate.vm_name, candidate.zone,
|
||||
)
|
||||
|
||||
def _clear_active_override(self) -> None:
|
||||
"""Clear active_override fields (primary is healthy again).
|
||||
|
||||
Idempotent: safe to call when no override is currently set.
|
||||
"""
|
||||
snapshot = self._doc_ref().get()
|
||||
if not snapshot.exists:
|
||||
return
|
||||
data = snapshot.to_dict() or {}
|
||||
if not data.get("active_override_vm"):
|
||||
return # nothing to clear
|
||||
self._doc_ref().update({
|
||||
"active_override_vm": None,
|
||||
"active_override_ip": None,
|
||||
"active_override_zone": None,
|
||||
"active_override_set_at": None,
|
||||
})
|
||||
logger.info("Cleared active_override (primary is healthy again)")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Compute operation helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _wait_for_compute_operation(
|
||||
self,
|
||||
operation: Any,
|
||||
*,
|
||||
vm_name: str,
|
||||
zone: str,
|
||||
timeout: float = START_OPERATION_TIMEOUT_SECONDS,
|
||||
) -> None:
|
||||
"""Block on a compute v1 ExtendedOperation; raise typed exceptions on error.
|
||||
|
||||
google.cloud.compute_v1 returns an ExtendedOperation. Calling .result()
|
||||
blocks until done; successful operations return None, failures raise.
|
||||
Some failure modes set .error_code/.error_message on the operation
|
||||
without raising (depending on SDK version), so we check both paths.
|
||||
"""
|
||||
result_exc: Optional[BaseException] = None
|
||||
try:
|
||||
if hasattr(operation, "result"):
|
||||
operation.result(timeout=timeout)
|
||||
except Exception as e: # noqa: BLE001 — we re-raise as a typed error below
|
||||
result_exc = e
|
||||
|
||||
code = (getattr(operation, "error_code", "") or "")
|
||||
message = (getattr(operation, "error_message", "") or "")
|
||||
|
||||
if not code and result_exc is None:
|
||||
return # Success.
|
||||
|
||||
if not code and result_exc is not None:
|
||||
# Operation raised but did not set error_code (e.g. timeout, transport
|
||||
# failure). Fall back to the raised exception text.
|
||||
raise EncodingWorkerStartError(
|
||||
f"VM {vm_name} start operation failed in {zone}: {result_exc}",
|
||||
vm_name=vm_name,
|
||||
zone=zone,
|
||||
code="",
|
||||
) from result_exc
|
||||
|
||||
# error_code populated — classify it.
|
||||
raise classify_gce_error(code, message, vm_name=vm_name, zone=zone) from result_exc
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Task 3: cold-start readiness gate
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def wait_for_worker_ready(
|
||||
self,
|
||||
vm_name: str,
|
||||
health_url: str,
|
||||
*,
|
||||
zone: Optional[str] = None,
|
||||
vm_timeout: float = 120.0,
|
||||
health_timeout: float = 180.0,
|
||||
poll_interval: float = 5.0,
|
||||
) -> None:
|
||||
"""Block until the VM is RUNNING and the worker /health endpoint returns 200.
|
||||
|
||||
Two-phase wait, used after ensure_primary_running() reports started=True
|
||||
(i.e., the VM was actually TERMINATED and is cold-booting):
|
||||
|
||||
Phase 1 — poll get_vm_status until RUNNING (max vm_timeout seconds)
|
||||
Phase 2 — poll GET health_url until 200 (max health_timeout seconds)
|
||||
|
||||
Connection errors and non-200 responses during phase 2 are treated as
|
||||
"not ready, keep polling". A TimeoutError is raised if either phase
|
||||
exceeds its budget.
|
||||
|
||||
Args:
|
||||
vm_name: Name of the GCE VM to poll.
|
||||
health_url: Full URL of the worker /health endpoint
|
||||
(e.g. "http://10.0.0.1:8080/health").
|
||||
zone: Override the manager's default zone. Required when waiting on
|
||||
capacity-fallback VMs that live in alternate zones — without
|
||||
this override the status poll hits the wrong zone and 404s
|
||||
("instance not found"), the readiness wait gives up, and the
|
||||
next request hits a VM that hasn't finished booting.
|
||||
vm_timeout: Max seconds to wait for VM RUNNING.
|
||||
health_timeout: Max seconds to wait for /health 200.
|
||||
poll_interval: Seconds between polls in either phase.
|
||||
|
||||
Raises:
|
||||
TimeoutError: If VM never reaches RUNNING, or /health never returns 200.
|
||||
"""
|
||||
# Phase 1: VM status
|
||||
loop = asyncio.get_event_loop()
|
||||
deadline = loop.time() + vm_timeout
|
||||
last_status = None
|
||||
last_log = 0.0
|
||||
while loop.time() < deadline:
|
||||
last_status = self.get_vm_status(vm_name, zone=zone)
|
||||
if last_status == "RUNNING":
|
||||
logger.info("VM %s reached RUNNING", vm_name)
|
||||
break
|
||||
now = loop.time()
|
||||
if now - last_log >= 30.0:
|
||||
logger.info("Waiting for VM %s (status=%s)", vm_name, last_status)
|
||||
last_log = now
|
||||
await asyncio.sleep(poll_interval)
|
||||
else:
|
||||
raise TimeoutError(
|
||||
f"VM {vm_name} did not reach RUNNING within {vm_timeout}s "
|
||||
f"(last status: {last_status})"
|
||||
)
|
||||
|
||||
# Phase 2: worker /health
|
||||
deadline = loop.time() + health_timeout
|
||||
last_log = 0.0
|
||||
last_detail = "no response"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
while loop.time() < deadline:
|
||||
try:
|
||||
async with session.get(health_url, timeout=5.0) as resp:
|
||||
if resp.status == 200:
|
||||
logger.info("Worker at %s is healthy", health_url)
|
||||
return
|
||||
last_detail = f"HTTP {resp.status}"
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as e:
|
||||
last_detail = f"{type(e).__name__}: {e}" if str(e) else type(e).__name__
|
||||
now = loop.time()
|
||||
if now - last_log >= 30.0:
|
||||
logger.info("Waiting for worker /health at %s (last: %s)", health_url, last_detail)
|
||||
last_log = now
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
raise TimeoutError(
|
||||
f"Worker at {health_url} did not become healthy within {health_timeout}s "
|
||||
f"(last: {last_detail})"
|
||||
)
|
||||
|
||||
|
||||
@@ -177,7 +177,23 @@ class FirestoreService:
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
|
||||
"""List all jobs belonging to a Bulk Mode batch (state_data.batch_id == batch_id).
|
||||
|
||||
Single-field equality, so no composite index is required.
|
||||
"""
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(self.collection)
|
||||
.where(filter=FieldFilter('state_data.batch_id', '==', batch_id))
|
||||
.limit(limit)
|
||||
)
|
||||
return [Job(**doc.to_dict()) for doc in query.stream()]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs for batch {batch_id}: {e}")
|
||||
raise
|
||||
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
@@ -188,6 +204,14 @@ class FirestoreService:
|
||||
'state_data.audio_progress', 'state_data.lyrics_progress',
|
||||
'state_data.audio_complete', 'state_data.lyrics_complete',
|
||||
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
|
||||
'state_data.render_pending_capacity',
|
||||
'state_data.cloud_run_retry_pending',
|
||||
'state_data.credits_charged',
|
||||
'state_data.pending_additional_credits',
|
||||
'state_data.duration_actual_seconds',
|
||||
'state_data.duration_confirm_reason',
|
||||
'state_data.batch_id',
|
||||
'state_data.bulk_auto_selected',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
'processing_metadata',
|
||||
]
|
||||
|
||||
@@ -680,7 +680,8 @@ class FlacfetchClient:
|
||||
|
||||
Returns:
|
||||
Dict with keys: available, video_id, title, error,
|
||||
is_geo_restricted, is_age_restricted, is_private, is_removed
|
||||
is_geo_restricted, is_age_restricted, is_private, is_removed,
|
||||
is_bot_blocked
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On request failure
|
||||
|
||||
@@ -11,6 +11,7 @@ import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
@@ -19,10 +20,48 @@ from google.cloud import storage
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .persistence import JobStatePersister
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(title="Encoding Worker", version="1.0.0")
|
||||
|
||||
# Job tracking — process-local dict, mirrored to Firestore via `persister`
|
||||
# so polls after a worker restart return the *last known* status instead of
|
||||
# 404. Hot path stays in-memory; persistence is best-effort.
|
||||
jobs: dict[str, dict] = {}
|
||||
executor = ThreadPoolExecutor(max_workers=4) # 4 parallel encoding jobs
|
||||
|
||||
# Persister is initialized lazily — see persistence.py — so import-time
|
||||
# stays free of GCP creds. Tests can monkey-patch this attribute.
|
||||
persister = JobStatePersister()
|
||||
|
||||
|
||||
def _persist(job_id: str) -> None:
|
||||
"""Mirror a job's current state to Firestore (best-effort, never raises)."""
|
||||
state = jobs.get(job_id)
|
||||
if state is not None:
|
||||
persister.save(state)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup: read back any in-progress jobs from Firestore. They were
|
||||
# interrupted by the restart that brought us here — their work_dir is
|
||||
# gone, so mark them failed with the restart code so polls return a
|
||||
# clear failure instead of 404.
|
||||
try:
|
||||
marked = persister.mark_orphans_failed_on_startup(jobs)
|
||||
if marked:
|
||||
logger.warning(
|
||||
"Marked %d orphaned encoding job(s) failed on startup", marked,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Encoding worker startup orphan-recovery failed: %r", exc)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="Encoding Worker", version="1.0.0", lifespan=lifespan)
|
||||
|
||||
# API key authentication
|
||||
API_KEY = os.environ.get("ENCODING_API_KEY", "")
|
||||
@@ -37,10 +76,6 @@ async def verify_api_key(x_api_key: str = Header(None)):
|
||||
raise HTTPException(status_code=401, detail="Invalid API key")
|
||||
return True
|
||||
|
||||
# Job tracking
|
||||
jobs: dict[str, dict] = {}
|
||||
executor = ThreadPoolExecutor(max_workers=4) # 4 parallel encoding jobs
|
||||
|
||||
# GCS client
|
||||
storage_client = storage.Client()
|
||||
|
||||
@@ -213,6 +248,7 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
# Run FFmpeg encoding for preview video (480x270, fast settings)
|
||||
jobs[job_id]["status"] = "running"
|
||||
jobs[job_id]["progress"] = 10
|
||||
_persist(job_id)
|
||||
|
||||
try:
|
||||
# Download input files
|
||||
@@ -309,6 +345,7 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
logger.error(f"Preview encoding failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
raise
|
||||
|
||||
|
||||
@@ -324,6 +361,7 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
"""
|
||||
jobs[job_id]["status"] = "running"
|
||||
jobs[job_id]["progress"] = 5
|
||||
_persist(job_id)
|
||||
|
||||
try:
|
||||
# Import from installed karaoke-gen wheel
|
||||
@@ -490,12 +528,14 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
logger.error(error_msg)
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = error_msg
|
||||
_persist(job_id)
|
||||
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)
|
||||
_persist(job_id)
|
||||
raise
|
||||
|
||||
|
||||
@@ -617,6 +657,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
'''
|
||||
jobs[job_id]["status"] = "running"
|
||||
jobs[job_id]["progress"] = 10
|
||||
_persist(job_id)
|
||||
|
||||
try:
|
||||
# Import LocalEncodingService from installed wheel (required, no fallback)
|
||||
@@ -786,6 +827,20 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
|
||||
jobs[job_id]["progress"] = 90
|
||||
|
||||
# Include the standalone 5-second screen videos in the uploaded outputs so they
|
||||
# land in the Dropbox folder. They are generated above (or passed in) purely as
|
||||
# concat inputs and used to live only in screens/; copy them into outputs/ with
|
||||
# the canonical names. Regression fix: screen MOVs disappeared from Dropbox after
|
||||
# #647/#650 moved screen generation to this encoder.
|
||||
for screen_video, suffix in ((title_video, "Title"), (end_video, "End")):
|
||||
if screen_video and Path(screen_video).is_file():
|
||||
dest = output_dir / f"{base_name} ({suffix}).mov"
|
||||
try:
|
||||
shutil.copy2(screen_video, dest)
|
||||
logger.info(f"Staged screen video for upload: {dest.name}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to stage {suffix} MOV into outputs: {e}")
|
||||
|
||||
# Collect output files
|
||||
output_files = [str(f) for f in output_dir.glob("*") if f.is_file()]
|
||||
jobs[job_id]["output_files"] = output_files
|
||||
@@ -803,12 +858,14 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
logger.error(error_msg)
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = error_msg
|
||||
_persist(job_id)
|
||||
raise RuntimeError(error_msg) from e
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Encoding failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
raise
|
||||
|
||||
|
||||
@@ -871,12 +928,14 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
|
||||
jobs[job_id]["status"] = "complete"
|
||||
jobs[job_id]["progress"] = 100
|
||||
_persist(job_id)
|
||||
logger.info(f"Job {job_id} complete")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id} failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
|
||||
|
||||
async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
@@ -899,12 +958,14 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
|
||||
jobs[job_id]["status"] = "complete"
|
||||
jobs[job_id]["progress"] = 100
|
||||
_persist(job_id)
|
||||
logger.info(f"Preview job {job_id} complete")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Preview job {job_id} failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
|
||||
|
||||
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
@@ -929,12 +990,14 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
|
||||
jobs[job_id]["status"] = "complete"
|
||||
jobs[job_id]["progress"] = 100
|
||||
_persist(job_id)
|
||||
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)
|
||||
_persist(job_id)
|
||||
|
||||
|
||||
@app.post("/encode-preview")
|
||||
@@ -962,6 +1025,7 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
}
|
||||
_persist(job_id)
|
||||
|
||||
background_tasks.add_task(process_preview_job, job_id, request)
|
||||
|
||||
@@ -993,6 +1057,7 @@ async def submit_render_video_job(request: RenderVideoRequest, background_tasks:
|
||||
"output_files": None,
|
||||
"metadata": None,
|
||||
}
|
||||
_persist(job_id)
|
||||
|
||||
background_tasks.add_task(process_render_video_job, job_id, request)
|
||||
|
||||
@@ -1024,6 +1089,7 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
}
|
||||
_persist(job_id)
|
||||
|
||||
background_tasks.add_task(process_job, job_id, request)
|
||||
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Firestore persistence for the encoding worker's in-memory job state.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
The encoding worker holds job state in a process-local `dict`. When the
|
||||
systemd service restarts (deploy, crash, OOM, manual restart) the dict is
|
||||
empty, so polls from the Cloud Run side return 404 and the orchestrator
|
||||
either fails the user's job or triggers wasteful re-renders.
|
||||
|
||||
This module mirrors per-job state to Firestore so that:
|
||||
|
||||
1. Polls after a restart return the *last known* status (typically `failed`
|
||||
with `code: encoding_worker_restart`), not 404 — orchestrator can react
|
||||
intelligently instead of guessing.
|
||||
2. On startup, the worker reads back any jobs it had in flight and marks
|
||||
them failed with that restart code, so the in-memory dict and Firestore
|
||||
stay in sync after a crash.
|
||||
|
||||
Scope
|
||||
-----
|
||||
Each row is keyed by `job_id` and tagged with `vm_name`. Loads are filtered
|
||||
to the current VM — VMs don't see each other's jobs. (We never have two
|
||||
VMs simultaneously holding the same `job_id` — Cloud Run only submits to
|
||||
one VM at a time, and on restart that same VM is the only one that owned
|
||||
the doc.)
|
||||
|
||||
A Firestore field-level TTL on `expires_at` cleans completed/failed rows
|
||||
automatically after 7 days; we set it on every write.
|
||||
|
||||
Cost / latency
|
||||
--------------
|
||||
Writes are best-effort. A Firestore failure logs a warning but does NOT
|
||||
fail the encoding job — persistence is observability/recovery, not
|
||||
correctness. The hot path stays in-memory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_RESTART_FAIL_CODE = "encoding_worker_restart"
|
||||
_TERMINAL_STATUSES = frozenset({"complete", "failed"})
|
||||
_DEFAULT_TTL_DAYS = 7
|
||||
_COLLECTION = "encoding_worker_jobs"
|
||||
|
||||
|
||||
def _now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def get_vm_name() -> str:
|
||||
"""Return the VM's identifier.
|
||||
|
||||
Prefer the GCE instance name (set by infrastructure/encoding-worker/
|
||||
startup.sh as `ENCODING_WORKER_VM_NAME`), falling back to the OS
|
||||
hostname so this still works in tests/local dev.
|
||||
"""
|
||||
return (
|
||||
os.environ.get("ENCODING_WORKER_VM_NAME")
|
||||
or socket.gethostname()
|
||||
or "unknown"
|
||||
)
|
||||
|
||||
|
||||
class JobStatePersister:
|
||||
"""Mirror in-memory job state to Firestore.
|
||||
|
||||
Lazily initializes the Firestore client so import-time has zero cost
|
||||
and tests/local-dev that don't have GCP creds don't blow up.
|
||||
|
||||
All operations are thread-safe — the encoding worker uses a
|
||||
ThreadPoolExecutor and may call save() from multiple worker threads.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vm_name: Optional[str] = None,
|
||||
collection: str = _COLLECTION,
|
||||
ttl_days: int = _DEFAULT_TTL_DAYS,
|
||||
client: Any = None, # for tests
|
||||
) -> None:
|
||||
self.vm_name = vm_name or get_vm_name()
|
||||
self.collection = collection
|
||||
self.ttl_days = ttl_days
|
||||
self._client = client
|
||||
self._client_lock = threading.Lock()
|
||||
self._enabled: Optional[bool] = None # None = not yet probed
|
||||
|
||||
def _get_client(self):
|
||||
"""Return a Firestore client or None if creds are missing."""
|
||||
if self._client is not None:
|
||||
return self._client
|
||||
with self._client_lock:
|
||||
if self._client is not None:
|
||||
return self._client
|
||||
try:
|
||||
from google.cloud import firestore # type: ignore
|
||||
self._client = firestore.Client()
|
||||
self._enabled = True
|
||||
logger.info(
|
||||
"JobStatePersister initialized (vm=%s, collection=%s)",
|
||||
self.vm_name, self.collection,
|
||||
)
|
||||
except Exception as exc:
|
||||
# Don't fail the worker if creds aren't available — just
|
||||
# disable persistence and log loudly so it's discoverable.
|
||||
self._enabled = False
|
||||
logger.warning(
|
||||
"JobStatePersister disabled (Firestore unavailable): %s",
|
||||
exc,
|
||||
)
|
||||
return self._client
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
if self._enabled is None:
|
||||
self._get_client()
|
||||
return bool(self._enabled)
|
||||
|
||||
def save(self, job_state: dict) -> None:
|
||||
"""Persist a single job's state.
|
||||
|
||||
Adds `vm_name`, `updated_at`, and `expires_at` (TTL) fields. Never
|
||||
raises — Firestore failures are logged and swallowed because
|
||||
encoding is the source of truth and persistence is best-effort.
|
||||
|
||||
On the first PermissionDenied (typically: IAM not yet applied for
|
||||
the encoding worker SA), self-disables to avoid logging a warning
|
||||
on every save call. Caller can re-enable by re-instantiating after
|
||||
IAM lands.
|
||||
"""
|
||||
client = self._get_client()
|
||||
if client is None:
|
||||
return
|
||||
job_id = job_state.get("job_id")
|
||||
if not job_id:
|
||||
logger.warning("JobStatePersister.save called without job_id; skipping")
|
||||
return
|
||||
try:
|
||||
doc = {
|
||||
**job_state,
|
||||
"vm_name": self.vm_name,
|
||||
"updated_at": _now_utc(),
|
||||
"expires_at": _now_utc() + timedelta(days=self.ttl_days),
|
||||
}
|
||||
client.collection(self.collection).document(job_id).set(doc)
|
||||
except Exception as exc:
|
||||
# If this is a permanent auth failure (IAM not applied yet),
|
||||
# log once and self-disable so we don't spam ERROR per save.
|
||||
# Other transient errors are logged at WARNING per occurrence.
|
||||
if self._looks_like_auth_error(exc):
|
||||
if self._enabled is not False: # only log on transition
|
||||
logger.warning(
|
||||
"JobStatePersister disabling: Firestore auth failed "
|
||||
"(likely IAM not yet applied to encoding-worker-sa: "
|
||||
"needs roles/datastore.user). Subsequent saves will "
|
||||
"be no-ops. Error: %r",
|
||||
exc,
|
||||
)
|
||||
self._enabled = False
|
||||
self._client = None
|
||||
return
|
||||
logger.warning(
|
||||
"[job:%s] Failed to persist job state to Firestore: %r",
|
||||
job_id, exc,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _looks_like_auth_error(exc: BaseException) -> bool:
|
||||
"""Heuristic — google.api_core.exceptions.PermissionDenied or 403/401."""
|
||||
type_name = type(exc).__name__
|
||||
if type_name in ("PermissionDenied", "Unauthenticated", "Forbidden"):
|
||||
return True
|
||||
msg = str(exc).lower()
|
||||
return any(s in msg for s in ("permission_denied", "permissiondenied",
|
||||
"403", "401", "unauthenticated",
|
||||
"missing or insufficient permissions"))
|
||||
|
||||
def load_active_jobs(self) -> dict[str, dict]:
|
||||
"""Return any non-terminal jobs persisted for this VM.
|
||||
|
||||
Used at startup to recover state from before the restart. Terminal
|
||||
jobs (complete/failed) are also persisted but not returned here —
|
||||
their docs serve only post-restart status polls.
|
||||
|
||||
Self-disables on auth errors (same pattern as save).
|
||||
"""
|
||||
client = self._get_client()
|
||||
if client is None:
|
||||
return {}
|
||||
try:
|
||||
query = (
|
||||
client.collection(self.collection)
|
||||
.where("vm_name", "==", self.vm_name)
|
||||
)
|
||||
recovered: dict[str, dict] = {}
|
||||
for doc_snapshot in query.stream():
|
||||
data = doc_snapshot.to_dict() or {}
|
||||
status = data.get("status")
|
||||
if status in _TERMINAL_STATUSES:
|
||||
continue
|
||||
# Strip the persistence-only fields before handing back
|
||||
for k in ("vm_name", "updated_at", "expires_at"):
|
||||
data.pop(k, None)
|
||||
recovered[doc_snapshot.id] = data
|
||||
return recovered
|
||||
except Exception as exc:
|
||||
if self._looks_like_auth_error(exc):
|
||||
if self._enabled is not False:
|
||||
logger.warning(
|
||||
"JobStatePersister disabling: Firestore auth failed "
|
||||
"during load_active_jobs (likely IAM not applied). "
|
||||
"Error: %r", exc,
|
||||
)
|
||||
self._enabled = False
|
||||
self._client = None
|
||||
return {}
|
||||
logger.warning(
|
||||
"JobStatePersister.load_active_jobs failed: %r", exc,
|
||||
)
|
||||
return {}
|
||||
|
||||
def mark_orphans_failed_on_startup(self, jobs: dict[str, dict]) -> int:
|
||||
"""Mark any in-progress jobs as failed with the restart code.
|
||||
|
||||
Called at worker startup. Mutates `jobs` in place AND persists each
|
||||
change so polls from the orchestrator see consistent state.
|
||||
|
||||
The work_dir for an interrupted job is gone (tmpfs / temp dir wiped
|
||||
by systemd restart), so we cannot resume — the only safe thing is
|
||||
to surface a clear failure so the caller can decide to retry.
|
||||
|
||||
Returns the number of jobs marked failed.
|
||||
"""
|
||||
active = self.load_active_jobs()
|
||||
if not active:
|
||||
return 0
|
||||
marked = 0
|
||||
for job_id, job_state in active.items():
|
||||
job_state["status"] = "failed"
|
||||
job_state["error"] = (
|
||||
f"Encoding worker restarted mid-job (code: {_RESTART_FAIL_CODE}). "
|
||||
"Worker process restart wiped in-memory state and the temp "
|
||||
"work directory; resubmit to retry."
|
||||
)
|
||||
job_state["restart_failure_code"] = _RESTART_FAIL_CODE
|
||||
jobs[job_id] = job_state
|
||||
self.save(job_state)
|
||||
marked += 1
|
||||
logger.warning(
|
||||
"[job:%s] Marked failed at startup due to encoding worker restart "
|
||||
"(was status=%s, progress=%s)",
|
||||
job_id,
|
||||
job_state.get("_pre_restart_status", "unknown"),
|
||||
job_state.get("progress"),
|
||||
)
|
||||
return marked
|
||||
@@ -8,6 +8,10 @@ uvicorn>=0.27.0
|
||||
# GCS client
|
||||
google-cloud-storage>=2.14.0
|
||||
|
||||
# Firestore client - persists job state across systemd restarts so polls
|
||||
# survive a worker restart instead of returning 404. See persistence.py.
|
||||
google-cloud-firestore>=2.14.0
|
||||
|
||||
# Async utilities (optional, for future improvements)
|
||||
aiofiles>=23.2.0
|
||||
aiohttp>=3.9.0
|
||||
|
||||
@@ -266,6 +266,7 @@ class GoogleDriveService:
|
||||
brand_code: str,
|
||||
base_name: str,
|
||||
output_files: dict,
|
||||
warnings: Optional[list] = None,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Upload final files to public share folder structure.
|
||||
@@ -322,6 +323,30 @@ class GoogleDriveService:
|
||||
uploaded_files["mp4_720p"] = file_id
|
||||
logger.info(f"Uploaded 720p MP4 to MP4-720p/ folder")
|
||||
|
||||
# Fast-sync the 720p master straight to the Divebar GCS mirror so kjbox
|
||||
# (which mirrors that folder every 5 min) picks it up within minutes,
|
||||
# instead of waiting for the nightly Drive->GCS VM. Nomad-brand only,
|
||||
# best-effort, never fatal to the Drive upload. A failure is surfaced as
|
||||
# a distribution warning (drives the admin alert) so this can't silently
|
||||
# rot into "nightly VM only" — the nightly VM stays the backfill net.
|
||||
fast_sync_warning = self._fast_sync_nomad_master(
|
||||
brand_code, mp4_720p_path, f"{filename_base}.mp4"
|
||||
)
|
||||
if fast_sync_warning and warnings is not None:
|
||||
warnings.append(fast_sync_warning)
|
||||
|
||||
# Push the padded original-vocals guide (silence[intro] + mixed_vocals) to the
|
||||
# vocals prefix in the same Divebar mirror, so kjbox can layer it under the master
|
||||
# at the "Original Vocals" slider. Same Nomad-brand gating + best-effort contract
|
||||
# as the 720p push; the guide was pre-built by the orchestrator when available.
|
||||
guide_path = output_files.get("original_vocals_guide")
|
||||
if guide_path and os.path.exists(guide_path):
|
||||
guide_warning = self._fast_sync_vocals_guide(
|
||||
brand_code, guide_path, f"{filename_base}.flac"
|
||||
)
|
||||
if guide_warning and warnings is not None:
|
||||
warnings.append(guide_warning)
|
||||
|
||||
# Upload CDG ZIP to CDG/
|
||||
cdg_zip_path = output_files.get("final_karaoke_cdg_zip")
|
||||
if cdg_zip_path and os.path.exists(cdg_zip_path):
|
||||
@@ -337,6 +362,74 @@ class GoogleDriveService:
|
||||
logger.info(f"Public share upload complete: {len(uploaded_files)} files uploaded")
|
||||
return uploaded_files
|
||||
|
||||
def _fast_sync_nomad_master(
|
||||
self, brand_code: str, local_720p_path: str, filename: str
|
||||
) -> Optional[str]:
|
||||
"""Best-effort push of a freshly-published Nomad 720p master to the Divebar
|
||||
GCS mirror so kjbox picks it up within minutes (vs the nightly VM).
|
||||
|
||||
No-op unless the fast-sync is enabled and this is a public Nomad release
|
||||
(``NOMAD-####``, excluding ``NOMADNP`` private tracks). Never raises — the
|
||||
Drive upload has already succeeded and the nightly VM is the backfill net.
|
||||
|
||||
Returns a human-readable warning string on failure (so the caller can surface
|
||||
it via ``distribution_warnings`` / the admin alert), or ``None`` on
|
||||
success or when skipped.
|
||||
"""
|
||||
try:
|
||||
from backend.config import settings
|
||||
from backend.services.nomad_master_mirror import (
|
||||
NomadMasterMirror,
|
||||
is_nomad_public_brand,
|
||||
)
|
||||
|
||||
if not settings.nomad_master_fast_sync_enabled:
|
||||
return None
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return None
|
||||
|
||||
if NomadMasterMirror().push_720p(local_720p_path, filename):
|
||||
return None
|
||||
return (
|
||||
f"Nomad master fast-sync to the GCS mirror failed for {filename} "
|
||||
f"(the nightly Drive->GCS VM will backfill it)"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning(f"Nomad master fast-sync skipped (unexpected error): {e}")
|
||||
return f"Nomad master fast-sync errored for {filename}: {e}"
|
||||
|
||||
def _fast_sync_vocals_guide(
|
||||
self, brand_code: str, local_path: str, filename: str
|
||||
) -> Optional[str]:
|
||||
"""Best-effort push of a freshly-built original-vocals guide to the Divebar GCS
|
||||
mirror's vocals prefix so kjbox can pull it into ``NOMAD-vocals-padded/``.
|
||||
|
||||
No-op unless the fast-sync is enabled and this is a public Nomad release
|
||||
(``NOMAD-####``, excluding ``NOMADNP``). Never raises — nothing downstream
|
||||
depends on the guide. Returns a human-readable warning on failure (surfaced via
|
||||
``distribution_warnings`` / the admin alert), or ``None`` on success or skip.
|
||||
"""
|
||||
try:
|
||||
from backend.config import settings
|
||||
from backend.services.nomad_master_mirror import (
|
||||
NomadMasterMirror,
|
||||
is_nomad_public_brand,
|
||||
)
|
||||
|
||||
if not settings.nomad_master_fast_sync_enabled:
|
||||
return None
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return None
|
||||
|
||||
if NomadMasterMirror().push_vocals_guide(local_path, filename):
|
||||
return None
|
||||
return (
|
||||
f"Original-vocals guide sync to the GCS mirror failed for {filename}"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning(f"Original-vocals guide sync skipped (unexpected error): {e}")
|
||||
return f"Original-vocals guide sync errored for {filename}: {e}"
|
||||
|
||||
def delete_file(self, file_id: str) -> bool:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
@@ -387,6 +480,69 @@ class GoogleDriveService:
|
||||
results[file_id] = self.delete_file(file_id)
|
||||
return results
|
||||
|
||||
def _search_subfolder_for_brand(
|
||||
self, root_folder_id: str, subfolder: str, brand_code: str
|
||||
) -> list[str]:
|
||||
"""Return file IDs in ``subfolder`` whose name starts with ``{brand_code} - ``.
|
||||
|
||||
Read-only Drive lookups, wrapped in retry-with-backoff so transient
|
||||
connection drops (SSL EOF / BrokenPipe against idle Cloud Run containers)
|
||||
self-heal instead of surfacing as "GDrive brand_code search incomplete".
|
||||
Non-transient errors reraise immediately for the caller to record.
|
||||
"""
|
||||
|
||||
def _do_search() -> list[str]:
|
||||
ids: list[str] = []
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
return ids
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
return ids
|
||||
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
return _do_search()
|
||||
|
||||
return [] # pragma: no cover - Retrying always returns or raises
|
||||
|
||||
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
|
||||
"""
|
||||
Search for files in public share subfolders matching a brand code prefix.
|
||||
@@ -411,43 +567,9 @@ class GoogleDriveService:
|
||||
|
||||
for subfolder in subfolders:
|
||||
try:
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
found_ids.extend(
|
||||
self._search_subfolder_for_brand(root_folder_id, subfolder, brand_code)
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
continue
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
found_ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
|
||||
|
||||
@@ -17,6 +17,7 @@ from backend.config import settings
|
||||
from backend.exceptions import InvalidStateTransitionError, InsufficientCreditsError
|
||||
from backend.models.job import Job, JobStatus, JobCreate, STATE_TRANSITIONS
|
||||
from backend.models.worker_log import WorkerLogEntry
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
@@ -57,15 +58,16 @@ class JobManager:
|
||||
ValueError: If theme_id is not provided (all jobs require a theme)
|
||||
"""
|
||||
# Check credits (skip for admins)
|
||||
credits_to_charge = job_create.credits
|
||||
if job_create.user_email and not is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
if not user_service.has_credits(job_create.user_email):
|
||||
credits_available = user_service.check_credits(job_create.user_email)
|
||||
credits_available = user_service.check_credits(job_create.user_email)
|
||||
if credits_available < credits_to_charge:
|
||||
raise InsufficientCreditsError(
|
||||
message="You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
credits_available=credits_available,
|
||||
credits_required=1,
|
||||
credits_required=credits_to_charge,
|
||||
)
|
||||
|
||||
# Enforce theme requirement - all jobs must have a theme
|
||||
@@ -126,17 +128,27 @@ class JobManager:
|
||||
"is_admin": is_admin,
|
||||
"created_from": job_create.request_metadata.get("created_from", "unknown"),
|
||||
},
|
||||
# Record how many credits were charged for this job (authoritative running total).
|
||||
# When charging is bypassed (admin / no user_email), set credits_charged=0 and
|
||||
# payment_bypassed=True so duration reconciliation short-circuits without pausing,
|
||||
# charging, or refunding.
|
||||
state_data=(
|
||||
{"credits_charged": 0, "payment_bypassed": True}
|
||||
if (is_admin or not job_create.user_email)
|
||||
else {"credits_charged": credits_to_charge}
|
||||
),
|
||||
)
|
||||
|
||||
self.firestore.create_job(job)
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
# Deduct credit atomically (after job is persisted so we have job_id for transaction record)
|
||||
# Deduct credits atomically (after job is persisted so we have job_id for transaction record)
|
||||
if job_create.user_email and not is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
success, _remaining, deduct_msg = user_service.deduct_credit(
|
||||
job_create.user_email, job_id, reason="job_creation"
|
||||
success, _remaining, deduct_msg = user_service.deduct_credits(
|
||||
job_create.user_email, job_id, amount=credits_to_charge, reason="job_creation",
|
||||
count_as_job_creation=True,
|
||||
)
|
||||
if not success:
|
||||
# Deduction failed (e.g., race condition) - delete the job and raise error
|
||||
@@ -148,7 +160,7 @@ class JobManager:
|
||||
raise InsufficientCreditsError(
|
||||
message="Failed to deduct credit. Please try again.",
|
||||
credits_available=0,
|
||||
credits_required=1,
|
||||
credits_required=credits_to_charge,
|
||||
)
|
||||
|
||||
return job
|
||||
@@ -177,6 +189,10 @@ class JobManager:
|
||||
def update_job(self, job_id: str, updates: Dict[str, Any]) -> None:
|
||||
"""Update job with arbitrary fields."""
|
||||
self.firestore.update_job(job_id, updates)
|
||||
|
||||
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
|
||||
"""List all jobs in a Bulk Mode batch (state_data.batch_id == batch_id)."""
|
||||
return self.firestore.list_jobs_by_batch_id(batch_id, limit=limit)
|
||||
|
||||
def list_jobs(
|
||||
self,
|
||||
@@ -338,7 +354,9 @@ class JobManager:
|
||||
if delete_files and job and job.output_files:
|
||||
for gcs_path in job.output_files.values():
|
||||
try:
|
||||
self.storage.delete_file(gcs_path)
|
||||
# ignore_missing: a job being deleted whose recorded file is
|
||||
# already gone is not an error, just skip it quietly.
|
||||
self.storage.delete_file(gcs_path, ignore_missing=True)
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting file {gcs_path}: {e}")
|
||||
|
||||
@@ -395,9 +413,16 @@ class JobManager:
|
||||
valid_transitions = STATE_TRANSITIONS.get(current_status, [])
|
||||
|
||||
if new_status not in valid_transitions:
|
||||
# Normalise both sides to their string values so the message reads
|
||||
# 'downloading -> downloading' rather than the misleading
|
||||
# 'downloading -> JobStatus.DOWNLOADING'. The asymmetry exists
|
||||
# because Job.status is deserialised with use_enum_values=True
|
||||
# (plain str) while new_status is typically an enum at call time.
|
||||
from_value = current_status.value if hasattr(current_status, 'value') else str(current_status)
|
||||
to_value = new_status.value if hasattr(new_status, 'value') else str(new_status)
|
||||
error_msg = (
|
||||
f"Invalid state transition for job {job_id}: "
|
||||
f"{current_status} -> {new_status}. "
|
||||
f"{from_value} -> {to_value}. "
|
||||
f"Valid transitions: {[s.value for s in valid_transitions]}"
|
||||
)
|
||||
logger.error(error_msg)
|
||||
@@ -406,8 +431,8 @@ class JobManager:
|
||||
raise InvalidStateTransitionError(
|
||||
message=error_msg,
|
||||
job_id=job_id,
|
||||
from_status=current_status,
|
||||
to_status=new_status.value if hasattr(new_status, 'value') else str(new_status),
|
||||
from_status=from_value,
|
||||
to_status=to_value,
|
||||
valid_transitions=[s.value for s in valid_transitions]
|
||||
)
|
||||
return False
|
||||
@@ -539,13 +564,15 @@ class JobManager:
|
||||
self._send_push_notification(job, "complete")
|
||||
|
||||
# Idle reminder scheduling for blocking states
|
||||
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT]:
|
||||
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM]:
|
||||
self._schedule_idle_reminder(job, new_status)
|
||||
# Send push notification for blocking states
|
||||
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
|
||||
action_type = "audio_edit"
|
||||
elif new_status == JobStatus.AWAITING_REVIEW:
|
||||
action_type = "lyrics"
|
||||
elif new_status == JobStatus.AWAITING_DURATION_CONFIRM:
|
||||
action_type = "duration_confirm"
|
||||
else:
|
||||
action_type = "instrumental"
|
||||
self._send_push_notification(job, action_type)
|
||||
@@ -625,7 +652,9 @@ class JobManager:
|
||||
Schedule an idle reminder for a blocking state.
|
||||
|
||||
Records the timestamp when the blocking state was entered and
|
||||
schedules a Cloud Tasks task for 5 minutes later.
|
||||
schedules a Cloud Tasks task after a state-specific delay:
|
||||
- AWAITING_DURATION_CONFIRM: 15 minutes (900s) — user needs to confirm extra cost
|
||||
- All other blocking states: default delay (IDLE_REMINDER_DELAY_SECONDS)
|
||||
"""
|
||||
import asyncio
|
||||
import threading
|
||||
@@ -638,6 +667,8 @@ class JobManager:
|
||||
action_type = "audio_edit"
|
||||
elif new_status == JobStatus.AWAITING_REVIEW:
|
||||
action_type = "lyrics"
|
||||
elif new_status == JobStatus.AWAITING_DURATION_CONFIRM:
|
||||
action_type = "duration_confirm"
|
||||
else:
|
||||
action_type = "instrumental"
|
||||
|
||||
@@ -653,12 +684,19 @@ class JobManager:
|
||||
'state_data': {**existing_state_data, **state_data_update}
|
||||
})
|
||||
|
||||
# Schedule the idle reminder check via worker service (5 min delay)
|
||||
# Schedule the idle reminder check via worker service.
|
||||
# Duration-confirm uses 15-min delay; other states use the default.
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
# Capture action_type for the closure
|
||||
_action_type = action_type
|
||||
|
||||
async def schedule_reminder():
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.schedule_idle_reminder(job.job_id)
|
||||
if _action_type == "duration_confirm":
|
||||
await worker_service.schedule_idle_reminder(job.job_id, delay_seconds=900)
|
||||
else:
|
||||
await worker_service.schedule_idle_reminder(job.job_id)
|
||||
|
||||
# Try to get existing event loop, create new one if none exists
|
||||
try:
|
||||
@@ -829,9 +867,12 @@ class JobManager:
|
||||
|
||||
def _refund_credit_for_job(self, job_id: str, job: Job, reason: str) -> bool:
|
||||
"""
|
||||
Refund one credit for a job if eligible.
|
||||
Refund all credits charged for a job if eligible.
|
||||
|
||||
Skips refund if: already refunded, no user email, or admin-owned job.
|
||||
Reads ``state_data.credits_charged`` (defaulting to 1 for legacy jobs
|
||||
that pre-date the field) and refunds that many credits in a single
|
||||
``add_credits`` call. Skips refund if: already refunded, no user
|
||||
email, admin-owned job, or credits_charged == 0 (payment_bypassed).
|
||||
Never raises — refund failure must not block the calling operation.
|
||||
|
||||
Returns:
|
||||
@@ -851,14 +892,30 @@ class JobManager:
|
||||
if is_admin_email(job.user_email):
|
||||
return False
|
||||
|
||||
# Determine how many credits to refund. ``credits_charged`` is set
|
||||
# at job creation (and updated on duration-confirm). Legacy jobs
|
||||
# that pre-date the field are guaranteed to be 1-credit jobs, so we
|
||||
# default to 1. payment_bypassed admin/no-email jobs have
|
||||
# credits_charged=0 and must not be refunded.
|
||||
state_data = job.state_data or {}
|
||||
credits_charged = int(state_data.get("credits_charged", 1))
|
||||
|
||||
if credits_charged == 0:
|
||||
# Admin / payment-bypassed job — nothing to refund.
|
||||
logger.info(f"Job {job_id}: credits_charged=0 (payment_bypassed), skipping refund")
|
||||
return False
|
||||
|
||||
user_service = get_user_service()
|
||||
refund_ok, new_balance, refund_msg = user_service.refund_credit(
|
||||
job.user_email, job_id, reason=reason
|
||||
refund_ok, new_balance, refund_msg = user_service.add_credits(
|
||||
job.user_email, amount=credits_charged, reason=reason, job_id=job_id
|
||||
)
|
||||
if refund_ok:
|
||||
# Mark job as refunded to prevent double-refund
|
||||
self.update_job(job_id, {'credit_refunded': True})
|
||||
logger.info(f"Refunded credit for {reason} job {job_id} to {_mask_email(job.user_email)} (balance: {new_balance})")
|
||||
logger.info(
|
||||
f"Refunded {credits_charged} credit(s) for {reason} job {job_id} "
|
||||
f"to {_mask_email(job.user_email)} (balance: {new_balance})"
|
||||
)
|
||||
return True
|
||||
else:
|
||||
logger.warning(f"Credit refund failed for job {job_id}: {refund_msg}")
|
||||
@@ -1001,6 +1058,14 @@ class JobManager:
|
||||
message=message
|
||||
)
|
||||
|
||||
# Reconcile credit charge against actual audio duration before triggering workers.
|
||||
# Probes input_media_gcs_path (already set by the upload handler) via ffprobe.
|
||||
# Returns True when the job is paused (AWAITING_DURATION_CONFIRM) or cancelled,
|
||||
# in which case we must NOT start downstream workers.
|
||||
if await reconcile_and_maybe_pause(job_id):
|
||||
logger.info(f"Job {job_id}: Paused for duration confirmation (or cancelled); workers not started")
|
||||
return
|
||||
|
||||
# Check if audio separation can be skipped
|
||||
# Jobs with an existing instrumental (e.g. tenant uploads) don't need
|
||||
# GPU-powered audio separation — saves 5-10 minutes of processing time
|
||||
|
||||
@@ -317,6 +317,69 @@ class JobNotificationService:
|
||||
logger.exception(f"Error sending {action_type} reminder for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_duration_confirm_reminder(self, job) -> bool:
|
||||
"""
|
||||
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
|
||||
|
||||
Called when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes and
|
||||
the user has not yet confirmed the extra cost.
|
||||
|
||||
Args:
|
||||
job: Job object with at minimum job_id, user_email, artist, title,
|
||||
and state_data (may contain pending_additional_credits,
|
||||
duration_actual_seconds).
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully.
|
||||
"""
|
||||
if not ENABLE_AUTO_EMAILS:
|
||||
logger.info(f"Auto emails disabled, skipping duration-confirm reminder for job {job.job_id}")
|
||||
return False
|
||||
|
||||
user_email = getattr(job, "user_email", None)
|
||||
if not user_email:
|
||||
logger.warning(f"No user email for job {job.job_id}, skipping duration-confirm reminder")
|
||||
return False
|
||||
|
||||
try:
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
job_id = job.job_id
|
||||
artist = getattr(job, "artist", None)
|
||||
title = getattr(job, "title", None)
|
||||
state_data = getattr(job, "state_data", None) or {}
|
||||
|
||||
# Extract extra-cost details from state_data (best-effort)
|
||||
pending_credits = state_data.get("pending_additional_credits")
|
||||
duration_seconds = state_data.get("duration_actual_seconds")
|
||||
|
||||
confirm_url = (
|
||||
f"{self.frontend_url}{get_locale_prefix(user_locale)}/app"
|
||||
)
|
||||
|
||||
success = self.email_service.send_duration_confirm_reminder(
|
||||
to_email=user_email,
|
||||
job_id=job_id,
|
||||
artist=artist,
|
||||
title=title,
|
||||
pending_credits=pending_credits,
|
||||
duration_seconds=duration_seconds,
|
||||
confirm_url=confirm_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info(
|
||||
f"Sent duration_confirm reminder for job {job_id} to {_mask_email(user_email)}"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Failed to send duration_confirm reminder for job {job_id}")
|
||||
|
||||
return success
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error sending duration_confirm reminder for job {job.job_id}: {e}")
|
||||
return False
|
||||
|
||||
def get_completion_message(
|
||||
self,
|
||||
job_id: str,
|
||||
|
||||
@@ -5,6 +5,7 @@ Scrapes karaokenerds.com to check if a song already has community-approved
|
||||
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
@@ -14,12 +15,22 @@ from urllib.parse import urlencode
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# karaokenerds.com's search silently returns zero results once a query exceeds
|
||||
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
|
||||
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
|
||||
# artist blow past this, so the song is falsely reported as having no community
|
||||
# version. When that happens we retry with the title alone (the highest-signal
|
||||
# term) and keep only results whose artist matches.
|
||||
MAX_RELIABLE_QUERY_TERMS = 10
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
@@ -145,6 +156,45 @@ def parse_results(html: str) -> list[dict]:
|
||||
return songs
|
||||
|
||||
|
||||
async def _search_songs(query: str) -> list[dict] | None:
|
||||
"""Run a single karaokenerds search and parse the results.
|
||||
|
||||
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
|
||||
caller can distinguish "search errored" from "search returned nothing").
|
||||
"""
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
return None
|
||||
return parse_results(resp.text)
|
||||
|
||||
|
||||
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
|
||||
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
|
||||
community_songs: list[dict] = []
|
||||
best_youtube_url: str | None = None
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
return community_songs, best_youtube_url
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
@@ -160,39 +210,32 @@ async def check_community_versions(artist: str, title: str) -> dict:
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
songs = await _search_songs(query)
|
||||
if songs is None:
|
||||
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
|
||||
# site, matching prior behaviour.
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
songs = parse_results(resp.text)
|
||||
# karaokenerds chokes on overlong queries and returns nothing. If the
|
||||
# combined "artist title" query was too long AND came back empty, retry with
|
||||
# the title alone, then keep only results whose artist matches (title-only is
|
||||
# broader, so this guards against same-titled songs by other artists).
|
||||
if (
|
||||
not songs
|
||||
and title.strip()
|
||||
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
|
||||
):
|
||||
fallback = await _search_songs(title)
|
||||
if fallback:
|
||||
key_artist = normalize_for_match(artist)
|
||||
songs = [
|
||||
s for s in fallback
|
||||
if normalize_for_match(s.get("artist") or "") == key_artist
|
||||
]
|
||||
|
||||
# Filter to only songs that have community tracks with YouTube URLs
|
||||
community_songs = []
|
||||
best_youtube_url = None
|
||||
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
community_songs, best_youtube_url = _extract_community_songs(songs)
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
@@ -201,3 +244,54 @@ async def check_community_versions(artist: str, title: str) -> dict:
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
|
||||
async def check_community_versions_batch(
|
||||
songs: list[dict], concurrency: int = 5
|
||||
) -> list[dict]:
|
||||
"""Check community-version availability for many songs (Bulk Mode).
|
||||
|
||||
``songs`` is a list of ``{"artist": str, "title": str}``. Returns a list in the
|
||||
same order, each ``{"artist", "title", "available": bool, "brands": [str],
|
||||
"brand_count": int, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
|
||||
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
|
||||
uses to render clickable links; ``brands``/``brand_count`` are retained for
|
||||
back-compat. Bounded concurrency keeps us polite to karaokenerds.com; per-song
|
||||
results reuse the existing 1h cache. A failed lookup degrades to
|
||||
``available=False`` (the track simply stays selectable) — never raises.
|
||||
"""
|
||||
sem = asyncio.Semaphore(max(1, concurrency))
|
||||
|
||||
async def _one(song: dict) -> dict:
|
||||
artist = (song.get("artist") or "").strip()
|
||||
title = (song.get("title") or "").strip()
|
||||
if not artist or not title:
|
||||
return {"artist": artist, "title": title, "available": False,
|
||||
"brands": [], "brand_count": 0, "versions": []}
|
||||
async with sem:
|
||||
res = await check_community_versions(artist, title)
|
||||
versions: list[dict] = []
|
||||
versioned_brands: set[str] = set()
|
||||
brands: list[str] = []
|
||||
for matched in res.get("songs", []):
|
||||
for track in matched.get("community_tracks", []):
|
||||
name = track.get("brand_name")
|
||||
if not name:
|
||||
continue
|
||||
if name not in brands:
|
||||
brands.append(name)
|
||||
# A clickable version needs a URL; brand still counts as "exists" without one.
|
||||
url = track.get("youtube_url")
|
||||
if url and name not in versioned_brands:
|
||||
versioned_brands.add(name)
|
||||
versions.append({"brand": name, "url": url})
|
||||
return {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"available": bool(res.get("has_community")),
|
||||
"brands": brands,
|
||||
"brand_count": len(brands),
|
||||
"versions": versions,
|
||||
}
|
||||
|
||||
return await asyncio.gather(*[_one(s) for s in songs])
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Artist/title match-judge: deterministic + catalog + light-AI formatting and
|
||||
match-acceptance decisions for the job-submission flow.
|
||||
|
||||
See docs/archive/2026-06-15-artist-title-matching-rework-plan.md.
|
||||
"""
|
||||
from backend.services.match_judge.verdict import MatchVerdict
|
||||
|
||||
__all__ = ["MatchVerdict"]
|
||||
@@ -0,0 +1,174 @@
|
||||
"""The light-AI layer of the match judge.
|
||||
|
||||
Invoked only when the deterministic+catalog classifier can't decide. Uses a
|
||||
small Vertex Gemini model to judge whether the typed artist/title is a real
|
||||
song, what its canonical formatting is, and whether any change is cosmetic,
|
||||
content-level, or ambiguous. The model call is injectable for testing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_AMBIGUOUS,
|
||||
KIND_CONTENT,
|
||||
KIND_COSMETIC,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_VALID_KINDS = {KIND_COSMETIC, KIND_CONTENT, KIND_AMBIGUOUS}
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You normalise song metadata for a karaoke service. Given what a user typed "
|
||||
"for an artist and title (plus optional catalog candidates), decide whether it "
|
||||
"refers to a real, released song and how its artist/title should be formatted.\n"
|
||||
"Return JSON with: kind, confident, canonical_artist, canonical_title, "
|
||||
"alternatives, reason.\n"
|
||||
"kind:\n"
|
||||
" 'cosmetic' – same song, only formatting/casing/punctuation/diacritics differ.\n"
|
||||
" 'content' – the user made a typo or used a wrong/variant title; the correct "
|
||||
"song text differs in actual characters.\n"
|
||||
" 'ambiguous' – more than one plausible song matches; list them in alternatives.\n"
|
||||
" 'none' – already correct, or you cannot confidently suggest anything.\n"
|
||||
"confident: true only when you are sure. Never invent songs. Prefer the user's "
|
||||
"input when unsure (kind='none'). canonical_artist/canonical_title must use "
|
||||
"official formatting. alternatives is a list of {artist,title}."
|
||||
)
|
||||
|
||||
# OpenAPI-style schema handed to the Vertex genai client at runtime.
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
|
||||
"confident": {"type": "boolean"},
|
||||
"canonical_artist": {"type": "string"},
|
||||
"canonical_title": {"type": "string"},
|
||||
"alternatives": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"reason": {"type": "string"},
|
||||
},
|
||||
"required": ["kind", "confident"],
|
||||
}
|
||||
|
||||
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return "gemini-3.5-flash"
|
||||
|
||||
|
||||
def build_prompts(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> tuple[str, str]:
|
||||
lines = [f'User typed: artist="{artist}" title="{title}"']
|
||||
if audio_tier is not None:
|
||||
lines.append(
|
||||
f"Audio-search confidence tier: {audio_tier} "
|
||||
"(1 = strong match found, 3 = weak/no results — a weak tier hints the "
|
||||
"title may be misspelled)."
|
||||
)
|
||||
if candidates:
|
||||
lines.append("Catalog candidates (canonical formatting):")
|
||||
for c in candidates:
|
||||
lines.append(f'- {c.get("artist_name", "")} — {c.get("track_name", "")}')
|
||||
else:
|
||||
lines.append("No catalog candidates were found.")
|
||||
return _SYSTEM_PROMPT, "\n".join(lines)
|
||||
|
||||
|
||||
def _verdict_from_response(
|
||||
data: object, *, fallback_artist: str, fallback_title: str
|
||||
) -> MatchVerdict:
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
kind = data.get("kind")
|
||||
if kind not in _VALID_KINDS:
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, fallback_artist, fallback_title,
|
||||
engine="ai", reason="no suggestion",
|
||||
)
|
||||
canonical_artist = (data.get("canonical_artist") or "").strip() or fallback_artist
|
||||
canonical_title = (data.get("canonical_title") or "").strip() or fallback_title
|
||||
alternatives = []
|
||||
for alt in data.get("alternatives") or []:
|
||||
if isinstance(alt, dict) and alt.get("artist") and alt.get("title"):
|
||||
alternatives.append(
|
||||
{"artist": str(alt["artist"]), "title": str(alt["title"])}
|
||||
)
|
||||
return MatchVerdict(
|
||||
kind=kind,
|
||||
confident=bool(data.get("confident", False)),
|
||||
canonical_artist=canonical_artist,
|
||||
canonical_title=canonical_title,
|
||||
alternatives=alternatives,
|
||||
engine="ai",
|
||||
reason=str(data.get("reason") or ""),
|
||||
)
|
||||
|
||||
|
||||
async def ai_judge_match(
|
||||
artist: str,
|
||||
title: str,
|
||||
candidates: list[dict],
|
||||
audio_tier: Optional[int],
|
||||
*,
|
||||
model: Optional[str] = None,
|
||||
generate: Optional[Generate] = None,
|
||||
) -> MatchVerdict:
|
||||
model = model or _model()
|
||||
gen = generate or _default_generate
|
||||
system_prompt, user_prompt = build_prompts(artist, title, candidates, audio_tier)
|
||||
data = await gen(model, system_prompt, user_prompt)
|
||||
return _verdict_from_response(
|
||||
data, fallback_artist=artist, fallback_title=title
|
||||
)
|
||||
|
||||
|
||||
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
import copy
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Deterministic + catalog match classification (no AI, no network).
|
||||
|
||||
`classify_catalog_match` returns a confident :class:`MatchVerdict` when the
|
||||
typed artist/title clearly correspond to a catalog candidate (a cosmetic
|
||||
formatting fix, or nothing to change). When it cannot confidently decide, it
|
||||
returns ``None`` — the caller should then escalate to the AI judge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Optional
|
||||
|
||||
from karaoke_gen.utils import normalize_text
|
||||
|
||||
from backend.services.match_judge.verdict import (
|
||||
KIND_COSMETIC,
|
||||
KIND_NONE,
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
|
||||
_WS = re.compile(r"\s+")
|
||||
|
||||
|
||||
def _fold_accents(text: str) -> str:
|
||||
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
|
||||
decomposed = unicodedata.normalize("NFKD", text)
|
||||
return "".join(c for c in decomposed if not unicodedata.combining(c))
|
||||
|
||||
|
||||
def normalize_for_match(text: str) -> str:
|
||||
"""Aggressive key used only for equality comparison (never displayed).
|
||||
|
||||
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
|
||||
"""
|
||||
s = normalize_text(text or "")
|
||||
s = s.replace("&", " and ")
|
||||
s = _fold_accents(s)
|
||||
s = s.casefold()
|
||||
s = _NON_ALNUM.sub(" ", s)
|
||||
s = _WS.sub(" ", s).strip()
|
||||
return s
|
||||
|
||||
|
||||
def classify_catalog_match(
|
||||
artist: str, title: str, candidates: list[dict]
|
||||
) -> Optional[MatchVerdict]:
|
||||
"""Return a confident verdict from catalog candidates, or None to escalate.
|
||||
|
||||
candidates: dicts with ``artist_name`` and ``track_name`` (Spotify/MB canonical).
|
||||
"""
|
||||
key_artist = normalize_for_match(artist)
|
||||
key_title = normalize_for_match(title)
|
||||
|
||||
for cand in candidates:
|
||||
cand_artist = cand.get("artist_name") or ""
|
||||
cand_title = cand.get("track_name") or ""
|
||||
if (
|
||||
normalize_for_match(cand_artist) == key_artist
|
||||
and normalize_for_match(cand_title) == key_title
|
||||
):
|
||||
# Same song. Cosmetic fix unless the user already typed it exactly.
|
||||
if cand_artist == artist and cand_title == title:
|
||||
return MatchVerdict(
|
||||
kind=KIND_NONE,
|
||||
confident=True,
|
||||
canonical_artist=artist,
|
||||
canonical_title=title,
|
||||
engine="catalog",
|
||||
reason="already canonical",
|
||||
)
|
||||
return MatchVerdict(
|
||||
kind=KIND_COSMETIC,
|
||||
confident=True,
|
||||
canonical_artist=cand_artist,
|
||||
canonical_title=cand_title,
|
||||
engine="catalog",
|
||||
reason="formatting differs from catalog",
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Match-judge orchestration.
|
||||
|
||||
Composes the deterministic+catalog classifier with the AI judge. The AI judge
|
||||
runs ONLY when the classifier can't confidently decide, and never blocks or
|
||||
errors the caller — any failure degrades to "no suggestion".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Literal, Optional
|
||||
|
||||
from backend.services.match_judge.classifier import classify_catalog_match
|
||||
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CATALOG_CANDIDATE_LIMIT = 8
|
||||
|
||||
Stage = Literal["fast", "full"]
|
||||
|
||||
# Audio tiers at or above this are "weak" (poor / no results). A weak tier hints
|
||||
# the typed title may be a typo, so even a confident catalog match is verified
|
||||
# with the AI judge (it can be a junk/misspelled Spotify entry).
|
||||
WEAK_TIER = 3
|
||||
|
||||
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
|
||||
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
|
||||
|
||||
|
||||
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
return await search_tracks(query, artist, limit)
|
||||
|
||||
|
||||
async def _default_ai_judge(
|
||||
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
|
||||
) -> MatchVerdict:
|
||||
from backend.services.match_judge.ai import ai_judge_match
|
||||
return await ai_judge_match(artist, title, candidates, audio_tier)
|
||||
|
||||
|
||||
def _default_enabled() -> bool:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return bool(getattr(settings, "match_judge_enabled", True))
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return True
|
||||
|
||||
|
||||
async def judge_match(
|
||||
artist: str,
|
||||
title: str,
|
||||
audio_tier: Optional[int] = None,
|
||||
*,
|
||||
stage: Stage = "full",
|
||||
search_tracks: Optional[SearchTracks] = None,
|
||||
ai_judge: Optional[AiJudge] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
) -> MatchVerdict:
|
||||
"""Return a :class:`MatchVerdict` for the typed artist/title.
|
||||
|
||||
audio_tier: the audio search's confidence tier (1=best..3=poor), used by the
|
||||
AI judge to decide whether weak results suggest a typo. May be None.
|
||||
|
||||
stage:
|
||||
"fast" — catalog-only pass (no AI, tier ignored). Runs in parallel with the
|
||||
audio search so the common cosmetic tidy is ready before results render.
|
||||
Returns the catalog verdict if confident, else a ``needs_ai=True`` marker
|
||||
telling the caller to make a "full" call once the tier is known.
|
||||
"full" — the complete pipeline: catalog, then the AI judge when catalog isn't
|
||||
confident OR (item 4) when a confident catalog match coincides with a weak
|
||||
audio tier (the match may be a junk/typo'd entry — let AI override).
|
||||
"""
|
||||
search = search_tracks or _default_search_tracks
|
||||
ai = ai_judge or _default_ai_judge
|
||||
if enabled is None:
|
||||
enabled = _default_enabled()
|
||||
|
||||
try:
|
||||
candidates = await search(title, artist, CATALOG_CANDIDATE_LIMIT)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"match-judge catalog search failed; continuing without candidates",
|
||||
exc_info=True,
|
||||
)
|
||||
candidates = []
|
||||
|
||||
catalog_verdict = classify_catalog_match(artist, title, candidates)
|
||||
|
||||
# Fast pass: catalog only. Never touches the AI layer.
|
||||
if stage == "fast":
|
||||
if catalog_verdict is not None:
|
||||
return catalog_verdict
|
||||
return MatchVerdict(
|
||||
KIND_NONE, False, artist, title,
|
||||
engine="catalog", reason="needs ai", needs_ai=True,
|
||||
)
|
||||
|
||||
# Full pass.
|
||||
if catalog_verdict is not None:
|
||||
weak = audio_tier is not None and audio_tier >= WEAK_TIER
|
||||
if not (enabled and weak):
|
||||
return catalog_verdict
|
||||
# Item 4: weak audio results make the typo hypothesis plausible even though
|
||||
# the catalog "matched" — verify with AI and let a confident verdict override.
|
||||
try:
|
||||
ai_verdict = await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"match-judge AI verification failed; keeping catalog verdict"
|
||||
)
|
||||
return catalog_verdict
|
||||
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
|
||||
return ai_verdict
|
||||
return catalog_verdict
|
||||
|
||||
if not enabled:
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="deterministic", reason="ai disabled"
|
||||
)
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
logger.exception("match-judge AI call failed; returning no-suggestion")
|
||||
return MatchVerdict(
|
||||
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""The verdict returned by the match judge."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
|
||||
# kind values:
|
||||
# "cosmetic" – same song, formatting-only fix → apply invisibly
|
||||
# "content" – actual characters change (typo/different title) → surface + maybe re-search
|
||||
# "ambiguous" – more than one plausible song → ask the user first
|
||||
# "none" – nothing to change (already correct, or no confident suggestion)
|
||||
KIND_COSMETIC = "cosmetic"
|
||||
KIND_CONTENT = "content"
|
||||
KIND_AMBIGUOUS = "ambiguous"
|
||||
KIND_NONE = "none"
|
||||
|
||||
|
||||
Kind = Literal["cosmetic", "content", "ambiguous", "none"]
|
||||
Engine = Literal["deterministic", "catalog", "ai"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchVerdict:
|
||||
kind: Kind
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[dict] = field(default_factory=list) # [{"artist","title"}]
|
||||
engine: Engine = "deterministic"
|
||||
reason: str = ""
|
||||
# True only from a "fast" (catalog-only) pass that couldn't confidently decide:
|
||||
# the caller should escalate to a "full" pass (with the audio tier) for an AI
|
||||
# verdict. Always False on a full-pass verdict.
|
||||
needs_ai: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"kind": self.kind,
|
||||
"confident": self.confident,
|
||||
"canonical_artist": self.canonical_artist,
|
||||
"canonical_title": self.canonical_title,
|
||||
"alternatives": self.alternatives,
|
||||
"engine": self.engine,
|
||||
"reason": self.reason,
|
||||
"needs_ai": self.needs_ai,
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
"""MusicBrainz lookup service for Bulk Mode album/release lookup.
|
||||
|
||||
Provides artist search, album (release-group) listing, canonical-release
|
||||
selection, and tracklist retrieval with "extra track" detection (live /
|
||||
remix / bonus / demo / acoustic / instrumental).
|
||||
|
||||
MusicBrainz asks for a descriptive User-Agent and ~1 request/second. We add a
|
||||
small process-wide throttle and a short in-memory TTL cache because album
|
||||
lookups are interactive and low-volume.
|
||||
|
||||
API shapes (captured from the live API, 2026-06):
|
||||
- GET /ws/2/artist?query=&fmt=json -> {artists: [{id,name,disambiguation,type,score,country}]}
|
||||
- GET /ws/2/release-group?artist=&type=album&fmt=json
|
||||
-> {release-groups: [{id,title,primary-type,secondary-types:[str],first-release-date}]}
|
||||
- GET /ws/2/release?release-group=&inc=media&fmt=json
|
||||
-> {releases: [{id,title,status,date,country,packaging,disambiguation,media:[{track-count}]}]}
|
||||
- GET /ws/2/release/{id}?inc=recordings&fmt=json
|
||||
-> {id,title,status,date,country,media:[{format,track-count,
|
||||
tracks:[{position,title,length,recording:{id,title,disambiguation,length}}]}]}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import Counter
|
||||
from typing import Any, Dict, List, Optional
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MB_BASE = "https://musicbrainz.org/ws/2"
|
||||
USER_AGENT = "NomadKaraoke/1.0 (contact@nomadkaraoke.com)"
|
||||
_MIN_INTERVAL_S = 1.0 # MusicBrainz politeness: ~1 req/s
|
||||
_CACHE_TTL_S = 600 # 10 min — album metadata is effectively static
|
||||
_REQUEST_TIMEOUT_S = 15.0
|
||||
_MAX_RETRIES = 3 # MusicBrainz 503s / transient transport errors are common from cloud egress
|
||||
_RETRY_BACKOFF_S = 0.5
|
||||
|
||||
# Country preference for canonical-release tie-breaks (worldwide / Europe / US / UK).
|
||||
_PREFERRED_COUNTRIES = ["XW", "XE", "US", "GB"]
|
||||
|
||||
# Locale → ordered country preference for picking which pressing backs a variant.
|
||||
# Biases the representative release toward the user's likely region; falls back to
|
||||
# the worldwide default for anything unmapped. Keyed by the language part of the
|
||||
# locale (region suffix is ignored, e.g. "en-US" → "en").
|
||||
_LOCALE_COUNTRY_PREFS: Dict[str, List[str]] = {
|
||||
"en": ["GB", "US", "AU", "CA", "IE", "NZ"],
|
||||
"es": ["ES", "MX", "AR"],
|
||||
"fr": ["FR", "CA", "BE"],
|
||||
"de": ["DE", "AT", "CH"],
|
||||
"it": ["IT"],
|
||||
"pt": ["PT", "BR"],
|
||||
"nl": ["NL", "BE"],
|
||||
"sv": ["SE"],
|
||||
"ja": ["JP"],
|
||||
"ko": ["KR"],
|
||||
"zh": ["CN", "TW", "HK"],
|
||||
}
|
||||
|
||||
|
||||
def country_prefs_for_locale(locale: Optional[str]) -> List[str]:
|
||||
"""Map a next-intl locale to an ordered country preference list.
|
||||
|
||||
Returns a copy of the worldwide default (``_PREFERRED_COUNTRIES``) for an
|
||||
empty/unknown locale so callers can mutate freely.
|
||||
"""
|
||||
if not locale:
|
||||
return list(_PREFERRED_COUNTRIES)
|
||||
base = re.split(r"[-_]", locale)[0].lower()
|
||||
return list(_LOCALE_COUNTRY_PREFS.get(base, _PREFERRED_COUNTRIES))
|
||||
|
||||
# "Extra" track qualifier keywords. Matched only inside (), [], or after " - "
|
||||
# so we don't misfire on legitimate titles that happen to contain a word.
|
||||
_EXTRA_KEYWORDS = [
|
||||
"live",
|
||||
"remix",
|
||||
"remixed",
|
||||
"bonus",
|
||||
"demo",
|
||||
"acoustic",
|
||||
"instrumental",
|
||||
"rehearsal",
|
||||
"alternate",
|
||||
"alternative",
|
||||
"radio edit",
|
||||
"single edit",
|
||||
"extended",
|
||||
"re-recorded",
|
||||
"rerecorded",
|
||||
"session",
|
||||
"outtake",
|
||||
]
|
||||
_EXTRA_KEYWORDS_RE = "|".join(re.escape(k) for k in _EXTRA_KEYWORDS)
|
||||
# A qualifier segment: (...keyword...), [...keyword...], or " - ...keyword..."
|
||||
_QUALIFIER_RE = re.compile(
|
||||
r"(?:[\(\[][^\)\]]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b[^\)\]]*[\)\]])"
|
||||
r"|(?:\s[-–]\s[^\(\[]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def classify_extra(title: str, disambiguation: str = "") -> tuple[bool, str]:
|
||||
"""Return (is_extra, reason). Conservative: only flags clear qualifiers."""
|
||||
disamb = (disambiguation or "").strip().lower()
|
||||
if disamb:
|
||||
for kw in _EXTRA_KEYWORDS:
|
||||
if re.search(r"\b" + re.escape(kw) + r"\b", disamb):
|
||||
return True, disamb
|
||||
m = _QUALIFIER_RE.search(title or "")
|
||||
if m:
|
||||
return True, m.group(0).strip(" -–()[]")
|
||||
return False, ""
|
||||
|
||||
|
||||
class MusicBrainzService:
|
||||
"""Thin async client around the MusicBrainz web service."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._last_request_at = 0.0
|
||||
self._throttle_lock = asyncio.Lock()
|
||||
self._cache: Dict[str, tuple[float, Any]] = {}
|
||||
|
||||
# -- HTTP plumbing -----------------------------------------------------
|
||||
|
||||
async def _throttle(self) -> None:
|
||||
# Non-blocking: yields to the event loop instead of stalling it.
|
||||
async with self._throttle_lock:
|
||||
now = time.monotonic()
|
||||
wait = self._last_request_at + _MIN_INTERVAL_S - now
|
||||
if wait > 0:
|
||||
await asyncio.sleep(wait)
|
||||
self._last_request_at = time.monotonic()
|
||||
|
||||
async def _get(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
cache_key = path + "?" + urlencode(sorted(params.items()))
|
||||
cached = self._cache.get(cache_key)
|
||||
if cached and (time.monotonic() - cached[0]) < _CACHE_TTL_S:
|
||||
return cached[1]
|
||||
params = {**params, "fmt": "json"}
|
||||
last_exc: Optional[Exception] = None
|
||||
for attempt in range(_MAX_RETRIES):
|
||||
await self._throttle()
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT_S) as client:
|
||||
resp = await client.get(
|
||||
f"{MB_BASE}/{path}", params=params, headers={"User-Agent": USER_AGENT}
|
||||
)
|
||||
# MusicBrainz returns 503 when rate-limited/throttled — retry those.
|
||||
if resp.status_code == 503 and attempt < _MAX_RETRIES - 1:
|
||||
last_exc = httpx.HTTPStatusError(
|
||||
"503 from MusicBrainz", request=resp.request, response=resp
|
||||
)
|
||||
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
|
||||
continue
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
self._cache[cache_key] = (time.monotonic(), data)
|
||||
return data
|
||||
except (httpx.TransportError, httpx.TimeoutException) as e:
|
||||
# Connection/timeout errors — retry with backoff.
|
||||
last_exc = e
|
||||
logger.warning("MusicBrainz %s attempt %d/%d failed: %r", path, attempt + 1, _MAX_RETRIES, e)
|
||||
if attempt < _MAX_RETRIES - 1:
|
||||
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
|
||||
# Exhausted retries.
|
||||
raise last_exc if last_exc else RuntimeError(f"MusicBrainz request failed: {path}")
|
||||
|
||||
# -- Public API --------------------------------------------------------
|
||||
|
||||
async def search_artists(self, name: str, limit: int = 8) -> List[Dict[str, Any]]:
|
||||
"""Search artists by name."""
|
||||
if not name or not name.strip():
|
||||
return []
|
||||
data = await self._get("artist", {"query": name.strip(), "limit": limit})
|
||||
out = []
|
||||
for a in data.get("artists", []):
|
||||
out.append(
|
||||
{
|
||||
"mbid": a.get("id"),
|
||||
"name": a.get("name"),
|
||||
"disambiguation": a.get("disambiguation") or "",
|
||||
"type": a.get("type"),
|
||||
"country": a.get("country"),
|
||||
"score": a.get("score"),
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
async def get_albums(self, artist_mbid: str, limit: int = 100) -> List[Dict[str, Any]]:
|
||||
"""List an artist's albums (release-groups), studio albums first, then by date."""
|
||||
data = await self._get(
|
||||
"release-group",
|
||||
{"artist": artist_mbid, "type": "album|ep", "limit": limit},
|
||||
)
|
||||
groups = []
|
||||
for rg in data.get("release-groups", []):
|
||||
secondary = rg.get("secondary-types") or []
|
||||
groups.append(
|
||||
{
|
||||
"release_group_mbid": rg.get("id"),
|
||||
"title": rg.get("title"),
|
||||
"primary_type": rg.get("primary-type"),
|
||||
"secondary_types": secondary,
|
||||
"first_release_date": rg.get("first-release-date") or "",
|
||||
"is_studio": len(secondary) == 0,
|
||||
}
|
||||
)
|
||||
# Studio albums first, then earliest release date.
|
||||
groups.sort(key=lambda g: (not g["is_studio"], g["first_release_date"] or "9999"))
|
||||
return groups
|
||||
|
||||
@staticmethod
|
||||
def _total_tracks(release: Dict[str, Any]) -> int:
|
||||
return sum((m.get("track-count") or 0) for m in (release.get("media") or []))
|
||||
|
||||
async def _list_editions(self, release_group_mbid: str) -> List[Dict[str, Any]]:
|
||||
data = await self._get(
|
||||
"release",
|
||||
{"release-group": release_group_mbid, "inc": "media", "limit": 100},
|
||||
)
|
||||
editions = []
|
||||
for r in data.get("releases", []):
|
||||
editions.append(
|
||||
{
|
||||
"release_mbid": r.get("id"),
|
||||
"title": r.get("title"),
|
||||
"status": r.get("status"),
|
||||
"date": r.get("date") or "",
|
||||
"country": r.get("country"),
|
||||
"packaging": r.get("packaging"),
|
||||
"disambiguation": r.get("disambiguation") or "",
|
||||
"track_count": self._total_tracks(r),
|
||||
}
|
||||
)
|
||||
return editions
|
||||
|
||||
@staticmethod
|
||||
def pick_canonical_edition(
|
||||
editions: List[Dict[str, Any]],
|
||||
preferred_countries: Optional[List[str]] = None,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""Pick the standard edition: official, modal track count, earliest, preferred country.
|
||||
|
||||
Choosing the most common track count avoids deluxe/remaster editions that
|
||||
tack bonus tracks on the end. ``preferred_countries`` overrides the default
|
||||
worldwide-first tie-break (used for locale-aware selection).
|
||||
"""
|
||||
if not editions:
|
||||
return None
|
||||
prefs = preferred_countries or _PREFERRED_COUNTRIES
|
||||
official = [e for e in editions if e.get("status") == "Official"] or editions
|
||||
with_tracks = [e for e in official if e.get("track_count", 0) > 0] or official
|
||||
counts = Counter(e["track_count"] for e in with_tracks if e.get("track_count", 0) > 0)
|
||||
if counts:
|
||||
standard = counts.most_common(1)[0][0]
|
||||
candidates = [e for e in with_tracks if e["track_count"] == standard]
|
||||
else:
|
||||
candidates = with_tracks
|
||||
|
||||
def country_rank(e: Dict[str, Any]) -> int:
|
||||
c = e.get("country")
|
||||
return prefs.index(c) if c in prefs else len(prefs)
|
||||
|
||||
candidates.sort(key=lambda e: (e.get("date") or "9999", country_rank(e)))
|
||||
return candidates[0]
|
||||
|
||||
@staticmethod
|
||||
def build_variants(
|
||||
editions: List[Dict[str, Any]],
|
||||
preferred_countries: Optional[List[str]] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Collapse a release-group's editions into distinct tracklist *variants*.
|
||||
|
||||
Country pressings are irrelevant for karaoke (we only need the track names),
|
||||
so editions are grouped by ``track_count`` — within one release-group, same
|
||||
count ≈ same songs. Each variant exposes a representative release (earliest +
|
||||
preferred-country), the earliest year, how many pressings collapsed in, and a
|
||||
label/delta relative to the "Original" (earliest) variant. Editions without a
|
||||
track count are dropped. See
|
||||
``docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md``.
|
||||
"""
|
||||
if not editions:
|
||||
return []
|
||||
official = [e for e in editions if e.get("status") == "Official"] or editions
|
||||
with_tracks = [e for e in official if (e.get("track_count") or 0) > 0]
|
||||
if not with_tracks:
|
||||
return []
|
||||
|
||||
groups: Dict[int, List[Dict[str, Any]]] = {}
|
||||
for e in with_tracks:
|
||||
groups.setdefault(e["track_count"], []).append(e)
|
||||
|
||||
variants: List[Dict[str, Any]] = []
|
||||
for track_count, group in groups.items():
|
||||
rep = MusicBrainzService.pick_canonical_edition(group, preferred_countries)
|
||||
earliest = min((e.get("date") or "9999") for e in group)
|
||||
year = earliest[:4] if earliest and earliest != "9999" else ""
|
||||
variants.append(
|
||||
{
|
||||
"representative_release_mbid": rep["release_mbid"],
|
||||
"track_count": track_count,
|
||||
"year": year,
|
||||
"pressing_count": len(group),
|
||||
"_earliest": earliest,
|
||||
}
|
||||
)
|
||||
|
||||
# Original = earliest release, then most pressings, then fewest tracks.
|
||||
variants.sort(key=lambda v: (v["_earliest"], -v["pressing_count"], v["track_count"]))
|
||||
original = variants[0]
|
||||
original_tc = original["track_count"]
|
||||
for v in variants:
|
||||
v["delta_vs_original"] = v["track_count"] - original_tc
|
||||
v["label"] = "Original" if v is original else "Reissue"
|
||||
del v["_earliest"]
|
||||
|
||||
# Display order: Original first, then by year ascending, then track count.
|
||||
variants.sort(key=lambda v: (v["label"] != "Original", v["year"] or "9999", v["track_count"]))
|
||||
return variants
|
||||
|
||||
async def get_release_tracklist(self, release_mbid: str) -> Dict[str, Any]:
|
||||
"""Fetch a release's tracklist with per-track extra detection."""
|
||||
data = await self._get(f"release/{release_mbid}", {"inc": "recordings"})
|
||||
tracks: List[Dict[str, Any]] = []
|
||||
for medium in data.get("media") or []:
|
||||
for t in medium.get("tracks") or []:
|
||||
rec = t.get("recording") or {}
|
||||
title = t.get("title") or rec.get("title") or ""
|
||||
disamb = rec.get("disambiguation") or ""
|
||||
is_extra, reason = classify_extra(title, disamb)
|
||||
length_ms = t.get("length") or rec.get("length")
|
||||
tracks.append(
|
||||
{
|
||||
"position": t.get("position"),
|
||||
"title": title,
|
||||
"recording_mbid": rec.get("id"),
|
||||
"disambiguation": disamb,
|
||||
"length_ms": length_ms,
|
||||
"is_extra": is_extra,
|
||||
"extra_reason": reason,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"release_mbid": data.get("id"),
|
||||
"title": data.get("title"),
|
||||
"date": data.get("date") or "",
|
||||
"country": data.get("country"),
|
||||
"tracks": tracks,
|
||||
}
|
||||
|
||||
async def get_album_tracklist(
|
||||
self,
|
||||
release_group_mbid: str,
|
||||
preferred_countries: Optional[List[str]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Resolve the canonical edition of an album and return its tracklist, the raw
|
||||
editions, and the collapsed tracklist ``variants``. ``preferred_countries``
|
||||
biases representative selection (locale-aware)."""
|
||||
editions = await self._list_editions(release_group_mbid)
|
||||
canonical = self.pick_canonical_edition(editions, preferred_countries)
|
||||
variants = self.build_variants(editions, preferred_countries)
|
||||
if not canonical:
|
||||
return {
|
||||
"release_mbid": None,
|
||||
"title": None,
|
||||
"tracks": [],
|
||||
"editions": editions,
|
||||
"variants": variants,
|
||||
"selected_variant_mbid": None,
|
||||
}
|
||||
tracklist = await self.get_release_tracklist(canonical["release_mbid"])
|
||||
tracklist["editions"] = editions
|
||||
tracklist["canonical_release_mbid"] = canonical["release_mbid"]
|
||||
tracklist["variants"] = variants
|
||||
tracklist["selected_variant_mbid"] = canonical["release_mbid"]
|
||||
return tracklist
|
||||
|
||||
|
||||
_service: Optional[MusicBrainzService] = None
|
||||
|
||||
|
||||
def get_musicbrainz_service() -> MusicBrainzService:
|
||||
global _service
|
||||
if _service is None:
|
||||
_service = MusicBrainzService()
|
||||
return _service
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
Fast-path mirror of freshly-published Nomad masters into the Divebar GCS bucket.
|
||||
|
||||
New Nomad releases are uploaded to Google Drive at finalize time, but the Drive->GCS
|
||||
byte-sync VM only runs nightly, so kjbox (which mirrors that GCS folder every 5 min)
|
||||
would otherwise wait up to ~24h for a new master. This pushes the 720p master straight
|
||||
to the exact GCS object the nightly VM would produce, so kjbox picks it up within minutes.
|
||||
|
||||
Idempotent with the nightly VM: identical object name + size means its additive
|
||||
`gcloud storage rsync` sees the file already present and skips it.
|
||||
|
||||
Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding the
|
||||
``NOMADNP`` private-track prefix). Every operation is best-effort / non-fatal: a failure
|
||||
here must never break the distribution pipeline — the nightly VM remains the safety net.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import storage
|
||||
from google.cloud.exceptions import NotFound
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
|
||||
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
|
||||
if not brand_code:
|
||||
return False
|
||||
prefix = brand_code.split("-", 1)[0].strip().upper()
|
||||
return prefix == "NOMAD"
|
||||
|
||||
|
||||
class NomadMasterMirror:
|
||||
"""Push/remove Nomad 720p masters in the Divebar GCS bucket that kjbox mirrors."""
|
||||
|
||||
def __init__(self, client: Optional[storage.Client] = None):
|
||||
self._client = client or storage.Client(project=settings.google_cloud_project)
|
||||
self._bucket = self._client.bucket(settings.divebar_files_bucket)
|
||||
|
||||
def _blob_name(self, filename: str) -> str:
|
||||
prefix = settings.nomad_master_gcs_prefix.strip("/")
|
||||
return f"{prefix}/{filename}"
|
||||
|
||||
def _vocals_blob_name(self, filename: str) -> str:
|
||||
prefix = settings.nomad_vocals_guide_gcs_prefix.strip("/")
|
||||
return f"{prefix}/{filename}"
|
||||
|
||||
def push_720p(self, local_path: str, filename: str) -> bool:
|
||||
"""Upload a 720p master to the divebar GCS mirror. Best-effort; returns success."""
|
||||
blob_name = self._blob_name(filename)
|
||||
try:
|
||||
blob = self._bucket.blob(blob_name)
|
||||
blob.upload_from_filename(local_path)
|
||||
logger.info(
|
||||
"Fast-synced Nomad master to gs://%s/%s",
|
||||
settings.divebar_files_bucket,
|
||||
blob_name,
|
||||
)
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Nomad master fast-sync push failed for %s: %s", blob_name, e)
|
||||
return False
|
||||
|
||||
def delete_720p(self, filename: str) -> bool:
|
||||
"""Delete a 720p master from the mirror. Best-effort; 404 == already gone."""
|
||||
blob_name = self._blob_name(filename)
|
||||
try:
|
||||
self._bucket.blob(blob_name).delete()
|
||||
logger.info(
|
||||
"Removed Nomad master from gs://%s/%s",
|
||||
settings.divebar_files_bucket,
|
||||
blob_name,
|
||||
)
|
||||
return True
|
||||
except NotFound:
|
||||
logger.debug("Nomad master already absent in mirror: %s", blob_name)
|
||||
return False
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Nomad master mirror delete failed for %s: %s", blob_name, e)
|
||||
return False
|
||||
|
||||
def push_vocals_guide(self, local_path: str, filename: str) -> bool:
|
||||
"""Upload a padded original-vocals guide to the divebar GCS mirror's vocals
|
||||
prefix (which kjbox pulls into ``NOMAD-vocals-padded/``). Best-effort."""
|
||||
blob_name = self._vocals_blob_name(filename)
|
||||
try:
|
||||
blob = self._bucket.blob(blob_name)
|
||||
blob.upload_from_filename(local_path)
|
||||
logger.info(
|
||||
"Pushed original-vocals guide to gs://%s/%s",
|
||||
settings.divebar_files_bucket,
|
||||
blob_name,
|
||||
)
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Vocals-guide push failed for %s: %s", blob_name, e)
|
||||
return False
|
||||
|
||||
def delete_vocals_guides_by_brand(self, brand_code: str) -> int:
|
||||
"""Delete ALL original-vocals guide objects for a Nomad release, matched by the
|
||||
unique ``{brand_code} - `` filename prefix (covers renames). Best-effort; returns
|
||||
the count deleted. Refuses a non-Nomad / bare brand code (same guardrail as the
|
||||
master prefix-delete) so a broad prefix can never wipe unrelated objects."""
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return 0
|
||||
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
|
||||
if not suffix.strip():
|
||||
return 0
|
||||
prefix = f"{settings.nomad_vocals_guide_gcs_prefix.strip('/')}/{brand_code} - "
|
||||
deleted = 0
|
||||
try:
|
||||
for blob in self._bucket.list_blobs(prefix=prefix):
|
||||
try:
|
||||
blob.delete()
|
||||
deleted += 1
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to delete vocals-guide object %s: %s", blob.name, e)
|
||||
if deleted:
|
||||
logger.info(
|
||||
"Removed %d original-vocals guide object(s) from gs://%s/%s*",
|
||||
deleted, settings.divebar_files_bucket, prefix,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Vocals-guide mirror prefix-delete failed for %s: %s", prefix, e)
|
||||
return deleted
|
||||
|
||||
def delete_masters_by_brand(self, brand_code: str) -> int:
|
||||
"""Delete ALL 720p master objects for a Nomad release, matched by the unique
|
||||
``{brand_code} - `` filename prefix.
|
||||
|
||||
Keying on the brand_code prefix (rather than a reconstructed title) covers
|
||||
renames for free: every artist/title variant a release was ever published
|
||||
under shares the same ``NOMAD-#### - `` prefix. Best-effort; returns the count
|
||||
deleted. Refuses to run for a non-Nomad / empty brand code so a broad prefix
|
||||
can never match unrelated objects.
|
||||
"""
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return 0
|
||||
# Require a full ``NOMAD-####`` code (non-empty suffix after the hyphen) so the
|
||||
# delete prefix is always specific to one release — never a bare ``NOMAD``.
|
||||
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
|
||||
if not suffix.strip():
|
||||
return 0
|
||||
prefix = f"{settings.nomad_master_gcs_prefix.strip('/')}/{brand_code} - "
|
||||
deleted = 0
|
||||
try:
|
||||
for blob in self._bucket.list_blobs(prefix=prefix):
|
||||
try:
|
||||
blob.delete()
|
||||
deleted += 1
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
|
||||
if deleted:
|
||||
logger.info(
|
||||
"Removed %d Nomad master object(s) from gs://%s/%s*",
|
||||
deleted, settings.divebar_files_bucket, prefix,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Nomad master mirror prefix-delete failed for %s: %s", prefix, e)
|
||||
return deleted
|
||||
|
||||
|
||||
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
|
||||
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
|
||||
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
|
||||
brands or when fast-sync is disabled. Never raises — a cleanup failure must not
|
||||
break job delete/edit flows (the object just lingers until overwritten). Call this
|
||||
wherever the pipeline deletes a job's Drive/Dropbox outputs.
|
||||
"""
|
||||
try:
|
||||
if not settings.nomad_master_fast_sync_enabled:
|
||||
return 0
|
||||
if not is_nomad_public_brand(brand_code):
|
||||
return 0
|
||||
mirror = NomadMasterMirror()
|
||||
deleted = mirror.delete_masters_by_brand(brand_code)
|
||||
# A recycled brand must not keep serving its old original-vocals guide, so remove
|
||||
# the GCS guide(s) too. (Note: with the device's additive-only vocals sync this
|
||||
# won't auto-remove an already-downloaded device copy — a documented limitation.)
|
||||
mirror.delete_vocals_guides_by_brand(brand_code)
|
||||
return deleted
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the caller
|
||||
logger.warning("Nomad master mirror cleanup skipped: %s", e)
|
||||
return 0
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Helpers for locating and naming a job's original input audio.
|
||||
|
||||
The original downloaded/uploaded audio (the source used for separation,
|
||||
transcription and the With Vocals video) is stored in GCS but is no longer
|
||||
copied into the final output folder by the distributed pipeline. These helpers
|
||||
let the orchestrator (and the backfill script) restore it to the Dropbox track
|
||||
folder with the historical source-tagged name, e.g.::
|
||||
|
||||
<artist> - <title> (flacfetch).flac
|
||||
<artist> - <title> (uploaded).mp3
|
||||
<artist> - <title> (YouTube).webm
|
||||
|
||||
The naming mirrors the legacy monolith convention.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
# Map a job's audio_source_type to the historical filename suffix.
|
||||
_SOURCE_TAGS = {
|
||||
"file_upload": "uploaded",
|
||||
"youtube_url": "YouTube",
|
||||
"audio_search": "flacfetch",
|
||||
}
|
||||
|
||||
|
||||
def original_audio_source_tag(job) -> str:
|
||||
"""Return the parenthesised source suffix for a job's original audio.
|
||||
|
||||
Falls back gracefully for older jobs that predate ``audio_source_type``.
|
||||
"""
|
||||
tag = _SOURCE_TAGS.get(getattr(job, "audio_source_type", None))
|
||||
if tag:
|
||||
return tag
|
||||
# Fallbacks for legacy jobs without an explicit source type.
|
||||
if getattr(job, "url", None):
|
||||
return "YouTube"
|
||||
if getattr(job, "filename", None) or getattr(job, "input_media_gcs_path", None):
|
||||
return "uploaded"
|
||||
return "input"
|
||||
|
||||
|
||||
def original_audio_gcs_path(job) -> Optional[str]:
|
||||
"""Return the GCS blob path of the original input audio, or None.
|
||||
|
||||
Prefers ``input_media_gcs_path`` (uploads are persisted under jobs/ and URL
|
||||
jobs record their downloaded file here), then falls back to
|
||||
``file_urls['input']`` which may be a plain string or a nested
|
||||
``{'audio': ...}`` dict depending on the code path that wrote it.
|
||||
"""
|
||||
path = getattr(job, "input_media_gcs_path", None)
|
||||
if path:
|
||||
return path
|
||||
file_urls = getattr(job, "file_urls", None) or {}
|
||||
inp = file_urls.get("input")
|
||||
if isinstance(inp, dict):
|
||||
return inp.get("audio")
|
||||
if isinstance(inp, str):
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def original_audio_output_filename(job, base_name: str) -> Optional[str]:
|
||||
"""Return the output filename for the original audio, or None if absent.
|
||||
|
||||
e.g. ``"<artist> - <title> (flacfetch).flac"``. The extension is preserved
|
||||
from the GCS path.
|
||||
"""
|
||||
gcs_path = original_audio_gcs_path(job)
|
||||
if not gcs_path:
|
||||
return None
|
||||
ext = os.path.splitext(gcs_path)[1]
|
||||
return f"{base_name} ({original_audio_source_tag(job)}){ext}"
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Build the padded original-vocals guide that feeds kjbox's "Original Vocals" slider.
|
||||
|
||||
At render time karaoke-gen already has the isolated ``mixed_vocals`` stem (a byproduct
|
||||
of making the karaoke instrumental) and knows the exact intro offset (the master is
|
||||
``[silent title-card intro] + song + [tail]`` and the intro length is the job's style
|
||||
``intro_video_duration``). So the guide is simply ``silence[intro] + vocals``, capped to
|
||||
the master's duration — no cross-correlation, no human review, no alignment measurement.
|
||||
This is byte-compatible with what the kjbox retro-fit ``pad_vocals.sh`` produced.
|
||||
|
||||
Every function here is best-effort: it returns ``None`` / ``0`` on any failure and never
|
||||
raises, so a guide problem can never break the distribution pipeline.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def probe_duration(path: str, ffprobe_path: str = "ffprobe") -> Optional[float]:
|
||||
"""Return a media file's duration in seconds, or ``None`` if it can't be measured."""
|
||||
try:
|
||||
if not path or not os.path.isfile(path):
|
||||
return None
|
||||
result = subprocess.run(
|
||||
[
|
||||
ffprobe_path, "-v", "error", "-show_entries", "format=duration",
|
||||
"-of", "default=noprint_wrappers=1:nokey=1", path,
|
||||
],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return float(result.stdout.strip())
|
||||
except Exception as e: # noqa: BLE001 - never fatal
|
||||
logger.warning("Could not probe duration for %s: %s", path, e)
|
||||
return None
|
||||
|
||||
|
||||
def build_original_vocals_guide(
|
||||
mixed_vocals_path: str,
|
||||
intro_seconds: float,
|
||||
dest_path: str,
|
||||
master_duration: Optional[float] = None,
|
||||
ffmpeg_path: str = "ffmpeg",
|
||||
) -> Optional[str]:
|
||||
"""Emit ``silence[intro] + mixed_vocals`` as a FLAC guide aligned to the master.
|
||||
|
||||
Args:
|
||||
mixed_vocals_path: The isolated vocals stem (all vocals: lead + backing).
|
||||
intro_seconds: The master's silent title-card length (job's ``intro_video_duration``).
|
||||
dest_path: Where to write the guide (``.flac``).
|
||||
master_duration: If given, the output is capped to this length (``-t``) so the
|
||||
guide can never bleed past the master. Omit to leave the vocals' own length.
|
||||
ffmpeg_path: ffmpeg binary.
|
||||
|
||||
Returns:
|
||||
``dest_path`` on success, else ``None`` (missing input / ffmpeg failure). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not mixed_vocals_path or not os.path.isfile(mixed_vocals_path):
|
||||
logger.warning("Vocals guide: missing mixed-vocals stem %s", mixed_vocals_path)
|
||||
return None
|
||||
if intro_seconds is None or intro_seconds < 0:
|
||||
logger.warning("Vocals guide: invalid intro_seconds %r", intro_seconds)
|
||||
return None
|
||||
|
||||
delay_ms = int(round(float(intro_seconds) * 1000))
|
||||
os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True)
|
||||
tmp_path = dest_path + ".part"
|
||||
|
||||
cmd = [
|
||||
ffmpeg_path, "-y", "-hide_banner", "-nostats", "-loglevel", "error",
|
||||
"-i", mixed_vocals_path,
|
||||
"-af", f"adelay={delay_ms}:all=1",
|
||||
]
|
||||
if master_duration and master_duration > 0:
|
||||
cmd += ["-t", f"{float(master_duration):.3f}"]
|
||||
# ``-f flac`` is mandatory: the ``.part`` extension would otherwise make the
|
||||
# muxer guess the container from the extension and fail.
|
||||
cmd += ["-c:a", "flac", "-f", "flac", tmp_path]
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
|
||||
if result.returncode != 0 or not os.path.isfile(tmp_path):
|
||||
logger.warning(
|
||||
"Vocals guide: ffmpeg failed (rc=%s) for %s: %s",
|
||||
result.returncode, mixed_vocals_path, (result.stderr or "")[-200:].strip(),
|
||||
)
|
||||
_quiet_remove(tmp_path)
|
||||
return None
|
||||
|
||||
os.replace(tmp_path, dest_path)
|
||||
logger.info("Built original-vocals guide: %s", dest_path)
|
||||
return dest_path
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
|
||||
logger.warning("Vocals guide build failed for %s: %s", mixed_vocals_path, e)
|
||||
_quiet_remove(dest_path + ".part")
|
||||
return None
|
||||
|
||||
|
||||
def _quiet_remove(path: str) -> None:
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
"""Batch karaoke-filename → {artist, title, confidence} parser (Vertex Gemini)."""
|
||||
from backend.services.parse_titles.service import parse_titles # noqa: F401
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Vertex-Gemini layer for batch karaoke-filename parsing.
|
||||
|
||||
Turns messy karaoke *filenames* (YouTube titles, community/producer naming,
|
||||
KaraFun-reversed order) into canonical {artist, title, confidence}. Distinct
|
||||
from match_judge (which judges an already-split artist/title). The model call
|
||||
is injectable for tests.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You extract canonical song metadata from karaoke video/file names for a "
|
||||
"karaoke library. Each item has an id and a filename (sometimes a channel or "
|
||||
"source). Filenames are noisy: they carry karaoke markers ('(Karaoke Version)', "
|
||||
"'KARAOKE', '[karaoke]', 'Instrumental', producer/brand tags), YouTube ids or "
|
||||
"channel names, and inconsistent separators. Crucially the artist/title ORDER "
|
||||
"is inconsistent — most are 'Artist - Title' but some sources (e.g. KaraFun) are "
|
||||
"'Title - Artist'. Use your knowledge of real songs to put artist and title in "
|
||||
"the correct fields.\n"
|
||||
"Return JSON: {\"results\": [{\"id\", \"artist\", \"title\", \"confidence\"}]}. "
|
||||
"Return exactly one result per input id, echoing the id verbatim.\n"
|
||||
"artist/title: official formatting, karaoke noise removed, no brand codes or "
|
||||
"YouTube ids. If you cannot identify one field, return it as an empty string.\n"
|
||||
"confidence: 0.0-1.0 — your certainty the artist/title (and their order) are "
|
||||
"correct. Be honest; low confidence for ambiguous or unknown songs. Never invent "
|
||||
"a song; if unsure, return best-effort split with low confidence."
|
||||
)
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
"confidence": {"type": "number"},
|
||||
},
|
||||
"required": ["id"],
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["results"],
|
||||
}
|
||||
|
||||
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "parse_titles_model", "gemini-3.5-flash")
|
||||
except Exception: # pragma: no cover - config guard
|
||||
return "gemini-3.5-flash"
|
||||
|
||||
|
||||
def build_prompts(items: list[dict]) -> tuple[str, str]:
|
||||
lines = ["Parse these karaoke filenames:"]
|
||||
for it in items:
|
||||
parts = [f'id={it.get("id")!r}', f'filename={it.get("filename", "")!r}']
|
||||
if it.get("channel"):
|
||||
parts.append(f'channel={it["channel"]!r}')
|
||||
if it.get("source"):
|
||||
parts.append(f'source={it["source"]!r}')
|
||||
lines.append("- " + " ".join(parts))
|
||||
return _SYSTEM_PROMPT, "\n".join(lines)
|
||||
|
||||
|
||||
def _clean(v) -> str:
|
||||
return (v or "").strip() if isinstance(v, str) else ""
|
||||
|
||||
|
||||
def _conf(v) -> float:
|
||||
try:
|
||||
f = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
return max(0.0, min(1.0, f))
|
||||
|
||||
|
||||
def parse_map_from_response(data: object, items: list[dict]) -> list[dict]:
|
||||
"""Return one id-aligned result per input, filling any misses with blanks."""
|
||||
by_id: dict[str, dict] = {}
|
||||
if isinstance(data, dict):
|
||||
for r in data.get("results") or []:
|
||||
if isinstance(r, dict) and r.get("id") is not None:
|
||||
by_id[str(r["id"])] = r
|
||||
out = []
|
||||
for it in items:
|
||||
rid = str(it.get("id"))
|
||||
r = by_id.get(rid, {})
|
||||
out.append({
|
||||
"id": rid,
|
||||
"artist": _clean(r.get("artist")),
|
||||
"title": _clean(r.get("title")),
|
||||
"confidence": _conf(r.get("confidence")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
async def ai_parse(
|
||||
items: list[dict], *, model: Optional[str] = None,
|
||||
generate: Optional[Generate] = None,
|
||||
) -> list[dict]:
|
||||
gen = generate or _default_generate
|
||||
system, user = build_prompts(items)
|
||||
data = await gen(model or _model(), system, user)
|
||||
return parse_map_from_response(data, items)
|
||||
|
||||
|
||||
async def _default_generate(model: str, system: str, user: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system, user)
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Batch orchestration + graceful degrade for karaoke-filename parsing."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from backend.services.parse_titles import ai
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _blanks(items: list[dict]) -> list[dict]:
|
||||
return [
|
||||
{"id": str(it.get("id")), "artist": "", "title": "", "confidence": 0.0}
|
||||
for it in items
|
||||
]
|
||||
|
||||
|
||||
async def parse_titles(
|
||||
items: list[dict], *, model=None, generate=None
|
||||
) -> list[dict]:
|
||||
"""Parse a batch of filenames → id-aligned {id, artist, title, confidence}.
|
||||
|
||||
Large batches are split into concurrent chunks of parse_titles_chunk_size
|
||||
so a single Gemini call never outgrows parse_titles_timeout_ms (a 100-item
|
||||
single call did, and the timeout blanked the whole batch).
|
||||
|
||||
Never raises: a disabled kill-switch or any model failure yields blank
|
||||
results — per chunk, so one bad chunk doesn't blank its neighbours — and
|
||||
the (kjbox) caller keeps its deterministic guess.
|
||||
"""
|
||||
if not items:
|
||||
return []
|
||||
try:
|
||||
from backend.config import settings
|
||||
enabled = getattr(settings, "parse_titles_enabled", True)
|
||||
max_items = int(getattr(settings, "parse_titles_max_items", 200))
|
||||
chunk_size = max(1, int(getattr(settings, "parse_titles_chunk_size", 10)))
|
||||
except Exception: # pragma: no cover
|
||||
# Fail closed: if config can't load, don't reach for the external AI.
|
||||
logger.warning("parse_titles settings unavailable; disabling parser")
|
||||
enabled, max_items, chunk_size = False, 200, 10
|
||||
if not enabled:
|
||||
return _blanks(items)
|
||||
|
||||
head, tail = items[:max_items], items[max_items:]
|
||||
chunks = [head[i:i + chunk_size] for i in range(0, len(head), chunk_size)]
|
||||
parsed = await asyncio.gather(
|
||||
*(_parse_chunk(chunk, model=model, generate=generate) for chunk in chunks)
|
||||
)
|
||||
return [r for chunk_results in parsed for r in chunk_results] + _blanks(tail)
|
||||
|
||||
|
||||
async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
|
||||
"""One Gemini call; any failure degrades to blanks for this chunk only."""
|
||||
try:
|
||||
results = await ai.ai_parse(chunk, model=model, generate=generate)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
|
||||
return _blanks(chunk)
|
||||
# ai_parse is id-aligned by construction; guard the contract defensively so a
|
||||
# future refactor can't silently return a mis-aligned/short batch.
|
||||
if len(results) != len(chunk):
|
||||
logger.warning(
|
||||
"parse_titles chunk length mismatch; blanks for %d items", len(chunk))
|
||||
return _blanks(chunk)
|
||||
return results
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Duration-based credit pricing. Single source of truth for credit cost.
|
||||
|
||||
credits = max(1, ceil(duration_seconds / 600)) # 10-minute tiers
|
||||
blocked = duration_seconds > 3600 # 60-minute hard ceiling
|
||||
"""
|
||||
from typing import Optional
|
||||
import math
|
||||
|
||||
SECONDS_PER_CREDIT_TIER = 600 # 10 minutes per credit tier
|
||||
DURATION_CREDIT_BLOCK_SECONDS = 3600 # inputs longer than 60 min are not supported
|
||||
|
||||
|
||||
def duration_to_credits(seconds: Optional[float]) -> int:
|
||||
"""Credits required to process `seconds` of audio. Minimum 1."""
|
||||
if seconds is None or not math.isfinite(seconds) or seconds < 0:
|
||||
return 1
|
||||
return max(1, math.ceil(seconds / SECONDS_PER_CREDIT_TIER))
|
||||
|
||||
|
||||
def is_blocked(seconds: Optional[float]) -> bool:
|
||||
"""True if the input exceeds the supported duration ceiling."""
|
||||
return seconds is not None and seconds > DURATION_CREDIT_BLOCK_SECONDS
|
||||
@@ -247,6 +247,11 @@ class PushNotificationService:
|
||||
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
|
||||
url = f"/app/jobs#/{job_id}/review"
|
||||
tag = f"lyrics-{job_id}"
|
||||
elif action_type == "duration_confirm":
|
||||
notif_title = t(locale, "pushNotifications.confirmDurationTitle")
|
||||
notif_body = t(locale, "pushNotifications.confirmDurationBody", title=title, artist=artist)
|
||||
url = "/app"
|
||||
tag = f"duration-confirm-{job_id}"
|
||||
else: # instrumental
|
||||
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
|
||||
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
|
||||
|
||||
Loaded 100 of 527 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user