mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
21
Commits
No files matched your search
@@ -21,7 +21,7 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variants:
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all" (= all except build)'
|
||||
required: false
|
||||
default: 'all'
|
||||
skip_prune:
|
||||
@@ -55,7 +55,10 @@ jobs:
|
||||
run: |
|
||||
requested='${{ github.event.inputs.variants || 'all' }}'
|
||||
if [[ "$requested" == "all" || -z "$requested" ]]; then
|
||||
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
# "build" (docker-build label) is excluded from "all": no job uses it
|
||||
# since deploy-backend moved to ubuntu-latest + Cloud Build
|
||||
# (2026-10-01). Still buildable via an explicit variants=build.
|
||||
echo 'variants=["general","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
|
||||
echo "variants=$json" >> "$GITHUB_OUTPUT"
|
||||
|
||||
+160
-233
@@ -382,13 +382,16 @@ jobs:
|
||||
# hardening as the emulator job's Firestore-emulator install).
|
||||
for attempt in 1 2 3 4 5; do
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
if sudo apt-get update -y && sudo apt-get install -y ffmpeg; then
|
||||
# fonts-noto-core/-cjk: Hebrew, Arabic and CJK glyphs for the CJK/RTL karaoke
|
||||
# render tests (tests/unit/lyrics_transcriber/output/test_ass_render_highlight.py),
|
||||
# matching the fonts in the backend image and encoding worker.
|
||||
if sudo apt-get update -y && sudo apt-get install -y ffmpeg fonts-noto-core fonts-noto-cjk; then
|
||||
break
|
||||
fi
|
||||
echo "apt install attempt ${attempt} failed (likely a transient Hash Sum mismatch); retrying in 15s..."
|
||||
sleep 15
|
||||
done
|
||||
dpkg -s ffmpeg >/dev/null 2>&1
|
||||
dpkg -s ffmpeg fonts-noto-core fonts-noto-cjk >/dev/null 2>&1
|
||||
|
||||
- name: Cache spaCy model
|
||||
uses: actions/cache@v4
|
||||
@@ -1030,6 +1033,11 @@ jobs:
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
# The backend deploy splices PR_TITLE into the comma-delimited
|
||||
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
|
||||
# double-quoted shell string): a comma in a PR title broke the v0.261.2
|
||||
# deploy. Commas → ';', drop newlines and shell-active chars.
|
||||
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
@@ -1087,7 +1095,10 @@ jobs:
|
||||
deploy-backend:
|
||||
name: "Deploy - Backend (Cloud Run)"
|
||||
needs: [package-build]
|
||||
runs-on: [self-hosted, linux, gcp, docker-build]
|
||||
# GitHub-hosted (free for this public repo). Docker images are built in
|
||||
# Cloud Build us-central1 (see "Build and push images" below), so nothing
|
||||
# large is pulled from Artifact Registry to this runner.
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1114,28 +1125,6 @@ jobs:
|
||||
CPU_JOBS_REPOSITORY: karaoke-backend-gpu
|
||||
CPU_JOBS_IMAGE_NAME: karaoke-backend-cpu
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 50 ]; then
|
||||
echo "Disk usage above 50%, cleaning unused images..."
|
||||
docker system prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After image cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Still above 70%, clearing build cache..."
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After build cache cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -1169,6 +1158,11 @@ jobs:
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
# The backend deploy splices PR_TITLE into the comma-delimited
|
||||
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
|
||||
# double-quoted shell string): a comma in a PR title broke the v0.261.2
|
||||
# deploy. Commas → ';', drop newlines and shell-active chars.
|
||||
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
@@ -1756,14 +1750,19 @@ jobs:
|
||||
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
|
||||
|
||||
# ============================================
|
||||
# Docker Build with BuildKit + Registry Cache
|
||||
# This replaces expensive Cloud Build with free GitHub Actions
|
||||
# Registry cache persists between builds for fast rebuilds
|
||||
# Image builds run in Cloud Build (us-central1), not on this runner.
|
||||
#
|
||||
# This job runs on a free GitHub-hosted runner. The app images are built
|
||||
# FROM large bases in us-central1 AR (CPU ~4.2 GB, GPU ~13 GB compressed);
|
||||
# pulling those to a GitHub-hosted runner is GCP internet egress
|
||||
# (~$0.12/GB → ~$2/deploy, far more than the old self-hosted build VM).
|
||||
# Cloud Build in us-central1 pulls them same-region (free) and the
|
||||
# e2-standard-2 default pool is in the 2,500 build-min/month free tier
|
||||
# (~7 min/deploy, CPU+GPU built in parallel). Only the hash checks below
|
||||
# (manifest + ~10KB config blob) touch AR from here.
|
||||
# See infrastructure/cloudbuild/build-backend-images.sh.
|
||||
# ============================================
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Calculate base image hash
|
||||
id: base-hash
|
||||
run: |
|
||||
@@ -1778,7 +1777,6 @@ jobs:
|
||||
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
# Fetch hash label directly from registry (10KB config blob, not full image)
|
||||
# This avoids issues with stale local Docker cache on GitHub runners
|
||||
EXISTING_HASH=""
|
||||
|
||||
# Get the manifest (small JSON, ~1KB) - includes config digest
|
||||
@@ -1809,71 +1807,133 @@ jobs:
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build and push base image (if needed)
|
||||
if: steps.check-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 20
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
# Registry cache for ALL layers (mode=max) - persists between builds
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.base-hash.outputs.hash }}
|
||||
# Provenance disabled for smaller image and faster push
|
||||
provenance: false
|
||||
|
||||
- name: Ensure local base image is current (if not rebuilt)
|
||||
if: steps.check-base.outputs.needs_rebuild == 'false'
|
||||
- name: Calculate GPU base image hash
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
|
||||
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
|
||||
# Using poetry.lock instead of pyproject.toml so that version-only bumps
|
||||
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
# Get the config digest from registry manifest (identifies the image content)
|
||||
# This is the same value as Docker's Image ID for the same image
|
||||
REGISTRY_CONFIG_DIGEST=$(docker manifest inspect $BASE_IMAGE 2>/dev/null | jq -r '.config.digest' || echo "")
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
# Get local image's ID (which is the config digest)
|
||||
LOCAL_IMAGE_ID=$(docker image inspect $BASE_IMAGE --format='{{.Id}}' 2>/dev/null || echo "")
|
||||
# Read the base.content.hash label without pulling the image
|
||||
# (manifest ~1KB + config blob ~10KB). The GPU base lives in
|
||||
# us-central1 (karaoke-repo), next to Cloud Build. The one-time copy
|
||||
# from the legacy us-east4 location was removed: it ran via
|
||||
# `buildx imagetools create` on THIS runner, which on a GitHub-hosted
|
||||
# runner would stream ~13 GB through internet egress.
|
||||
host="${GPU_BASE_IMAGE%%/*}"
|
||||
path="${GPU_BASE_IMAGE#*/}"
|
||||
path="${path%:*}"
|
||||
MANIFEST=$(docker manifest inspect "$GPU_BASE_IMAGE" 2>/dev/null || echo "")
|
||||
# A base copied with `buildx imagetools create` is a single-entry
|
||||
# index — follow it to the image manifest.
|
||||
CHILD=$(echo "$MANIFEST" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
|
||||
if [ -n "$CHILD" ] && [ "$CHILD" != "null" ]; then
|
||||
MANIFEST=$(docker manifest inspect "${GPU_BASE_IMAGE%:*}@${CHILD}" 2>/dev/null || echo "")
|
||||
fi
|
||||
DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
EXISTING_HASH=""
|
||||
if [ -n "$DIGEST" ] && [ "$DIGEST" != "null" ]; then
|
||||
EXISTING_HASH=$(curl -sL -H "Authorization: Bearer $(gcloud auth print-access-token)" \
|
||||
"https://${host}/v2/${path}/blobs/${DIGEST}" 2>/dev/null \
|
||||
| jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
|
||||
fi
|
||||
echo "📋 Registry GPU base image hash: ${EXISTING_HASH:-<none>}"
|
||||
|
||||
echo "Registry config digest: $REGISTRY_CONFIG_DIGEST"
|
||||
echo "Local image ID: $LOCAL_IMAGE_ID"
|
||||
|
||||
if [ -z "$LOCAL_IMAGE_ID" ]; then
|
||||
echo "📥 Base image not in local cache - pulling from registry"
|
||||
docker pull $BASE_IMAGE
|
||||
elif [ "$LOCAL_IMAGE_ID" != "$REGISTRY_CONFIG_DIGEST" ]; then
|
||||
echo "🔄 Local cache has different image - pulling latest"
|
||||
docker pull $BASE_IMAGE
|
||||
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "✅ Local cache matches registry - skipping pull"
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or poetry.lock changed)"
|
||||
echo " Current: $WANT_HASH"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Build and push app image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:latest
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
# Registry cache for app layers
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
- name: Build and push images (Cloud Build us-central1)
|
||||
id: images
|
||||
env:
|
||||
BUILD_BASE: ${{ steps.check-base.outputs.needs_rebuild }}
|
||||
BUILD_GPU_BASE: ${{ steps.check-gpu-base.outputs.needs_rebuild }}
|
||||
BASE_HASH: ${{ steps.base-hash.outputs.hash }}
|
||||
GPU_BASE_HASH: ${{ steps.gpu-base-hash.outputs.hash }}
|
||||
VERSION: ${{ steps.version_check.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Normal deploy: app layers only → free-tier e2-standard-2 (~7 min,
|
||||
# measured). A base rebuild (≈monthly, on poetry.lock / Dockerfile.*base
|
||||
# changes) gets a bigger paid machine + disk + timeout.
|
||||
if [ "$BUILD_BASE" = "true" ] || [ "$BUILD_GPU_BASE" = "true" ]; then
|
||||
MACHINE_ARGS=(--machine-type=e2-highcpu-8 --disk-size=300 --timeout=7200s)
|
||||
echo "🔄 Base rebuild needed (cpu=$BUILD_BASE gpu=$BUILD_GPU_BASE) → e2-highcpu-8"
|
||||
else
|
||||
MACHINE_ARGS=(--disk-size=150 --timeout=3600s)
|
||||
fi
|
||||
|
||||
# Minimal build context (what the Dockerfiles COPY + the build script).
|
||||
SRC="$RUNNER_TEMP/backend-image-src.tgz"
|
||||
tar -czf "$SRC" backend karaoke_gen lyrics_transcriber_temp \
|
||||
pyproject.toml poetry.lock README.md LICENSE .dockerignore \
|
||||
infrastructure/cloudbuild
|
||||
|
||||
BUILD_ID=$(gcloud builds submit "$SRC" \
|
||||
--region=us-central1 \
|
||||
--project=${{ env.PROJECT_ID }} \
|
||||
--config=infrastructure/cloudbuild/backend-images.yaml \
|
||||
"${MACHINE_ARGS[@]}" \
|
||||
--substitutions="_SHA=${{ github.sha }},_VERSION=${VERSION},_RUN_ID=${{ github.run_id }},_BUILD_BASE=${BUILD_BASE},_BASE_HASH=${BASE_HASH},_BUILD_GPU_BASE=${BUILD_GPU_BASE},_GPU_BASE_HASH=${GPU_BASE_HASH}" \
|
||||
--async --format='value(id)')
|
||||
# Recorded before waiting so the cancel step below can stop the build
|
||||
# if this job is cancelled (ci concurrency cancels superseded deploys;
|
||||
# an orphaned build would otherwise still push :latest tags).
|
||||
echo "$BUILD_ID" > "$RUNNER_TEMP/cloudbuild_id"
|
||||
echo "build_id=$BUILD_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "☁️ Cloud Build: https://console.cloud.google.com/cloud-build/builds;region=us-central1/${BUILD_ID}?project=${{ env.PROJECT_ID }}"
|
||||
|
||||
# Stream logs (returns when the build finishes), then check status.
|
||||
gcloud builds log "$BUILD_ID" --region=us-central1 --project=${{ env.PROJECT_ID }} --stream \
|
||||
|| echo "::warning::log streaming ended early; checking build status"
|
||||
# Tolerate transient API errors: a failed poll must not abort the
|
||||
# step (the cancel step below would then kill a healthy build).
|
||||
FAILS=0
|
||||
while true; do
|
||||
if ! STATUS=$(gcloud builds describe "$BUILD_ID" --region=us-central1 \
|
||||
--project=${{ env.PROJECT_ID }} --format='value(status)'); then
|
||||
FAILS=$((FAILS + 1))
|
||||
if [ "$FAILS" -ge 5 ]; then
|
||||
echo "::error::Cannot read Cloud Build $BUILD_ID status"
|
||||
exit 1
|
||||
fi
|
||||
sleep 15
|
||||
continue
|
||||
fi
|
||||
FAILS=0
|
||||
case "$STATUS" in
|
||||
QUEUED|PENDING|WORKING) sleep 15 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
echo "Cloud Build status: $STATUS"
|
||||
if [ "$STATUS" != "SUCCESS" ]; then
|
||||
echo "::error::Cloud Build $BUILD_ID finished with status $STATUS"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Cancel Cloud Build if this job did not finish
|
||||
if: always() && steps.images.outcome != 'success' && steps.images.outcome != 'skipped'
|
||||
run: |
|
||||
ID_FILE="$RUNNER_TEMP/cloudbuild_id"
|
||||
[ -s "$ID_FILE" ] || exit 0
|
||||
gcloud builds cancel "$(cat "$ID_FILE")" --region=us-central1 \
|
||||
--project=${{ env.PROJECT_ID }} --quiet || true
|
||||
|
||||
- name: Pre-import CPU image for us-east4 jobs
|
||||
# A new image digest costs a one-time ~2.5 min "Container image import" on
|
||||
@@ -1892,142 +1952,6 @@ jobs:
|
||||
--quiet \
|
||||
|| echo "::warning::us-east4 CPU image pre-import execution failed to start (non-fatal)"
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# Same pattern as base image: hash check → rebuild if needed.
|
||||
#
|
||||
# Region layout (cost): the ~13 GB GPU base image and all BuildKit
|
||||
# caches live in us-central1 (karaoke-repo), next to this runner, so
|
||||
# building the app layer on top of the base is same-region (free). Only
|
||||
# the FINAL app image is pushed to us-east4 (karaoke-backend-gpu), where
|
||||
# the audio-separation Cloud Run job pulls it same-region. That push only
|
||||
# uploads the small changed app layers — the base layers already exist
|
||||
# there. Previously the base lived in us-east4 and every deploy pulled
|
||||
# ~13 GB across regions (~$12-16/mo AR inter-region egress).
|
||||
# ============================================
|
||||
|
||||
- name: Calculate GPU base image hash
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
|
||||
# Using poetry.lock instead of pyproject.toml so that version-only bumps
|
||||
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
# Legacy location (pre cost-fix). Only used to seed us-central1 once.
|
||||
LEGACY_GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
# Read the base.content.hash label of an image without pulling it
|
||||
# (manifest ~1KB + config blob ~10KB).
|
||||
image_hash() {
|
||||
local image="$1" host path manifest digest
|
||||
host="${image%%/*}"
|
||||
path="${image#*/}"
|
||||
path="${path%:*}"
|
||||
manifest=$(docker manifest inspect "$image" 2>/dev/null || echo "")
|
||||
# `buildx imagetools create` (the one-time copy below) wraps the
|
||||
# image in a single-entry index — follow it to the image manifest.
|
||||
local child
|
||||
child=$(echo "$manifest" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
|
||||
if [ -n "$child" ] && [ "$child" != "null" ]; then
|
||||
manifest=$(docker manifest inspect "${image%:*}@${child}" 2>/dev/null || echo "")
|
||||
fi
|
||||
digest=$(echo "$manifest" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
if [ -z "$digest" ] || [ "$digest" = "null" ]; then
|
||||
echo ""
|
||||
return
|
||||
fi
|
||||
curl -sL -H "Authorization: Bearer $(gcloud auth print-access-token)" \
|
||||
"https://${host}/v2/${path}/blobs/${digest}" 2>/dev/null \
|
||||
| jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo ""
|
||||
}
|
||||
|
||||
EXISTING_HASH=$(image_hash "$GPU_BASE_IMAGE")
|
||||
echo "📋 Registry GPU base image hash (us-central1): ${EXISTING_HASH:-<none>}"
|
||||
|
||||
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# One-time migration: if the legacy us-east4 base is already current,
|
||||
# copy it byte-for-byte (same digests) instead of rebuilding from
|
||||
# scratch, so the image content is unchanged by the move.
|
||||
LEGACY_HASH=$(image_hash "$LEGACY_GPU_BASE_IMAGE")
|
||||
echo "📋 Legacy GPU base image hash (us-east4): ${LEGACY_HASH:-<none>}"
|
||||
if [ -n "$LEGACY_HASH" ] && [ "$LEGACY_HASH" = "$WANT_HASH" ]; then
|
||||
echo "📦 Copying current GPU base from us-east4 to us-central1 (one-time)..."
|
||||
if timeout 30m docker buildx imagetools create --tag "$GPU_BASE_IMAGE" "$LEGACY_GPU_BASE_IMAGE"; then
|
||||
echo "✅ GPU base copied to us-central1"
|
||||
# imagetools wraps the image in a single-entry index; tag the
|
||||
# child manifest too so AR's delete-untagged cleanup policy can
|
||||
# never treat it as an orphan.
|
||||
CHILD=$(docker manifest inspect "$GPU_BASE_IMAGE" | jq -r '.manifests[0].digest // ""' || echo "")
|
||||
if [ -n "$CHILD" ]; then
|
||||
gcloud artifacts docker tags add "${GPU_BASE_IMAGE%:*}@${CHILD}" \
|
||||
"${GPU_BASE_IMAGE%:*}:content-${WANT_HASH:0:12}" --quiet \
|
||||
|| echo "⚠️ Could not tag child manifest (non-fatal)"
|
||||
fi
|
||||
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
echo "⚠️ Copy failed — falling back to a rebuild"
|
||||
fi
|
||||
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or poetry.lock changed)"
|
||||
echo " Current: $WANT_HASH"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push GPU base image (if needed)
|
||||
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 45
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.gpu-base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
|
||||
provenance: false
|
||||
|
||||
- name: Build and push GPU app image
|
||||
# Normally ~2 min (only app layers are new). After a GPU base rebuild
|
||||
# this push also uploads the ~13 GB base layers to us-east4 (they can't
|
||||
# be cross-mounted from the us-central1 registry), hence the headroom.
|
||||
timeout-minutes: 40
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
# Final image → us-east4 (same region as the audio-separation job).
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
# Base + cache → us-central1 (same region as this runner).
|
||||
build-args: |
|
||||
BASE_IMAGE=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
@@ -2072,9 +1996,13 @@ jobs:
|
||||
# forced scale-out, and each overflow request waited out a ~16s app
|
||||
# cold start (2026-09-22 16-tab test: warm instance served in 1.2s,
|
||||
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gave 64
|
||||
# warm slots; min-instances was cut to 1 on 2026-09-26 (GCP cost cut,
|
||||
# accepted perf trade-off: big bursts may hit a ~15s cold start) while
|
||||
# staying far below the wedge-era 80. --clear-vpc-connector: the
|
||||
# warm slots; min-instances was cut to 1 on 2026-09-26 and to 0 on
|
||||
# 2026-10-01 (GCP cost cuts, ~$24/mo idle min-instance charge; Andrew
|
||||
# accepts a ~15s cold start on the first request after idle). In
|
||||
# practice the 60s /api/health uptime check and the */10 Cloud
|
||||
# Scheduler jobs keep an instance warm most of the time — with
|
||||
# --cpu-throttling (request-based billing) a warm-but-idle non-min
|
||||
# instance costs nothing. Concurrency stays far below the wedge-era 80. --clear-vpc-connector: the
|
||||
# serverless VPC connector was deleted (flacfetch is public now).
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
@@ -2091,10 +2019,10 @@ jobs:
|
||||
--timeout 1800 \
|
||||
--concurrency 32 \
|
||||
--max-instances 20 \
|
||||
--min-instances 1 \
|
||||
--min-instances 0 \
|
||||
--clear-vpc-connector \
|
||||
--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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
|
||||
|
||||
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
|
||||
- name: Smoke candidate revision
|
||||
@@ -2240,8 +2168,7 @@ jobs:
|
||||
echo "Branch: ${{ github.ref_name }}"
|
||||
echo "Run: ${{ github.run_number }}"
|
||||
echo ""
|
||||
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
|
||||
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
|
||||
echo "📊 Images built in Cloud Build us-central1: ${{ steps.images.outputs.build_id }}"
|
||||
|
||||
# NOTE: Pulumi infrastructure deploys are done locally, not in CI.
|
||||
# CI runners run on the infrastructure Pulumi manages, creating a circular
|
||||
|
||||
@@ -60,8 +60,10 @@ jobs:
|
||||
# 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.
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. Secrets DO
|
||||
# upload to S3 nightly, so they stay at 36h. GCS job files are NOT
|
||||
# tracked: their off-site copy was stopped 2026-10-01 (egress cost
|
||||
# cut) — they rely on GCS versioning + soft-delete only.
|
||||
# Git repos are also weekly (Sundays) AND incremental since
|
||||
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
|
||||
# quiet week legitimately leaves every .bundle older than 8 days.
|
||||
@@ -70,7 +72,6 @@ jobs:
|
||||
# a run where every repo failed still reads as stale.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 192, None),
|
||||
("GCS job files", "gcs/job-files/", 36, None),
|
||||
("Encrypted secrets", "secrets/", 36, None),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
|
||||
("Git repos", "git-repos/manifest.json", 192, None),
|
||||
|
||||
@@ -112,7 +112,7 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- 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.8 Flash via Vertex AI with GCS cache for efficiency
|
||||
- Translation uses Gemini 3.8 Flash via the **Gemini Developer API** (key: `GEMINI_API_KEY`, else Secret Manager `gemini-api-key` via your gcloud login — `frontend/scripts/gemini_client.py`) with GCS cache for efficiency. **Vertex AI is disabled in the GCP project — never use `vertexai=True`; backend code uses `backend/services/gemini_client.get_genai_client()`.**
|
||||
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
|
||||
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
|
||||
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
|
||||
|
||||
+128
-86
@@ -98,6 +98,8 @@ class JobUpdateRequest(BaseModel):
|
||||
review_mode: Optional[str] = None
|
||||
# Backing-vocals preference: "auto" | "clean" | "review"
|
||||
backing_preference: Optional[str] = None
|
||||
# Translated lyrics language code ("" turns it off)
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
# Editable boolean fields
|
||||
enable_cdg: Optional[bool] = None
|
||||
@@ -136,6 +138,7 @@ EDITABLE_JOB_FIELDS = {
|
||||
"is_private",
|
||||
"review_mode",
|
||||
"backing_preference",
|
||||
"translation_language",
|
||||
# Exempts a job from the stale-review auto-expiry (48h cancel+refund) —
|
||||
# the stale_review_processor skips made_for_you jobs. Used for admin-driven
|
||||
# batches (e.g. KaraokeHunt outreach) that must wait at review indefinitely.
|
||||
@@ -1021,6 +1024,16 @@ async def update_job(
|
||||
detail='review_mode must be "auto" or "always_review"',
|
||||
)
|
||||
|
||||
# Translated lyrics: "" / null turns it off; otherwise a supported language code
|
||||
if "translation_language" in updates:
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
|
||||
raw = updates["translation_language"]
|
||||
code = normalize_language(raw) if raw else None
|
||||
if raw and code is None:
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported translation_language: {raw}")
|
||||
updates["translation_language"] = code
|
||||
|
||||
# backing_preference likewise gates the instrumental decision — reject typos.
|
||||
if "backing_preference" in updates and updates["backing_preference"] not in (
|
||||
"auto", "clean", "review",
|
||||
@@ -1310,6 +1323,9 @@ async def reset_job(
|
||||
# backend/workers/supersede.py. Atomic with the clears above so an in-flight
|
||||
# worker can never observe a half-applied reset.
|
||||
clear_updates["state_data.worker_generation"] = Increment(1)
|
||||
# A reset starts a new run: drop any failed admin re-render's marker.
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
clear_updates.update(clear_admin_rerender_update(job))
|
||||
|
||||
# Add timeline event
|
||||
clear_updates["timeline"] = ArrayUnion([timeline_event])
|
||||
@@ -1685,7 +1701,6 @@ async def delete_job_outputs(
|
||||
Returns:
|
||||
Deletion results for each service
|
||||
"""
|
||||
import re
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
@@ -1711,97 +1726,29 @@ async def delete_job_outputs(
|
||||
)
|
||||
|
||||
state_data = job.state_data or {}
|
||||
results = {
|
||||
"youtube": {"status": "skipped", "reason": "no youtube_url in state_data"},
|
||||
"dropbox": {"status": "skipped", "reason": "no brand_code or dropbox_path"},
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
|
||||
}
|
||||
from backend.services.published_outputs_cleanup import (
|
||||
delete_dropbox_folder,
|
||||
delete_gdrive_files,
|
||||
delete_youtube_video,
|
||||
snapshot_published_outputs,
|
||||
)
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
deleted_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
deleted_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
deleted_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
deleted_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
deleted_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
deleted_outputs = snapshot_published_outputs(state_data)
|
||||
|
||||
log_to_job(job_id, "admin", "INFO", f"Output deletion initiated by {admin_email}", {"deleted_outputs": deleted_outputs})
|
||||
|
||||
# Clean up YouTube
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
results["youtube"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"video_id": video_id
|
||||
}
|
||||
else:
|
||||
results["youtube"] = {"status": "skipped", "reason": "YouTube credentials not configured"}
|
||||
else:
|
||||
results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
|
||||
results["youtube"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Dropbox
|
||||
# Shared helpers (same as Edit / admin re-render): the Dropbox folder name is
|
||||
# sanitised exactly like the uploader names it.
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
base_name = f"{job.artist} - {job.title}"
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": full_path
|
||||
}
|
||||
else:
|
||||
results["dropbox"] = {"status": "skipped", "reason": "Dropbox credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Google Drive
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "skipped", "reason": "Google Drive credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
results = {
|
||||
"youtube": delete_youtube_video(job_id, state_data.get('youtube_url')),
|
||||
"dropbox": delete_dropbox_folder(
|
||||
job_id, getattr(job, 'dropbox_path', None), brand_code, job.artist, job.title
|
||||
),
|
||||
# Mirror cleanup happens below for any brand_code, Drive files or not.
|
||||
"gdrive": delete_gdrive_files(job_id, state_data.get('gdrive_files'), brand_code, cleanup_mirror=False),
|
||||
}
|
||||
|
||||
# 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.
|
||||
@@ -1861,6 +1808,9 @@ async def delete_job_outputs(
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
cleared_keys.append(key)
|
||||
# Outputs are gone; a failed admin re-render's marker no longer applies.
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
update_payload.update(clear_admin_rerender_update(job))
|
||||
|
||||
# Add timeline event with structured metadata
|
||||
timeline_event = {
|
||||
@@ -2448,6 +2398,86 @@ async def regenerate_screens(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Re-render Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class AdminRerenderRequest(BaseModel):
|
||||
"""Request body for POST /api/admin/jobs/{job_id}/rerender."""
|
||||
notify_customer: bool = Field(
|
||||
False,
|
||||
description="Email/push the customer when the re-render completes (default: no notification)",
|
||||
)
|
||||
|
||||
|
||||
class AdminRerenderResponse(BaseModel):
|
||||
"""Response from the admin re-render endpoint."""
|
||||
status: str
|
||||
job_id: str
|
||||
message: str
|
||||
brand_code: Optional[str] = None
|
||||
notify_customer: bool
|
||||
previous_outputs: Dict[str, Any]
|
||||
cleanup_results: Dict[str, Any]
|
||||
warnings: List[str] = []
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/rerender", response_model=AdminRerenderResponse)
|
||||
async def admin_rerender_job(
|
||||
job_id: str,
|
||||
body: Optional[AdminRerenderRequest] = None,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Re-render a completed job end to end without review (admin only).
|
||||
|
||||
Regenerates title/end screens, the karaoke video, every encoded format and
|
||||
the CDG/TXT packages from the job's existing reviewed lyrics and
|
||||
instrumental selection, with the job's existing style snapshot. Published
|
||||
outputs (YouTube video, Google Drive files, Dropbox folder) the re-render
|
||||
will re-publish are deleted up front and re-published under the SAME brand
|
||||
code when the pipeline finishes (the YouTube URL changes); outputs for
|
||||
destinations no longer configured are left in place (see ``warnings``).
|
||||
The customer (and Discord / community voters) are only notified on
|
||||
completion when ``notify_customer`` is true.
|
||||
|
||||
Works for tenant and consumer, public and private jobs in ``complete``
|
||||
status (or ``failed`` after a previous admin re-render).
|
||||
"""
|
||||
from backend.services.admin_rerender_service import AdminRerenderService
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
|
||||
body = body or AdminRerenderRequest()
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
job_manager = JobManager()
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
try:
|
||||
result = await AdminRerenderService(job_manager).start(
|
||||
job, requested_by=admin_email, notify_customer=body.notify_customer
|
||||
)
|
||||
except RerenderError as e:
|
||||
logger.warning(f"Admin {admin_email} re-render of job {job_id} rejected ({e.status_code}): {e}")
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_email} started re-render of job {job_id} "
|
||||
f"(notify_customer={body.notify_customer}, brand_code={result['brand_code']})"
|
||||
)
|
||||
return AdminRerenderResponse(
|
||||
status="processing",
|
||||
job_id=job_id,
|
||||
message="Re-render started. Published outputs will be replaced when it completes.",
|
||||
brand_code=result["brand_code"],
|
||||
notify_customer=body.notify_customer,
|
||||
previous_outputs=result["previous_outputs"],
|
||||
cleanup_results=result["cleanup_results"],
|
||||
warnings=result.get("warnings") or [],
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Restart Job Endpoint
|
||||
# =============================================================================
|
||||
@@ -2538,6 +2568,12 @@ async def restart_job(
|
||||
workers_triggered = []
|
||||
error_msg = None
|
||||
|
||||
# A restart starts a new run: drop any failed admin re-render's marker —
|
||||
# folded into the restart's own atomic update below, so a restart that is
|
||||
# rejected (e.g. 400 on preserve_audio_stems) keeps the marker.
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
marker_clear = clear_admin_rerender_update(job)
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
db = job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
@@ -2590,6 +2626,9 @@ async def restart_job(
|
||||
]
|
||||
|
||||
update_payload = {}
|
||||
update_payload.update(marker_clear)
|
||||
if marker_clear:
|
||||
cleared_keys.append("admin_rerender")
|
||||
for key in keys_to_clear:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
@@ -2643,6 +2682,9 @@ async def restart_job(
|
||||
]
|
||||
|
||||
update_payload = {}
|
||||
update_payload.update(marker_clear)
|
||||
if marker_clear:
|
||||
cleared_keys.append("admin_rerender")
|
||||
for key in keys_to_clear:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
@@ -146,6 +146,7 @@ class AudioSearchRequest(BaseModel):
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
@@ -808,6 +809,7 @@ async def search_audio(
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
|
||||
@@ -261,6 +261,7 @@ class BulkSettings(BaseModel):
|
||||
# Full-auto review (workstream C): batch default autonomy + backing preference.
|
||||
review_mode: str = "auto"
|
||||
backing_preference: str = "auto"
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
@@ -347,6 +348,7 @@ async def bulk_submit(
|
||||
is_private=body.settings.is_private,
|
||||
review_mode=body.settings.review_mode,
|
||||
backing_preference=body.settings.backing_preference,
|
||||
translation_language=body.settings.translation_language,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
|
||||
@@ -188,6 +188,7 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
@@ -250,6 +251,7 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
@@ -496,6 +498,7 @@ async def upload_and_create_job(
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Form("auto", description="'auto' (skip review when confident) or 'always_review'"),
|
||||
backing_preference: str = Form("auto", description="'auto' (retain backing where safe), 'clean', or 'review'"),
|
||||
translation_language: Optional[str] = Form(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none"),
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
|
||||
# Audio editing
|
||||
@@ -727,6 +730,7 @@ async def upload_and_create_job(
|
||||
# Review autonomy + backing-vocals preference (full-auto review)
|
||||
review_mode=review_mode,
|
||||
backing_preference=backing_preference,
|
||||
translation_language=translation_language,
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
@@ -1382,6 +1386,7 @@ async def create_job_with_upload_urls(
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
@@ -2088,6 +2093,7 @@ async def create_job_from_url(
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
|
||||
@@ -312,16 +312,14 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
|
||||
|
||||
def check_audio_separator_status() -> Dict[str, Any]:
|
||||
"""Check audio separator availability without calling the remote GPU service."""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
"""Report audio separation availability.
|
||||
|
||||
Separation runs in the ``audio-separation-job`` GPU Cloud Run Job (local
|
||||
GPU mode, models baked into the image). The standalone ``audio-separator``
|
||||
Cloud Run GPU service was shut down on 2026-10-01 (cost cut), so there is
|
||||
no remote service to probe — this reports the installed package version
|
||||
only and never calls out to anything.
|
||||
"""
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
@@ -331,6 +329,7 @@ def check_audio_separator_status() -> Dict[str, Any]:
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"mode": "gpu_job",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
@@ -338,34 +337,12 @@ def check_audio_separator_status() -> Dict[str, Any]:
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return the installed audio-separator package version.
|
||||
Return audio separation status (installed audio-separator package version).
|
||||
|
||||
Does NOT call the remote GPU service — that would cold-start an expensive
|
||||
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
|
||||
installed package version, which matches what the audio worker uses.
|
||||
|
||||
No authentication required.
|
||||
Does NOT call any remote service — separation runs in the
|
||||
audio-separation-job GPU Cloud Run Job. No authentication required.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
return check_audio_separator_status()
|
||||
|
||||
|
||||
def _get_encoding_worker_manager():
|
||||
|
||||
@@ -204,6 +204,26 @@ async def trigger_auto_approval_eval(
|
||||
return {"job_id": job_id, **result}
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/vocal-gaps")
|
||||
async def analyze_vocal_gaps_endpoint(
|
||||
job_id: str,
|
||||
dry_run: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Find sung stretches with no transcribed lyrics for a job (admin only).
|
||||
|
||||
Shadow-mode calibration/backfill for the missing-lyrics detector: downloads the
|
||||
lead-vocal stem server-side, analyzes the job's current lyrics and stores
|
||||
``state_data.vocal_gaps`` (unless ``dry_run``). Never changes job status.
|
||||
"""
|
||||
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
|
||||
|
||||
logger.info(f"[job:{job_id}] vocal gap analysis requested (dry_run={dry_run})")
|
||||
result = await asyncio.to_thread(analyze_job_vocal_gaps, job_id, not dry_run)
|
||||
return {"job_id": job_id, **result}
|
||||
|
||||
|
||||
@router.post("/workers/lyrics", response_model=WorkerResponse)
|
||||
async def trigger_lyrics_worker(
|
||||
request: WorkerRequest,
|
||||
|
||||
+134
-80
@@ -293,7 +293,6 @@ async def edit_completed_track(
|
||||
No additional credits are consumed — the original credit covers re-edits.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
import re
|
||||
from datetime import timezone
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
@@ -324,94 +323,30 @@ async def edit_completed_track(
|
||||
cleanup_results = {}
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
previous_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
previous_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
previous_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
previous_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
previous_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
from backend.services.published_outputs_cleanup import (
|
||||
delete_dropbox_folder,
|
||||
delete_gdrive_files,
|
||||
delete_youtube_video,
|
||||
snapshot_published_outputs,
|
||||
)
|
||||
previous_outputs = snapshot_published_outputs(state_data)
|
||||
|
||||
log_to_job(job_id, "edit", "INFO", f"Edit initiated by {user_email}", {"previous_outputs": previous_outputs})
|
||||
|
||||
# --- Phase 1: Clean up distributed outputs ---
|
||||
|
||||
# Delete YouTube video
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
cleanup_results["youtube"] = {"status": "success" if success else "failed", "video_id": video_id}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "skipped", "reason": "YouTube not configured"}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["youtube"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "skipped", "reason": "no youtube_url"}
|
||||
cleanup_results["youtube"] = delete_youtube_video(job_id, state_data.get('youtube_url'))
|
||||
log_to_job(job_id, "edit", "INFO", f"YouTube cleanup: {cleanup_results['youtube'].get('status')}", cleanup_results["youtube"])
|
||||
|
||||
# Delete Dropbox folder
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
base_name = f"{job.artist} - {job.title}"
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
cleanup_results["dropbox"] = {"status": "success" if success else "failed", "path": full_path}
|
||||
else:
|
||||
cleanup_results["dropbox"] = {"status": "skipped", "reason": "Dropbox not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["dropbox"] = {"status": "skipped", "reason": "no brand_code or dropbox_path"}
|
||||
cleanup_results["dropbox"] = delete_dropbox_folder(
|
||||
job_id, getattr(job, 'dropbox_path', None), brand_code, job.artist, job.title
|
||||
)
|
||||
log_to_job(job_id, "edit", "INFO", f"Dropbox cleanup: {cleanup_results['dropbox'].get('status')}", cleanup_results["dropbox"])
|
||||
|
||||
# Delete Google Drive files
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
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:
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "no gdrive_files"}
|
||||
# Also removes the Nomad 720p master from the GCS fast-sync mirror (the
|
||||
# brand code is recycled below, so the mirror copy must go).
|
||||
cleanup_results["gdrive"] = delete_gdrive_files(job_id, state_data.get('gdrive_files'), brand_code)
|
||||
log_to_job(job_id, "edit", "INFO", f"GDrive cleanup: {cleanup_results['gdrive'].get('status')}", cleanup_results["gdrive"])
|
||||
|
||||
# Delete GCS finals folder
|
||||
@@ -468,6 +403,11 @@ async def edit_completed_track(
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
# An earlier (failed) admin re-render's marker must not leak into the
|
||||
# edited run (notification suppression, forced brand code).
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
update_payload.update(clear_admin_rerender_update(job))
|
||||
|
||||
# Clear processing state so workers re-run from scratch
|
||||
processing_keys = ["render_progress", "video_progress", "encoding_progress", "review_complete"]
|
||||
for key in processing_keys:
|
||||
@@ -2060,6 +2000,16 @@ async def retry_job(
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
# A failed admin re-render is admin-only to resume: every retry path keeps
|
||||
# its marker (brand code, deleted/re-published outputs, notification choice).
|
||||
from backend.services.admin_rerender_service import active_admin_rerender
|
||||
admin_rerender = active_admin_rerender(job)
|
||||
if admin_rerender and not auth_result.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=t(locale, "jobs.adminRerenderRetryAdminOnly"),
|
||||
)
|
||||
|
||||
# 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).
|
||||
@@ -2080,7 +2030,51 @@ async def retry_job(
|
||||
# Check what state exists to determine retry point
|
||||
file_urls = job.file_urls or {}
|
||||
state_data = job.state_data or {}
|
||||
|
||||
|
||||
# A theme re-render that failed before its new screens were made: re-run
|
||||
# the re-render (not the generic ladder below, which could send the job
|
||||
# back to review). Once screens exist, the render/video branches below
|
||||
# resume it correctly.
|
||||
theme_rerender = state_data.get('theme_rerender') or {}
|
||||
if (theme_rerender.get('theme_id') and original_status == JobStatus.FAILED
|
||||
and not _has_title_screen(file_urls)):
|
||||
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
|
||||
try:
|
||||
await ThemeRerenderService(job_manager).start(
|
||||
job, theme_id=theme_rerender['theme_id'],
|
||||
requested_by=auth_result.user_email or "unknown",
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "lyrics_complete",
|
||||
"message": "Job retry: re-running the theme re-render",
|
||||
"retry_stage": "theme_rerender",
|
||||
}
|
||||
|
||||
# Same for an admin re-render (state_data.admin_rerender): re-run it,
|
||||
# keeping the admin's notify_customer choice. Its published outputs were
|
||||
# already removed on the first attempt (recorded in the marker).
|
||||
if (admin_rerender and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
|
||||
and not _has_title_screen(file_urls)):
|
||||
from backend.services.admin_rerender_service import AdminRerenderService
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
try:
|
||||
await AdminRerenderService(job_manager).start(
|
||||
job,
|
||||
requested_by=auth_result.user_email or "unknown",
|
||||
notify_customer=bool(admin_rerender.get('notify_customer', False)),
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "lyrics_complete",
|
||||
"message": "Job retry: re-running the admin re-render",
|
||||
"retry_stage": "admin_rerender",
|
||||
}
|
||||
|
||||
# If we have a video with vocals and instrumental selection, retry video generation
|
||||
if (file_urls.get('videos', {}).get('with_vocals') and
|
||||
state_data.get('instrumental_selection')):
|
||||
@@ -2664,6 +2658,7 @@ class CreateFromSearchRequest(BaseModel):
|
||||
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
@validator('display_artist', 'display_title')
|
||||
def strip_whitespace(cls, v):
|
||||
@@ -2821,6 +2816,7 @@ async def create_job_from_search(
|
||||
is_private=body.is_private,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
tenant_id=tenant_id,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
@@ -2962,6 +2958,64 @@ async def change_visibility(
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Re-render With Current Theme Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@router.post("/{job_id}/rerender")
|
||||
async def rerender_with_current_theme(
|
||||
job_id: str,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Re-render a finished tenant track with the tenant's current theme.
|
||||
|
||||
Regenerates title/end screens, the lyrics video, final encodes and CDG/TXT
|
||||
packages from the already-reviewed lyrics and instrumental selection — no
|
||||
review step. Used after a tenant edits their theme. Free (tenant jobs are
|
||||
never charged); only the job owner (still on the tenant allowlist) or an
|
||||
admin may trigger it.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job_manager = JobManager()
|
||||
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):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
from backend.services.tenant_admin_service import _theme_id_for
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderError,
|
||||
ThemeRerenderService,
|
||||
validate_rerender,
|
||||
)
|
||||
|
||||
reason = validate_rerender(job)
|
||||
if reason:
|
||||
raise HTTPException(status_code=400, detail=reason)
|
||||
|
||||
tenant = get_tenant_service().get_tenant_config(job.tenant_id)
|
||||
if tenant is None or not tenant.is_active:
|
||||
raise HTTPException(status_code=400, detail="This track's portal is no longer active.")
|
||||
# Re-rendering is free work, so (like tenant billing) require the caller to
|
||||
# still be on the tenant's allowlist — X-Tenant-ID alone proves nothing.
|
||||
if not auth_result.is_admin and not tenant.is_email_allowed(auth_result.user_email or ""):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
theme_id = _theme_id_for(tenant)
|
||||
try:
|
||||
await ThemeRerenderService(job_manager).start(
|
||||
job, theme_id=theme_id, requested_by=auth_result.user_email or "unknown"
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
|
||||
return {"status": "processing", "job_id": job_id, "theme_id": theme_id}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Duration Confirmation Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@@ -802,6 +802,8 @@ async def get_correction_data(
|
||||
- All lyrics correction data (segments, reference lyrics, anchors, etc.)
|
||||
- instrumental_options: List of available instrumental tracks with audio URLs
|
||||
- backing_vocals_analysis: Analysis data to help users choose instrumental
|
||||
- vocal_gaps: sung stretches with no transcribed words (possible missing
|
||||
lyrics) — see services/auto_approval/vocal_gaps.py
|
||||
|
||||
Replay mode (``?replay=true``, requires full auth — admin/owner, not a
|
||||
review-token link): serves the SAME payload for a job in ANY status so the
|
||||
@@ -899,6 +901,10 @@ async def get_correction_data(
|
||||
backing_vocals_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
corrections_data['backing_vocals_analysis'] = backing_vocals_analysis
|
||||
|
||||
# Possible missing lyrics (auto-approval analysis): the review UI marks
|
||||
# "evidenced" gaps and offers the reference lines for insertion.
|
||||
corrections_data['vocal_gaps'] = job.state_data.get('vocal_gaps') or None
|
||||
|
||||
# Per-screen skip (C1): tell the frontend whether each review half is
|
||||
# confidently auto-resolved, so it can skip the instrumental screen (or the
|
||||
# lyrics screen). Derived from the stored auto-approval verdict + the job's
|
||||
|
||||
@@ -55,6 +55,7 @@ class TenantSummary(BaseModel):
|
||||
locked_theme: Optional[str] = None
|
||||
theme_id: Optional[str] = None
|
||||
dropbox_path: Optional[str] = None
|
||||
brand_prefix: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
|
||||
|
||||
@@ -262,8 +263,12 @@ async def admin_update_tenant(
|
||||
)
|
||||
except TenantNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
except TenantConflictError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
except TenantValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except TenantProvisioningError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid config: {exc}")
|
||||
except ValueError as exc:
|
||||
|
||||
@@ -6,6 +6,7 @@ These endpoints are public (no authentication required) to allow theme selection
|
||||
before job creation.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
@@ -43,6 +44,35 @@ async def list_themes(request: Request) -> ThemesListResponse:
|
||||
)
|
||||
|
||||
|
||||
@router.get("/translation-preview")
|
||||
async def get_translation_preview(language: str, request: Request) -> dict:
|
||||
"""
|
||||
Preview frame of a translated-lyrics karaoke video in ``language``.
|
||||
|
||||
Renders the default theme's karaoke frame with sample lyrics and their
|
||||
(pre-generated) translation beneath each line, so users can see the option
|
||||
before enabling it at job creation. Public, like the other theme endpoints.
|
||||
|
||||
Returns:
|
||||
Object with ``image`` (JPEG data URL)
|
||||
|
||||
Raises:
|
||||
400: Unsupported language
|
||||
"""
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
from backend.services.translation_preview import render_translation_preview
|
||||
|
||||
code = normalize_language(language)
|
||||
if code is None:
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported language: {language}")
|
||||
try:
|
||||
image = await asyncio.to_thread(render_translation_preview, code)
|
||||
except Exception as e:
|
||||
logger.error(f"Error rendering translation preview for {code}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail="Could not render the translation preview")
|
||||
return {"image": image}
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
"""
|
||||
|
||||
@@ -15,9 +15,9 @@ steps:
|
||||
- '-f'
|
||||
- 'backend/Dockerfile.gpu-base'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- '--build-arg'
|
||||
- 'BUILD_DATE=$_BUILD_DATE'
|
||||
- '--build-arg'
|
||||
@@ -25,8 +25,8 @@ steps:
|
||||
- '.'
|
||||
|
||||
images:
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
|
||||
timeout: '3600s'
|
||||
|
||||
|
||||
+6
-2
@@ -82,9 +82,9 @@ class Settings(BaseSettings):
|
||||
|
||||
# Agentic AI Correction (for lyrics correction via LLM)
|
||||
# Only used when skip_correction=false
|
||||
# When enabled, uses Gemini via Vertex AI for intelligent lyrics correction
|
||||
# When enabled, uses Gemini (Developer API, key GEMINI_API_KEY) for intelligent lyrics correction
|
||||
use_agentic_ai: bool = os.getenv("USE_AGENTIC_AI", "true").lower() in ("true", "1", "yes")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3.8-flash")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "gemini/gemini-3.8-flash")
|
||||
# Timeout for agentic correction in seconds. If correction takes longer, abort and
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
@@ -117,6 +117,10 @@ class Settings(BaseSettings):
|
||||
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
|
||||
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
|
||||
|
||||
# Translated lyrics — per-job opt-in (Job.translation_language): the reviewed
|
||||
# lyrics are translated line-by-line just before the karaoke video renders.
|
||||
lyrics_translation_model: str = os.getenv("LYRICS_TRANSLATION_MODEL", "gemini-3.8-flash")
|
||||
|
||||
# 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.
|
||||
|
||||
@@ -290,6 +290,11 @@ class Job(BaseModel):
|
||||
# instrumental. Consumed by the auto-approval instrumental decision.
|
||||
backing_preference: str = "auto"
|
||||
|
||||
# Translated lyrics: language code (one of the UI locales, e.g. "en", "es") whose
|
||||
# LLM translation of each reviewed line is drawn in smaller text beneath it in the
|
||||
# karaoke videos. None = no translation row. See backend/services/lyrics_translation.py.
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
|
||||
@@ -586,6 +591,8 @@ class JobCreate(BaseModel):
|
||||
# "auto" (default) = retain backing vocals where confidently safe; "clean" =
|
||||
# always strip backing vocals; "review" = always let a human pick the instrumental.
|
||||
backing_preference: str = "auto"
|
||||
# Translated lyrics language (see Job.translation_language); None = off
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
@@ -684,6 +691,16 @@ class JobCreate(BaseModel):
|
||||
executor already treats any non-"auto" value as an enforcement blocker."""
|
||||
return v if v in ("auto", "always_review") else "always_review"
|
||||
|
||||
@validator('translation_language')
|
||||
def _normalize_translation_language(cls, v):
|
||||
"""Supported language code; empty or unsupported values turn the feature off
|
||||
(every creation route passes the client value straight through)."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
|
||||
return normalize_language(v)
|
||||
|
||||
@validator('backing_preference')
|
||||
def _normalize_backing_preference(cls, v):
|
||||
"""Coerce an out-of-set value to the default. Every creation route passes
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Regenerate backend/services/translation_preview_samples.py.
|
||||
|
||||
The job-creation "translated lyrics" preview renders sample lyrics with their
|
||||
translation beneath. Translations are generated once with the production
|
||||
translation service and committed, so the preview never calls the LLM.
|
||||
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke python backend/scripts/generate_translation_preview_samples.py
|
||||
"""
|
||||
import os
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||
|
||||
from backend.services.lyrics_translation import TRANSLATION_LANGUAGES, LyricsTranslationService # noqa: E402
|
||||
from backend.services.theme_preview_service import DEFAULT_SAMPLE_LYRICS # noqa: E402
|
||||
|
||||
# Shown instead of the English sample when the target language is English
|
||||
SPANISH_SAMPLE_LYRICS = [
|
||||
"Cada noche canto sin parar",
|
||||
"Se apagan las luces, es mi lugar",
|
||||
"Tomo el micrófono y subo al escenario",
|
||||
"Doy la vuelta a la página otra vez",
|
||||
]
|
||||
|
||||
|
||||
class _NoCache:
|
||||
def file_exists(self, path):
|
||||
return False
|
||||
|
||||
def upload_json(self, path, data):
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
service = LyricsTranslationService(storage=_NoCache())
|
||||
samples = {}
|
||||
for code in TRANSLATION_LANGUAGES:
|
||||
source = SPANISH_SAMPLE_LYRICS if code == "en" else DEFAULT_SAMPLE_LYRICS
|
||||
samples[code] = {"lyrics": source, "translations": service.translate_lines(source, code)}
|
||||
print(code, samples[code]["translations"][0], file=sys.stderr)
|
||||
out = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "services", "translation_preview_samples.py")
|
||||
with open(out, "w", encoding="utf-8") as f:
|
||||
f.write('"""Sample lyrics + translations for the translated-lyrics preview.\n\n')
|
||||
f.write("Generated by backend/scripts/generate_translation_preview_samples.py; don't edit by hand.\n")
|
||||
f.write('"""\n\n')
|
||||
f.write("SAMPLES = " + pprint.pformat(samples, width=110, sort_dicts=False) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,546 @@
|
||||
"""
|
||||
Admin re-render: rebuild ANY finished job end to end without a review step.
|
||||
|
||||
Use case: a renderer fix (e.g. RTL/Hebrew lyrics, v0.255.0) needs videos that
|
||||
were already delivered regenerated. Unlike the tenant "Re-render with current
|
||||
theme" (theme_rerender_service), this:
|
||||
|
||||
- works for every job (consumer or tenant, public or private);
|
||||
- keeps the job's EXISTING style snapshot (``jobs/{id}/style/...``,
|
||||
``style_params_gcs_path``, ``style_assets``) — no theme re-snapshot;
|
||||
- deletes the published outputs (YouTube video, Google Drive files, Dropbox
|
||||
folder) up front, like Edit — but only for destinations the re-render will
|
||||
re-publish to (see ``plan_republish``); others are left in place with a
|
||||
warning. The brand code is KEPT (never recycled): the video worker
|
||||
re-publishes under the same code via ``rerender_brand_code``. YouTube gets a
|
||||
new upload, so the YouTube URL changes;
|
||||
- doesn't email/push the customer (or Discord / community voters) on
|
||||
completion unless the admin opted in (``notify_customer``) — see
|
||||
``suppress_customer_notifications``.
|
||||
|
||||
Mechanism (shared with the theme re-render and the private->public visibility
|
||||
flow): atomically move the job COMPLETE -> LYRICS_COMPLETE with
|
||||
``state_data.regen_restore_status = "review_complete"`` and trigger the screens
|
||||
worker. The screens worker regenerates the screens, restores REVIEW_COMPLETE and
|
||||
triggers the render worker, which renders from the existing
|
||||
corrections_updated.json; the video worker then encodes, distributes and
|
||||
completes using ``state_data.instrumental_selection``.
|
||||
|
||||
``state_data.admin_rerender`` is the in-progress marker. The video worker clears
|
||||
it on success; a FAILED admin re-render keeps it, which lets an admin
|
||||
``POST /api/jobs/{id}/retry`` (or another admin re-render) resume it. The marker
|
||||
only applies to its own run: it records the job's ``review_token`` at claim
|
||||
(a new token is minted whenever the job goes back through review), and the
|
||||
admin reset/restart, Edit, visibility and delete-outputs flows clear it.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.published_outputs_cleanup import (
|
||||
delete_dropbox_folder,
|
||||
delete_gdrive_files,
|
||||
delete_youtube_video,
|
||||
snapshot_published_outputs,
|
||||
)
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderConflictError,
|
||||
RerenderError,
|
||||
delete_regenerated_artifacts,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ADMIN_RERENDER_MARKER = "admin_rerender"
|
||||
_LOG_SOURCE = "admin-rerender"
|
||||
|
||||
# destination -> state_data keys that reference its published output
|
||||
_DESTINATION_KEYS = {
|
||||
"youtube": ("youtube_url", "youtube_video_id", "youtube_upload_queued"),
|
||||
"dropbox": ("dropbox_link",),
|
||||
"gdrive": ("gdrive_files",),
|
||||
}
|
||||
# state_data link a destination's output is recorded under (kept_outputs keys)
|
||||
_DESTINATION_LINK = {"youtube": "youtube_url", "dropbox": "dropbox_link", "gdrive": "gdrive_files"}
|
||||
|
||||
|
||||
# --- Marker helpers ------------------------------------------------------------
|
||||
|
||||
def raw_admin_rerender_marker(job) -> Dict[str, Any]:
|
||||
"""The stored marker, regardless of whether it belongs to the current run."""
|
||||
state_data = getattr(job, "state_data", None)
|
||||
marker = state_data.get(ADMIN_RERENDER_MARKER) if isinstance(state_data, dict) else None
|
||||
return marker if isinstance(marker, dict) else {}
|
||||
|
||||
|
||||
def active_admin_rerender(job) -> Dict[str, Any]:
|
||||
"""The marker if it belongs to the job's current run, else ``{}``.
|
||||
|
||||
A job that has since gone back through review (admin reset, Edit, ...) has a
|
||||
new ``review_token``, so a stale marker from a failed admin re-render no
|
||||
longer suppresses notifications or forces the brand code.
|
||||
"""
|
||||
marker = raw_admin_rerender_marker(job)
|
||||
if marker and "review_token" in marker:
|
||||
if marker["review_token"] != getattr(job, "review_token", None):
|
||||
return {}
|
||||
return marker
|
||||
|
||||
|
||||
def admin_rerender_blocks_upload(job_data: Dict[str, Any]) -> bool:
|
||||
"""True if a queued YouTube upload must not start for this job (raw job doc).
|
||||
|
||||
An ACTIVE (review_token-scoped) admin re-render on a job that isn't complete
|
||||
is rebuilding (or failed while rebuilding) the finals. Used inside the
|
||||
queue's claim transaction, which reads the job doc.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
view = SimpleNamespace(
|
||||
state_data=job_data.get("state_data") or {},
|
||||
review_token=job_data.get("review_token"),
|
||||
)
|
||||
return bool(active_admin_rerender(view)) and job_data.get("status") != JobStatus.COMPLETE.value
|
||||
|
||||
|
||||
UPLOAD_IN_PROGRESS_MESSAGE = (
|
||||
"A YouTube upload for this track is in progress — try again in a few minutes."
|
||||
)
|
||||
|
||||
|
||||
def claim_with_youtube_queue(
|
||||
db, job_id: str, update: Dict[str, Any], allowed_statuses: set,
|
||||
cancel_deferred_upload: bool, keep_reason: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Atomically claim the job for an admin re-render, reading its YouTube queue doc too.
|
||||
|
||||
- job status not claimable → RerenderConflictError (409);
|
||||
- a deferred upload is ``processing`` → RerenderConflictError (409): an
|
||||
upload of the old finals must never overlap the re-render;
|
||||
- a ``queued``/``failed`` entry is cancelled in the same transaction when
|
||||
the re-render will re-publish YouTube, otherwise left in place (warning).
|
||||
|
||||
The queue's ``mark_processing`` transaction reads the job doc and refuses
|
||||
while an admin re-render is active, so the two can never interleave.
|
||||
Returns the queue outcome, e.g. ``{"status": "cancelled", "previous_status": "queued"}``.
|
||||
"""
|
||||
from backend.services.youtube_upload_queue_service import (
|
||||
PACIFIC_TZ,
|
||||
YOUTUBE_UPLOAD_QUEUE_COLLECTION,
|
||||
)
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
# Same collection the YouTube queue's mark_processing transaction reads, so
|
||||
# the two claims always contend on the same job document.
|
||||
job_ref = db.collection(get_settings().firestore_collection).document(job_id)
|
||||
queue_ref = db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
marker_key = f"state_data.{ADMIN_RERENDER_MARKER}"
|
||||
|
||||
@firestore.transactional
|
||||
def claim(transaction):
|
||||
snapshot = job_ref.get(transaction=transaction)
|
||||
queue_snapshot = queue_ref.get(transaction=transaction)
|
||||
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
|
||||
if status not in allowed_statuses:
|
||||
return "not_claimable", None
|
||||
queue_status = (queue_snapshot.to_dict() or {}).get("status") if queue_snapshot.exists else None
|
||||
if queue_status == "processing":
|
||||
return "uploading", None
|
||||
|
||||
payload = dict(update) # fresh copy per transaction attempt
|
||||
if queue_status in ("queued", "failed"):
|
||||
if cancel_deferred_upload:
|
||||
transaction.update(queue_ref, {
|
||||
"status": "cancelled",
|
||||
"last_error": "Cancelled: admin re-render will re-upload",
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
outcome = {"status": "cancelled", "previous_status": queue_status}
|
||||
else:
|
||||
warning = f"pending deferred YouTube upload left queued (YouTube not re-published: {keep_reason})"
|
||||
marker = dict(payload[marker_key])
|
||||
marker["warnings"] = [*marker.get("warnings", []), warning]
|
||||
payload[marker_key] = marker
|
||||
outcome = {"status": "kept", "previous_status": queue_status, "reason": keep_reason,
|
||||
"warning": warning}
|
||||
else:
|
||||
outcome = {"status": "skipped",
|
||||
"reason": "no queue entry" if queue_status is None else f"entry is {queue_status}"}
|
||||
transaction.update(job_ref, payload)
|
||||
return "ok", outcome
|
||||
|
||||
result, outcome = claim(db.transaction())
|
||||
if result == "uploading":
|
||||
raise RerenderConflictError(UPLOAD_IN_PROGRESS_MESSAGE)
|
||||
if result != "ok":
|
||||
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
|
||||
return outcome
|
||||
|
||||
|
||||
def clear_admin_rerender_update(job) -> Dict[str, Any]:
|
||||
"""Firestore update that drops the marker (empty if there is none)."""
|
||||
if raw_admin_rerender_marker(job):
|
||||
return {f"state_data.{ADMIN_RERENDER_MARKER}": DELETE_FIELD}
|
||||
return {}
|
||||
|
||||
|
||||
def suppress_customer_notifications(job) -> bool:
|
||||
"""True if this run's customer-facing notifications must be skipped.
|
||||
|
||||
Only an active admin re-render the admin didn't opt into announcing
|
||||
suppresses them; normal jobs and the tenant theme re-render always notify.
|
||||
"""
|
||||
marker = active_admin_rerender(job)
|
||||
return bool(marker) and not marker.get("notify_customer", False)
|
||||
|
||||
|
||||
def admin_rerender_brand_code(job) -> Optional[str]:
|
||||
return active_admin_rerender(job).get("brand_code") or None
|
||||
|
||||
|
||||
def admin_rerender_kept_outputs(job) -> Dict[str, Any]:
|
||||
"""Published outputs left in place (not re-published) by the active re-render."""
|
||||
return active_admin_rerender(job).get("kept_outputs") or {}
|
||||
|
||||
|
||||
# --- Validation / planning -----------------------------------------------------
|
||||
|
||||
def _claimable_statuses(job) -> set:
|
||||
"""COMPLETE, plus FAILED/CANCELLED when that was an admin re-render (resume)."""
|
||||
statuses = {JobStatus.COMPLETE.value}
|
||||
if active_admin_rerender(job):
|
||||
statuses.update({JobStatus.FAILED.value, JobStatus.CANCELLED.value})
|
||||
return statuses
|
||||
|
||||
|
||||
def validate_admin_rerender(job) -> Optional[str]:
|
||||
"""Return a reason the job can't be re-rendered, or None if it can."""
|
||||
if job.status not in _claimable_statuses(job):
|
||||
return f"Only completed jobs can be re-rendered (current status: {job.status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This job's outputs were deleted, so it can't be re-rendered."
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "Prep-only / finalise-only jobs can't be re-rendered."
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get("visibility_change_in_progress"):
|
||||
return "A visibility change is in progress for this job."
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "This job has no instrumental selection to re-render with."
|
||||
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "This job has no reviewed lyrics to re-render with."
|
||||
return None
|
||||
|
||||
|
||||
def plan_republish(job) -> Dict[str, Tuple[bool, Optional[str]]]:
|
||||
"""Which destinations the re-render's distribution step will publish to.
|
||||
|
||||
Mirrors the video worker: YouTube needs ``enable_youtube_upload`` on a
|
||||
non-private job (effective distribution) and configured YouTube credentials;
|
||||
Dropbox needs an effective ``dropbox_path`` and ``brand_prefix``; Google
|
||||
Drive needs an effective ``gdrive_folder_id``. Returns
|
||||
``{destination: (will_republish, reason_if_not)}``. Does blocking I/O
|
||||
(YouTube credential lookup) — call off the event loop.
|
||||
"""
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
plan: Dict[str, Tuple[bool, Optional[str]]] = {}
|
||||
|
||||
if getattr(job, "is_private", False) or not dist.enable_youtube_upload:
|
||||
plan["youtube"] = (False, "YouTube upload is disabled for this job")
|
||||
else:
|
||||
try:
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
configured = get_youtube_service().is_configured
|
||||
reason = "YouTube credentials are not configured"
|
||||
except Exception as e:
|
||||
# Can't plan → don't delete or cancel anything YouTube; warn instead.
|
||||
logger.warning(f"[job:{job.job_id}] YouTube credential check failed: {e}")
|
||||
configured = False
|
||||
reason = f"couldn't verify YouTube credentials ({e})"
|
||||
plan["youtube"] = (True, None) if configured else (False, reason)
|
||||
|
||||
if dist.dropbox_path and dist.brand_prefix:
|
||||
plan["dropbox"] = (True, None)
|
||||
else:
|
||||
plan["dropbox"] = (False, "Dropbox upload is not configured for this job")
|
||||
|
||||
if dist.gdrive_folder_id:
|
||||
plan["gdrive"] = (True, None)
|
||||
else:
|
||||
plan["gdrive"] = (False, "Google Drive upload is not configured for this job")
|
||||
return plan
|
||||
|
||||
|
||||
def _has_output(state_data: dict, destination: str) -> bool:
|
||||
return bool(state_data.get(_DESTINATION_LINK[destination]))
|
||||
|
||||
|
||||
# --- Service ---------------------------------------------------------------------
|
||||
|
||||
class AdminRerenderService:
|
||||
def __init__(
|
||||
self,
|
||||
job_manager: Optional[JobManager] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
self.storage = storage or StorageService()
|
||||
|
||||
async def start(self, job, requested_by: str, notify_customer: bool = False) -> Dict[str, Any]:
|
||||
"""Claim the job, delete its re-publishable outputs and kick off the re-render.
|
||||
|
||||
Blocking Firestore/GCS/YouTube/Dropbox/GDrive work runs in worker
|
||||
threads. Any failure after the claim marks the job FAILED with the
|
||||
marker kept (so it can be retried) and raises RerenderError.
|
||||
|
||||
Returns ``{"brand_code", "previous_outputs", "cleanup_results", "warnings"}``.
|
||||
Raises RerenderError (400/500/503) or RerenderConflictError (409).
|
||||
"""
|
||||
reason = validate_admin_rerender(job)
|
||||
if reason:
|
||||
raise RerenderError(reason)
|
||||
|
||||
plan = await asyncio.to_thread(plan_republish, job)
|
||||
update, context = self._build_claim(job, requested_by, notify_customer, plan)
|
||||
queue_outcome = await asyncio.to_thread(
|
||||
claim_with_youtube_queue, self.job_manager.firestore.db, job.job_id, update,
|
||||
_claimable_statuses(job), plan["youtube"][0], plan["youtube"][1],
|
||||
)
|
||||
context["youtube_queue"] = queue_outcome
|
||||
if queue_outcome.get("warning"):
|
||||
context["warnings"].append(queue_outcome["warning"])
|
||||
|
||||
job_id = job.job_id
|
||||
try:
|
||||
cleanup_results = await asyncio.to_thread(self._after_claim, job, context, plan)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
except Exception as e:
|
||||
logger.exception(f"[job:{job_id}] Admin re-render failed after claim")
|
||||
await asyncio.to_thread(self._fail_run, job_id, f"Admin re-render failed to start: {e}", "start_error")
|
||||
raise RerenderError(
|
||||
f"The re-render failed to start ({e}). The job was marked failed; retry it to continue.",
|
||||
status_code=500,
|
||||
) from e
|
||||
|
||||
if not triggered:
|
||||
await asyncio.to_thread(
|
||||
self._fail_run, job_id,
|
||||
"Admin re-render couldn't start the screens worker. Retry the job to continue.",
|
||||
"screens_trigger_failed",
|
||||
)
|
||||
raise RerenderError("Couldn't start the re-render. Please retry the job.", status_code=503)
|
||||
|
||||
await asyncio.to_thread(log_to_job, job_id, _LOG_SOURCE, "INFO",
|
||||
"Re-render started (screens worker triggered)",
|
||||
{"cleanup_results": cleanup_results})
|
||||
return {
|
||||
"brand_code": context["brand_code"],
|
||||
"previous_outputs": context["previous_outputs"],
|
||||
"cleanup_results": cleanup_results,
|
||||
"warnings": context["warnings"],
|
||||
}
|
||||
|
||||
def _build_claim(self, job, requested_by: str, notify_customer: bool, plan) -> Tuple[dict, dict]:
|
||||
state_data = job.state_data or {}
|
||||
# Only the ACTIVE (same-run) marker carries over: a stale one from an
|
||||
# earlier run must not leak its brand code / history into this run.
|
||||
previous_marker = active_admin_rerender(job)
|
||||
# On a retry the re-published outputs were already removed (and cleared
|
||||
# from state_data) by the first attempt — keep that attempt's record.
|
||||
previous_outputs = {
|
||||
**(previous_marker.get("previous_outputs") or {}),
|
||||
**snapshot_published_outputs(state_data),
|
||||
}
|
||||
brand_code = state_data.get("brand_code") or previous_marker.get("brand_code")
|
||||
is_retry = bool(previous_marker)
|
||||
|
||||
warnings: List[str] = []
|
||||
kept_outputs: Dict[str, Any] = {}
|
||||
for destination, (republish, why) in plan.items():
|
||||
if not republish and _has_output(state_data, destination):
|
||||
link_key = _DESTINATION_LINK[destination]
|
||||
kept_outputs[link_key] = state_data[link_key]
|
||||
warnings.append(f"{destination} output left in place (not re-published): {why}")
|
||||
republish_youtube = plan["youtube"][0]
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
message = (
|
||||
f"Admin re-render requested by {requested_by} "
|
||||
f"(existing style, no review; brand code {brand_code or 'n/a'} kept; "
|
||||
f"customer notification {'on' if notify_customer else 'off'})"
|
||||
)
|
||||
update: Dict[str, Any] = {
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"progress": 50,
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"state_data.distribution_warnings": DELETE_FIELD,
|
||||
f"state_data.{ADMIN_RERENDER_MARKER}": {
|
||||
"requested_by": requested_by,
|
||||
"requested_at": now.isoformat(),
|
||||
"notify_customer": bool(notify_customer),
|
||||
"brand_code": brand_code,
|
||||
"previous_outputs": previous_outputs,
|
||||
"kept_outputs": kept_outputs,
|
||||
"warnings": warnings,
|
||||
"republish_youtube": republish_youtube,
|
||||
# Run identity: a later trip through review mints a new token,
|
||||
# which retires this marker (see active_admin_rerender).
|
||||
"review_token": getattr(job, "review_token", None),
|
||||
},
|
||||
# Old screens are deleted after the claim; drop their file_urls so
|
||||
# nothing (e.g. a later retry) reuses them.
|
||||
"file_urls.screens": DELETE_FIELD,
|
||||
"file_urls.videos.with_vocals": DELETE_FIELD,
|
||||
"updated_at": now,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": message,
|
||||
"metadata": {
|
||||
"action": "admin_rerender_initiated",
|
||||
"initiated_by": requested_by,
|
||||
"notify_customer": bool(notify_customer),
|
||||
"brand_code": brand_code,
|
||||
"previous_outputs": previous_outputs,
|
||||
"kept_outputs": kept_outputs,
|
||||
"warnings": warnings,
|
||||
"retry": is_retry,
|
||||
},
|
||||
}]),
|
||||
}
|
||||
# Drop the links of outputs about to be deleted and re-published (dead
|
||||
# links otherwise). brand_code stays — it's reused.
|
||||
for destination, (republish, _) in plan.items():
|
||||
if republish:
|
||||
for key in _DESTINATION_KEYS[destination]:
|
||||
update[f"state_data.{key}"] = DELETE_FIELD
|
||||
# youtube_upload_queued is only cleared (and the deferred upload
|
||||
# cancelled) when YouTube will be re-published — it's in
|
||||
# _DESTINATION_KEYS["youtube"] above.
|
||||
|
||||
context = {
|
||||
"message": message,
|
||||
"brand_code": brand_code,
|
||||
"previous_outputs": previous_outputs,
|
||||
"warnings": warnings,
|
||||
"notify_customer": bool(notify_customer),
|
||||
"is_retry": is_retry,
|
||||
"republish_youtube": republish_youtube,
|
||||
}
|
||||
return update, context
|
||||
|
||||
def _after_claim(self, job, context: dict, plan) -> Dict[str, Any]:
|
||||
"""Blocking post-claim work: audit log, stale artifacts, published outputs."""
|
||||
job_id = job.job_id
|
||||
logger.info(
|
||||
f"[job:{job_id}] Admin re-render claimed: brand_code={context['brand_code']} "
|
||||
f"notify_customer={context['notify_customer']} retry={context['is_retry']} "
|
||||
f"previous_outputs={sorted(context['previous_outputs'])} warnings={context['warnings']}"
|
||||
)
|
||||
log_to_job(job_id, _LOG_SOURCE, "INFO", context["message"], {
|
||||
"previous_outputs": context["previous_outputs"],
|
||||
"notify_customer": context["notify_customer"],
|
||||
"retry": context["is_retry"],
|
||||
})
|
||||
for warning in context["warnings"]:
|
||||
log_to_job(job_id, _LOG_SOURCE, "WARNING", warning)
|
||||
|
||||
delete_regenerated_artifacts(self.storage, job_id)
|
||||
return self._delete_published_outputs(
|
||||
job, job.state_data or {}, context["brand_code"], plan, context.get("youtube_queue")
|
||||
)
|
||||
|
||||
def _fail_run(self, job_id: str, error: str, reason: str) -> None:
|
||||
"""Mark the run FAILED, keeping the marker so it can be retried."""
|
||||
logger.error(f"[job:{job_id}] {error}")
|
||||
try:
|
||||
self.job_manager.update_job(job_id, {
|
||||
"status": JobStatus.FAILED.value,
|
||||
"error_message": error,
|
||||
"error_details": {"stage": "admin_rerender", "reason": reason},
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
log_to_job(job_id, _LOG_SOURCE, "ERROR", error)
|
||||
except Exception:
|
||||
logger.exception(f"[job:{job_id}] Failed to mark admin re-render as failed")
|
||||
|
||||
def _delete_published_outputs(
|
||||
self, job, state_data: dict, brand_code: Optional[str], plan,
|
||||
youtube_queue: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete outputs the re-render will re-publish; keep the rest. Best-effort.
|
||||
|
||||
Failures don't abort the re-render: the re-publish targets the same
|
||||
names (same brand code), and the server-side YouTube upload and GDrive
|
||||
upload both replace a same-named leftover, while Dropbox uploads overwrite.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
def kept(destination):
|
||||
return {"status": "kept", "reason": plan[destination][1]}
|
||||
|
||||
results: Dict[str, Any] = {}
|
||||
results["youtube"] = (
|
||||
delete_youtube_video(job_id, state_data.get("youtube_url"))
|
||||
if plan["youtube"][0] else kept("youtube")
|
||||
)
|
||||
# Private jobs publish to the private Dropbox path, not job.dropbox_path.
|
||||
results["dropbox"] = (
|
||||
delete_dropbox_folder(
|
||||
job_id, get_effective_distribution_for_job(job).dropbox_path,
|
||||
brand_code, job.artist, job.title,
|
||||
)
|
||||
if plan["dropbox"][0] else kept("dropbox")
|
||||
)
|
||||
# Same brand code is re-published, so the kjbox GCS mirror copy is
|
||||
# overwritten in place rather than removed.
|
||||
results["gdrive"] = (
|
||||
delete_gdrive_files(job_id, state_data.get("gdrive_files"), brand_code, cleanup_mirror=False)
|
||||
if plan["gdrive"][0] else kept("gdrive")
|
||||
)
|
||||
# Handled atomically by the claim transaction (claim_with_youtube_queue).
|
||||
results["youtube_queue"] = youtube_queue or {"status": "skipped", "reason": "no queue entry"}
|
||||
results["brand_code"] = {"status": "kept", "code": brand_code}
|
||||
|
||||
for service in ("youtube", "dropbox", "gdrive", "youtube_queue"):
|
||||
status = results[service].get("status")
|
||||
level = "WARNING" if status in ("failed", "partial", "error", "kept", "processing") else "INFO"
|
||||
log_to_job(job_id, _LOG_SOURCE, level, f"{service} cleanup: {status}", results[service])
|
||||
logger.info(
|
||||
f"[job:{job_id}] Admin re-render cleanup: "
|
||||
+ ", ".join(f"{k}={v.get('status')}" for k, v in results.items())
|
||||
)
|
||||
try:
|
||||
now = datetime.now(timezone.utc)
|
||||
self.job_manager.update_job(job_id, {
|
||||
f"state_data.{ADMIN_RERENDER_MARKER}.cleanup_results": results,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": "Admin re-render: previous published outputs removed",
|
||||
"metadata": {"action": "admin_rerender_cleanup", "cleanup_results": results},
|
||||
}]),
|
||||
})
|
||||
except Exception as e: # audit only — never block the re-render
|
||||
logger.warning(f"[job:{job_id}] Failed to record admin re-render cleanup results: {e}")
|
||||
return results
|
||||
@@ -33,9 +33,12 @@ review. Auto-approval must never be the reason a job fails.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.auto_approval.instrumental import (
|
||||
@@ -125,7 +128,16 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
audio_complete = bool(state_data.get("audio_complete", False))
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
|
||||
verdict = score_job(corrections, backing_analysis, ai_suggestions)
|
||||
# Missing-lyrics gate input: sung stretches the transcription has no words
|
||||
# for. Gates only when reference lyrics put lines in the gap ("evidenced");
|
||||
# fail-OPEN on pending audio / analysis errors (recorded below). Stem
|
||||
# download + decode: keep it off the event loop.
|
||||
vocal_gaps_info, vocal_gaps = await asyncio.to_thread(
|
||||
_vocal_gaps_shadow,
|
||||
job_id, job, corrections, ai_suggestions, stems, audio_complete, storage, job_manager,
|
||||
)
|
||||
|
||||
verdict = score_job(corrections, backing_analysis, ai_suggestions, vocal_gaps=vocal_gaps)
|
||||
|
||||
# Timing-plausibility gate: word timing vs the lead-vocal stem. Audio
|
||||
# IO (~15MB stem + a few seconds of numpy), so it runs only when the
|
||||
@@ -154,7 +166,7 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
if signals.fired:
|
||||
verdict = score_job(
|
||||
corrections, backing_analysis, ai_suggestions,
|
||||
timing_signals=signals,
|
||||
timing_signals=signals, vocal_gaps=vocal_gaps,
|
||||
)
|
||||
|
||||
blockers = _enforcement_blockers(job, settings)
|
||||
@@ -216,6 +228,7 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
"trigger": trigger,
|
||||
"enforcement_blockers": blockers,
|
||||
"timing": timing_info,
|
||||
"vocal_gaps": vocal_gaps_info,
|
||||
"audio_complete_at_scoring": audio_complete,
|
||||
"backing_analysis_available": backing_analysis is not None,
|
||||
"ai_suggestions_available": ai_suggestions is not None,
|
||||
@@ -324,6 +337,136 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
return {"outcome": "error", "error": str(e)}
|
||||
|
||||
|
||||
def _published_segments(corrections, ai_suggestions):
|
||||
"""The segments auto-ship would publish: raw + auto-applied AI suggestions."""
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if ai_suggestions:
|
||||
applied = build_applied_segments(corrections, ai_suggestions)
|
||||
if not applied.get("aborted"):
|
||||
segments = applied["segments"]
|
||||
return segments
|
||||
|
||||
|
||||
def analyze_vocal_gaps(job_id, corrections, segments, stems, storage):
|
||||
"""Download the lead-vocal stem and find sung stretches with no transcribed words.
|
||||
|
||||
Returns ``None`` when no lead/vocals stem is registered, else a
|
||||
``VocalGapsResult`` (``.error`` set on analysis failure). Never raises.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from backend.services.auto_approval.vocal_gaps import VocalGapsResult, compute_vocal_gaps
|
||||
|
||||
stem_path = stems.get("lead_vocals") or stems.get("vocals_clean")
|
||||
if not stem_path:
|
||||
return None
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
storage.download_file(stem_path, local)
|
||||
result = compute_vocal_gaps(segments, local, corrections)
|
||||
logger.info(
|
||||
f"[job:{job_id}] vocal gaps: {len(result.gaps)} gap(s), "
|
||||
f"suspect={result.suspect_count} max_run={result.max_suspect_run_s}s error={result.error}"
|
||||
)
|
||||
return result
|
||||
except Exception as e: # noqa: BLE001 — shadow analysis is best-effort
|
||||
logger.warning(f"[job:{job_id}] vocal gap analysis failed non-fatally: {e}")
|
||||
return VocalGapsResult(error=str(e))
|
||||
|
||||
|
||||
def vocal_gaps_input_key(segments, stems) -> str:
|
||||
"""Fingerprint of what a vocal-gap analysis looked at: word timings, stem, detector
|
||||
version. A reset, re-transcription, audio edit or new AI suggestions changes it."""
|
||||
from backend.services.auto_approval.vocal_gaps import VOCAL_GAPS_VERSION
|
||||
|
||||
words = [(w.get("id"), round(w.get("start_time") or 0, 2), round(w.get("end_time") or 0, 2))
|
||||
for seg in segments for w in (seg.get("words") or [])]
|
||||
stem = stems.get("lead_vocals") or stems.get("vocals_clean")
|
||||
blob = json.dumps([VOCAL_GAPS_VERSION, stem, words], ensure_ascii=False)
|
||||
return hashlib.sha1(blob.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _vocal_gaps_shadow(job_id, job, corrections, ai_suggestions, stems, audio_complete,
|
||||
storage, job_manager) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]:
|
||||
"""Analyze when stems exist and store ``state_data.vocal_gaps``; reuse a stored
|
||||
result only if it was computed from the same lyrics + stem (``input_key``).
|
||||
|
||||
Returns ``(summary for the payload, full vocal-gaps dict or None)``. Never raises.
|
||||
Blocking (stem download + decode): call via ``asyncio.to_thread``.
|
||||
"""
|
||||
try:
|
||||
if not audio_complete:
|
||||
return {"status": "pending_audio"}, None
|
||||
segments = _published_segments(corrections, ai_suggestions)
|
||||
input_key = vocal_gaps_input_key(segments, stems)
|
||||
existing = (job.state_data or {}).get("vocal_gaps")
|
||||
if existing and existing.get("input_key") == input_key:
|
||||
return {"status": "cached", "suspect_count": existing.get("suspect_count"),
|
||||
"evidenced_count": existing.get("evidenced_count", 0),
|
||||
"max_suspect_run_s": existing.get("max_suspect_run_s")}, existing
|
||||
result = analyze_vocal_gaps(job_id, corrections, segments, stems, storage)
|
||||
if result is None:
|
||||
return {"status": "no_lead_stem"}, None
|
||||
if result.error:
|
||||
return {"status": "error", "error": result.error}, None
|
||||
stored = {**result.to_dict(), "analyzed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"source": "auto_approval", "input_key": input_key}
|
||||
job_manager.update_state_data(job_id, "vocal_gaps", stored)
|
||||
return {"status": "checked", "suspect_count": result.suspect_count,
|
||||
"evidenced_count": result.evidenced_count,
|
||||
"max_suspect_run_s": result.max_suspect_run_s}, stored
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] vocal gap analysis failed non-fatally: {e}")
|
||||
return {"status": "error", "error": str(e)}, None
|
||||
|
||||
|
||||
def analyze_job_vocal_gaps(job_id: str, store: bool = True) -> Dict[str, Any]:
|
||||
"""Backfill/inspect: vocal gaps for the lyrics a job actually has now.
|
||||
|
||||
Uses the reviewed ``corrections_updated.json`` segments when present (what was
|
||||
rendered), with reference lyrics + anchors from ``corrections.json``. Runs
|
||||
synchronously (stem download + numpy, a few seconds). Never raises.
|
||||
"""
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
try:
|
||||
job_manager, storage = JobManager(), StorageService()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
return {"status": "no_job"}
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
return {"status": "no_corrections"}
|
||||
corrections = storage.download_json(corrections_path)
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
lyrics_source = "corrections"
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
if storage.file_exists(updated_path):
|
||||
updated = storage.download_json(updated_path)
|
||||
if updated.get("corrected_segments"):
|
||||
segments, lyrics_source = updated["corrected_segments"], "corrections_updated"
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
result = analyze_vocal_gaps(job_id, corrections, segments, stems, storage)
|
||||
if result is None:
|
||||
return {"status": "no_lead_stem"}
|
||||
if result.error:
|
||||
return {"status": "error", "error": result.error}
|
||||
payload = {**result.to_dict(), "analyzed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"source": "backfill", "lyrics_source": lyrics_source,
|
||||
"input_key": vocal_gaps_input_key(segments, stems)}
|
||||
if store:
|
||||
job_manager.update_state_data(job_id, "vocal_gaps", payload)
|
||||
return {"status": "checked", "stored": store, "vocal_gaps": payload}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] vocal gap backfill failed: {e}")
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
|
||||
def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage):
|
||||
"""Download the lead-vocal stem and run the timing-plausibility analysis
|
||||
on the POST-AI word stream (the state auto-ship would publish).
|
||||
@@ -335,7 +478,6 @@ def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage)
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
from backend.services.auto_approval.timing_check import (
|
||||
TimingSignals,
|
||||
compute_timing_signals,
|
||||
@@ -348,11 +490,7 @@ def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage)
|
||||
# The published state is raw + auto-applied suggestions; on an apply
|
||||
# abort the executor falls back to human review anyway, so analyzing
|
||||
# the raw segments there is only shadow data.
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if ai_suggestions:
|
||||
applied = build_applied_segments(corrections, ai_suggestions)
|
||||
if not applied.get("aborted"):
|
||||
segments = applied["segments"]
|
||||
segments = _published_segments(corrections, ai_suggestions)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
storage.download_file(stem_path, local)
|
||||
|
||||
@@ -41,7 +41,7 @@ from backend.services.auto_approval.models import (
|
||||
LyricsVerdict,
|
||||
)
|
||||
|
||||
SCORER_VERSION = "0.4.0"
|
||||
SCORER_VERSION = "0.5.0"
|
||||
|
||||
# --- Lyrics thresholds (deliberately conservative; the safe intersection first) ---
|
||||
# The AUTO tier requires a synced reference the transcription matches with ZERO
|
||||
@@ -373,13 +373,43 @@ def extract_lyrics_signals(
|
||||
)
|
||||
|
||||
|
||||
def _fmt_time(seconds: float) -> str:
|
||||
return f"{int(seconds // 60)}:{int(seconds % 60):02d}"
|
||||
|
||||
|
||||
def missing_lyrics_reasons(vocal_gaps: Optional[Dict[str, Any]]) -> List[str]:
|
||||
"""Human-readable reasons for each evidenced vocal gap (sung, no lyrics, and the
|
||||
reference lyrics put lines there). Empty when there's nothing to flag."""
|
||||
reasons = []
|
||||
for gap in (vocal_gaps or {}).get("gaps") or []:
|
||||
if not gap.get("evidenced"):
|
||||
continue
|
||||
lines = max(
|
||||
[len(v) for v in (gap.get("synced_reference_lines") or {}).values()]
|
||||
+ [len(v) for v in (gap.get("reference_lines") or {}).values()] + [0]
|
||||
)
|
||||
reasons.append(
|
||||
f"possible missing lyrics: ~{gap['longest_run_s']:.0f}s of singing at "
|
||||
f"{_fmt_time(gap['start'])}-{_fmt_time(gap['end'])} has no transcribed words, and the "
|
||||
f"reference lyrics have {lines} line(s) there"
|
||||
)
|
||||
return reasons
|
||||
|
||||
|
||||
def score_lyrics(
|
||||
correction_data: Dict[str, Any],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
timing_signals: Optional[Any] = None,
|
||||
vocal_gaps: Optional[Dict[str, Any]] = None,
|
||||
) -> LyricsResult:
|
||||
"""Decide whether the lyrics look safe to auto-approve.
|
||||
|
||||
``vocal_gaps`` (a stored ``VocalGapsResult`` dict) is a never-auto gate when any
|
||||
gap is *evidenced*: the lead vocal sings for >=3s with no transcribed words AND
|
||||
the reference lyrics place lines there (transcription dropped them — anchor
|
||||
coverage can't see omissions). Audio-only gaps don't gate (2026-10 audit:
|
||||
~25% precision without reference evidence).
|
||||
|
||||
``timing_signals`` (a ``timing_check.TimingSignals``) is optional because
|
||||
computing it needs the lead-vocal stem (audio IO the executor performs only
|
||||
when the text signals would otherwise be AUTO). When provided and fired,
|
||||
@@ -416,6 +446,11 @@ def score_lyrics(
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "phantom-gate", s, reasons)
|
||||
|
||||
missing = missing_lyrics_reasons(vocal_gaps)
|
||||
if missing:
|
||||
reasons.extend(missing)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "missing-lyrics-gate", s, reasons)
|
||||
|
||||
if timing_signals is not None and getattr(timing_signals, "fired", None):
|
||||
sig = timing_signals
|
||||
reasons.append(
|
||||
@@ -635,13 +670,14 @@ def score_job(
|
||||
backing_analysis: Optional[Dict[str, Any]],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
timing_signals: Optional[Any] = None,
|
||||
vocal_gaps: Optional[Dict[str, Any]] = None,
|
||||
) -> AutoApprovabilityVerdict:
|
||||
"""Produce the combined shadow verdict for a job.
|
||||
|
||||
``overall_auto`` is the narrow safe intersection: confident lyrics AND a
|
||||
non-subjective (no-audible-backing) backing decision.
|
||||
"""
|
||||
lyrics = score_lyrics(correction_data, ai_suggestions, timing_signals)
|
||||
lyrics = score_lyrics(correction_data, ai_suggestions, timing_signals, vocal_gaps)
|
||||
backing = score_backing(backing_analysis)
|
||||
overall_auto = lyrics.verdict == LyricsVerdict.AUTO and backing.non_subjective
|
||||
return AutoApprovabilityVerdict(
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
"""Vocal gaps: stretches where the lead vocal is singing but the transcription has no words.
|
||||
|
||||
Transcription can silently drop whole sung lines (job 5710831e: 11.7s of a Hebrew
|
||||
pre-chorus, three lines, no words at all). Nothing downstream notices:
|
||||
|
||||
- the scorer's anchor coverage is the fraction of *transcribed* words that match the
|
||||
reference, so omitted lines don't lower it;
|
||||
- ``SectionDetector`` labels any >=10s gap between segments "INSTRUMENTAL" without
|
||||
looking at the audio, so the video shows "♪ INSTRUMENTAL ♪" over singing;
|
||||
- a reviewer who doesn't read the language can't see that lines are missing.
|
||||
|
||||
For every transcription gap of at least ``MIN_GAP_S`` this measures how much of it the
|
||||
lead-vocal stem is active (short breaths bridged), and which reference lyrics sit
|
||||
between the reference positions of the words either side of the gap. Lines in the
|
||||
reference there are the strongest evidence that lyrics were dropped rather than the gap
|
||||
being ad-libs or a vocal sample.
|
||||
|
||||
Shadow-only for now: results are stored on the job (``state_data.vocal_gaps``) for
|
||||
calibration before anything gates on them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
from backend.services.auto_approval.timing_check import _load_mono, _rms_activity
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VOCAL_GAPS_VERSION = "0.2.0"
|
||||
|
||||
MIN_GAP_S = 3.0 # shorter gaps are normal phrasing
|
||||
BREATH_BRIDGE_S = 0.5 # silences this short inside singing don't end a vocal run
|
||||
# Shadow "suspect" threshold — calibrate on the backfill audit. Keyed on the longest
|
||||
# continuous (breath-bridged) vocal run, NOT the gap's active fraction: dropped lines
|
||||
# followed by an instrumental inside one transcription gap dilute the fraction (a 4s
|
||||
# dropped line in a 20s gap is only 20% active). On job 5710831e genuine
|
||||
# instrumentals peaked at 0.16s runs vs 11.76s for the dropped lines.
|
||||
SUSPECT_MIN_RUN_S = 3.0
|
||||
# A vocal run that starts at the gap's first frame is usually the previous word's held
|
||||
# note (transcribed end_time under-extended — a known AudioShake failure). Don't count
|
||||
# its first seconds as "unlyricked"; dropped lines run far longer (11.76s on 5710831e).
|
||||
# Held notes up to ALLOWANCE + SUSPECT_MIN_RUN_S (4.5s) past the word's end are tolerated.
|
||||
HELD_NOTE_ALLOWANCE_S = 1.5 # calibrate with the audit; 2.0 hid a single 4s dropped line
|
||||
MAX_REFERENCE_LINES = 12 # more than this between anchors = misaligned anchors, not a gap
|
||||
|
||||
|
||||
@dataclass
|
||||
class VocalGap:
|
||||
start: float
|
||||
end: float
|
||||
duration: float
|
||||
active_fraction: float # share of the gap where the lead vocal is active
|
||||
longest_run_s: float # longest vocal run inside the gap, breaths bridged
|
||||
reference_lines: Dict[str, List[str]] = field(default_factory=dict) # source -> lines
|
||||
# Synced reference lines (e.g. LRCLIB) whose timestamp falls inside the gap
|
||||
synced_reference_lines: Dict[str, List[str]] = field(default_factory=dict)
|
||||
suspect: bool = False # sung run long enough to be dropped lyrics (audio only)
|
||||
evidenced: bool = False # suspect AND reference lyrics place lines in this gap
|
||||
|
||||
|
||||
@dataclass
|
||||
class VocalGapsResult:
|
||||
version: str = VOCAL_GAPS_VERSION
|
||||
gaps: List[VocalGap] = field(default_factory=list)
|
||||
suspect_count: int = 0
|
||||
evidenced_count: int = 0
|
||||
max_suspect_run_s: float = 0.0
|
||||
error: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
# ---- transcription gaps ---------------------------------------------------------
|
||||
|
||||
def _words(segments: List[dict]) -> List[dict]:
|
||||
words = [w for seg in segments for w in (seg.get("words") or [])
|
||||
if w.get("start_time") is not None and w.get("end_time") is not None]
|
||||
return sorted(words, key=lambda w: w["start_time"])
|
||||
|
||||
|
||||
def transcription_gaps(segments: List[dict], audio_duration: float,
|
||||
min_gap_s: float = MIN_GAP_S) -> List[Tuple[float, float, Optional[dict], Optional[dict]]]:
|
||||
"""(start, end, word_before, word_after) for every gap >= ``min_gap_s``.
|
||||
|
||||
Includes the stretch before the first word and after the last one.
|
||||
"""
|
||||
words = _words(segments)
|
||||
gaps = []
|
||||
cursor, prev = 0.0, None
|
||||
for w in words:
|
||||
if w["start_time"] - cursor >= min_gap_s:
|
||||
gaps.append((cursor, w["start_time"], prev, w))
|
||||
cursor = max(cursor, w["end_time"])
|
||||
prev = w
|
||||
if audio_duration - cursor >= min_gap_s:
|
||||
gaps.append((cursor, audio_duration, prev, None))
|
||||
return gaps
|
||||
|
||||
|
||||
# ---- vocal activity -------------------------------------------------------------
|
||||
|
||||
def _bridge(active: np.ndarray, max_gap_frames: int) -> np.ndarray:
|
||||
"""Fill inactive runs of <= ``max_gap_frames`` that sit between active frames."""
|
||||
out = active.copy()
|
||||
idx = np.flatnonzero(active)
|
||||
if len(idx) < 2:
|
||||
return out
|
||||
for a, b in zip(idx[:-1], idx[1:]):
|
||||
if 1 < b - a <= max_gap_frames + 1:
|
||||
out[a:b] = True
|
||||
return out
|
||||
|
||||
|
||||
def _longest_run(mask: np.ndarray) -> int:
|
||||
best = run = 0
|
||||
for v in mask:
|
||||
run = run + 1 if v else 0
|
||||
best = max(best, run)
|
||||
return best
|
||||
|
||||
|
||||
# ---- reference lines in a gap ---------------------------------------------------
|
||||
|
||||
def _reference_index(correction_data: Dict[str, Any]) -> Dict[str, Dict[str, Tuple[int, int, int]]]:
|
||||
"""source -> reference word id -> (line index, word index within line, line length)."""
|
||||
index: Dict[str, Dict[str, Tuple[int, int, int]]] = {}
|
||||
for source, ref in (correction_data.get("reference_lyrics") or {}).items():
|
||||
ids: Dict[str, Tuple[int, int, int]] = {}
|
||||
for li, seg in enumerate((ref or {}).get("segments") or []):
|
||||
seg_words = seg.get("words") or []
|
||||
for wi, w in enumerate(seg_words):
|
||||
if w.get("id"):
|
||||
ids[w["id"]] = (li, wi, len(seg_words))
|
||||
index[source] = ids
|
||||
return index
|
||||
|
||||
|
||||
def _transcribed_to_reference(correction_data: Dict[str, Any]) -> Dict[str, Dict[str, List[str]]]:
|
||||
"""transcribed word id -> source -> reference word ids (anchors + gap sequences)."""
|
||||
mapping: Dict[str, Dict[str, List[str]]] = {}
|
||||
for seq in (correction_data.get("anchor_sequences") or []) + (correction_data.get("gap_sequences") or []):
|
||||
t_ids = seq.get("transcribed_word_ids") or []
|
||||
r_ids = seq.get("reference_word_ids") or {}
|
||||
for source, refs in r_ids.items():
|
||||
if len(refs) == len(t_ids): # anchors: 1:1 by position
|
||||
for t, r in zip(t_ids, refs):
|
||||
mapping.setdefault(t, {})[source] = [r]
|
||||
else: # gap sequences: not aligned word-for-word
|
||||
for t in t_ids:
|
||||
mapping.setdefault(t, {})[source] = list(refs)
|
||||
return mapping
|
||||
|
||||
|
||||
def reference_lines_between(correction_data: Dict[str, Any], word_before: Optional[dict],
|
||||
word_after: Optional[dict], _indexes=None) -> Dict[str, List[str]]:
|
||||
"""Reference lines strictly between the reference positions of the words around a gap.
|
||||
|
||||
Only whole reference lines are returned, and only when both neighbours map to the
|
||||
same source in increasing order (repeated choruses can anchor to a different
|
||||
occurrence; those cases return nothing rather than a misleading span).
|
||||
"""
|
||||
if not word_before or not word_after:
|
||||
return {}
|
||||
ref_index, t2r = _indexes or (_reference_index(correction_data), _transcribed_to_reference(correction_data))
|
||||
before = t2r.get(word_before.get("id"), {})
|
||||
after = t2r.get(word_after.get("id"), {})
|
||||
out: Dict[str, List[str]] = {}
|
||||
for source in set(before) & set(after):
|
||||
ids = ref_index.get(source, {})
|
||||
b = [ids[r] for r in before[source] if r in ids]
|
||||
a = [ids[r] for r in after[source] if r in ids]
|
||||
if not b or not a:
|
||||
continue
|
||||
b_line, b_word, _ = max(b, key=lambda x: (x[0], x[1]))
|
||||
a_line, a_word, a_len = min(a, key=lambda x: (x[0], x[1]))
|
||||
# Anchor reference ids can be off by one word at line boundaries (section
|
||||
# headers like "[Chorus]" tokenised differently): a gap's preceding word
|
||||
# "landing" on the first word of a line really ended the previous line, and
|
||||
# a following word landing on the last word of a line starts the next one.
|
||||
b_len = len(correction_data["reference_lyrics"][source]["segments"][b_line].get("words") or [])
|
||||
if b_word == 0 and b_len > 1:
|
||||
b_line -= 1
|
||||
if a_word == a_len - 1 and a_len > 1:
|
||||
a_line += 1
|
||||
# Whole lines only: after the line holding word_before, before the line of word_after
|
||||
first, last = b_line + 1, a_line - 1
|
||||
if first > last or last - first + 1 > MAX_REFERENCE_LINES:
|
||||
continue
|
||||
segs = correction_data["reference_lyrics"][source]["segments"]
|
||||
lines = [(segs[i].get("text") or "").strip() for i in range(first, last + 1)]
|
||||
lines = [l for l in lines if l and not (l.startswith("[") and l.endswith("]"))] # drop [Chorus] headers
|
||||
if lines:
|
||||
out[source] = lines
|
||||
return out
|
||||
|
||||
|
||||
# ---- synced reference lines in a gap ---------------------------------------------
|
||||
|
||||
SYNCED_EDGE_S = 0.5 # line must start this far inside the gap (tolerates small offsets)
|
||||
|
||||
|
||||
def _synced_reference_lines(correction_data: Dict[str, Any]) -> Dict[str, List[Tuple[float, str]]]:
|
||||
"""source -> [(line start time, text)] for reference sources with word timings."""
|
||||
out: Dict[str, List[Tuple[float, str]]] = {}
|
||||
for source, ref in (correction_data.get("reference_lyrics") or {}).items():
|
||||
lines = []
|
||||
for seg in (ref or {}).get("segments") or []:
|
||||
starts = [w.get("start_time") for w in seg.get("words") or [] if w.get("start_time") is not None]
|
||||
text = (seg.get("text") or "").strip()
|
||||
if starts and text and not (text.startswith("[") and text.endswith("]")):
|
||||
lines.append((float(starts[0]), text))
|
||||
if lines:
|
||||
out[source] = lines
|
||||
return out
|
||||
|
||||
|
||||
def synced_lines_in_gap(synced: Dict[str, List[Tuple[float, str]]], start: float, end: float) -> Dict[str, List[str]]:
|
||||
"""Synced reference lines that start inside (start, end), with an edge tolerance.
|
||||
|
||||
On the 2026-10 audit this was the most reliable evidence of dropped lyrics: only ~25%
|
||||
of audio-only suspect gaps had a synced reference line inside them.
|
||||
"""
|
||||
found = {src: [t for ts, t in lines if start + SYNCED_EDGE_S <= ts <= end - SYNCED_EDGE_S]
|
||||
for src, lines in synced.items()}
|
||||
return {src: lines for src, lines in found.items() if lines}
|
||||
|
||||
|
||||
# ---- entry point ----------------------------------------------------------------
|
||||
|
||||
def compute_vocal_gaps(segments: List[dict], lead_vocals_path: str,
|
||||
correction_data: Optional[Dict[str, Any]] = None) -> VocalGapsResult:
|
||||
"""Never raises: failures return ``VocalGapsResult(error=...)``."""
|
||||
try:
|
||||
samples, sr = _load_mono(lead_vocals_path)
|
||||
active, frame_s = _rms_activity(samples, sr)
|
||||
if len(active) == 0 or not active.any():
|
||||
# A failed separation must not be recorded as a clean "no gaps" pass
|
||||
return VocalGapsResult(error="empty or silent lead-vocal audio")
|
||||
bridged = _bridge(active, int(round(BREATH_BRIDGE_S / frame_s)))
|
||||
duration = len(active) * frame_s
|
||||
allowance = int(round(HELD_NOTE_ALLOWANCE_S / frame_s))
|
||||
|
||||
correction_data = correction_data or {}
|
||||
try:
|
||||
indexes = (_reference_index(correction_data), _transcribed_to_reference(correction_data))
|
||||
except Exception as e: # noqa: BLE001 — reference evidence is secondary
|
||||
logger.warning("vocal gaps: reference index failed: %s", e)
|
||||
indexes = None
|
||||
try:
|
||||
synced = _synced_reference_lines(correction_data)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("vocal gaps: synced reference parse failed: %s", e)
|
||||
synced = {}
|
||||
|
||||
result = VocalGapsResult()
|
||||
for start, end, before, after in transcription_gaps(segments, duration):
|
||||
i0, i1 = int(start / frame_s), min(len(active), int(np.ceil(end / frame_s)))
|
||||
if i1 <= i0:
|
||||
continue
|
||||
frac = float(active[i0:i1].mean())
|
||||
window = bridged[i0:i1].copy()
|
||||
# Discount a held note carried over from the word before the gap
|
||||
if before is not None and window[0]:
|
||||
window[:allowance] = False
|
||||
run_s = _longest_run(window) * frame_s
|
||||
try:
|
||||
refs = reference_lines_between(correction_data, before, after, indexes) if indexes else {}
|
||||
except Exception as e: # noqa: BLE001 — never lose the audio result to bad reference data
|
||||
logger.warning("vocal gaps: reference lookup failed: %s", e)
|
||||
refs = {}
|
||||
gap = VocalGap(
|
||||
start=round(start, 2), end=round(end, 2), duration=round(end - start, 2),
|
||||
active_fraction=round(frac, 3), longest_run_s=round(run_s, 2),
|
||||
reference_lines=refs,
|
||||
)
|
||||
gap.synced_reference_lines = synced_lines_in_gap(synced, start, end)
|
||||
gap.suspect = run_s >= SUSPECT_MIN_RUN_S
|
||||
gap.evidenced = gap.suspect and bool(gap.reference_lines or gap.synced_reference_lines)
|
||||
result.gaps.append(gap)
|
||||
|
||||
suspects = [g for g in result.gaps if g.suspect]
|
||||
result.suspect_count = len(suspects)
|
||||
result.evidenced_count = sum(1 for g in suspects if g.evidenced)
|
||||
result.max_suspect_run_s = max((g.longest_run_s for g in suspects), default=0.0)
|
||||
return result
|
||||
except Exception as e: # noqa: BLE001 — shadow analysis is best-effort
|
||||
logger.warning("vocal gap analysis failed: %s", e, exc_info=True)
|
||||
return VocalGapsResult(error=str(e))
|
||||
@@ -54,8 +54,10 @@ MODEL_PRICING: dict[str, _Rate] = {
|
||||
"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 (ESTIMATE — 3.x Pro preview, <=200K-token context tier;
|
||||
# confirm against current Google pricing before trusting USD). Calls go
|
||||
# via the Gemini Developer API (paid tier), assumed at Vertex list-price
|
||||
# parity. ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
# Promo rate through 2026-12-31; see _RATE_CHANGES for the standard rate.
|
||||
"gemini-3.8-flash": {"input": 0.75, "output": 3.75, "cache_read": 0.075},
|
||||
|
||||
@@ -710,22 +710,19 @@ class AutoCorrectService:
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
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),
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
|
||||
# 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:
|
||||
# Gemini Developer API (API key). Timeout in milliseconds bounds the
|
||||
# call so a hung model never strands the UI.
|
||||
client = get_genai_client(timeout_ms=120_000)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -736,6 +733,15 @@ class AutoCorrectService:
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if note_gemini_failure("auto_correct", exc):
|
||||
# Quota / prepaid credit / key problem: retrying won't help.
|
||||
# Non-retryable so compare mode drops the Gemini leg at once
|
||||
# and keeps the other model's (Opus) suggestions.
|
||||
raise AutoCorrectServiceError(
|
||||
"Gemini is unavailable (quota/billing/key) — skipped",
|
||||
status_code=503,
|
||||
retryable=False,
|
||||
) from exc
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
|
||||
@@ -295,16 +295,17 @@ class CreditEvaluationService:
|
||||
"""Call Gemini and return the response text."""
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=60_000)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.credit_eval_model,
|
||||
contents=prompt,
|
||||
config=genai.types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
# Grant/deny classification over a short signal list: low
|
||||
# thinking is ample (Gemini 3 Flash defaults to high).
|
||||
thinking_config=genai.types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
@@ -402,7 +403,13 @@ class CreditEvaluationService:
|
||||
feedback_content=feedback_content,
|
||||
)
|
||||
|
||||
response_text = self._call_gemini(prompt)
|
||||
try:
|
||||
response_text = self._call_gemini(prompt)
|
||||
except Exception as gemini_exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("credit_evaluation", gemini_exc)
|
||||
raise
|
||||
evaluation = _parse_gemini_response(response_text)
|
||||
evaluation.signals = signals
|
||||
|
||||
|
||||
@@ -562,36 +562,43 @@ class CustomLyricsService:
|
||||
pdf_bytes: Optional[bytes],
|
||||
settings: GenerationSettings,
|
||||
) -> list[str]:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
|
||||
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"}}
|
||||
try:
|
||||
# Bounded so a stalled call can't hang the request (Gemini Developer API).
|
||||
client = get_genai_client(timeout_ms=300_000)
|
||||
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"],
|
||||
},
|
||||
"required": ["lines"],
|
||||
},
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
except Exception as exc:
|
||||
if note_gemini_failure("custom_lyrics", exc):
|
||||
raise CustomLyricsServiceError(
|
||||
"The AI lyrics service is temporarily unavailable. Please try "
|
||||
"again later, or edit the lyrics manually.",
|
||||
status_code=503,
|
||||
) from exc
|
||||
raise
|
||||
# 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
|
||||
|
||||
@@ -86,8 +86,10 @@ class DropboxService:
|
||||
path: Dropbox path to list (e.g., "/Karaoke/Tracks-Organized")
|
||||
|
||||
Returns:
|
||||
List of folder names in the path
|
||||
List of folder names in the path (empty if the path doesn't exist yet,
|
||||
e.g. a brand-new tenant folder — the upload creates it)
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
from dropbox.files import FolderMetadata
|
||||
|
||||
# Ensure path starts with /
|
||||
@@ -96,7 +98,14 @@ class DropboxService:
|
||||
|
||||
logger.info(f"Listing folders at Dropbox path: {path}")
|
||||
|
||||
result = self.client.files_list_folder(path)
|
||||
try:
|
||||
result = self.client.files_list_folder(path)
|
||||
except ApiError as e:
|
||||
err = e.error
|
||||
if err.is_path() and err.get_path().is_not_found():
|
||||
logger.info(f"Dropbox path {path} does not exist yet; treating as empty")
|
||||
return []
|
||||
raise
|
||||
folders = []
|
||||
|
||||
# Get all entries (handling pagination)
|
||||
@@ -112,6 +121,32 @@ class DropboxService:
|
||||
logger.info(f"Found {len(folders)} folders in {path}")
|
||||
return folders
|
||||
|
||||
def ensure_folder(self, path: str) -> bool:
|
||||
"""
|
||||
Create a Dropbox folder (and any missing parents) if it doesn't exist.
|
||||
|
||||
Args:
|
||||
path: Dropbox folder path (e.g., "/MediaUnsynced/Karaoke/Tracks-RandyVild")
|
||||
|
||||
Returns:
|
||||
True if the folder was created, False if it already existed
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
if not path.startswith("/"):
|
||||
path = f"/{path}"
|
||||
|
||||
try:
|
||||
self.client.files_create_folder_v2(path)
|
||||
except ApiError as e:
|
||||
err = e.error
|
||||
write_err = err.get_path() if err.is_path() else None
|
||||
if write_err is not None and write_err.is_conflict() and write_err.get_conflict().is_folder():
|
||||
return False
|
||||
raise
|
||||
logger.info(f"Created Dropbox folder {path}")
|
||||
return True
|
||||
|
||||
def get_next_brand_code(self, path: str, brand_prefix: str) -> str:
|
||||
"""
|
||||
Calculate next brand code from existing folders, filling gaps in the sequence.
|
||||
|
||||
@@ -12,6 +12,7 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import NamedTuple, Optional, List
|
||||
@@ -174,6 +175,65 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
|
||||
API_URL = "https://api.postmarkapp.com/email"
|
||||
|
||||
# Seconds to sleep before each retry of a transient failure. Postmark's edge
|
||||
# intermittently answers some us-central1 Cloud Run egress IPs with a bare
|
||||
# nginx HTML 403 (not its JSON error format) — a fresh connection a moment
|
||||
# later often succeeds. Kept short: magic-link sends block the request.
|
||||
RETRY_DELAYS = (1.0, 3.0)
|
||||
|
||||
@staticmethod
|
||||
def _is_transient_failure(response: requests.Response) -> bool:
|
||||
"""True for failures worth retrying: 429, 5xx, or a non-JSON 403.
|
||||
|
||||
Postmark's own API errors (bad token, invalid payload, suppressed
|
||||
recipient) come back as JSON and are deterministic, so retrying them
|
||||
would just repeat the same answer. A 403 without a JSON body is an
|
||||
edge/IP-level block, not a verdict on the request itself.
|
||||
"""
|
||||
status = response.status_code
|
||||
if status == 429 or status >= 500:
|
||||
return True
|
||||
if status == 403:
|
||||
try:
|
||||
response.json()
|
||||
except ValueError:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _post_with_retry(self, payload: dict) -> requests.Response:
|
||||
"""POST to Postmark, retrying transient failures with backoff.
|
||||
|
||||
Only connect-phase errors are retried among exceptions: a read timeout
|
||||
may mean Postmark already accepted the message, and it has no
|
||||
idempotency key, so retrying could send a duplicate.
|
||||
"""
|
||||
attempts = len(self.RETRY_DELAYS) + 1
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
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,
|
||||
)
|
||||
except requests.ConnectTimeout:
|
||||
if attempt == attempts:
|
||||
raise
|
||||
logger.warning(f"Postmark connect timeout (attempt {attempt}/{attempts}); retrying")
|
||||
else:
|
||||
if attempt == attempts or not self._is_transient_failure(response):
|
||||
return response
|
||||
logger.warning(
|
||||
f"Postmark returned transient status {response.status_code} "
|
||||
f"(attempt {attempt}/{attempts}); retrying"
|
||||
)
|
||||
time.sleep(self.RETRY_DELAYS[attempt - 1])
|
||||
raise AssertionError("unreachable") # pragma: no cover
|
||||
|
||||
def __init__(self, server_token: str, from_email: str, from_name: str = "Nomad Karaoke"):
|
||||
self.server_token = server_token
|
||||
self.from_email = from_email
|
||||
@@ -235,16 +295,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
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,
|
||||
)
|
||||
response = self._post_with_retry(payload)
|
||||
|
||||
if 200 <= response.status_code < 300:
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
|
||||
@@ -110,7 +110,6 @@ Shared infrastructure:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-3.8-flash")
|
||||
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "global")
|
||||
|
||||
#: Minimum number of active error patterns required before triggering LLM analysis.
|
||||
MIN_PATTERNS_FOR_ANALYSIS: int = 3
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""LLM-powered incident analysis and duplicate detection for the error monitor.
|
||||
|
||||
Uses Gemini Flash via the google-generativeai library to:
|
||||
Uses Gemini Flash via the Gemini Developer API (backend.services.gemini_client) to:
|
||||
1. Group related error patterns into incidents with root-cause analysis.
|
||||
2. Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
@@ -17,13 +17,11 @@ import time
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LLM_ANALYSIS_MODEL,
|
||||
LLM_VERTEX_LOCATION,
|
||||
MIN_PATTERNS_FOR_ANALYSIS,
|
||||
SERVICE_DEPENDENCY_MAP,
|
||||
)
|
||||
@@ -96,11 +94,7 @@ def _call_llm(
|
||||
|
||||
for attempt in range(_RETRY_ATTEMPTS):
|
||||
try:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=GCP_PROJECT,
|
||||
location=LLM_VERTEX_LOCATION,
|
||||
)
|
||||
client = get_genai_client(timeout_ms=120_000)
|
||||
response = client.models.generate_content(
|
||||
model=LLM_ANALYSIS_MODEL,
|
||||
contents=user_prompt,
|
||||
@@ -111,6 +105,10 @@ def _call_llm(
|
||||
)
|
||||
return response.text
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if note_gemini_failure("error_monitor", exc):
|
||||
# Quota/credit/key problem: don't retry — callers fall back to
|
||||
# alerts without the AI summary.
|
||||
raise
|
||||
last_exc = exc
|
||||
delay = _RETRY_BASE_DELAY * (2**attempt)
|
||||
logger.warning(
|
||||
|
||||
@@ -155,6 +155,8 @@ class RenderVideoRequest(BaseModel):
|
||||
# Multi-singer / duet rendering. When True, OutputConfig is_duet is set
|
||||
# so the SubtitlesGenerator and CDGGenerator emit per-singer styles.
|
||||
is_duet: bool = False
|
||||
# Translated lyrics (lyrics/translations.json) drawn beneath each line.
|
||||
translations_gcs_path: Optional[str] = None
|
||||
|
||||
|
||||
class JobStatus(BaseModel):
|
||||
@@ -452,6 +454,17 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
# 2b. Translated lyrics (shown beneath each line)
|
||||
if request.translations_gcs_path:
|
||||
from karaoke_gen.lyrics_transcriber.output.translations import load_and_apply_translations
|
||||
|
||||
translations_path = work_dir / "translations.json"
|
||||
try:
|
||||
download_single_file_from_gcs(request.translations_gcs_path, translations_path)
|
||||
load_and_apply_translations(correction_result.corrected_segments, str(translations_path))
|
||||
except Exception as e: # translations are best-effort: never fail the render
|
||||
logger.error(f"[job:{job_id}] Translated lyrics unavailable, rendering without: {e}")
|
||||
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
@@ -965,6 +978,13 @@ def render_portrait_into_outputs(
|
||||
with open(corrections_file, "r", encoding="utf-8") as f:
|
||||
correction_result = CorrectionResult.from_dict(json.load(f))
|
||||
|
||||
# Translated lyrics, if the job has them (downloaded with the job's lyrics/)
|
||||
translations_file = work_dir / "lyrics" / "translations.json"
|
||||
if translations_file.is_file():
|
||||
from karaoke_gen.lyrics_transcriber.output.translations import load_and_apply_translations
|
||||
|
||||
load_and_apply_translations(correction_result.corrected_segments, str(translations_file))
|
||||
|
||||
# Theme styles (optional — renderer fills defaults).
|
||||
styles = {}
|
||||
style_params = work_dir / "style" / "style_params.json"
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Shared Gemini client for the backend: Gemini Developer API (API key), not Vertex.
|
||||
|
||||
Every backend Gemini call goes through :func:`get_genai_client`. Vertex AI is
|
||||
disabled in the nomadkaraoke GCP project so AI spend never lands on it; calls are
|
||||
billed to whichever AI Studio key is stored in Secret Manager ``gemini-api-key``.
|
||||
|
||||
Key resolution (via :meth:`backend.config.Settings.get_secret`):
|
||||
1. ``GEMINI_API_KEY`` env var — injected on Cloud Run from
|
||||
``gemini-api-key:latest`` (CI ``--set-secrets`` for the service, Pulumi
|
||||
for the jobs).
|
||||
2. Secret Manager ``gemini-api-key`` (latest) — read directly with the
|
||||
runtime service account / your ADC when the env var isn't set.
|
||||
|
||||
Rotating the key: add a new version of ``gemini-api-key``. New instances / job
|
||||
executions pick it up; no code change.
|
||||
|
||||
Degradation: when the key's quota or prepaid credit is exhausted (or the key is
|
||||
rejected), callers must degrade rather than fail jobs. Use
|
||||
:func:`is_quota_or_billing_error` to classify and :func:`note_gemini_failure`
|
||||
from the caller's ``except`` block — it also sends a Discord ops alert at most
|
||||
once per ``GEMINI_QUOTA_ALERT_HOURS`` (default 6h) across all instances.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SECRET_NAME = "gemini-api-key"
|
||||
|
||||
QUOTA_EXHAUSTED_MESSAGE = (
|
||||
"Gemini quota/credit exhausted — top up AI Studio or rotate gemini-api-key "
|
||||
"(add a new version of Secret Manager secret 'gemini-api-key' in project nomadkaraoke)."
|
||||
)
|
||||
|
||||
# Firestore dedup doc id (in ops_alerts' collection) shared by every instance/job.
|
||||
_ALERT_KEY = "gemini-quota-exhausted"
|
||||
_DEFAULT_ALERT_HOURS = 6.0
|
||||
|
||||
|
||||
class GeminiKeyUnavailableError(RuntimeError):
|
||||
"""No Gemini API key could be resolved (env var unset and Secret Manager failed)."""
|
||||
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Return the Gemini Developer API key or raise GeminiKeyUnavailableError."""
|
||||
env_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
||||
if env_key:
|
||||
return env_key
|
||||
from backend.config import get_settings
|
||||
|
||||
key = (get_settings().get_secret(SECRET_NAME) or "").strip()
|
||||
if not key:
|
||||
raise GeminiKeyUnavailableError(
|
||||
"GEMINI_API_KEY is not set and Secret Manager secret 'gemini-api-key' "
|
||||
"could not be read"
|
||||
)
|
||||
return key
|
||||
|
||||
|
||||
def get_genai_client(timeout_ms: Optional[int] = None) -> Any:
|
||||
"""Build a google-genai client for the Gemini Developer API.
|
||||
|
||||
``timeout_ms`` bounds each HTTP request (milliseconds). No project/location:
|
||||
those only apply to Vertex AI.
|
||||
"""
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
http_options = types.HttpOptions(timeout=int(timeout_ms)) if timeout_ms else None
|
||||
# vertexai=False pins the Developer API even if GOOGLE_GENAI_USE_VERTEXAI is set.
|
||||
return genai.Client(vertexai=False, api_key=get_api_key(), http_options=http_options)
|
||||
|
||||
|
||||
# Message fragments that mean "the key/account can't pay or isn't valid" — a
|
||||
# retry won't help; a human must top up credit or rotate the key.
|
||||
_QUOTA_PATTERNS = re.compile(
|
||||
r"RESOURCE_EXHAUSTED|exceeded your current quota|quota exceeded|"
|
||||
r"billing (details|account)|prepa(id|yment)|credits? (are |is |have been )?"
|
||||
r"(exhausted|depleted|used up)|insufficient (credit|funds|balance)|"
|
||||
r"API_KEY_INVALID|API key not valid|API key expired|API_KEY_SERVICE_BLOCKED|"
|
||||
r"\b429 Too Many Requests",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# A 429 that names a per-minute quota / carries a retry delay is an ordinary
|
||||
# rate limit (transient — retry with backoff), not exhausted credit.
|
||||
_RATE_LIMIT_PATTERNS = re.compile(r"PerMinute|retryDelay|retry in \d", re.IGNORECASE)
|
||||
# ...unless it names a per-day quota: that won't clear for hours — treat as exhausted.
|
||||
_DAILY_QUOTA_PATTERN = re.compile(r"PerDay", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_rate_limit(text: str) -> bool:
|
||||
return bool(_RATE_LIMIT_PATTERNS.search(text)) and not _DAILY_QUOTA_PATTERN.search(text)
|
||||
|
||||
|
||||
def is_quota_or_billing_error(exc: Optional[BaseException]) -> bool:
|
||||
"""True if ``exc`` (or anything in its ``__cause__`` chain) is a Gemini quota,
|
||||
prepaid-credit, billing or API-key error — i.e. needs a top-up/key rotation,
|
||||
not a retry.
|
||||
|
||||
Matches google-genai ``APIError`` (``.code`` 429 / 403 or status
|
||||
RESOURCE_EXHAUSTED / PERMISSION_DENIED, or a billing/key message on a 400),
|
||||
a missing key, and wrapped/stringified errors from other layers (LangChain).
|
||||
Per-minute rate limits (429 naming a ``PerMinute`` quota or a retry delay)
|
||||
are NOT matched — those are transient; retry them.
|
||||
"""
|
||||
seen: set[int] = set()
|
||||
while exc is not None and id(exc) not in seen:
|
||||
seen.add(id(exc))
|
||||
if isinstance(exc, GeminiKeyUnavailableError):
|
||||
return True
|
||||
code = getattr(exc, "code", None)
|
||||
if code is None:
|
||||
code = getattr(exc, "status_code", None)
|
||||
status = str(getattr(exc, "status", "") or "")
|
||||
if code == 429 or status == "RESOURCE_EXHAUSTED":
|
||||
return not _is_rate_limit(str(exc))
|
||||
if code == 403 or status == "PERMISSION_DENIED":
|
||||
return True
|
||||
text = str(exc)
|
||||
if _QUOTA_PATTERNS.search(text) and not _is_rate_limit(text):
|
||||
return True
|
||||
# Only explicit chaining (`raise X from e`): implicit __context__ could
|
||||
# attribute an unrelated earlier error (e.g. a Firestore 403) to Gemini.
|
||||
exc = exc.__cause__
|
||||
return False
|
||||
|
||||
|
||||
def _alert_hours() -> float:
|
||||
try:
|
||||
return float(os.environ.get("GEMINI_QUOTA_ALERT_HOURS", _DEFAULT_ALERT_HOURS))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_ALERT_HOURS
|
||||
|
||||
|
||||
# In-process throttle so a burst of failures in one instance doesn't hit
|
||||
# Firestore on every call; the Firestore doc throttles across instances/jobs.
|
||||
_last_alert_attempt: float = 0.0
|
||||
_alert_lock = threading.Lock()
|
||||
# Alert I/O (Firestore + Secret Manager + Discord) runs on a daemon thread so it
|
||||
# never blocks the caller — several callers are on the asyncio event loop.
|
||||
# Tests flip this off to run it inline.
|
||||
_ALERT_IN_BACKGROUND = True
|
||||
|
||||
|
||||
def note_gemini_failure(caller: str, exc: BaseException) -> bool:
|
||||
"""Classify a Gemini failure; on quota/billing/key errors log + alert.
|
||||
|
||||
Call from a caller's ``except`` block. Returns True when the error is a
|
||||
quota/billing/key error (caller should skip retries and degrade). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not is_quota_or_billing_error(exc):
|
||||
return False
|
||||
logger.error("Gemini unavailable (quota/billing/key) in %s: %s", caller, exc)
|
||||
_maybe_alert(caller, exc)
|
||||
return True
|
||||
except Exception: # noqa: BLE001 - classification/alerting must never raise
|
||||
logger.warning("note_gemini_failure failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def _maybe_alert(caller: str, exc: BaseException) -> None:
|
||||
global _last_alert_attempt
|
||||
window = _alert_hours() * 3600
|
||||
now = time.monotonic()
|
||||
with _alert_lock:
|
||||
if _last_alert_attempt and now - _last_alert_attempt < window:
|
||||
return
|
||||
_last_alert_attempt = now
|
||||
if _ALERT_IN_BACKGROUND:
|
||||
threading.Thread(
|
||||
target=_send_alert, args=(caller, exc, window), name="gemini-quota-alert", daemon=True
|
||||
).start()
|
||||
else:
|
||||
_send_alert(caller, exc, window)
|
||||
|
||||
|
||||
def _send_alert(caller: str, exc: BaseException, window: float) -> None:
|
||||
global _last_alert_attempt
|
||||
from backend.services import ops_alerts
|
||||
|
||||
err = str(exc).strip()
|
||||
if len(err) > 800:
|
||||
err = err[:800] + " …[truncated]"
|
||||
message = (
|
||||
"🟠 **Gemini API unavailable — quota / prepaid credit / key problem**\n"
|
||||
f"**First seen in:** `{caller}`\n"
|
||||
"Callers are degrading (auto-correct keeps Opus only, match-judge/parse-titles "
|
||||
"return no suggestion, credit evals go to manual review, translations are "
|
||||
"skipped).\n"
|
||||
f"**Fix:** {QUOTA_EXHAUSTED_MESSAGE}\n"
|
||||
f"**Error:** ```{err}```"
|
||||
)
|
||||
try:
|
||||
ops_alerts.send_throttled_ops_alert(_ALERT_KEY, message, throttle_minutes=int(window / 60))
|
||||
except Exception: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("Gemini quota alert failed", exc_info=True)
|
||||
# Let the next failure in this instance try again.
|
||||
with _alert_lock:
|
||||
_last_alert_attempt = 0.0
|
||||
@@ -142,6 +142,8 @@ class JobManager:
|
||||
review_mode=job_create.review_mode,
|
||||
# Backing-vocals preference ("auto"=retain-where-safe | clean | review)
|
||||
backing_preference=job_create.backing_preference,
|
||||
# Translated lyrics beneath each line (None = off)
|
||||
translation_language=job_create.translation_language,
|
||||
# Distribution settings
|
||||
brand_prefix=job_create.brand_prefix,
|
||||
discord_webhook_url=job_create.discord_webhook_url,
|
||||
@@ -494,6 +496,9 @@ class JobManager:
|
||||
state_data_updates: Optional[Dict[str, Any]] = None,
|
||||
raise_on_invalid: bool = True,
|
||||
timeline_metadata: Optional[Dict[str, Any]] = None,
|
||||
notify: bool = True,
|
||||
extra_updates: Optional[Dict[str, Any]] = None,
|
||||
count_completion: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
Transition job to new state with validation.
|
||||
@@ -507,6 +512,14 @@ class JobManager:
|
||||
raise_on_invalid: If True (default), raise InvalidStateTransitionError
|
||||
on invalid transitions. If False, return False silently.
|
||||
timeline_metadata: Optional structured metadata to attach to the timeline event
|
||||
notify: If False, skip the user email/push notifications for this
|
||||
transition (e.g. an admin re-render the admin didn't opt
|
||||
into announcing to the customer).
|
||||
extra_updates: Additional Firestore field updates (dot paths allowed,
|
||||
e.g. ``{"state_data.admin_rerender": DELETE_FIELD}``) written
|
||||
in the SAME update as the status change.
|
||||
count_completion: If False, don't increment the user's completed-jobs
|
||||
counter on COMPLETE (an admin re-render isn't a new job).
|
||||
|
||||
Returns:
|
||||
True if transition succeeded, False if failed (only when raise_on_invalid=False)
|
||||
@@ -514,6 +527,17 @@ class JobManager:
|
||||
Raises:
|
||||
InvalidStateTransitionError: If transition is invalid and raise_on_invalid=True
|
||||
"""
|
||||
if state_data_updates and any(
|
||||
key == "state_data" or key.startswith("state_data.") for key in (extra_updates or {})
|
||||
):
|
||||
# state_data_updates rewrites the whole state_data map; a dot-path
|
||||
# write to state_data.* in the same Firestore update is a
|
||||
# conflicting-path error (and would be ambiguous anyway).
|
||||
raise ValueError(
|
||||
"transition_to_state: pass state_data changes via state_data_updates OR "
|
||||
"extra_updates['state_data.*'], not both"
|
||||
)
|
||||
|
||||
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
|
||||
return False
|
||||
|
||||
@@ -542,6 +566,7 @@ class JobManager:
|
||||
merged_state_data = {**job.state_data, **state_data_updates}
|
||||
|
||||
# Update job status (includes timeline event), passing state_data if present
|
||||
extra = dict(extra_updates or {})
|
||||
if merged_state_data is not None:
|
||||
self.update_job_status(
|
||||
job_id=job_id,
|
||||
@@ -549,7 +574,8 @@ class JobManager:
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
state_data=merged_state_data
|
||||
state_data=merged_state_data,
|
||||
**extra,
|
||||
)
|
||||
else:
|
||||
self.update_job_status(
|
||||
@@ -558,6 +584,7 @@ class JobManager:
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
**extra,
|
||||
)
|
||||
|
||||
# Apply review token update separately if generated
|
||||
@@ -570,7 +597,9 @@ class JobManager:
|
||||
logger.info(f"Job {job_id} transitioned to {new_status}")
|
||||
|
||||
# Increment user's completed jobs counter on terminal success states
|
||||
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
|
||||
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE) and not count_completion:
|
||||
logger.info(f"Job {job_id}: completion not counted towards the user's jobs_completed")
|
||||
elif new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
|
||||
try:
|
||||
job = self.get_job(job_id)
|
||||
if job and job.user_email:
|
||||
@@ -581,7 +610,10 @@ class JobManager:
|
||||
logger.exception(f"Failed to increment jobs_completed for job {job_id}")
|
||||
|
||||
# Trigger notifications asynchronously (fire-and-forget)
|
||||
self._trigger_state_notifications(job_id, new_status)
|
||||
if notify:
|
||||
self._trigger_state_notifications(job_id, new_status)
|
||||
else:
|
||||
logger.info(f"Job {job_id}: notifications suppressed for transition to {new_status}")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Translated lyrics: an LLM translation of each reviewed lyric line.
|
||||
|
||||
A job created with ``translation_language`` gets its final (post-review) lyrics
|
||||
translated once, just before the karaoke video renders. The result is stored at
|
||||
``jobs/{job_id}/lyrics/translations.json`` (format in
|
||||
``karaoke_gen.lyrics_transcriber.output.translations``), which the renderers draw in
|
||||
smaller text beneath each line. Translations aren't editable; they're regenerated
|
||||
from the reviewed text, and identical requests are served from a GCS cache (so a
|
||||
re-render costs no new LLM call).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Languages a user can pick: the app's UI locales (code -> English name for the prompt).
|
||||
TRANSLATION_LANGUAGES: Dict[str, str] = {
|
||||
"ar": "Arabic",
|
||||
"ca": "Catalan",
|
||||
"cs": "Czech",
|
||||
"da": "Danish",
|
||||
"de": "German",
|
||||
"el": "Greek",
|
||||
"en": "English",
|
||||
"es": "Spanish",
|
||||
"fi": "Finnish",
|
||||
"fr": "French",
|
||||
"he": "Hebrew",
|
||||
"hi": "Hindi",
|
||||
"hr": "Croatian",
|
||||
"hu": "Hungarian",
|
||||
"id": "Indonesian",
|
||||
"it": "Italian",
|
||||
"ja": "Japanese",
|
||||
"ko": "Korean",
|
||||
"ms": "Malay",
|
||||
"nb": "Norwegian (Bokmål)",
|
||||
"nl": "Dutch",
|
||||
"pl": "Polish",
|
||||
"pt": "Portuguese",
|
||||
"ro": "Romanian",
|
||||
"ru": "Russian",
|
||||
"sk": "Slovak",
|
||||
"sv": "Swedish",
|
||||
"th": "Thai",
|
||||
"tl": "Filipino (Tagalog)",
|
||||
"tr": "Turkish",
|
||||
"uk": "Ukrainian",
|
||||
"vi": "Vietnamese",
|
||||
"zh": "Simplified Chinese",
|
||||
}
|
||||
|
||||
TRANSLATIONS_GCS_NAME = "translations.json"
|
||||
CACHE_PREFIX = "lyrics-translation-cache"
|
||||
CACHE_VERSION = 1
|
||||
MAX_ATTEMPTS = 2
|
||||
BACKOFF_SECONDS = 2.0
|
||||
# More than this share of lines coming back unchanged = the song is already in the
|
||||
# target language, so a translation row would just repeat the lyrics.
|
||||
SAME_LANGUAGE_THRESHOLD = 0.8
|
||||
|
||||
SYSTEM_PROMPT = """You translate song lyrics for karaoke videos. Each translated line is shown \
|
||||
in small text directly beneath the original line while the singer sings it, so language \
|
||||
learners understand what they are singing.
|
||||
|
||||
Rules:
|
||||
- Return exactly one translation per input line, in the same order (same count).
|
||||
- Translate the meaning naturally and idiomatically; it does not need to rhyme or be singable.
|
||||
- A sentence often continues across lines: keep each translation aligned with the words of \
|
||||
its own line where the target grammar allows, so the meaning lines up with what is being sung.
|
||||
- Keep each translation about as short as its line; no explanations, notes, quotes or brackets.
|
||||
- Keep names, places and brand names. Keep pure vocables (oh, ooh, la la, yeah, na na) as they are.
|
||||
- If a line is already in the target language, return it unchanged.
|
||||
"""
|
||||
|
||||
|
||||
class LyricsTranslationError(Exception):
|
||||
"""The lyrics couldn't be translated (model error or malformed output)."""
|
||||
|
||||
|
||||
def normalize_language(code: Optional[str]) -> Optional[str]:
|
||||
"""Supported language code for ``code`` (case/region-insensitive), else None."""
|
||||
if not code:
|
||||
return None
|
||||
base = str(code).strip().lower().replace("_", "-")
|
||||
if base in TRANSLATION_LANGUAGES:
|
||||
return base
|
||||
base = base.split("-")[0]
|
||||
if base == "no":
|
||||
base = "nb"
|
||||
if base == "fil":
|
||||
base = "tl"
|
||||
return base if base in TRANSLATION_LANGUAGES else None
|
||||
|
||||
|
||||
def _norm(text: str) -> str:
|
||||
return " ".join((text or "").lower().split())
|
||||
|
||||
|
||||
def is_same_language(lines: List[str], translations: List[str]) -> bool:
|
||||
"""True when nearly every line came back unchanged (song already in that language)."""
|
||||
pairs = [(a, b) for a, b in zip(lines, translations) if _norm(a)]
|
||||
if not pairs:
|
||||
return False
|
||||
unchanged = sum(1 for a, b in pairs if _norm(a) == _norm(b))
|
||||
return unchanged / len(pairs) >= SAME_LANGUAGE_THRESHOLD
|
||||
|
||||
|
||||
def _user_prompt(lines: List[str], language: str, artist: Optional[str], title: Optional[str]) -> str:
|
||||
song = " - ".join(p for p in (artist, title) if p) or "unknown song"
|
||||
numbered = "\n".join(f"{i + 1}. {line}" for i, line in enumerate(lines))
|
||||
return (
|
||||
f"Song: {song}\n"
|
||||
f"Target language: {TRANSLATION_LANGUAGES[language]}\n"
|
||||
f"Translate these {len(lines)} lyric lines. Return JSON "
|
||||
f'{{"translations": [...]}} with exactly {len(lines)} strings, one per line, '
|
||||
f"without the line numbers.\n\n{numbered}"
|
||||
)
|
||||
|
||||
|
||||
def _is_transient(exc: BaseException) -> bool:
|
||||
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
|
||||
if isinstance(code, int) and code in {429, 500, 502, 503, 504}:
|
||||
return True
|
||||
text = str(exc).upper()
|
||||
return any(m in text for m in ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "DEADLINE", "429", "503"))
|
||||
|
||||
|
||||
class LyricsTranslationService:
|
||||
def __init__(self, storage=None, model: Optional[str] = None):
|
||||
self.settings = get_settings()
|
||||
self.model = model or self.settings.lyrics_translation_model
|
||||
self._storage = storage
|
||||
|
||||
def _get_storage(self):
|
||||
if self._storage is None:
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._storage = StorageService()
|
||||
return self._storage
|
||||
|
||||
# ---- cache (GCS, best-effort) ----
|
||||
|
||||
def _cache_path(self, lines: List[str], language: str, artist: Optional[str], title: Optional[str]) -> str:
|
||||
payload = {"v": CACHE_VERSION, "model": self.model, "language": language,
|
||||
"lines": lines, "artist": artist, "title": title}
|
||||
digest = hashlib.sha256(json.dumps(payload, ensure_ascii=False).encode()).hexdigest()[:32]
|
||||
return f"{CACHE_PREFIX}/{digest}.json"
|
||||
|
||||
def _cache_get(self, path: str, n: int) -> Optional[List[str]]:
|
||||
try:
|
||||
storage = self._get_storage()
|
||||
if not storage.file_exists(path):
|
||||
return None
|
||||
data = storage.download_json(path)
|
||||
translations = data.get("translations")
|
||||
if isinstance(translations, list) and len(translations) == n:
|
||||
return [str(t) for t in translations]
|
||||
except Exception:
|
||||
logger.warning("lyrics translation cache read failed for %s", path, exc_info=True)
|
||||
return None
|
||||
|
||||
def _cache_put(self, path: str, translations: List[str]) -> None:
|
||||
try:
|
||||
self._get_storage().upload_json(path, {"model": self.model, "translations": translations})
|
||||
except Exception:
|
||||
logger.warning("lyrics translation cache write failed for %s", path, exc_info=True)
|
||||
|
||||
# ---- model ----
|
||||
|
||||
def _call_gemini(self, user_prompt: str) -> Any:
|
||||
from google.genai import types
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=90_000) # 2 attempts: render waits <= ~3 min
|
||||
response = client.models.generate_content(
|
||||
model=self.model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
temperature=0.3,
|
||||
response_mime_type="application/json",
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"properties": {"translations": {"type": "array", "items": {"type": "string"}}},
|
||||
"required": ["translations"],
|
||||
},
|
||||
),
|
||||
)
|
||||
if response.text is None:
|
||||
raise LyricsTranslationError("model returned an empty response")
|
||||
return json.loads(response.text)
|
||||
|
||||
def _translate_once(self, lines: List[str], language: str, artist, title) -> List[str]:
|
||||
data = self._call_gemini(_user_prompt(lines, language, artist, title))
|
||||
translations = data.get("translations") if isinstance(data, dict) else None
|
||||
if not isinstance(translations, list) or len(translations) != len(lines):
|
||||
got = len(translations) if isinstance(translations, list) else "no"
|
||||
raise LyricsTranslationError(f"expected {len(lines)} translations, got {got}")
|
||||
return [" ".join(str(t).split()) for t in translations]
|
||||
|
||||
def translate_lines(
|
||||
self,
|
||||
lines: List[str],
|
||||
language: str,
|
||||
*,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> List[str]:
|
||||
"""One translation per line (same order). Raises LyricsTranslationError."""
|
||||
lang = normalize_language(language)
|
||||
if lang is None:
|
||||
raise LyricsTranslationError(f"unsupported language {language!r}")
|
||||
if not lines:
|
||||
return []
|
||||
cache_path = self._cache_path(lines, lang, artist, title)
|
||||
cached = self._cache_get(cache_path, len(lines))
|
||||
if cached is not None:
|
||||
logger.info("lyrics translation cache hit (%d lines, %s)", len(lines), lang)
|
||||
return cached
|
||||
|
||||
last_error: Optional[BaseException] = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
started = time.time()
|
||||
translations = self._translate_once(lines, lang, artist, title)
|
||||
logger.info(
|
||||
"lyrics translation: %d lines -> %s via %s in %.1fs",
|
||||
len(lines), lang, self.model, time.time() - started,
|
||||
)
|
||||
self._cache_put(cache_path, translations)
|
||||
return translations
|
||||
except (LyricsTranslationError, ValueError) as exc: # malformed output: retry
|
||||
last_error = exc
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
if note_gemini_failure("lyrics_translation", exc):
|
||||
# Quota/credit/key problem: don't retry; the render goes ahead
|
||||
# without the translation row.
|
||||
raise LyricsTranslationError(
|
||||
"translation service unavailable (Gemini quota/billing) — rendered without translation"
|
||||
) from exc
|
||||
if not _is_transient(exc):
|
||||
raise LyricsTranslationError(f"translation model error: {exc}") from exc
|
||||
last_error = exc
|
||||
if attempt < MAX_ATTEMPTS:
|
||||
backoff = BACKOFF_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
"lyrics translation attempt %d/%d failed (%s); retrying in %.1fs",
|
||||
attempt, MAX_ATTEMPTS, last_error, backoff,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
raise LyricsTranslationError(f"translation failed after {MAX_ATTEMPTS} attempts: {last_error}")
|
||||
|
||||
|
||||
def load_final_segments(storage, job_id: str):
|
||||
"""The reviewed lyric segments the video renders (corrections + review edits)."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
|
||||
base = CorrectionResult.from_dict(storage.download_json(f"jobs/{job_id}/lyrics/corrections.json"))
|
||||
updated_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
if storage.file_exists(updated_path):
|
||||
updated = storage.download_json(updated_path)
|
||||
if isinstance(updated, dict) and "corrections" in updated:
|
||||
return CorrectionOperations.update_correction_result_with_data(base, updated).corrected_segments
|
||||
return base.corrected_segments
|
||||
|
||||
|
||||
def prepare_job_translations(
|
||||
job_id: str, job, storage, job_manager=None, service: Optional[LyricsTranslationService] = None
|
||||
) -> Optional[str]:
|
||||
"""Translate a job's final lyrics and store ``translations.json``.
|
||||
|
||||
Returns the GCS path (relative to the bucket) when the video should show
|
||||
translations, else None: no language requested, the song is already in that
|
||||
language, or translation failed. A failure never blocks the render; it's logged as
|
||||
an error and recorded in ``state_data.lyrics_translation`` so an admin can
|
||||
re-render once fixed.
|
||||
"""
|
||||
stored_path = f"jobs/{job_id}/lyrics/{TRANSLATIONS_GCS_NAME}"
|
||||
language = normalize_language(getattr(job, "translation_language", None))
|
||||
if not language:
|
||||
_remove_stale(storage, stored_path)
|
||||
if job_manager is not None and (getattr(job, "state_data", None) or {}).get("lyrics_translation"):
|
||||
# Translation was turned off since a previous render: clear the old outcome
|
||||
# so the republished video isn't labelled "(With Translation into X)".
|
||||
try:
|
||||
job_manager.update_state_data(job_id, "lyrics_translation", {"status": "off"})
|
||||
except Exception:
|
||||
logger.warning(f"[job:{job_id}] could not clear lyrics_translation status", exc_info=True)
|
||||
return None
|
||||
status: Dict[str, Any] = {"language": language}
|
||||
path: Optional[str] = None
|
||||
try:
|
||||
segments = [s for s in load_final_segments(storage, job_id) if (s.text or "").strip()]
|
||||
lines = [s.text.strip() for s in segments]
|
||||
service = service or LyricsTranslationService(storage=storage)
|
||||
translations = service.translate_lines(lines, language, artist=job.artist, title=job.title)
|
||||
status.update(model=service.model, lines=len(lines))
|
||||
if is_same_language(lines, translations):
|
||||
logger.info(f"[job:{job_id}] Lyrics already in {language}; no translation row")
|
||||
status["status"] = "same_language"
|
||||
else:
|
||||
path = stored_path
|
||||
storage.upload_json(path, {
|
||||
"language": language,
|
||||
"language_name": TRANSLATION_LANGUAGES[language],
|
||||
"model": service.model,
|
||||
"lines": [
|
||||
{"segment_id": s.id, "text": line, "translation": tr}
|
||||
for s, line, tr in zip(segments, lines, translations)
|
||||
],
|
||||
})
|
||||
status["status"] = "translated"
|
||||
except Exception as exc:
|
||||
logger.error(f"[job:{job_id}] Lyrics translation to {language} failed; rendering without it: {exc}", exc_info=True)
|
||||
status.update(status="failed", error=str(exc)[:500])
|
||||
path = None
|
||||
if path is None:
|
||||
# The encoder also reads lyrics/translations.json for the portrait video
|
||||
_remove_stale(storage, stored_path)
|
||||
if job_manager is not None:
|
||||
try:
|
||||
job_manager.update_state_data(job_id, "lyrics_translation", status)
|
||||
except Exception:
|
||||
logger.warning(f"[job:{job_id}] could not record lyrics_translation status", exc_info=True)
|
||||
return path
|
||||
|
||||
|
||||
def _remove_stale(storage, path: str) -> None:
|
||||
"""Delete a translations file left by an earlier render (best-effort)."""
|
||||
try:
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
except Exception:
|
||||
logger.warning("could not delete stale %s", path, exc_info=True)
|
||||
@@ -149,18 +149,14 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
|
||||
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
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
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),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -169,6 +165,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -141,6 +141,9 @@ async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
|
||||
data = await (generate or _default_generate)(
|
||||
model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"')
|
||||
except Exception as e:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("match_judge_free_text", e)
|
||||
logger.warning(f"resolve_free_text failed: {e}")
|
||||
return _none(query, "unavailable")
|
||||
return verdict_from_response(data, query)
|
||||
@@ -200,17 +203,13 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=int(getattr(settings, "match_judge_timeout_ms", 12000))),
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=int(getattr(settings, "match_judge_timeout_ms", 12000)))
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -219,6 +218,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -126,7 +126,10 @@ async def judge_match(
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("match_judge", exc)
|
||||
# Graceful degradation: returning no-suggestion is a safe fallback (the
|
||||
# user just gets no auto-match). Log at WARNING (with traceback) so a
|
||||
# transient AI blip does not page as a red "new error pattern".
|
||||
|
||||
@@ -134,7 +134,9 @@ def _signature(error_message: str) -> str:
|
||||
return hashlib.sha256((error_message or "").encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, int, Any]:
|
||||
def _should_alert(
|
||||
db: Any, signature: str, now: datetime, throttle_minutes: Optional[int] = None
|
||||
) -> tuple[bool, bool, int, Any]:
|
||||
"""Decide whether to send, WITHOUT yet acknowledging delivery.
|
||||
|
||||
Returns ``(should_send, is_novel, suppressed_since_last, doc_ref)``:
|
||||
@@ -182,7 +184,8 @@ def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, i
|
||||
if last_alerted_raw:
|
||||
try:
|
||||
last_alerted = datetime.fromisoformat(last_alerted_raw)
|
||||
within_window = (now - last_alerted) < timedelta(minutes=_throttle_minutes())
|
||||
window = throttle_minutes if throttle_minutes is not None else _throttle_minutes()
|
||||
within_window = (now - last_alerted) < timedelta(minutes=window)
|
||||
except (TypeError, ValueError):
|
||||
within_window = False
|
||||
|
||||
@@ -225,6 +228,36 @@ def _mark_alerted(doc_ref: Any, now: datetime) -> None:
|
||||
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
|
||||
|
||||
|
||||
def send_throttled_ops_alert(key: str, message: str, throttle_minutes: int) -> bool:
|
||||
"""Send an ops alert at most once per ``throttle_minutes`` for ``key``.
|
||||
|
||||
The throttle lives in Firestore (same dedup collection as job-failure
|
||||
alerts), so it holds across every Cloud Run instance and job execution.
|
||||
Fails open (sends) if Firestore is unreachable. Best-effort; never raises.
|
||||
Returns True if an alert was sent.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
return False
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
should_send, _novel, suppressed, doc_ref = _should_alert(
|
||||
get_firestore_client(), key, now, throttle_minutes=throttle_minutes
|
||||
)
|
||||
if not should_send:
|
||||
return False
|
||||
if suppressed:
|
||||
message += f"\n_(Collapsed {suppressed} earlier occurrence(s).)_"
|
||||
sent = send_ops_alert(message)
|
||||
if sent:
|
||||
_mark_alerted(doc_ref, now)
|
||||
return sent
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: throttled alert %s failed: %s", key, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _retry_pending(state_data: dict) -> bool:
|
||||
"""True if state_data.cloud_run_retry_pending is set and unexpired."""
|
||||
pending = (state_data or {}).get("cloud_run_retry_pending")
|
||||
|
||||
@@ -123,18 +123,14 @@ async def _default_generate(model: str, system: str, user: str) -> dict:
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
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),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user],
|
||||
@@ -143,6 +139,9 @@ def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -56,6 +56,9 @@ async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
|
||||
try:
|
||||
results = await ai.ai_parse(chunk, model=model, generate=generate)
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("parse_titles", exc)
|
||||
logger.warning(
|
||||
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
|
||||
return _blanks(chunk)
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
Delete a job's published (distributed) outputs: YouTube video, Dropbox folder,
|
||||
Google Drive files.
|
||||
|
||||
Shared by the track Edit flow (``POST /api/jobs/{id}/edit``) and the admin
|
||||
re-render (``POST /api/admin/jobs/{id}/rerender``). Each helper returns a small
|
||||
result dict (``{"status": "success" | "failed" | "partial" | "skipped" |
|
||||
"error", ...}``) suitable for the job timeline and API responses, and never
|
||||
raises — the caller decides which failures are fatal.
|
||||
|
||||
Brand-code recycling is deliberately NOT done here: Edit recycles the code,
|
||||
the admin re-render keeps it and re-publishes under the same code.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_YOUTUBE_ID_RE = re.compile(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)')
|
||||
|
||||
# state_data keys that point at published outputs.
|
||||
PUBLISHED_OUTPUT_KEYS = ("youtube_url", "dropbox_link", "brand_code", "gdrive_files")
|
||||
|
||||
|
||||
def snapshot_published_outputs(state_data: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""The job's current published-output references (for the timeline/audit)."""
|
||||
state_data = state_data or {}
|
||||
return {key: state_data[key] for key in PUBLISHED_OUTPUT_KEYS if state_data.get(key)}
|
||||
|
||||
|
||||
def youtube_video_id(youtube_url: Optional[str]) -> Optional[str]:
|
||||
match = _YOUTUBE_ID_RE.search(youtube_url or "")
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def delete_youtube_video(job_id: str, youtube_url: Optional[str]) -> Dict[str, Any]:
|
||||
"""Delete the job's YouTube video (via the server-side YouTube credentials)."""
|
||||
if not youtube_url:
|
||||
return {"status": "skipped", "reason": "no youtube_url"}
|
||||
video_id = None
|
||||
try:
|
||||
# Inside the try: a malformed (e.g. non-string) URL must not raise.
|
||||
video_id = youtube_video_id(youtube_url)
|
||||
if not video_id:
|
||||
return {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
youtube_service = get_youtube_service()
|
||||
if not youtube_service.is_configured:
|
||||
return {"status": "skipped", "reason": "YouTube not configured"}
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict(),
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
return {"status": "success" if success else "failed", "video_id": video_id}
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Error deleting YouTube video {video_id}: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e), "video_id": video_id}
|
||||
|
||||
|
||||
def legacy_dropbox_folder_path(
|
||||
dropbox_path: str, brand_code: str, artist: Optional[str], title: Optional[str]
|
||||
) -> str:
|
||||
"""Raw-name folder (no sanitisation) that older Edit/delete code assumed."""
|
||||
return f"{dropbox_path}/{brand_code} - {artist or 'Unknown'} - {title or 'Unknown'}"
|
||||
|
||||
|
||||
def dropbox_folder_path(dropbox_path: str, brand_code: str, artist: Optional[str], title: Optional[str]) -> str:
|
||||
"""The Dropbox folder the distribution step uploads to (same sanitisation)."""
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
safe_artist = sanitize_filename(artist) if artist else "Unknown"
|
||||
safe_title = sanitize_filename(title) if title else "Unknown"
|
||||
return f"{dropbox_path}/{brand_code} - {safe_artist} - {safe_title}"
|
||||
|
||||
|
||||
def delete_dropbox_folder(
|
||||
job_id: str,
|
||||
dropbox_path: Optional[str],
|
||||
brand_code: Optional[str],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete the job's ``{dropbox_path}/{brand_code} - {Artist} - {Title}`` folder.
|
||||
|
||||
The uploader sanitises artist/title; older code paths assumed the raw names.
|
||||
When the two differ, both are checked and whichever exists is deleted.
|
||||
``success`` (which lets callers recycle the brand code) only when no folder
|
||||
remains; ``deleted`` lists what was removed.
|
||||
"""
|
||||
if not (brand_code and dropbox_path):
|
||||
return {"status": "skipped", "reason": "no brand_code or dropbox_path"}
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
return {"status": "skipped", "reason": "Dropbox not configured"}
|
||||
full_path = dropbox_folder_path(dropbox_path, brand_code, artist, title)
|
||||
legacy_path = legacy_dropbox_folder_path(dropbox_path, brand_code, artist, title)
|
||||
candidates = [full_path] if legacy_path == full_path else [full_path, legacy_path]
|
||||
|
||||
deleted, failed = [], []
|
||||
for path in candidates:
|
||||
if len(candidates) > 1:
|
||||
try:
|
||||
if not dropbox.file_exists(path):
|
||||
continue
|
||||
except Exception as e: # unknown → attempt the delete anyway
|
||||
logger.warning(f"[job:{job_id}] Dropbox existence check failed for {path}: {e}")
|
||||
# delete_folder is True when deleted OR already absent.
|
||||
(deleted if dropbox.delete_folder(path) else failed).append(path)
|
||||
result = {"status": "failed" if failed else "success", "path": full_path, "deleted": deleted}
|
||||
if failed:
|
||||
result["failed"] = failed
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Error deleting Dropbox folder: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
|
||||
def delete_gdrive_files(
|
||||
job_id: str,
|
||||
gdrive_files: Optional[Dict[str, str]],
|
||||
brand_code: Optional[str] = None,
|
||||
cleanup_mirror: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete the job's Google Drive public-share files.
|
||||
|
||||
``cleanup_mirror`` also removes the Nomad 720p master from the GCS
|
||||
fast-sync mirror (kjbox). A re-render that re-publishes under the same brand
|
||||
code skips it: the new upload overwrites the same mirror object, so kjbox
|
||||
keeps the old master until the new one lands instead of losing the song.
|
||||
"""
|
||||
if not gdrive_files:
|
||||
return {"status": "skipped", "reason": "no gdrive_files"}
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
|
||||
gdrive = get_gdrive_service()
|
||||
if not gdrive.is_configured:
|
||||
return {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
if cleanup_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)
|
||||
return {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Error deleting Google Drive files: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e)}
|
||||
@@ -80,6 +80,7 @@ IMAGE_CONTENT_TYPES = {
|
||||
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$")
|
||||
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
_DOMAIN_RE = re.compile(r"^(?!-)[a-z0-9-]+(\.[a-z0-9-]+)+$")
|
||||
_BRAND_PREFIX_RE = re.compile(r"^[A-Z][A-Z0-9]{1,11}$")
|
||||
|
||||
|
||||
class TenantValidationError(ValueError):
|
||||
@@ -136,6 +137,77 @@ def _normalize_domains(domains: Optional[List[str]]) -> List[str]:
|
||||
return cleaned
|
||||
|
||||
|
||||
def _normalize_delivery(
|
||||
dropbox_path: Optional[str], brand_prefix: Optional[str]
|
||||
) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
Normalize + validate the tenant's Dropbox delivery settings.
|
||||
|
||||
The video worker only delivers to Dropbox when BOTH a path and a brand prefix
|
||||
are set (outputs are filed as ``<PREFIX>-0001 - Artist - Title``), so one
|
||||
without the other would silently fall back to download-only.
|
||||
"""
|
||||
path = (dropbox_path or "").strip().rstrip("/")
|
||||
if path and not path.startswith("/"):
|
||||
path = f"/{path}"
|
||||
prefix = (brand_prefix or "").strip().upper()
|
||||
if bool(path) != bool(prefix):
|
||||
raise TenantValidationError(
|
||||
"Dropbox delivery needs both a Dropbox path and a brand prefix "
|
||||
"(outputs are filed as <PREFIX>-0001 - Artist - Title)."
|
||||
)
|
||||
if prefix and not _BRAND_PREFIX_RE.match(prefix):
|
||||
raise TenantValidationError(
|
||||
"Brand prefix must be 2-12 uppercase letters/numbers, starting with a letter."
|
||||
)
|
||||
return (path or None), (prefix or None)
|
||||
|
||||
|
||||
def _check_brand_prefix_available(
|
||||
prefix: str, tenant_id: str, storage: StorageService
|
||||
) -> None:
|
||||
"""Reject a brand prefix used by the consumer defaults or another tenant.
|
||||
|
||||
Brand-code counters are keyed by prefix alone, so sharing one would
|
||||
interleave numbering across two different Dropbox folders.
|
||||
"""
|
||||
reserved = {
|
||||
p.upper()
|
||||
for p in (settings.default_brand_prefix, settings.default_private_brand_prefix)
|
||||
if p
|
||||
}
|
||||
if prefix in reserved:
|
||||
raise TenantValidationError(f"Brand prefix '{prefix}' is reserved for Nomad Karaoke.")
|
||||
for other in list_tenants(storage=storage):
|
||||
if other.get("id") != tenant_id and (other.get("brand_prefix") or "").upper() == prefix:
|
||||
raise TenantConflictError(
|
||||
f"Brand prefix '{prefix}' is already used by tenant '{other.get('id')}'."
|
||||
)
|
||||
|
||||
|
||||
def get_dropbox_service():
|
||||
"""Lazy accessor — dropbox_service pulls in secretmanager, kept off the startup import graph."""
|
||||
from backend.services.dropbox_service import get_dropbox_service as _get_dropbox_service
|
||||
|
||||
return _get_dropbox_service()
|
||||
|
||||
|
||||
def _ensure_dropbox_folder(path: str) -> None:
|
||||
"""Create the tenant's Dropbox output folder so delivery works from job one."""
|
||||
try:
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
raise TenantProvisioningError(
|
||||
"Dropbox isn't configured on the backend; can't create the output folder."
|
||||
)
|
||||
created = dropbox.ensure_folder(path)
|
||||
except TenantProvisioningError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise TenantProvisioningError(f"Couldn't create Dropbox folder '{path}': {exc}") from exc
|
||||
logger.info(f"Dropbox output folder {path} {'created' if created else 'already exists'}")
|
||||
|
||||
|
||||
def _content_type_for(ext: str) -> str:
|
||||
return IMAGE_CONTENT_TYPES.get(ext.lower(), "application/octet-stream")
|
||||
|
||||
@@ -269,6 +341,10 @@ def create_tenant(
|
||||
if tenant_service.tenant_exists(tenant_id):
|
||||
raise TenantConflictError(f"Tenant '{tenant_id}' already exists.")
|
||||
|
||||
dropbox_path, brand_prefix = _normalize_delivery(dropbox_path, brand_prefix)
|
||||
if brand_prefix:
|
||||
_check_brand_prefix_available(brand_prefix, tenant_id, storage)
|
||||
|
||||
theme_id = tenant_id # 1:1 theme per tenant, mirrors the setup scripts
|
||||
|
||||
# The tenant id doubles as the theme id, and theme writes are not create-only.
|
||||
@@ -289,6 +365,11 @@ def create_tenant(
|
||||
except TenantDomainError as exc:
|
||||
raise TenantProvisioningError(str(exc)) from exc
|
||||
|
||||
# Create the Dropbox output folder up front (idempotent) so the first job
|
||||
# delivers there and the completion email carries a real folder link.
|
||||
if dropbox_path:
|
||||
_ensure_dropbox_folder(dropbox_path)
|
||||
|
||||
# --- Derive theme from the default Nomad theme ---------------------------
|
||||
base_theme_id = theme_service.get_default_theme_id()
|
||||
if not base_theme_id:
|
||||
@@ -571,7 +652,26 @@ def update_tenant(
|
||||
branding["logo_url"] = f"gs://{settings.gcs_bucket_name}/{logo_path}"
|
||||
merged_updates["branding"] = branding
|
||||
|
||||
# 4. Config merge (access lists normalized; any allowlist => enforced)
|
||||
# 4. Dropbox delivery (path + prefix validated together; folder created;
|
||||
# the feature flag always follows the path so the two can't drift)
|
||||
defaults_updates = merged_updates.get("defaults")
|
||||
if isinstance(defaults_updates, dict) and (
|
||||
"dropbox_path" in defaults_updates or "brand_prefix" in defaults_updates
|
||||
):
|
||||
defaults_updates = dict(defaults_updates)
|
||||
dropbox_path, brand_prefix = _normalize_delivery(
|
||||
defaults_updates.get("dropbox_path", config.defaults.dropbox_path),
|
||||
defaults_updates.get("brand_prefix", config.defaults.brand_prefix),
|
||||
)
|
||||
if brand_prefix:
|
||||
_check_brand_prefix_available(brand_prefix, tenant_id, storage)
|
||||
if dropbox_path and dropbox_path != config.defaults.dropbox_path:
|
||||
_ensure_dropbox_folder(dropbox_path)
|
||||
defaults_updates["dropbox_path"] = dropbox_path
|
||||
defaults_updates["brand_prefix"] = brand_prefix
|
||||
merged_updates["defaults"] = defaults_updates
|
||||
|
||||
# 5. Config merge (access lists normalized; any allowlist => enforced)
|
||||
auth_updates = merged_updates.get("auth")
|
||||
if isinstance(auth_updates, dict):
|
||||
auth_updates = dict(auth_updates)
|
||||
@@ -584,6 +684,7 @@ def update_tenant(
|
||||
merged_updates["auth"] = auth_updates
|
||||
if merged_updates:
|
||||
config = _merge_config(config, merged_updates)
|
||||
config.features.dropbox_upload = bool(config.defaults.dropbox_path)
|
||||
if isinstance(auth_updates, dict) and "require_email_domain" not in auth_updates:
|
||||
config.auth.require_email_domain = bool(
|
||||
config.auth.allowed_email_domains or config.auth.allowed_emails
|
||||
@@ -626,6 +727,7 @@ def list_tenants(storage: Optional[StorageService] = None) -> List[Dict[str, obj
|
||||
"locked_theme": defaults.get("locked_theme"),
|
||||
"theme_id": defaults.get("theme_id"),
|
||||
"dropbox_path": defaults.get("dropbox_path"),
|
||||
"brand_prefix": defaults.get("brand_prefix"),
|
||||
"created_at": data.get("created_at"),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -431,6 +431,9 @@ def analyze_filenames(
|
||||
llm_rows, leftover = _llm_analyze(leftover, generate)
|
||||
rows.extend(llm_rows)
|
||||
except Exception as e: # pragma: no cover - resilience guard
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("tenant_bulk_analyze", e)
|
||||
logger.warning("Bulk-analyze LLM pass failed, using regex result: %s", e)
|
||||
|
||||
unpaired = [_describe_unpaired(fn) for fn in leftover]
|
||||
@@ -438,7 +441,7 @@ def analyze_filenames(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Default Vertex-Gemini generate (mirrors backend.services.match_judge.ai)
|
||||
# Default Gemini generate (mirrors backend.services.match_judge.ai)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _default_model() -> str:
|
||||
@@ -451,22 +454,18 @@ def _default_model() -> str:
|
||||
|
||||
|
||||
def default_generate(system_prompt: str, user_prompt: str) -> dict:
|
||||
"""Blocking Vertex-Gemini call producing schema-constrained JSON.
|
||||
"""Blocking Gemini (Developer API) call producing schema-constrained JSON.
|
||||
|
||||
Wrap in ``asyncio.to_thread`` when calling from async code.
|
||||
"""
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
timeout_ms = int(getattr(settings, "tenant_bulk_timeout_ms", 30000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=_default_model(),
|
||||
contents=[user_prompt],
|
||||
@@ -475,6 +474,9 @@ def default_generate(system_prompt: str, user_prompt: str) -> dict:
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -249,7 +249,7 @@ def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> by
|
||||
return _to_jpeg(f"{noext}.png")
|
||||
|
||||
|
||||
def _sample_segments(lines: List[str]):
|
||||
def _sample_segments(lines: List[str], translations: Optional[List[str]] = None):
|
||||
"""Evenly-timed segments: line i starts at 2+3i s, words spread over 2.5 s.
|
||||
|
||||
Starts < 10 s and gaps < 10 s so SectionDetector adds no intro/instrumental.
|
||||
@@ -266,7 +266,14 @@ def _sample_segments(lines: List[str]):
|
||||
for j, w in enumerate(words_text)
|
||||
]
|
||||
segments.append(
|
||||
LyricsSegment(id=f"s{i}", text=" ".join(words_text), words=words, start_time=start, end_time=start + 2.5)
|
||||
LyricsSegment(
|
||||
id=f"s{i}",
|
||||
text=" ".join(words_text),
|
||||
words=words,
|
||||
start_time=start,
|
||||
end_time=start + 2.5,
|
||||
translation=(translations[i] if translations and i < len(translations) else None) or None,
|
||||
)
|
||||
)
|
||||
return segments
|
||||
|
||||
@@ -330,8 +337,13 @@ class _FrameRenderer:
|
||||
raise ThemePreviewError("Karaoke frame render timed out") from exc
|
||||
|
||||
|
||||
def render_karaoke_frame(styles: Dict, lines: List[str], workdir: str) -> bytes:
|
||||
"""One frame of the karaoke video with the first line about half sung."""
|
||||
def render_karaoke_frame(
|
||||
styles: Dict, lines: List[str], workdir: str, translations: Optional[List[str]] = None
|
||||
) -> bytes:
|
||||
"""One frame of the karaoke video with the first line about half sung.
|
||||
|
||||
``translations`` (one per line) renders the translated-lyrics layout.
|
||||
"""
|
||||
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
|
||||
from karaoke_gen.lyrics_transcriber.output.subtitles import SubtitlesGenerator
|
||||
from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE
|
||||
@@ -345,7 +357,7 @@ def render_karaoke_frame(styles: Dict, lines: List[str], workdir: str) -> bytes:
|
||||
font_size = karaoke.get("font_size", DEFAULT_FONT_SIZE)
|
||||
max_line_length = karaoke.get("max_line_length", DEFAULT_MAX_LINE_LENGTH)
|
||||
segments = SegmentResizer(max_line_length=max_line_length, logger=logger).resize_segments(
|
||||
_sample_segments(lines)
|
||||
_sample_segments(lines, translations)
|
||||
)
|
||||
subtitles = SubtitlesGenerator(
|
||||
output_dir=workdir,
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
Re-render a completed tenant job with the tenant's CURRENT theme.
|
||||
|
||||
Tenant users can edit their theme at any time, but a job snapshots the theme's
|
||||
style at creation (``jobs/{id}/style/style_params.json`` + ``style_assets``), so
|
||||
existing videos keep the old look. This service re-snapshots the current theme
|
||||
onto the job and re-runs everything downstream of review — title/end screens,
|
||||
the lyrics video, final encodes and CDG/TXT packages — reusing the job's
|
||||
reviewed lyrics (corrections_updated.json) and instrumental selection, so the
|
||||
user never goes back through review.
|
||||
|
||||
Mechanism (same as VisibilityChangeService.change_to_public): move the job to
|
||||
LYRICS_COMPLETE with ``state_data.regen_restore_status = "review_complete"`` and
|
||||
trigger the screens worker. The screens worker regenerates the screens with the
|
||||
new style, restores REVIEW_COMPLETE and triggers the render worker, which renders
|
||||
from the existing corrections; the video worker then re-encodes and completes.
|
||||
|
||||
Scope: tenant jobs. A tenant Dropbox archive folder is refreshed in place under
|
||||
the job's existing brand code (see rerender_brand_code). Jobs published to
|
||||
YouTube/GDrive are rejected — those would need the delete/redistribute dance of
|
||||
the visibility flow, which tenants don't use.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Screens + lyrics video are regenerated; stale copies must go so the encoder
|
||||
# can't reuse them (it prefers an existing screens/*.mov over the new PNG).
|
||||
# Old title/end MOVs in finals/ are removed separately (see _delete_stale_artifacts).
|
||||
_REGENERATED_ARTIFACTS = [
|
||||
"screens/title.mov",
|
||||
"screens/title.jpg",
|
||||
"screens/title.png",
|
||||
"screens/end.mov",
|
||||
"screens/end.jpg",
|
||||
"screens/end.png",
|
||||
"videos/with_vocals.mkv",
|
||||
"videos/with_vocals.mov",
|
||||
]
|
||||
|
||||
|
||||
class RerenderError(Exception):
|
||||
"""Re-render request rejected; ``status_code`` maps to the HTTP response."""
|
||||
|
||||
def __init__(self, message: str, status_code: int = 400):
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class RerenderConflictError(RerenderError):
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message, status_code=409)
|
||||
|
||||
|
||||
def _claimable_statuses(job) -> set:
|
||||
"""COMPLETE, plus FAILED when the failure was a re-render (so it can be retried)."""
|
||||
statuses = {JobStatus.COMPLETE.value}
|
||||
if (job.state_data or {}).get("theme_rerender"):
|
||||
statuses.add(JobStatus.FAILED.value)
|
||||
return statuses
|
||||
|
||||
|
||||
def validate_rerender(job) -> Optional[str]:
|
||||
"""Return a reason the job can't be re-rendered, or None if it can."""
|
||||
if not getattr(job, "tenant_id", None):
|
||||
return "Re-rendering with the current theme is only available for portal tracks."
|
||||
if job.status not in _claimable_statuses(job):
|
||||
return f"Only finished tracks can be re-rendered (current status: {job.status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This track's outputs were deleted, so it can't be re-rendered."
|
||||
if not getattr(job, "theme_id", None):
|
||||
return "This track wasn't made from a theme, so there's nothing to re-apply."
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "This track type can't be re-rendered."
|
||||
state_data = job.state_data or {}
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "This track has no instrumental selection to re-render with."
|
||||
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "This track has no reviewed lyrics to re-render with."
|
||||
if state_data.get("youtube_url") or state_data.get("gdrive_files"):
|
||||
return "This track was published to YouTube/Google Drive and can't be re-rendered here."
|
||||
# Tenant Dropbox archives (e.g. RVILD-0001 - Artist - Title) are refreshed in
|
||||
# place, which needs the brand code the folder is named after.
|
||||
if state_data.get("dropbox_link") and not state_data.get("brand_code"):
|
||||
return "This track's Dropbox folder can't be identified, so it can't be re-rendered here."
|
||||
return None
|
||||
|
||||
|
||||
def rerender_brand_code(job) -> Optional[str]:
|
||||
"""Brand code a re-render (theme or admin) must reuse, if one is in progress.
|
||||
|
||||
A re-render refreshes the job's existing Dropbox folder / re-publishes under
|
||||
the same code instead of allocating a new one. Scoped to the re-render
|
||||
marker (cleared on success) rather than the job's ``keep_brand_code`` field
|
||||
so a later Edit, which recycles the code, can't reuse it.
|
||||
"""
|
||||
state_data = getattr(job, "state_data", None) or {}
|
||||
code = (state_data.get("theme_rerender") or {}).get("brand_code")
|
||||
if code:
|
||||
return code
|
||||
# Admin re-render (only while its marker belongs to the current run).
|
||||
from backend.services.admin_rerender_service import admin_rerender_brand_code
|
||||
return admin_rerender_brand_code(job)
|
||||
|
||||
|
||||
def delete_regenerated_artifacts(storage: StorageService, job_id: str) -> None:
|
||||
"""Best-effort removal of everything a re-render regenerates.
|
||||
|
||||
The GCE encoder looks up the title/end MOV with ``**/*Title*.mov`` /
|
||||
``**/*End*.mov`` across everything it downloaded from ``jobs/{id}/``, so
|
||||
once ``screens/title.mov`` is gone it would pick up the OLD
|
||||
``finals/<Artist> - <Title> (Title).mov`` (or ``finals/title_mov.mov``)
|
||||
and splice the old intro/outro around the new lyrics video.
|
||||
finals/ only holds MOVs for those title/end cards, so drop every MOV there.
|
||||
The MP4/MKV/zip finals stay (overwritten by the re-render).
|
||||
"""
|
||||
paths = [f"jobs/{job_id}/{rel}" for rel in _REGENERATED_ARTIFACTS]
|
||||
try:
|
||||
paths += [
|
||||
p for p in storage.list_files(f"jobs/{job_id}/finals/")
|
||||
if p.lower().endswith(".mov")
|
||||
]
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Re-render: failed to list finals: {e}")
|
||||
for path in paths:
|
||||
try:
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
except Exception as e: # best-effort, like the visibility flow
|
||||
logger.warning(f"[job:{job_id}] Re-render: failed to delete {path}: {e}")
|
||||
|
||||
|
||||
def claim_for_rerender(db, job_id: str, update: dict, allowed_statuses: set) -> None:
|
||||
"""Atomically apply ``update`` iff the job's status is still claimable.
|
||||
|
||||
Raises RerenderConflictError otherwise (e.g. a double-click already
|
||||
started a re-render).
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
# Same collection the YouTube queue's mark_processing transaction reads, so
|
||||
# the two claims always contend on the same job document.
|
||||
job_ref = db.collection(get_settings().firestore_collection).document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def claim(transaction):
|
||||
snapshot = job_ref.get(transaction=transaction)
|
||||
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
|
||||
if status not in allowed_statuses:
|
||||
return False
|
||||
transaction.update(job_ref, update)
|
||||
return True
|
||||
|
||||
if not claim(db.transaction()):
|
||||
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
|
||||
|
||||
|
||||
class ThemeRerenderService:
|
||||
def __init__(
|
||||
self,
|
||||
job_manager: Optional[JobManager] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
self.storage = storage or StorageService()
|
||||
|
||||
async def start(self, job, theme_id: str, requested_by: str) -> None:
|
||||
"""Re-snapshot ``theme_id`` onto the job and kick off the re-render.
|
||||
|
||||
Raises RerenderConflictError if the job stopped being COMPLETE (e.g. a
|
||||
double-click already started a re-render).
|
||||
"""
|
||||
job_id = job.job_id
|
||||
reason = validate_rerender(job)
|
||||
if reason:
|
||||
raise RerenderError(reason)
|
||||
|
||||
# Snapshot the current theme onto the job's style folder. Done before the
|
||||
# claim so a failure here leaves the job untouched; overwriting the style
|
||||
# copy of a still-complete job is harmless (its finals are already made).
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
style_params_path, style_assets, _ = _prepare_theme_for_job(
|
||||
job_id, theme_id, getattr(job, "color_overrides", None) or None
|
||||
)
|
||||
if not style_params_path:
|
||||
raise RerenderError(f"Theme '{theme_id}' has no style to apply.", status_code=500)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
update = {
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"progress": 50,
|
||||
"theme_id": theme_id,
|
||||
"style_params_gcs_path": style_params_path,
|
||||
"style_assets": style_assets,
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"state_data.theme_rerender": {
|
||||
"requested_by": requested_by,
|
||||
"requested_at": now.isoformat(),
|
||||
"theme_id": theme_id,
|
||||
"brand_code": (job.state_data or {}).get("brand_code")
|
||||
or ((job.state_data or {}).get("theme_rerender") or {}).get("brand_code"),
|
||||
},
|
||||
# The old screens are deleted below. Drop their file_urls so nothing
|
||||
# (e.g. a later retry) reuses them.
|
||||
"file_urls.screens": DELETE_FIELD,
|
||||
"file_urls.videos.with_vocals": DELETE_FIELD,
|
||||
"updated_at": now,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": f"Re-render with current theme '{theme_id}' requested by {requested_by}",
|
||||
}]),
|
||||
}
|
||||
self._claim(job_id, update, _claimable_statuses(job))
|
||||
|
||||
self._delete_stale_artifacts(job_id)
|
||||
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Re-render: failed to trigger screens worker, restoring {job.status}")
|
||||
self.job_manager.update_job(job_id, {
|
||||
"status": job.status,
|
||||
"progress": 100 if job.status == JobStatus.COMPLETE.value else job.progress,
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
"state_data.theme_rerender": DELETE_FIELD,
|
||||
})
|
||||
raise RerenderError("Couldn't start the re-render. Please try again.", status_code=503)
|
||||
|
||||
logger.info(f"[job:{job_id}] Re-render with theme '{theme_id}' started by {requested_by}")
|
||||
|
||||
def _delete_stale_artifacts(self, job_id: str) -> None:
|
||||
delete_regenerated_artifacts(self.storage, job_id)
|
||||
|
||||
def _claim(self, job_id: str, update: dict, allowed_statuses: set) -> None:
|
||||
claim_for_rerender(self.job_manager.firestore.db, job_id, update, allowed_statuses)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Preview of the translated-lyrics layout for the job-creation option.
|
||||
|
||||
Renders one karaoke frame of the default theme (same renderer as production, via
|
||||
``theme_preview_service``) with sample lyrics and their translation in the chosen
|
||||
language. Translations come from ``translation_preview_samples`` (generated once,
|
||||
committed), so the preview never calls the LLM.
|
||||
"""
|
||||
import base64
|
||||
import logging
|
||||
import tempfile
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
from backend.services.theme_preview_service import render_karaoke_frame, resolve_assets
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.translation_preview_samples import SAMPLES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FALLBACK_THEME_ID = "nomad"
|
||||
_CACHE: "OrderedDict[tuple, str]" = OrderedDict()
|
||||
_CACHE_MAX = 40
|
||||
_lock = threading.Lock()
|
||||
_key_locks: "dict[tuple, threading.Lock]" = {} # bounded: themes x 33 languages
|
||||
|
||||
|
||||
def render_translation_preview(language: str, theme_id: Optional[str] = None) -> str:
|
||||
"""JPEG data URL of a karaoke frame with translations in ``language``."""
|
||||
code = normalize_language(language)
|
||||
if code is None or code not in SAMPLES:
|
||||
raise ValueError(f"Unsupported language: {language}")
|
||||
theme_service = get_theme_service()
|
||||
theme_id = theme_id or theme_service.get_default_theme_id() or FALLBACK_THEME_ID
|
||||
key = (theme_id, code)
|
||||
with _lock:
|
||||
if key in _CACHE:
|
||||
_CACHE.move_to_end(key)
|
||||
return _CACHE[key]
|
||||
key_lock = _key_locks.setdefault(key, threading.Lock())
|
||||
# One render per key: concurrent cold requests wait for it instead of each running ffmpeg
|
||||
with key_lock:
|
||||
with _lock:
|
||||
if key in _CACHE:
|
||||
_CACHE.move_to_end(key)
|
||||
return _CACHE[key]
|
||||
return _render_and_cache(key, theme_service, theme_id, code)
|
||||
|
||||
|
||||
def _render_and_cache(key: tuple, theme_service, theme_id: str, code: str) -> str:
|
||||
style_params = theme_service.get_theme_style_params(theme_id)
|
||||
if style_params is None:
|
||||
raise ValueError(f"Theme not found: {theme_id}")
|
||||
styles = resolve_assets(style_params, theme_id)
|
||||
sample = SAMPLES[code]
|
||||
with tempfile.TemporaryDirectory(prefix="translation-preview-") as workdir:
|
||||
jpeg = render_karaoke_frame(styles, sample["lyrics"], workdir, translations=sample["translations"])
|
||||
data_url = "data:image/jpeg;base64," + base64.b64encode(jpeg).decode()
|
||||
with _lock:
|
||||
_CACHE[key] = data_url
|
||||
while len(_CACHE) > _CACHE_MAX:
|
||||
_CACHE.popitem(last=False)
|
||||
return data_url
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Sample lyrics + translations for the translated-lyrics preview.
|
||||
|
||||
Generated by backend/scripts/generate_translation_preview_samples.py; don't edit by hand.
|
||||
"""
|
||||
|
||||
SAMPLES = {'ar': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['كل ليلة أردد الغناء',
|
||||
'تخفت الأضواء وها هي أغنيتي',
|
||||
'أمسك الميكروفون وأعتلي المسرح',
|
||||
'اقلب الصفحة، اقلب الصفحة']},
|
||||
'ca': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Cada nit canto alhora',
|
||||
"S'apaguen els llums i arriba la meva cançó",
|
||||
"Agafo el micro i pujo a l'escenari",
|
||||
'Passa pàgina, passa pàgina']},
|
||||
'cs': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Každou noc si zpívám',
|
||||
'Světla zhasnou a je tu má píseň',
|
||||
'Vezmi mikrofon a vyjdi na pódium',
|
||||
'Otoč stránku, otoč stránku']},
|
||||
'da': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Hver aften synger jeg med',
|
||||
'Lyset dæmpes, og her er min sang',
|
||||
'Hold mikrofonen og indtag scenen',
|
||||
'Vend siden, vend siden']},
|
||||
'de': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Jede Nacht singe ich mit',
|
||||
'Die Lichter gehen aus und hier ist mein Lied',
|
||||
'Halt das Mikrofon und betritt die Bühne',
|
||||
'Schlag die Seite um, schlag die Seite um']},
|
||||
'el': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Κάθε βράδυ τραγουδάω μαζί',
|
||||
'Τα φώτα σβήνουν και να το τραγούδι μου',
|
||||
'Κράτα το μικρόφωνο κι ανέβα στη σκηνή',
|
||||
'Γύρισε σελίδα, γύρισε σελίδα']},
|
||||
'en': {'lyrics': ['Cada noche canto sin parar',
|
||||
'Se apagan las luces, es mi lugar',
|
||||
'Tomo el micrófono y subo al escenario',
|
||||
'Doy la vuelta a la página otra vez'],
|
||||
'translations': ['Every night I sing nonstop',
|
||||
"The lights go out, it's my place",
|
||||
'I grab the microphone and take the stage',
|
||||
'I turn the page once again']},
|
||||
'es': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Cada noche canto a coro',
|
||||
'Se apagan las luces y esta es mi canción',
|
||||
'Toma el micrófono y sube al escenario',
|
||||
'Pasa la página, pasa la página']},
|
||||
'fi': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Joka ilta laulan mukana',
|
||||
'Valot sammuvat ja tässä on lauluni',
|
||||
'Tartu mikkiin ja nouse lavalle',
|
||||
'Käännä sivua, käännä sivua']},
|
||||
'fr': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Chaque soir je chante avec',
|
||||
"Les lumières s'éteignent et voici ma chanson",
|
||||
'Prends le micro et monte sur scène',
|
||||
'Tourne la page, tourne la page']},
|
||||
'he': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['בכל לילה אני שר יחד',
|
||||
'האורות כבים והנה השיר שלי',
|
||||
'מחזיק במיקרופון ועולה לבמה',
|
||||
'להפוך את הדף, להפוך את הדף']},
|
||||
'hi': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['हर रात मैं साथ गाता हूँ',
|
||||
'रोशनी धीमी होती है और ये रहा मेरा गाना',
|
||||
'माइक थामो और मंच पर कदम रखो',
|
||||
'पन्ना पलटो, पन्ना पलटो']},
|
||||
'hr': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Svake noći pjevam uz nju',
|
||||
'Svjetla se gase i evo moje pjesme',
|
||||
'Uzmi mikrofon i stani na pozornicu',
|
||||
'Okreni stranicu, okreni stranicu']},
|
||||
'hu': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Minden éjjel együtt éneklek',
|
||||
'Kialszanak a fények, és itt a dalom',
|
||||
'Fogd a mikrofont, és lépj a színpadra',
|
||||
'Lapozz egyet, lapozz egyet']},
|
||||
'id': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Setiap malam kuikut bernyanyi',
|
||||
'Lampu padam dan inilah laguku',
|
||||
'Pegang mikrofon dan naik ke panggung',
|
||||
'Buka lembaran baru, buka lembaran baru']},
|
||||
'it': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Ogni notte canto insieme',
|
||||
'Le luci si spengono ed ecco la mia canzone',
|
||||
'Prendo il microfono e salgo sul palco',
|
||||
'Volto pagina, volto pagina']},
|
||||
'ja': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['毎晩 一緒に歌う', '明かりが落ち 私の歌が始まる', 'マイクを握り ステージに立つ', 'ページをめくって ページをめくる']},
|
||||
'ko': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['매일 밤 난 따라 불러', '불이 꺼지고 내 노래가 시작돼', '마이크를 잡고 무대에 올라', '페이지를 넘겨, 페이지를 넘겨']},
|
||||
'ms': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Setiap malam aku ikut menyanyi',
|
||||
'Lampu terpadam dan inilah laguku',
|
||||
'Pegang mikrofon dan naik ke pentas',
|
||||
'Selak halaman, selak halaman']},
|
||||
'nb': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Hver kveld synger jeg med',
|
||||
'Lyset dempes og her er sangen min',
|
||||
'Hold mikrofonen og innta scenen',
|
||||
'Bla om, bla om']},
|
||||
'nl': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Elke avond zing ik mee',
|
||||
'Het licht gaat uit en hier is mijn lied',
|
||||
'Pak de microfoon en betreed het podium',
|
||||
'Sla de bladzijde om, sla de bladzijde om']},
|
||||
'pl': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Każdej nocy śpiewam razem z nimi',
|
||||
'Gasną światła i oto moja piosenka',
|
||||
'Chwytam mikrofon i wchodzę na scenę',
|
||||
'Przewróć stronę, przewróć stronę']},
|
||||
'pt': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Toda noite eu canto junto',
|
||||
'Luzes se apagam e aqui está minha canção',
|
||||
'Seguro o microfone e subo ao palco',
|
||||
'Vire a página, vire a página']},
|
||||
'ro': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['În fiecare noapte cânt și eu',
|
||||
'Luminile se sting și iată cântecul meu',
|
||||
'Iau microfonul și urc pe scenă',
|
||||
'Întorc pagina, întorc pagina']},
|
||||
'ru': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Каждую ночь я подпеваю',
|
||||
'Гаснет свет, и вот моя песня',
|
||||
'Беру микрофон и выхожу на сцену',
|
||||
'Переверни страницу, переверни страницу']},
|
||||
'sk': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Každú noc si spievam',
|
||||
'Svetlá zhasnú a tu je moja pieseň',
|
||||
'Chyť mikrofón a vstúp na pódium',
|
||||
'Obráť list, obráť list']},
|
||||
'sv': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Varje kväll sjunger jag med',
|
||||
'Ljuset släcks och här är min sång',
|
||||
'Håll micken och inta scenen',
|
||||
'Vänd blad, vänd blad']},
|
||||
'th': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['ทุกคืนฉันร้องตามไป',
|
||||
'แสงไฟดับลงและนี่คือเพลงของฉัน',
|
||||
'จับไมค์แล้วก้าวขึ้นเวที',
|
||||
'เปิดหน้าใหม่ เปิดหน้าใหม่']},
|
||||
'tl': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Gabi-gabi akong sumasabay',
|
||||
'Nandidilim ang ilaw at heto ang awit ko',
|
||||
'Hawakan ang mic at umakyat sa entablado',
|
||||
'Ilipat ang pahina, ilipat ang pahina']},
|
||||
'tr': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Her gece şarkıya eşlik ederim',
|
||||
'Işıklar söner ve işte şarkım',
|
||||
'Mikrofonu tut ve sahneye çık',
|
||||
'Sayfayı çevir, sayfayı çevir']},
|
||||
'uk': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Щоночі я підспівую',
|
||||
'Світло гасне, і ось моя пісня',
|
||||
'Тримаю мікрофон і виходжу на сцену',
|
||||
'Перегорни сторінку, перегорни сторінку']},
|
||||
'vi': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['Mỗi đêm tôi đều hát theo',
|
||||
'Đèn tắt dần và đây là bài hát của tôi',
|
||||
'Cầm lấy mic và bước lên sân khấu',
|
||||
'Lật sang trang, lật sang trang']},
|
||||
'zh': {'lyrics': ['Every night I sing along',
|
||||
"Lights go down and here's my song",
|
||||
'Hold the mic and take the stage',
|
||||
'Turn the page, turn the page'],
|
||||
'translations': ['每晚我都跟着唱', '灯光暗下,这是我的歌', '握紧麦克风,登上舞台', '翻过这一页,翻过这一页']}}
|
||||
@@ -194,6 +194,8 @@ class VisibilityChangeService:
|
||||
job_id=job_id, theme_id="nomad"
|
||||
)
|
||||
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
|
||||
# Step 4: Reset styles and update job fields
|
||||
# Step 5: Set status to LYRICS_COMPLETE with regen_restore_status
|
||||
# Step 6: Clear progress keys and set guard flag
|
||||
@@ -215,6 +217,9 @@ class VisibilityChangeService:
|
||||
"outputs_deleted_at": None,
|
||||
"outputs_deleted_by": None,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
# New run (new theme, new brand code): drop any failed admin
|
||||
# re-render's marker so it can't suppress notifications here.
|
||||
**clear_admin_rerender_update(job),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "lyrics_complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
|
||||
@@ -20,7 +20,7 @@ predate placeholders keep the historical behaviour of appending
|
||||
``\n\nBrand Code: <code>`` when a brand code is available.
|
||||
"""
|
||||
import re
|
||||
from typing import List, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
# Total length budget for the YouTube ``tags`` field (API rejects > 500 chars,
|
||||
# counted as the sum of tag lengths plus separators). Stay comfortably under.
|
||||
@@ -44,11 +44,50 @@ def _collapse_blank_lines(text: str) -> str:
|
||||
return re.sub(r"\n{3,}", "\n\n", text)
|
||||
|
||||
|
||||
# YouTube rejects titles over 100 chars; the upload service truncates at 95.
|
||||
YOUTUBE_TITLE_MAX = 95
|
||||
|
||||
|
||||
def translated_language_name(state_data: Optional[Dict[str, Any]]) -> Optional[str]:
|
||||
"""English name of the language a job's video shows translated lyrics in, else None.
|
||||
|
||||
Only a ``translated`` outcome counts: a requested translation that failed or was
|
||||
skipped (song already in that language) renders without a translation row, so the
|
||||
published video must not claim one.
|
||||
"""
|
||||
info = (state_data or {}).get("lyrics_translation") or {}
|
||||
if info.get("status") != "translated":
|
||||
return None
|
||||
from backend.services.lyrics_translation import TRANSLATION_LANGUAGES
|
||||
|
||||
return TRANSLATION_LANGUAGES.get(info.get("language") or "")
|
||||
|
||||
|
||||
def build_youtube_title(
|
||||
artist: Optional[str], title: Optional[str], translation_language_name: Optional[str] = None
|
||||
) -> str:
|
||||
"""``Artist - Title (Karaoke)``, labelled when the video carries translated lyrics.
|
||||
|
||||
The translation label sits before "(Karaoke)" (like the tempo label, which is part
|
||||
of the title) and is never truncated away: an over-long artist/title is shortened
|
||||
instead. Untranslated titles are returned as-is for the caller's usual truncation.
|
||||
"""
|
||||
base = f"{artist} - {title}"
|
||||
if not translation_language_name:
|
||||
return f"{base} (Karaoke)"
|
||||
suffix = f" (With Translation into {translation_language_name}) (Karaoke)"
|
||||
budget = YOUTUBE_TITLE_MAX - len(suffix)
|
||||
if len(base) > budget:
|
||||
base = base[: budget - 4].rsplit(" ", 1)[0].rstrip(" -") + " ..."
|
||||
return f"{base}{suffix}"
|
||||
|
||||
|
||||
def render_youtube_description(
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
template: Optional[str] = None,
|
||||
translation_language_name: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Render a YouTube description from the template + per-video values.
|
||||
|
||||
@@ -58,6 +97,8 @@ def render_youtube_description(
|
||||
brand_code: NOMAD-#### style code, or falsy to omit the brand-code line.
|
||||
template: Override template. Defaults to
|
||||
``Settings.default_youtube_description``.
|
||||
translation_language_name: When the video shows translated lyrics (see
|
||||
``translated_language_name``), an up-front notice says so.
|
||||
|
||||
Returns:
|
||||
The fully rendered description string, stripped of trailing whitespace.
|
||||
@@ -104,6 +145,11 @@ def render_youtube_description(
|
||||
notice = tempo_description_notice(title)
|
||||
if notice:
|
||||
result = f"{notice}\n\n{result}"
|
||||
if translation_language_name:
|
||||
result = (
|
||||
f"This karaoke video includes translated lyrics ({translation_language_name}) "
|
||||
f"beneath each line.\n\n{result}"
|
||||
)
|
||||
|
||||
return _collapse_blank_lines(result).strip()
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
YOUTUBE_UPLOAD_QUEUE_COLLECTION = "youtube_upload_queue"
|
||||
@@ -43,6 +42,7 @@ class YouTubeUploadQueueService:
|
||||
title: str,
|
||||
brand_code: Optional[str],
|
||||
reason: str = "quota_exceeded",
|
||||
notify_user: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Queue a YouTube upload for later processing.
|
||||
@@ -54,6 +54,8 @@ class YouTubeUploadQueueService:
|
||||
title: Song title
|
||||
brand_code: Release ID (e.g., "NOMAD-1287")
|
||||
reason: Why the upload was deferred
|
||||
notify_user: Email the user when the deferred upload completes
|
||||
(False for an admin re-render without customer notification)
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
now = datetime.now(PACIFIC_TZ)
|
||||
@@ -72,6 +74,7 @@ class YouTubeUploadQueueService:
|
||||
"last_error": None,
|
||||
"youtube_url": None,
|
||||
"notification_sent": False,
|
||||
"notify_user": notify_user,
|
||||
"updated_at": now,
|
||||
})
|
||||
|
||||
@@ -127,10 +130,15 @@ class YouTubeUploadQueueService:
|
||||
True if successfully claimed, False if already processing/completed
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
job_ref = self.db.collection(settings.firestore_collection).document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def claim_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
# Read the job in the same transaction: an admin re-render claims the
|
||||
# job only if no upload is processing (and reads this queue doc), so
|
||||
# with both transactions reading both docs they can never overlap.
|
||||
job_doc = job_ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return False
|
||||
|
||||
@@ -138,6 +146,12 @@ class YouTubeUploadQueueService:
|
||||
if data.get("status") != "queued":
|
||||
return False
|
||||
|
||||
if job_doc.exists:
|
||||
from backend.services.admin_rerender_service import admin_rerender_blocks_upload
|
||||
if admin_rerender_blocks_upload(job_doc.to_dict() or {}):
|
||||
logger.info(f"YouTube upload for job {job_id} deferred: admin re-render in progress")
|
||||
return False # leave queued; picked up once the re-render completes
|
||||
|
||||
attempts = data.get("attempts", 0)
|
||||
max_attempts = data.get("max_attempts", 5)
|
||||
if attempts >= max_attempts:
|
||||
@@ -208,6 +222,22 @@ class YouTubeUploadQueueService:
|
||||
f"for job {job_id} (attempt {attempts}/{max_attempts}): {error}"
|
||||
)
|
||||
|
||||
def mark_post_upload_error(self, job_id: str, youtube_url: str, error: str) -> None:
|
||||
"""The video was uploaded but a follow-up step failed.
|
||||
|
||||
Terminal "completed" (never re-queued — that would upload it twice) with
|
||||
the URL and a ``needs_attention`` flag + error for an operator.
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
doc_ref.update({
|
||||
"status": "completed",
|
||||
"youtube_url": youtube_url,
|
||||
"needs_attention": True,
|
||||
"post_upload_error": error,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
logger.error(f"YouTube upload for job {job_id} succeeded ({youtube_url}) but a follow-up step failed: {error}")
|
||||
|
||||
def retry_upload(self, job_id: str) -> bool:
|
||||
"""
|
||||
Admin manual retry: reset a failed upload back to queued.
|
||||
|
||||
@@ -18,6 +18,8 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
|
||||
os.environ.setdefault('GCS_BUCKET_NAME', 'test-bucket')
|
||||
os.environ.setdefault('FIRESTORE_COLLECTION', 'jobs')
|
||||
os.environ.setdefault('ENVIRONMENT', 'test')
|
||||
# Gemini Developer API key: never let a test fall through to Secret Manager.
|
||||
os.environ.setdefault('GEMINI_API_KEY', 'test-gemini-key')
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, AsyncMock, patch
|
||||
|
||||
@@ -472,3 +472,237 @@ async def test_gated_lyrics_skip_timing_compute() -> None:
|
||||
compute.assert_not_called()
|
||||
payload = job_manager.update_processing_metadata.call_args[0][2]
|
||||
assert payload["timing"]["status"] == "not_needed"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- vocal gaps (shadow)
|
||||
|
||||
def _vocal_gaps_result(suspect_count=1, error=None, evidenced=False):
|
||||
from backend.services.auto_approval.vocal_gaps import VocalGap, VocalGapsResult
|
||||
|
||||
gaps = [VocalGap(start=20.66, end=32.4, duration=11.74, active_fraction=0.96,
|
||||
longest_run_s=11.76, suspect=True, evidenced=evidenced,
|
||||
reference_lines={"genius": ["line one", "line two"]})] if suspect_count else []
|
||||
return VocalGapsResult(gaps=gaps, suspect_count=suspect_count,
|
||||
evidenced_count=1 if (evidenced and suspect_count) else 0,
|
||||
max_suspect_run_s=11.76 if suspect_count else 0.0, error=error)
|
||||
|
||||
|
||||
def _stored_vocal_gaps(job_manager):
|
||||
calls = [c for c in job_manager.update_state_data.call_args_list if c[0][1] == "vocal_gaps"]
|
||||
return calls[0][0][2] if calls else None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_analyzed_and_stored_without_changing_outcome() -> None:
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result()) as analyze, \
|
||||
patch("backend.services.auto_approval.executor._compute_timing_signals",
|
||||
return_value=_timing_signals(fired=False)):
|
||||
result, job_manager, _, _ = await _run(_job_with_lead_stem())
|
||||
analyze.assert_called_once()
|
||||
# Shadow only: a suspect gap must not demote a confident job (yet)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
stored = _stored_vocal_gaps(job_manager)
|
||||
assert stored["suspect_count"] == 1
|
||||
assert stored["gaps"][0]["reference_lines"] == {"genius": ["line one", "line two"]}
|
||||
assert stored["source"] == "auto_approval" and "analyzed_at" in stored
|
||||
payload = job_manager.update_processing_metadata.call_args[0][2]
|
||||
assert payload["vocal_gaps"] == {"status": "checked", "suspect_count": 1, "evidenced_count": 0,
|
||||
"max_suspect_run_s": 11.76}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_evidenced_missing_lyrics_block_auto_approval() -> None:
|
||||
"""Singing with no words where the reference lyrics have lines = dropped lyrics:
|
||||
a confident job must go to review with an explicit reason."""
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result(evidenced=True)), \
|
||||
patch("backend.services.auto_approval.executor._compute_timing_signals") as timing:
|
||||
result, job_manager, _, worker = await _run(_job_with_lead_stem())
|
||||
assert result["outcome"] == "review"
|
||||
worker.trigger_render_video_worker.assert_not_called()
|
||||
timing.assert_not_called() # lyrics no longer AUTO, so the timing check is skipped
|
||||
payload = job_manager.update_processing_metadata.call_args[0][2]
|
||||
assert payload["lyrics"]["tier"] == "missing-lyrics-gate"
|
||||
assert any("possible missing lyrics" in r and "0:20-0:32" in r and "2 line(s)" in r
|
||||
for r in payload["lyrics"]["reasons"])
|
||||
assert payload["vocal_gaps"]["evidenced_count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cached_evidenced_gaps_still_gate() -> None:
|
||||
job = _job_with_lead_stem()
|
||||
gaps = _vocal_gaps_result(evidenced=True).to_dict()
|
||||
job.state_data["vocal_gaps"] = {**gaps, "input_key": _input_key_for(job)}
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps") as analyze:
|
||||
result, job_manager, _, _ = await _run(job)
|
||||
analyze.assert_not_called()
|
||||
assert result["outcome"] == "review"
|
||||
assert job_manager.update_processing_metadata.call_args[0][2]["lyrics"]["tier"] == "missing-lyrics-gate"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_analyzed_for_review_bound_jobs_too() -> None:
|
||||
"""Unlike the timing gate, gaps are analyzed whatever the lyrics verdict."""
|
||||
corrections = _confident_corrections()
|
||||
corrections["gap_sequences"] = [{"id": "g0", "transcribed_word_ids": ["w1", "w2", "w3"]}]
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result()) as analyze:
|
||||
result, job_manager, _, _ = await _run(_job_with_lead_stem(), corrections=corrections)
|
||||
assert result["outcome"] == "review"
|
||||
analyze.assert_called_once()
|
||||
assert _stored_vocal_gaps(job_manager)["suspect_count"] == 1
|
||||
|
||||
|
||||
def _input_key_for(job, corrections=None):
|
||||
from backend.services.auto_approval.executor import vocal_gaps_input_key
|
||||
|
||||
corrections = corrections or _confident_corrections()
|
||||
return vocal_gaps_input_key(corrections["corrected_segments"], job.file_urls["stems"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_not_recomputed_when_cached_for_same_inputs() -> None:
|
||||
job = _job_with_lead_stem()
|
||||
job.state_data["vocal_gaps"] = {"suspect_count": 0, "max_suspect_run_s": 0.0,
|
||||
"input_key": _input_key_for(job)}
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps") as analyze, \
|
||||
patch("backend.services.auto_approval.executor._compute_timing_signals",
|
||||
return_value=_timing_signals(fired=False)):
|
||||
_, job_manager, _, _ = await _run(job)
|
||||
analyze.assert_not_called()
|
||||
assert _stored_vocal_gaps(job_manager) is None
|
||||
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"]["status"] == "cached"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_vocal_gaps_recomputed_when_lyrics_changed() -> None:
|
||||
"""A stored result from different lyrics/stem (reset, edit, re-transcription) is
|
||||
not reused — it would corrupt the calibration data."""
|
||||
job = _job_with_lead_stem()
|
||||
job.state_data["vocal_gaps"] = {"suspect_count": 5, "max_suspect_run_s": 9.0, "input_key": "stale"}
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result(suspect_count=0)) as analyze, \
|
||||
patch("backend.services.auto_approval.executor._compute_timing_signals",
|
||||
return_value=_timing_signals(fired=False)):
|
||||
_, job_manager, _, _ = await _run(job)
|
||||
analyze.assert_called_once()
|
||||
stored = _stored_vocal_gaps(job_manager)
|
||||
assert stored["suspect_count"] == 0 and stored["input_key"] == _input_key_for(job)
|
||||
|
||||
|
||||
def test_input_key_changes_with_word_timing_and_stem() -> None:
|
||||
from backend.services.auto_approval.executor import vocal_gaps_input_key
|
||||
|
||||
segs = _confident_corrections()["corrected_segments"]
|
||||
stems = {"lead_vocals": "a.flac"}
|
||||
key = vocal_gaps_input_key(segs, stems)
|
||||
moved = [{**segs[0], "words": [{**segs[0]["words"][0], "start_time": 9.0}] + segs[0]["words"][1:]}]
|
||||
assert vocal_gaps_input_key(moved, stems) != key
|
||||
assert vocal_gaps_input_key(segs, {"lead_vocals": "b.flac"}) != key
|
||||
assert vocal_gaps_input_key(segs, stems) == key
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_wait_for_audio() -> None:
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps") as analyze:
|
||||
_, job_manager, _, _ = await _run(_job_with_lead_stem(audio_complete=False))
|
||||
analyze.assert_not_called()
|
||||
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"] == {"status": "pending_audio"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_without_lead_stem() -> None:
|
||||
with patch("backend.services.auto_approval.executor._compute_timing_signals", return_value=None):
|
||||
_, job_manager, _, _ = await _run(_job(backing=_clean_backing()))
|
||||
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"] == {"status": "no_lead_stem"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_error_is_nonfatal_and_not_stored() -> None:
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result(error="decode failed")), \
|
||||
patch("backend.services.auto_approval.executor._compute_timing_signals",
|
||||
return_value=_timing_signals(fired=False)):
|
||||
result, job_manager, _, _ = await _run(_job_with_lead_stem())
|
||||
assert result["outcome"] == "auto_completed"
|
||||
assert _stored_vocal_gaps(job_manager) is None
|
||||
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"]["status"] == "error"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vocal_gaps_exception_is_nonfatal() -> None:
|
||||
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps", side_effect=RuntimeError("boom")), \
|
||||
patch("backend.services.auto_approval.executor._compute_timing_signals",
|
||||
return_value=_timing_signals(fired=False)):
|
||||
result, job_manager, _, _ = await _run(_job_with_lead_stem())
|
||||
assert result["outcome"] == "auto_completed"
|
||||
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"]["status"] == "error"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- backfill
|
||||
|
||||
def _backfill(job, files: Dict[str, Any], analyze_result):
|
||||
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
storage = MagicMock()
|
||||
storage.file_exists.side_effect = lambda p: p in files
|
||||
storage.download_json.side_effect = lambda p: files[p]
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=analyze_result) as analyze:
|
||||
return analyze_job_vocal_gaps, job_manager, analyze
|
||||
|
||||
|
||||
def test_backfill_uses_reviewed_lyrics_and_stores() -> None:
|
||||
original = _confident_corrections()
|
||||
updated = {"corrected_segments": [{"id": "s9", "words": []}]}
|
||||
files = {"jobs/j1/lyrics/corrections.json": original,
|
||||
"jobs/j1/lyrics/corrections_updated.json": updated}
|
||||
fn, job_manager, analyze = _backfill(_job_with_lead_stem(), files, _vocal_gaps_result())
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService") as storage_cls, \
|
||||
patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result()) as analyze:
|
||||
storage = storage_cls.return_value
|
||||
storage.file_exists.side_effect = lambda p: p in files
|
||||
storage.download_json.side_effect = lambda p: files[p]
|
||||
out = fn("j1", store=True)
|
||||
assert out["status"] == "checked" and out["stored"] is True
|
||||
corrections_arg, segments_arg = analyze.call_args[0][1], analyze.call_args[0][2]
|
||||
assert corrections_arg is original # reference + anchors from the original
|
||||
assert segments_arg == updated["corrected_segments"] # words as reviewed/rendered
|
||||
assert out["vocal_gaps"]["lyrics_source"] == "corrections_updated"
|
||||
assert _stored_vocal_gaps(job_manager)["source"] == "backfill"
|
||||
|
||||
|
||||
def test_backfill_dry_run_does_not_store() -> None:
|
||||
files = {"jobs/j1/lyrics/corrections.json": _confident_corrections()}
|
||||
fn, job_manager, _ = _backfill(_job_with_lead_stem(), files, _vocal_gaps_result())
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService") as storage_cls, \
|
||||
patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
|
||||
return_value=_vocal_gaps_result()):
|
||||
storage_cls.return_value.file_exists.side_effect = lambda p: p in files
|
||||
storage_cls.return_value.download_json.side_effect = lambda p: files[p]
|
||||
out = fn("j1", store=False)
|
||||
assert out["status"] == "checked" and out["vocal_gaps"]["lyrics_source"] == "corrections"
|
||||
assert _stored_vocal_gaps(job_manager) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files,job,expected", [
|
||||
({}, "job", "no_corrections"),
|
||||
({"jobs/j1/lyrics/corrections.json": {}}, None, "no_job"),
|
||||
])
|
||||
def test_backfill_missing_inputs(files, job, expected) -> None:
|
||||
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = _job_with_lead_stem() if job else None
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService") as storage_cls:
|
||||
storage_cls.return_value.file_exists.side_effect = lambda p: p in files
|
||||
assert analyze_job_vocal_gaps("j1")["status"] == expected
|
||||
@@ -445,3 +445,38 @@ def test_timing_gate_flows_through_score_job() -> None:
|
||||
verdict = score_job(_corrections_json(), None, None, timing_signals=sig)
|
||||
assert verdict.lyrics.tier == "timing-gate"
|
||||
assert verdict.overall_auto is False
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- missing-lyrics gate
|
||||
|
||||
def _gap(evidenced, start=20.66, end=32.4, run=10.26, synced=None, refs=None):
|
||||
return {"start": start, "end": end, "longest_run_s": run, "suspect": True, "evidenced": evidenced,
|
||||
"synced_reference_lines": synced or {}, "reference_lines": refs or {}}
|
||||
|
||||
|
||||
class TestMissingLyricsGate:
|
||||
def test_reasons_only_for_evidenced_gaps(self):
|
||||
from backend.services.auto_approval.scorer import missing_lyrics_reasons
|
||||
|
||||
gaps = {"gaps": [_gap(True, synced={"lrclib": ["a", "b", "c"]}, refs={"genius": ["a", "b"]}),
|
||||
_gap(False, start=60, end=80)]}
|
||||
reasons = missing_lyrics_reasons(gaps)
|
||||
assert len(reasons) == 1
|
||||
assert "~10s of singing at 0:20-0:32" in reasons[0] and "3 line(s)" in reasons[0]
|
||||
|
||||
def test_no_gaps_no_reasons(self):
|
||||
from backend.services.auto_approval.scorer import missing_lyrics_reasons
|
||||
|
||||
assert missing_lyrics_reasons(None) == []
|
||||
assert missing_lyrics_reasons({"gaps": []}) == []
|
||||
|
||||
def test_evidenced_gap_overrides_confident_lyrics(self):
|
||||
from backend.services.auto_approval.scorer import score_lyrics
|
||||
from backend.services.auto_approval.models import LyricsVerdict
|
||||
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
assert score_lyrics(data).verdict == LyricsVerdict.AUTO
|
||||
gated = score_lyrics(data, vocal_gaps={"gaps": [_gap(True, synced={"lrclib": ["x"]})]})
|
||||
assert gated.verdict == LyricsVerdict.REVIEW and gated.tier == "missing-lyrics-gate"
|
||||
assert score_lyrics(data, vocal_gaps={"gaps": [_gap(False)]}).verdict == LyricsVerdict.AUTO
|
||||
@@ -0,0 +1,320 @@
|
||||
"""Tests for vocal-gap detection (sung stretches with no transcribed words).
|
||||
|
||||
Motivating case: job 5710831e — the transcription dropped three sung lines (11.7s,
|
||||
lead vocal ~96% active) and the video showed "INSTRUMENTAL" over the singing, while
|
||||
genuine instrumentals measured 1-2% active. These tests build that situation on
|
||||
synthesized audio plus synthetic correction data with the same structure (including
|
||||
the off-by-one anchor reference ids seen at "[Section]" header boundaries).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_approval.vocal_gaps import (
|
||||
MIN_GAP_S,
|
||||
VocalGapsResult,
|
||||
_bridge,
|
||||
_longest_run,
|
||||
compute_vocal_gaps,
|
||||
reference_lines_between,
|
||||
transcription_gaps,
|
||||
)
|
||||
|
||||
|
||||
def _synth_stem(tmp_path, sung_regions, duration_s=40.0):
|
||||
"""WAV 'vocal stem': silence with a 440Hz tone over ``sung_regions``."""
|
||||
from pydub import AudioSegment
|
||||
from pydub.generators import Sine
|
||||
|
||||
audio = AudioSegment.silent(duration=int(duration_s * 1000), frame_rate=22050)
|
||||
for start_s, end_s in sung_regions:
|
||||
tone = Sine(440, sample_rate=22050).to_audio_segment(
|
||||
duration=int((end_s - start_s) * 1000)
|
||||
).apply_gain(-6)
|
||||
audio = audio.overlay(tone, position=int(start_s * 1000))
|
||||
path = os.path.join(str(tmp_path), "lead_vocals.wav")
|
||||
audio.export(path, format="wav")
|
||||
return path
|
||||
|
||||
|
||||
def _word(wid, text, start, end):
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end}
|
||||
|
||||
|
||||
def _segments(*lines):
|
||||
return [{"id": f"s{i}", "text": " ".join(w["text"] for w in ws), "words": ws,
|
||||
"start_time": ws[0]["start_time"], "end_time": ws[-1]["end_time"]}
|
||||
for i, ws in enumerate(lines)]
|
||||
|
||||
|
||||
# --------------------------------------------------------------- gap finding
|
||||
|
||||
class TestTranscriptionGaps:
|
||||
def test_finds_leading_inner_and_trailing_gaps(self):
|
||||
segs = _segments([_word("a", "a", 5.0, 6.0), _word("b", "b", 6.2, 7.0)],
|
||||
[_word("c", "c", 15.0, 16.0)])
|
||||
gaps = transcription_gaps(segs, audio_duration=30.0)
|
||||
assert [(s, e) for s, e, _, _ in gaps] == [(0.0, 5.0), (7.0, 15.0), (16.0, 30.0)]
|
||||
assert gaps[1][2]["id"] == "b" and gaps[1][3]["id"] == "c"
|
||||
assert gaps[0][2] is None and gaps[2][3] is None
|
||||
|
||||
def test_short_gaps_ignored(self):
|
||||
segs = _segments([_word("a", "a", 0.5, 1.0), _word("b", "b", 1.0 + MIN_GAP_S - 0.1, 5.0)])
|
||||
assert transcription_gaps(segs, audio_duration=5.5) == []
|
||||
|
||||
def test_overlapping_words_do_not_create_negative_gaps(self):
|
||||
segs = _segments([_word("a", "a", 0.0, 10.0), _word("b", "b", 2.0, 3.0), _word("c", "c", 11.0, 12.0)])
|
||||
assert [(s, e) for s, e, _, _ in transcription_gaps(segs, 12.0)] == []
|
||||
|
||||
def test_words_without_timing_are_skipped(self):
|
||||
segs = _segments([_word("a", "a", 0.0, 1.0), {"id": "x", "text": "x", "start_time": None, "end_time": None}])
|
||||
assert [(s, e) for s, e, _, _ in transcription_gaps(segs, 10.0)] == [(1.0, 10.0)]
|
||||
|
||||
|
||||
class TestRunHelpers:
|
||||
def test_bridge_fills_short_breaths_only(self):
|
||||
a = np.array([1, 0, 0, 1, 0, 0, 0, 0, 1], dtype=bool)
|
||||
assert _bridge(a, 2).tolist() == [1, 1, 1, 1, 0, 0, 0, 0, 1]
|
||||
|
||||
def test_longest_run(self):
|
||||
assert _longest_run(np.array([1, 1, 0, 1, 1, 1, 0], dtype=bool)) == 3
|
||||
assert _longest_run(np.zeros(4, dtype=bool)) == 0
|
||||
|
||||
|
||||
# --------------------------------------------------------------- end to end (audio)
|
||||
|
||||
class TestComputeVocalGaps:
|
||||
def test_dropped_sung_lines_are_suspect_and_instrumental_is_not(self, tmp_path):
|
||||
# Words 2-8s; singing continues 8-20s with no words (dropped lines, with
|
||||
# short breaths); a silent instrumental 20-30s; words again 30-34s.
|
||||
sung = [(2.0, 8.0), (8.3, 12.0), (12.4, 16.0), (16.3, 20.0), (30.0, 34.0)]
|
||||
stem = _synth_stem(tmp_path, sung)
|
||||
segs = _segments([_word("a", "a", 2.0, 5.0), _word("b", "b", 5.0, 8.0)],
|
||||
[_word("c", "c", 30.0, 32.0), _word("d", "d", 32.0, 34.0)])
|
||||
result = compute_vocal_gaps(segs, stem)
|
||||
assert result.error is None
|
||||
by_start = {g.start: g for g in result.gaps}
|
||||
dropped = by_start[8.0]
|
||||
assert dropped.suspect
|
||||
# Diluted by the instrumental sharing the gap — the run, not the fraction, decides
|
||||
assert 0.4 < dropped.active_fraction < 0.6
|
||||
# 12s of bridged singing, minus the held-note allowance at the gap start
|
||||
assert dropped.longest_run_s >= 10.0, "breaths inside singing must be bridged"
|
||||
assert result.suspect_count == 1
|
||||
assert result.max_suspect_run_s == dropped.longest_run_s
|
||||
|
||||
def test_genuine_instrumental_is_not_suspect(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [(2.0, 8.0), (25.0, 30.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
|
||||
result = compute_vocal_gaps(segs, stem)
|
||||
assert [(g.start, g.suspect) for g in result.gaps] == [(8.0, False), (30.0, False)] # middle, outro
|
||||
assert result.suspect_count == 0
|
||||
|
||||
def test_short_dropped_line_in_long_gap_is_still_suspect(self, tmp_path):
|
||||
"""A 4s dropped line followed by a long instrumental in the same gap."""
|
||||
stem = _synth_stem(tmp_path, [(2.0, 8.0), (8.5, 12.5), (28.0, 30.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 28.0, 30.0)])
|
||||
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
|
||||
assert gap.active_fraction < 0.25
|
||||
assert gap.suspect
|
||||
|
||||
def test_held_note_past_last_word_is_not_suspect(self, tmp_path):
|
||||
"""The word's transcribed end is 3.5s before the singer stops (held note)."""
|
||||
stem = _synth_stem(tmp_path, [(2.0, 11.5), (25.0, 30.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
|
||||
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
|
||||
assert not gap.suspect
|
||||
assert gap.longest_run_s == pytest.approx(2.0, abs=0.1)
|
||||
|
||||
def test_singing_after_a_pause_gets_no_allowance(self, tmp_path):
|
||||
"""A dropped line that starts after a real pause is counted in full."""
|
||||
stem = _synth_stem(tmp_path, [(2.0, 8.0), (10.0, 14.0), (25.0, 30.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
|
||||
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
|
||||
assert gap.suspect
|
||||
assert gap.longest_run_s == pytest.approx(4.0, abs=0.1)
|
||||
|
||||
def test_silent_stem_is_an_error_not_a_clean_pass(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [], duration_s=20.0)
|
||||
result = compute_vocal_gaps(_segments([_word("a", "a", 2.0, 4.0)]), stem)
|
||||
assert result.error and "silent" in result.error
|
||||
assert result.gaps == []
|
||||
|
||||
def test_malformed_reference_does_not_lose_audio_result(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [(2.0, 20.0)], duration_s=25.0)
|
||||
bad = {"reference_lyrics": {"genius": {"segments": [{"words": [{"text": "no id"}]}]}},
|
||||
"anchor_sequences": [{"transcribed_word_ids": ["a"], "reference_word_ids": {"genius": ["zz"]}}]}
|
||||
result = compute_vocal_gaps(_segments([_word("a", "a", 2.0, 4.0)]), stem, bad)
|
||||
assert result.error is None
|
||||
assert result.suspect_count == 1
|
||||
|
||||
def test_brief_ad_lib_in_gap_is_not_suspect(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [(2.0, 8.0), (14.0, 15.5), (25.0, 30.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
|
||||
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
|
||||
assert not gap.suspect
|
||||
assert 1.0 < gap.longest_run_s < 2.0
|
||||
|
||||
def test_missing_stem_returns_error_not_raise(self, tmp_path):
|
||||
result = compute_vocal_gaps(_segments([_word("a", "a", 0.0, 1.0)]), str(tmp_path / "nope.flac"))
|
||||
assert isinstance(result, VocalGapsResult)
|
||||
assert result.error
|
||||
|
||||
def test_result_is_json_serializable(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [(2.0, 20.0)], duration_s=25.0)
|
||||
result = compute_vocal_gaps(_segments([_word("a", "a", 2.0, 4.0)]), stem)
|
||||
json.dumps(result.to_dict())
|
||||
|
||||
|
||||
# --------------------------------------------------------------- reference lines
|
||||
|
||||
def _ref(lines):
|
||||
"""Reference lyrics source: list of line strings -> segments with word ids."""
|
||||
segs = []
|
||||
for li, line in enumerate(lines):
|
||||
segs.append({"text": line, "words": [{"id": f"r{li}_{wi}", "text": t}
|
||||
for wi, t in enumerate(line.split())]})
|
||||
return {"segments": segs}
|
||||
|
||||
|
||||
REFERENCE = [
|
||||
"[Verse]",
|
||||
"come run far away",
|
||||
"[Pre-Chorus]",
|
||||
"like two crazy people",
|
||||
"we kept moments close", # dropped
|
||||
"you were pretty as a flower", # dropped
|
||||
"[Chorus]",
|
||||
"like two crazy people",
|
||||
]
|
||||
|
||||
|
||||
def _correction_data(before_ref_ids, after_ref_ids):
|
||||
return {
|
||||
"reference_lyrics": {"genius": _ref(REFERENCE)},
|
||||
"anchor_sequences": [
|
||||
{"transcribed_word_ids": ["t_before"], "reference_word_ids": {"genius": before_ref_ids}},
|
||||
{"transcribed_word_ids": ["t_after"], "reference_word_ids": {"genius": after_ref_ids}},
|
||||
],
|
||||
"gap_sequences": [],
|
||||
}
|
||||
|
||||
|
||||
class TestReferenceLinesBetween:
|
||||
before, after = {"id": "t_before"}, {"id": "t_after"}
|
||||
|
||||
def test_lines_between_neighbouring_anchors(self):
|
||||
data = _correction_data(["r3_3"], ["r7_0"]) # "people" ... "like"
|
||||
assert reference_lines_between(data, self.before, self.after) == {
|
||||
"genius": ["we kept moments close", "you were pretty as a flower"]
|
||||
}
|
||||
|
||||
def test_off_by_one_anchor_at_line_start_is_snapped(self):
|
||||
# Real job: the word before the gap mapped to the FIRST word of the next line
|
||||
# ("people" -> "we") because "[Section]" headers shift anchor ids by one.
|
||||
data = _correction_data(["r4_0"], ["r7_0"])
|
||||
assert reference_lines_between(data, self.before, self.after)["genius"][0] == "we kept moments close"
|
||||
|
||||
def test_off_by_one_anchor_at_line_end_is_snapped(self):
|
||||
data = _correction_data(["r3_3"], ["r6_0"]) # "like" landed on the "[Chorus]" header's last word
|
||||
assert reference_lines_between(data, self.before, self.after) == {
|
||||
"genius": ["we kept moments close", "you were pretty as a flower"]
|
||||
}
|
||||
|
||||
def test_single_word_line_before_gap_is_not_reported_missing(self):
|
||||
lines = ["intro words here", "Yeah", "dropped line one", "after the gap"]
|
||||
data = {"reference_lyrics": {"genius": _ref(lines)},
|
||||
"anchor_sequences": [
|
||||
{"transcribed_word_ids": ["t_before"], "reference_word_ids": {"genius": ["r1_0"]}},
|
||||
{"transcribed_word_ids": ["t_after"], "reference_word_ids": {"genius": ["r3_0"]}}],
|
||||
"gap_sequences": []}
|
||||
assert reference_lines_between(data, self.before, self.after) == {"genius": ["dropped line one"]}
|
||||
|
||||
def test_section_headers_are_dropped(self):
|
||||
data = _correction_data(["r1_3"], ["r7_0"])
|
||||
lines = reference_lines_between(data, self.before, self.after)["genius"]
|
||||
assert not any(l.startswith("[") for l in lines)
|
||||
|
||||
def test_reversed_order_from_repeated_chorus_returns_nothing(self):
|
||||
data = _correction_data(["r7_3"], ["r3_0"])
|
||||
assert reference_lines_between(data, self.before, self.after) == {}
|
||||
|
||||
def test_gap_at_song_edge_has_no_reference_lines(self):
|
||||
data = _correction_data(["r3_3"], ["r7_0"])
|
||||
assert reference_lines_between(data, None, self.after) == {}
|
||||
assert reference_lines_between(data, self.before, None) == {}
|
||||
|
||||
def test_unmapped_words_return_nothing(self):
|
||||
data = _correction_data(["r3_3"], ["r7_0"])
|
||||
assert reference_lines_between(data, {"id": "other"}, self.after) == {}
|
||||
|
||||
def test_compute_includes_reference_lines(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [(2.0, 20.0), (30.0, 34.0)])
|
||||
segs = _segments([_word("t_before", "people", 2.0, 8.0)], [_word("t_after", "like", 30.0, 34.0)])
|
||||
gap = next(g for g in compute_vocal_gaps(segs, stem, _correction_data(["r3_3"], ["r7_0"])).gaps
|
||||
if g.start == 8.0)
|
||||
assert gap.suspect
|
||||
assert gap.reference_lines == {"genius": ["we kept moments close", "you were pretty as a flower"]}
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------- synced reference evidence
|
||||
|
||||
class TestSyncedEvidence:
|
||||
def _synced_ref(self, lines):
|
||||
"""[(start, text)] -> reference source with word timings (like LRCLIB)."""
|
||||
segs = []
|
||||
for li, (start, text) in enumerate(lines):
|
||||
segs.append({"text": text, "words": [
|
||||
{"id": f"s{li}_{wi}", "text": t, "start_time": start + wi * 0.3, "end_time": start + wi * 0.3 + 0.25}
|
||||
for wi, t in enumerate(text.split())]})
|
||||
return {"segments": segs}
|
||||
|
||||
def test_lines_inside_gap_with_edge_tolerance(self):
|
||||
from backend.services.auto_approval.vocal_gaps import _synced_reference_lines, synced_lines_in_gap
|
||||
|
||||
data = {"reference_lyrics": {"lrclib": self._synced_ref(
|
||||
[(5.0, "before gap"), (8.2, "at the edge"), (12.0, "dropped one"), (18.0, "dropped two"),
|
||||
(19.8, "too close to end"), (25.0, "after gap")]),
|
||||
"genius": _ref(["unsynced line"])}}
|
||||
synced = _synced_reference_lines(data)
|
||||
assert set(synced) == {"lrclib"} # unsynced sources ignored
|
||||
assert synced_lines_in_gap(synced, 8.0, 20.0) == {"lrclib": ["dropped one", "dropped two"]}
|
||||
assert synced_lines_in_gap(synced, 30.0, 40.0) == {}
|
||||
|
||||
def test_section_headers_ignored(self):
|
||||
from backend.services.auto_approval.vocal_gaps import _synced_reference_lines
|
||||
|
||||
data = {"reference_lyrics": {"lrclib": self._synced_ref([(1.0, "[Chorus]"), (2.0, "real line")])}}
|
||||
assert _synced_reference_lines(data) == {"lrclib": [(2.0, "real line")]}
|
||||
|
||||
def test_evidenced_requires_suspect_and_reference(self, tmp_path):
|
||||
# singing 2-20s, words only 2-4s; synced reference has lines at 10s and 15s
|
||||
stem = _synth_stem(tmp_path, [(2.0, 20.0), (30.0, 34.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 4.0)], [_word("b", "b", 30.0, 34.0)])
|
||||
data = {"reference_lyrics": {"lrclib": self._synced_ref([(10.0, "dropped line"), (15.0, "another")])}}
|
||||
result = compute_vocal_gaps(segs, stem, data)
|
||||
gap = next(g for g in result.gaps if g.start == 4.0)
|
||||
assert gap.suspect and gap.evidenced
|
||||
assert gap.synced_reference_lines == {"lrclib": ["dropped line", "another"]}
|
||||
assert result.evidenced_count == 1
|
||||
|
||||
def test_reference_lines_without_singing_are_not_evidenced(self, tmp_path):
|
||||
"""An instrumental where the reference (mis)places lines must not gate."""
|
||||
stem = _synth_stem(tmp_path, [(2.0, 4.0), (30.0, 34.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 4.0)], [_word("b", "b", 30.0, 34.0)])
|
||||
data = {"reference_lyrics": {"lrclib": self._synced_ref([(10.0, "misplaced line")])}}
|
||||
gap = next(g for g in compute_vocal_gaps(segs, stem, data).gaps if g.start == 4.0)
|
||||
assert gap.synced_reference_lines and not gap.suspect and not gap.evidenced
|
||||
|
||||
def test_singing_without_reference_is_suspect_but_not_evidenced(self, tmp_path):
|
||||
stem = _synth_stem(tmp_path, [(2.0, 20.0), (30.0, 34.0)])
|
||||
segs = _segments([_word("a", "a", 2.0, 4.0)], [_word("b", "b", 30.0, 34.0)])
|
||||
result = compute_vocal_gaps(segs, stem, {})
|
||||
gap = next(g for g in result.gaps if g.start == 4.0)
|
||||
assert gap.suspect and not gap.evidenced
|
||||
assert result.evidenced_count == 0
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Tests for backend.services.gemini_client (Gemini Developer API helper) and the
|
||||
per-caller graceful degradation when Gemini's quota/credit/key is unusable."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import gemini_client
|
||||
from backend.services.gemini_client import (
|
||||
GeminiKeyUnavailableError,
|
||||
get_api_key,
|
||||
get_genai_client,
|
||||
is_quota_or_billing_error,
|
||||
note_gemini_failure,
|
||||
)
|
||||
|
||||
|
||||
class FakeAPIError(Exception):
|
||||
"""Mimics google.genai.errors.APIError (numeric ``code`` + ``status``)."""
|
||||
|
||||
def __init__(self, code, status, message=""):
|
||||
super().__init__(f"{code} {status}. {message}")
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
QUOTA = FakeAPIError(429, "RESOURCE_EXHAUSTED", "Your prepayment credits are depleted")
|
||||
RATE_LIMIT = FakeAPIError(
|
||||
429, "RESOURCE_EXHAUSTED",
|
||||
"quotaId: GenerateRequestsPerMinutePerProjectPerModel-PaidTier, retryDelay: 5s",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_alert_throttle(monkeypatch):
|
||||
monkeypatch.setattr(gemini_client, "_last_alert_attempt", 0.0)
|
||||
monkeypatch.setattr(gemini_client, "_ALERT_IN_BACKGROUND", False)
|
||||
|
||||
|
||||
# ---- classifier -------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
QUOTA,
|
||||
FakeAPIError(429, "RESOURCE_EXHAUSTED", "You exceeded your current quota"),
|
||||
FakeAPIError(403, "PERMISSION_DENIED", "Generative Language API has not been used"),
|
||||
FakeAPIError(400, "INVALID_ARGUMENT", "API key not valid. Please pass a valid API key."),
|
||||
FakeAPIError(400, "FAILED_PRECONDITION", "check your plan and billing details"),
|
||||
RuntimeError("API key expired. Please renew the API key."),
|
||||
GeminiKeyUnavailableError("no key"),
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerDayPerProjectPerModel, retryDelay 3600s"),
|
||||
],
|
||||
)
|
||||
def test_classifier_positive(exc):
|
||||
assert is_quota_or_billing_error(exc)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
RATE_LIMIT,
|
||||
FakeAPIError(500, "INTERNAL", "Internal error"),
|
||||
FakeAPIError(503, "UNAVAILABLE", "The model is overloaded"),
|
||||
FakeAPIError(400, "INVALID_ARGUMENT", "Request contains an invalid argument."),
|
||||
TimeoutError("timed out"),
|
||||
ValueError("processed 429 tokens"),
|
||||
None,
|
||||
],
|
||||
)
|
||||
def test_classifier_negative(exc):
|
||||
assert not is_quota_or_billing_error(exc)
|
||||
|
||||
|
||||
def test_classifier_walks_cause_chain():
|
||||
try:
|
||||
try:
|
||||
raise QUOTA
|
||||
except FakeAPIError as inner:
|
||||
raise RuntimeError("wrapped") from inner
|
||||
except RuntimeError as outer:
|
||||
assert is_quota_or_billing_error(outer)
|
||||
|
||||
|
||||
# ---- key + client -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_env_key_wins(monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", " env-key ")
|
||||
with patch("backend.config.Settings.get_secret") as get_secret:
|
||||
assert get_api_key() == "env-key"
|
||||
get_secret.assert_not_called()
|
||||
|
||||
|
||||
def test_falls_back_to_secret_manager(monkeypatch):
|
||||
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||
with patch("backend.config.Settings.get_secret", return_value="sm-key") as get_secret:
|
||||
assert get_api_key() == "sm-key"
|
||||
get_secret.assert_called_once_with("gemini-api-key")
|
||||
|
||||
|
||||
def test_missing_key_raises(monkeypatch):
|
||||
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||
with patch("backend.config.Settings.get_secret", return_value=None):
|
||||
with pytest.raises(GeminiKeyUnavailableError):
|
||||
get_api_key()
|
||||
|
||||
|
||||
def test_client_uses_api_key_never_vertex(monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
with patch("google.genai.Client") as client_cls:
|
||||
get_genai_client(timeout_ms=1234)
|
||||
kwargs = client_cls.call_args.kwargs
|
||||
assert kwargs["api_key"] == "k"
|
||||
assert kwargs["http_options"].timeout == 1234
|
||||
assert kwargs["vertexai"] is False and "project" not in kwargs and "location" not in kwargs
|
||||
|
||||
|
||||
# ---- note_gemini_failure / alert throttle --------------------------------------
|
||||
|
||||
|
||||
def test_note_failure_ignores_ordinary_errors():
|
||||
with patch.object(gemini_client, "_maybe_alert") as alert:
|
||||
assert note_gemini_failure("x", RATE_LIMIT) is False
|
||||
alert.assert_not_called()
|
||||
|
||||
|
||||
def test_note_failure_alerts_once_per_window():
|
||||
with patch("backend.services.ops_alerts.send_throttled_ops_alert", return_value=True) as send:
|
||||
assert note_gemini_failure("auto_correct", QUOTA) is True
|
||||
assert note_gemini_failure("match_judge", QUOTA) is True
|
||||
send.assert_called_once()
|
||||
key, message = send.call_args.args
|
||||
assert key == "gemini-quota-exhausted"
|
||||
assert "auto_correct" in message and "rotate gemini-api-key" in message
|
||||
assert send.call_args.kwargs["throttle_minutes"] == 360
|
||||
|
||||
|
||||
def test_note_failure_never_raises_and_rearms_after_failed_send():
|
||||
with patch("backend.services.ops_alerts.send_throttled_ops_alert", side_effect=RuntimeError) as send:
|
||||
assert note_gemini_failure("x", QUOTA) is True
|
||||
assert note_gemini_failure("x", QUOTA) is True
|
||||
# A failed send doesn't silence the instance for 6h.
|
||||
assert send.call_count == 2
|
||||
|
||||
|
||||
def test_alert_runs_in_background_thread(monkeypatch):
|
||||
import threading
|
||||
|
||||
monkeypatch.setattr(gemini_client, "_ALERT_IN_BACKGROUND", True)
|
||||
done = threading.Event()
|
||||
seen = {}
|
||||
|
||||
def fake_send(*_a, **_k):
|
||||
seen["thread"] = threading.current_thread().name
|
||||
done.set()
|
||||
return True
|
||||
|
||||
with patch("backend.services.ops_alerts.send_throttled_ops_alert", side_effect=fake_send):
|
||||
assert note_gemini_failure("x", QUOTA) is True
|
||||
assert done.wait(5)
|
||||
assert seen["thread"] == "gemini-quota-alert"
|
||||
|
||||
|
||||
def test_throttled_ops_alert_respects_firestore_window(monkeypatch):
|
||||
from backend.services import ops_alerts
|
||||
|
||||
monkeypatch.setenv("FAILURE_ALERTS_ENABLED", "true")
|
||||
db = MagicMock()
|
||||
with patch("backend.services.firestore_service.get_firestore_client", return_value=db), \
|
||||
patch.object(ops_alerts, "_should_alert", return_value=(False, False, 0, None)) as should, \
|
||||
patch.object(ops_alerts, "send_ops_alert") as send:
|
||||
assert ops_alerts.send_throttled_ops_alert("k", "msg", throttle_minutes=360) is False
|
||||
send.assert_not_called()
|
||||
assert should.call_args.kwargs["throttle_minutes"] == 360
|
||||
|
||||
with patch("backend.services.firestore_service.get_firestore_client", return_value=db), \
|
||||
patch.object(ops_alerts, "_should_alert", return_value=(True, False, 2, "ref")), \
|
||||
patch.object(ops_alerts, "send_ops_alert", return_value=True) as send, \
|
||||
patch.object(ops_alerts, "_mark_alerted") as mark:
|
||||
assert ops_alerts.send_throttled_ops_alert("k", "msg", throttle_minutes=360) is True
|
||||
assert "Collapsed 2" in send.call_args.args[0]
|
||||
mark.assert_called_once()
|
||||
|
||||
|
||||
# ---- per-caller degradation ----------------------------------------------------
|
||||
|
||||
|
||||
def _quota_client():
|
||||
client = MagicMock()
|
||||
client.models.generate_content.side_effect = QUOTA
|
||||
return client
|
||||
|
||||
|
||||
def test_auto_correct_quota_is_non_retryable_and_skips_gemini_leg():
|
||||
from backend.services.auto_correct.service import AutoCorrectService, AutoCorrectServiceError
|
||||
|
||||
service = AutoCorrectService()
|
||||
with patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert"), \
|
||||
patch("backend.services.auto_correct.service.time.sleep") as sleep:
|
||||
with pytest.raises(AutoCorrectServiceError) as ei:
|
||||
service._call_model("gemini-3.8-flash", "sys", "user", job_id="j")
|
||||
assert ei.value.retryable is False and ei.value.status_code == 503
|
||||
sleep.assert_not_called()
|
||||
|
||||
|
||||
def test_auto_correct_compare_keeps_opus_when_gemini_quota_exhausted():
|
||||
from backend.services.auto_correct.service import AutoCorrectService, AutoCorrectServiceError
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
segments = [{"id": "s1", "words": [{"id": "w0", "text": "glory"}]}]
|
||||
refs = {"genius": {"segments": [{"text": "chlorine"}]}}
|
||||
sugg = {"op": "replace", "start_idx": 0, "end_idx": 0, "new_text": "chlorine",
|
||||
"reason": "r", "category": "mishearing", "confidence": 0.9}
|
||||
|
||||
def fake_call(model, *_a, **_k):
|
||||
if model.startswith("gemini"):
|
||||
raise AutoCorrectServiceError("Gemini is unavailable", status_code=503)
|
||||
return {"suggestions": [sugg]}, None
|
||||
|
||||
service = AutoCorrectService()
|
||||
with patch.object(service.settings, "auto_correct_compare_models", "claude-opus-5-5;gemini-3.8-flash"), \
|
||||
patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
result = service.suggest(
|
||||
job_id="j", segments=segments, reference_lyrics=refs, artist="A", title="T",
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
)
|
||||
assert result.model == "claude-opus-5-5"
|
||||
assert any("gemini-3.8-flash failed" in w for w in result.warnings)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_judge_quota_returns_no_suggestion_and_alerts():
|
||||
from backend.services.match_judge import service as mj
|
||||
|
||||
async def no_candidates(*_a, **_k):
|
||||
return []
|
||||
|
||||
async def boom(*_a, **_k):
|
||||
raise QUOTA
|
||||
|
||||
with patch.object(gemini_client, "_maybe_alert") as alert:
|
||||
verdict = await mj.judge_match(
|
||||
"A", "T", search_tracks=no_candidates, ai_judge=boom, enabled=True
|
||||
)
|
||||
assert verdict.reason == "ai failed"
|
||||
alert.assert_called_once()
|
||||
|
||||
|
||||
def test_custom_lyrics_quota_is_clean_503():
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings
|
||||
from backend.services.custom_lyrics_service import CustomLyricsService, CustomLyricsServiceError
|
||||
|
||||
service = CustomLyricsService()
|
||||
with patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert"):
|
||||
with pytest.raises(CustomLyricsServiceError) as ei:
|
||||
service._call_gemini(system_prompt="s", user_prompt="u", pdf_bytes=None,
|
||||
settings=GenerationSettings())
|
||||
assert ei.value.status_code == 503
|
||||
assert "temporarily unavailable" in str(ei.value)
|
||||
|
||||
|
||||
def test_credit_eval_quota_goes_to_manual_review():
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
|
||||
svc = CreditEvaluationService.__new__(CreditEvaluationService)
|
||||
svc.settings = MagicMock(credit_eval_enabled=True, credit_eval_model="gemini-3.8-flash")
|
||||
signals = {"fingerprint_matches": [{"x": 1}], "ip_matches": [], "recent_signups_ip": 0,
|
||||
"recent_signups_fp": 0, "user_data": {}, "ip_geo": None, "user_agent": None}
|
||||
with patch.object(svc, "_collect_signals", return_value=signals), \
|
||||
patch.object(svc, "_log_evaluation"), \
|
||||
patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert") as alert:
|
||||
evaluation = svc.evaluate("a@b.c", "welcome")
|
||||
assert evaluation.decision == "pending_review"
|
||||
alert.assert_called_once()
|
||||
|
||||
|
||||
def test_error_monitor_llm_does_not_retry_on_quota():
|
||||
from backend.services.error_monitor import llm_analysis
|
||||
|
||||
with patch.object(llm_analysis, "get_genai_client", return_value=_quota_client()), \
|
||||
patch.object(gemini_client, "_maybe_alert"), \
|
||||
patch.object(llm_analysis.time, "sleep") as sleep:
|
||||
with pytest.raises(FakeAPIError):
|
||||
llm_analysis._call_llm("sys", "user")
|
||||
sleep.assert_not_called()
|
||||
|
||||
|
||||
def test_classifier_ignores_implicit_context():
|
||||
"""A Gemini-unrelated 403 raised earlier must not be blamed on Gemini."""
|
||||
try:
|
||||
try:
|
||||
raise FakeAPIError(403, "PERMISSION_DENIED", "firestore says no")
|
||||
except FakeAPIError:
|
||||
raise ValueError("later, unrelated failure") # implicit __context__ only
|
||||
except ValueError as exc:
|
||||
assert not is_quota_or_billing_error(exc)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -148,6 +148,25 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
|
||||
# Verify the returned data is the original
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
|
||||
@pytest.mark.parametrize("stored", [None, {"gaps": [{"start": 20.66, "end": 32.4, "evidenced": True}],
|
||||
"evidenced_count": 1}])
|
||||
def test_includes_vocal_gaps_for_missing_lyrics_marker(self, mock_job, original_corrections, stored):
|
||||
"""The review UI marks possible missing lyrics from state_data.vocal_gaps."""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
|
||||
if stored:
|
||||
mock_job.state_data = {"vocal_gaps": stored}
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService:
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
storage = MockStorageService.return_value
|
||||
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
|
||||
storage.download_json.return_value = original_corrections.copy()
|
||||
storage.generate_signed_url.return_value = "https://signed-url.com"
|
||||
import asyncio
|
||||
result = asyncio.run(get_correction_data("test-job-123", ("user@test.com", "job_owner")))
|
||||
assert result["vocal_gaps"] == stored
|
||||
|
||||
def test_returns_proxy_audio_urls_and_omits_waveform_without_signing(
|
||||
self, mock_job, original_corrections
|
||||
):
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -103,11 +104,11 @@ def test_text_only_happy_path(service: CustomLyricsService) -> None:
|
||||
assert result.line_count_mismatch is False
|
||||
assert result.iterations_used == 0
|
||||
assert result.model == "gemini-3.1-pro-preview"
|
||||
assert mock_client_cls.call_args.kwargs == {
|
||||
"vertexai": True,
|
||||
"project": "test-project",
|
||||
"location": "global",
|
||||
}
|
||||
# Gemini Developer API (API key) — never Vertex AI.
|
||||
kwargs = mock_client_cls.call_args.kwargs
|
||||
assert kwargs["api_key"] == os.environ["GEMINI_API_KEY"]
|
||||
assert kwargs["vertexai"] is False and "project" not in kwargs
|
||||
assert kwargs["http_options"].timeout == 300_000
|
||||
|
||||
|
||||
def test_docx_input_parsed_to_text(
|
||||
|
||||
@@ -597,3 +597,64 @@ class TestDropboxLosslessExclusion:
|
||||
assert len(dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-Organized")) == 2
|
||||
with patch("backend.config.get_settings", return_value=self._settings("")):
|
||||
assert dropbox_skip_suffixes_for("/MediaUnsynced/Karaoke/Tracks-Organized") == ()
|
||||
|
||||
|
||||
class TestEnsureFolderAndMissingPaths:
|
||||
"""ensure_folder idempotency + list_folders on a not-yet-created tenant folder."""
|
||||
|
||||
def _service(self):
|
||||
from backend.services.dropbox_service import DropboxService
|
||||
|
||||
service = DropboxService()
|
||||
service._client = Mock()
|
||||
return service
|
||||
|
||||
def _api_error(self, error):
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
return ApiError("req_id", error, "message", "headers")
|
||||
|
||||
def test_ensure_folder_creates(self):
|
||||
service = self._service()
|
||||
assert service.ensure_folder("MediaUnsynced/Karaoke/Tracks-X") is True
|
||||
service._client.files_create_folder_v2.assert_called_once_with("/MediaUnsynced/Karaoke/Tracks-X")
|
||||
|
||||
def test_ensure_folder_existing_folder_is_noop(self):
|
||||
from dropbox.files import CreateFolderError, WriteConflictError, WriteError
|
||||
|
||||
service = self._service()
|
||||
service._client.files_create_folder_v2.side_effect = self._api_error(
|
||||
CreateFolderError.path(WriteError.conflict(WriteConflictError.folder))
|
||||
)
|
||||
assert service.ensure_folder("/Tracks-X") is False
|
||||
|
||||
def test_ensure_folder_file_in_the_way_raises(self):
|
||||
from dropbox.exceptions import ApiError
|
||||
from dropbox.files import CreateFolderError, WriteConflictError, WriteError
|
||||
|
||||
service = self._service()
|
||||
service._client.files_create_folder_v2.side_effect = self._api_error(
|
||||
CreateFolderError.path(WriteError.conflict(WriteConflictError.file))
|
||||
)
|
||||
with pytest.raises(ApiError):
|
||||
service.ensure_folder("/Tracks-X")
|
||||
|
||||
def test_list_folders_missing_path_is_empty(self):
|
||||
from dropbox.files import ListFolderError, LookupError as DbxLookupError
|
||||
|
||||
service = self._service()
|
||||
service._client.files_list_folder.side_effect = self._api_error(
|
||||
ListFolderError.path(DbxLookupError.not_found)
|
||||
)
|
||||
assert service.list_folders("/Tracks-New") == []
|
||||
|
||||
def test_list_folders_other_errors_propagate(self):
|
||||
from dropbox.exceptions import ApiError
|
||||
from dropbox.files import ListFolderError, LookupError as DbxLookupError
|
||||
|
||||
service = self._service()
|
||||
service._client.files_list_folder.side_effect = self._api_error(
|
||||
ListFolderError.path(DbxLookupError.restricted_content)
|
||||
)
|
||||
with pytest.raises(ApiError):
|
||||
service.list_folders("/Tracks-New")
|
||||
@@ -257,6 +257,109 @@ class TestPostmarkEmailProvider:
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestPostmarkRetry:
|
||||
"""Transient Postmark failures are retried; deterministic errors are not."""
|
||||
|
||||
def _response(self, status_code, body=None, json_body=True):
|
||||
resp = Mock()
|
||||
resp.status_code = status_code
|
||||
if json_body:
|
||||
resp.json.return_value = body or {"MessageID": "abc"}
|
||||
else:
|
||||
resp.json.side_effect = ValueError("not json")
|
||||
resp.text = "" if json_body else "<html><center><h1>403 Forbidden</h1></center></html>"
|
||||
return resp
|
||||
|
||||
def _send(self, provider):
|
||||
return provider.send_email_detailed(
|
||||
to_email="user@example.com", subject="Test", html_content="<p>x</p>"
|
||||
)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_sleep(self):
|
||||
with patch("backend.services.email_service.time.sleep") as mock_sleep:
|
||||
self.mock_sleep = mock_sleep
|
||||
yield
|
||||
|
||||
@pytest.fixture
|
||||
def provider(self):
|
||||
return PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
def test_html_403_then_success_is_retried(self, provider):
|
||||
"""The prod failure mode: nginx HTML 403 from Postmark's edge, then OK."""
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = [self._response(403, json_body=False), self._response(200)]
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
assert result.message_id == "abc"
|
||||
assert mock_post.call_count == 2
|
||||
self.mock_sleep.assert_called_once_with(1.0)
|
||||
|
||||
def test_html_403_gives_up_after_all_attempts(self, provider):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(403, json_body=False)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert mock_post.call_count == 3
|
||||
assert [c.args[0] for c in self.mock_sleep.call_args_list] == [1.0, 3.0]
|
||||
|
||||
@pytest.mark.parametrize("status", [429, 500, 503])
|
||||
def test_rate_limit_and_server_errors_are_retried(self, provider, status):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = [self._response(status, body={"ErrorCode": 0}), self._response(200)]
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
assert mock_post.call_count == 2
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"status,body",
|
||||
[
|
||||
(403, {"ErrorCode": 10, "Message": "Bad or missing API token"}), # JSON 403 = real auth error
|
||||
(422, {"ErrorCode": 300, "Message": "Invalid email request"}),
|
||||
(422, {"ErrorCode": 406, "Message": "Inactive recipient"}),
|
||||
],
|
||||
)
|
||||
def test_deterministic_postmark_errors_not_retried(self, provider, status, body):
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._response(status, body=body)
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert mock_post.call_count == 1
|
||||
self.mock_sleep.assert_not_called()
|
||||
|
||||
def test_connect_timeout_is_retried(self, provider):
|
||||
import requests as _requests
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = [_requests.ConnectTimeout("slow"), self._response(200)]
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is True
|
||||
assert mock_post.call_count == 2
|
||||
|
||||
def test_connect_timeout_on_every_attempt_fails_cleanly(self, provider):
|
||||
import requests as _requests
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = _requests.ConnectTimeout("slow")
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert mock_post.call_count == 3
|
||||
|
||||
def test_read_timeout_not_retried_to_avoid_duplicate_send(self, provider):
|
||||
"""Postmark may have accepted the message; it has no idempotency key."""
|
||||
import requests as _requests
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.side_effect = _requests.ReadTimeout("no response")
|
||||
result = self._send(provider)
|
||||
|
||||
assert result.success is False
|
||||
assert mock_post.call_count == 1
|
||||
|
||||
|
||||
class TestEmailServiceProviderSelection:
|
||||
"""Tests for EmailService._get_provider() selection logic."""
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Simple classification/extraction Gemini callers must request LOW thinking.
|
||||
|
||||
Gemini 3 Flash defaults to high/dynamic thinking, and thinking tokens are billed
|
||||
as output — the dominant Vertex cost. These callers do short structured
|
||||
extraction or grant/deny classification, so low thinking is ample (cost cut
|
||||
2026-10-01). Quality-sensitive callers (auto-correct, custom lyrics, lyrics
|
||||
translation) deliberately keep the model default and are not covered here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _fake_client():
|
||||
client = MagicMock()
|
||||
client.models.generate_content.return_value = SimpleNamespace(text="{}")
|
||||
return client
|
||||
|
||||
|
||||
def _thinking_level(client) -> str:
|
||||
config = client.models.generate_content.call_args.kwargs["config"]
|
||||
return config.thinking_config.thinking_level.value.lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"module_path",
|
||||
[
|
||||
"backend.services.match_judge.ai",
|
||||
"backend.services.match_judge.free_text",
|
||||
"backend.services.parse_titles.ai",
|
||||
],
|
||||
)
|
||||
def test_blocking_generate_uses_low_thinking(module_path) -> None:
|
||||
import importlib
|
||||
|
||||
mod = importlib.import_module(module_path)
|
||||
client = _fake_client()
|
||||
with patch("google.genai.Client", return_value=client):
|
||||
mod._blocking_generate("gemini-3.8-flash", "sys", "user")
|
||||
assert _thinking_level(client) == "low"
|
||||
|
||||
|
||||
def test_tenant_bulk_generate_uses_low_thinking() -> None:
|
||||
from backend.services.tenant_bulk import analyze
|
||||
|
||||
client = _fake_client()
|
||||
with patch("google.genai.Client", return_value=client):
|
||||
analyze.default_generate("sys", "user")
|
||||
assert _thinking_level(client) == "low"
|
||||
|
||||
|
||||
def test_credit_eval_uses_low_thinking() -> None:
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
|
||||
client = _fake_client()
|
||||
svc = CreditEvaluationService.__new__(CreditEvaluationService)
|
||||
svc.settings = SimpleNamespace(google_cloud_project="p", credit_eval_model="gemini-3.8-flash")
|
||||
with patch("google.genai.Client", return_value=client):
|
||||
svc._call_gemini("prompt")
|
||||
assert _thinking_level(client) == "low"
|
||||
@@ -364,3 +364,35 @@ class TestAutoApprovalEval:
|
||||
def test_eval_requires_admin(self, client):
|
||||
response = client.post("/api/internal/jobs/test123/auto-approval-eval")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
class TestVocalGapsEndpoint:
|
||||
"""POST /api/internal/jobs/{job_id}/vocal-gaps — missing-lyrics backfill/inspect."""
|
||||
|
||||
def test_stores_by_default(self, client):
|
||||
with patch(
|
||||
'backend.services.auto_approval.executor.analyze_job_vocal_gaps',
|
||||
return_value={"status": "checked", "stored": True},
|
||||
) as analyze:
|
||||
response = client.post(
|
||||
"/api/internal/jobs/test123/vocal-gaps",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"job_id": "test123", "status": "checked", "stored": True}
|
||||
analyze.assert_called_once_with("test123", True)
|
||||
|
||||
def test_dry_run_does_not_store(self, client):
|
||||
with patch(
|
||||
'backend.services.auto_approval.executor.analyze_job_vocal_gaps',
|
||||
return_value={"status": "checked", "stored": False},
|
||||
) as analyze:
|
||||
client.post(
|
||||
"/api/internal/jobs/test123/vocal-gaps?dry_run=true",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
analyze.assert_called_once_with("test123", False)
|
||||
|
||||
def test_requires_admin(self, client):
|
||||
response = client.post("/api/internal/jobs/test123/vocal-gaps")
|
||||
assert response.status_code == 401
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Translated lyrics: LLM translation service + per-job translations.json."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import lyrics_translation as lt
|
||||
from backend.services.lyrics_translation import (
|
||||
LyricsTranslationError,
|
||||
LyricsTranslationService,
|
||||
is_same_language,
|
||||
normalize_language,
|
||||
prepare_job_translations,
|
||||
)
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self, files=None):
|
||||
self.files = dict(files or {})
|
||||
self.deleted = []
|
||||
|
||||
def file_exists(self, path):
|
||||
return path in self.files
|
||||
|
||||
def download_json(self, path):
|
||||
return self.files[path]
|
||||
|
||||
def upload_json(self, path, data):
|
||||
self.files[path] = data
|
||||
|
||||
def delete_file(self, path, ignore_missing=False):
|
||||
self.deleted.append(path)
|
||||
self.files.pop(path, None)
|
||||
return True
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_sleep(monkeypatch):
|
||||
monkeypatch.setattr(lt.time, "sleep", lambda s: None)
|
||||
|
||||
|
||||
# ---- language codes ----
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,expected", [
|
||||
("es", "es"), ("ES", "es"), ("pt-BR", "pt"), ("zh_CN", "zh"), ("no", "nb"), ("fil", "tl"),
|
||||
("xx", None), ("", None), (None, None),
|
||||
])
|
||||
def test_normalize_language(raw, expected):
|
||||
assert normalize_language(raw) == expected
|
||||
|
||||
|
||||
def test_supported_languages_match_ui_locales():
|
||||
import os
|
||||
|
||||
messages = os.path.join(os.path.dirname(__file__), "..", "..", "frontend", "messages")
|
||||
locales = {f[:-5] for f in os.listdir(messages) if f.endswith(".json") and not f.startswith(".")}
|
||||
assert set(lt.TRANSLATION_LANGUAGES) == locales
|
||||
|
||||
|
||||
def test_is_same_language():
|
||||
lines = ["Hola amigo", "Te quiero", "La la la", "Adiós"]
|
||||
assert is_same_language(lines, ["hola amigo", "Te quiero", "La la la", "Adiós"])
|
||||
assert not is_same_language(lines, ["Hi friend", "I love you", "La la la", "Bye"])
|
||||
assert not is_same_language([], [])
|
||||
|
||||
|
||||
# ---- translate_lines ----
|
||||
|
||||
|
||||
def make_service(responses, storage=None):
|
||||
svc = LyricsTranslationService(storage=storage or FakeStorage(), model="test-model")
|
||||
svc._call_gemini = MagicMock(side_effect=responses)
|
||||
return svc
|
||||
|
||||
|
||||
def test_translate_lines_returns_one_per_line_and_caches():
|
||||
storage = FakeStorage()
|
||||
svc = make_service([{"translations": ["Hola mundo", "Adiós"]}], storage)
|
||||
assert svc.translate_lines(["Hello world", "Goodbye"], "es") == ["Hola mundo", "Adiós"]
|
||||
cached = [p for p in storage.files if p.startswith(lt.CACHE_PREFIX)]
|
||||
assert len(cached) == 1
|
||||
# Second call is served from the cache
|
||||
svc2 = make_service([AssertionError("should not call the model")], storage)
|
||||
assert svc2.translate_lines(["Hello world", "Goodbye"], "es") == ["Hola mundo", "Adiós"]
|
||||
|
||||
|
||||
def test_cache_key_depends_on_language_and_lines():
|
||||
svc = make_service([])
|
||||
a = svc._cache_path(["x"], "es", None, None)
|
||||
assert a != svc._cache_path(["x"], "fr", None, None)
|
||||
assert a != svc._cache_path(["y"], "es", None, None)
|
||||
|
||||
|
||||
def test_wrong_count_is_retried():
|
||||
svc = make_service([{"translations": ["only one"]}, {"translations": ["uno", "dos"]}])
|
||||
assert svc.translate_lines(["one", "two"], "es") == ["uno", "dos"]
|
||||
assert svc._call_gemini.call_count == 2
|
||||
|
||||
|
||||
def test_gives_up_after_max_attempts():
|
||||
svc = make_service([{"translations": []}] * lt.MAX_ATTEMPTS)
|
||||
with pytest.raises(LyricsTranslationError):
|
||||
svc.translate_lines(["one", "two"], "es")
|
||||
assert svc._call_gemini.call_count == lt.MAX_ATTEMPTS
|
||||
|
||||
|
||||
def test_transient_error_retried_permanent_error_raised():
|
||||
# Per-minute rate limit: transient, retried.
|
||||
transient = Exception("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerMinutePerProjectPerModel")
|
||||
svc = make_service([transient, {"translations": ["uno"]}])
|
||||
assert svc.translate_lines(["one"], "es") == ["uno"]
|
||||
|
||||
svc = make_service([Exception("400 invalid argument")])
|
||||
with pytest.raises(LyricsTranslationError):
|
||||
svc.translate_lines(["one"], "es")
|
||||
assert svc._call_gemini.call_count == 1
|
||||
|
||||
|
||||
def test_quota_exhausted_not_retried_and_alerts():
|
||||
class QuotaError(Exception):
|
||||
code = 403
|
||||
status = "PERMISSION_DENIED"
|
||||
|
||||
svc = make_service([QuotaError("Your prepayment credits are depleted")])
|
||||
with patch("backend.services.gemini_client._maybe_alert") as alert:
|
||||
with pytest.raises(LyricsTranslationError, match="unavailable"):
|
||||
svc.translate_lines(["one"], "es")
|
||||
assert svc._call_gemini.call_count == 1
|
||||
alert.assert_called_once()
|
||||
|
||||
|
||||
def test_unsupported_language_raises():
|
||||
with pytest.raises(LyricsTranslationError):
|
||||
make_service([]).translate_lines(["one"], "xx")
|
||||
|
||||
|
||||
def test_prompt_lists_numbered_lines_and_language():
|
||||
prompt = lt._user_prompt(["first", "second"], "he", "Artist", "Song")
|
||||
assert "Hebrew" in prompt and "1. first\n2. second" in prompt and "exactly 2 strings" in prompt
|
||||
|
||||
|
||||
# ---- prepare_job_translations ----
|
||||
|
||||
|
||||
def corrections(*texts):
|
||||
segs = []
|
||||
for i, text in enumerate(texts):
|
||||
words = [{"id": f"w{i}{j}", "text": w, "start_time": i * 3 + j * 0.5, "end_time": i * 3 + j * 0.5 + 0.4}
|
||||
for j, w in enumerate(text.split())]
|
||||
segs.append({"id": f"s{i}", "text": text, "words": words,
|
||||
"start_time": words[0]["start_time"] if words else i * 3,
|
||||
"end_time": words[-1]["end_time"] if words else i * 3})
|
||||
return {
|
||||
"original_segments": segs, "corrected_segments": segs, "corrections": [], "corrections_made": 0,
|
||||
"confidence": 1.0, "reference_lyrics": {}, "anchor_sequences": [], "gap_sequences": [],
|
||||
"resized_segments": [], "metadata": {}, "correction_steps": [], "word_id_map": {}, "segment_id_map": {},
|
||||
}
|
||||
|
||||
|
||||
def job(language="es", job_id="job1"):
|
||||
return SimpleNamespace(job_id=job_id, translation_language=language, artist="A", title="T")
|
||||
|
||||
|
||||
def test_no_language_removes_stale_file_and_returns_none():
|
||||
storage = FakeStorage({"jobs/job1/lyrics/translations.json": {"lines": []}})
|
||||
assert prepare_job_translations("job1", job(None), storage) is None
|
||||
assert "jobs/job1/lyrics/translations.json" in storage.deleted
|
||||
|
||||
|
||||
def test_translation_turned_off_clears_previous_outcome():
|
||||
# A re-render after an admin removes the language must not keep the old
|
||||
# "translated" outcome, or YouTube would still be labelled with a translation.
|
||||
from backend.services.youtube_description import translated_language_name
|
||||
|
||||
j = job(None)
|
||||
j.state_data = {"lyrics_translation": {"language": "es", "status": "translated"}}
|
||||
jm = MagicMock()
|
||||
assert prepare_job_translations("job1", j, FakeStorage({}), jm) is None
|
||||
jm.update_state_data.assert_called_once_with("job1", "lyrics_translation", {"status": "off"})
|
||||
assert translated_language_name({"lyrics_translation": {"status": "off"}}) is None
|
||||
|
||||
|
||||
def test_translates_final_reviewed_lyrics():
|
||||
storage = FakeStorage({
|
||||
"jobs/job1/lyrics/corrections.json": corrections("Hello world", "Goodbye"),
|
||||
# Review edited the first line: the translation must use the edited text
|
||||
"jobs/job1/lyrics/corrections_updated.json": corrections("Hello there world", "Goodbye"),
|
||||
})
|
||||
svc = make_service([{"translations": ["Hola mundo", "Adiós"]}], storage)
|
||||
jm = MagicMock()
|
||||
path = prepare_job_translations("job1", job(), storage, jm, service=svc)
|
||||
assert path == "jobs/job1/lyrics/translations.json"
|
||||
data = storage.files[path]
|
||||
assert data["language"] == "es" and data["language_name"] == "Spanish"
|
||||
assert data["lines"][0] == {"segment_id": "s0", "text": "Hello there world", "translation": "Hola mundo"}
|
||||
sent = svc._call_gemini.call_args[0][0]
|
||||
assert "Hello there world" in sent
|
||||
jm.update_state_data.assert_called_once()
|
||||
assert jm.update_state_data.call_args[0][2]["status"] == "translated"
|
||||
|
||||
|
||||
def test_same_language_song_gets_no_translation_row():
|
||||
storage = FakeStorage({"jobs/job1/lyrics/corrections.json": corrections("Hola amigo", "Te quiero")})
|
||||
svc = make_service([{"translations": ["Hola amigo", "Te quiero"]}], storage)
|
||||
jm = MagicMock()
|
||||
assert prepare_job_translations("job1", job(), storage, jm, service=svc) is None
|
||||
assert jm.update_state_data.call_args[0][2]["status"] == "same_language"
|
||||
assert "jobs/job1/lyrics/translations.json" not in storage.files
|
||||
|
||||
|
||||
def test_failure_never_blocks_render():
|
||||
storage = FakeStorage({
|
||||
"jobs/job1/lyrics/corrections.json": corrections("Hello"),
|
||||
"jobs/job1/lyrics/translations.json": {"lines": []}, # stale from an earlier render
|
||||
})
|
||||
svc = make_service([Exception("400 bad request")], storage)
|
||||
jm = MagicMock()
|
||||
assert prepare_job_translations("job1", job(), storage, jm, service=svc) is None
|
||||
status = jm.update_state_data.call_args[0][2]
|
||||
assert status["status"] == "failed" and "bad request" in status["error"]
|
||||
assert "jobs/job1/lyrics/translations.json" not in storage.files
|
||||
|
||||
|
||||
# ---- job model ----
|
||||
|
||||
|
||||
def test_job_create_normalizes_translation_language():
|
||||
from backend.models.job import JobCreate
|
||||
|
||||
assert JobCreate(artist="a", title="b", translation_language="ES").translation_language == "es"
|
||||
assert JobCreate(artist="a", title="b", translation_language="").translation_language is None
|
||||
assert JobCreate(artist="a", title="b", translation_language="klingon").translation_language is None
|
||||
assert JobCreate(artist="a", title="b").translation_language is None
|
||||
|
||||
|
||||
def test_job_manager_copies_translation_language():
|
||||
from backend.models.job import JobCreate
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
with patch("backend.services.job_manager.FirestoreService"), patch("backend.services.job_manager.StorageService"):
|
||||
manager = JobManager()
|
||||
manager.firestore = MagicMock()
|
||||
created = manager.create_job(JobCreate(artist="a", title="b", theme_id="nomad", translation_language="ja"))
|
||||
assert created.translation_language == "ja"
|
||||
saved = manager.firestore.create_job.call_args[0][0]
|
||||
assert saved.translation_language == "ja"
|
||||
|
||||
|
||||
# ---- preview ----
|
||||
|
||||
|
||||
def test_preview_samples_cover_every_language():
|
||||
from backend.services.translation_preview_samples import SAMPLES
|
||||
|
||||
assert set(SAMPLES) == set(lt.TRANSLATION_LANGUAGES)
|
||||
for code, sample in SAMPLES.items():
|
||||
assert len(sample["lyrics"]) == len(sample["translations"]) == 4, code
|
||||
assert all(t.strip() for t in sample["translations"]), code
|
||||
|
||||
|
||||
def test_preview_route_rejects_unknown_language():
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.themes import router
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
client = TestClient(app)
|
||||
assert client.get("/api/themes/translation-preview?language=xx").status_code == 400
|
||||
with patch("backend.services.translation_preview.render_translation_preview", return_value="data:image/jpeg;base64,AA"):
|
||||
resp = client.get("/api/themes/translation-preview?language=he")
|
||||
assert resp.status_code == 200 and resp.json() == {"image": "data:image/jpeg;base64,AA"}
|
||||
|
||||
|
||||
def test_preview_renders_sample_with_translations():
|
||||
from backend.services import translation_preview as tp
|
||||
|
||||
tp._CACHE.clear()
|
||||
theme_service = MagicMock()
|
||||
theme_service.get_default_theme_id.return_value = "nomad"
|
||||
theme_service.get_theme_style_params.return_value = {"karaoke": {}}
|
||||
with patch.object(tp, "get_theme_service", return_value=theme_service), \
|
||||
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
|
||||
patch.object(tp, "render_karaoke_frame", return_value=b"jpeg") as render:
|
||||
url = tp.render_translation_preview("fr")
|
||||
tp.render_translation_preview("fr") # cached
|
||||
assert url.startswith("data:image/jpeg;base64,")
|
||||
render.assert_called_once()
|
||||
assert render.call_args.kwargs["translations"] == tp.SAMPLES["fr"]["translations"]
|
||||
|
||||
|
||||
def test_concurrent_cold_previews_render_once():
|
||||
import threading
|
||||
import time as _time
|
||||
|
||||
from backend.services import translation_preview as tp
|
||||
|
||||
tp._CACHE.clear()
|
||||
theme_service = MagicMock()
|
||||
theme_service.get_default_theme_id.return_value = "nomad"
|
||||
theme_service.get_theme_style_params.return_value = {"karaoke": {}}
|
||||
|
||||
def slow_render(*a, **k):
|
||||
_time.sleep(0.2)
|
||||
return b"jpeg"
|
||||
|
||||
with patch.object(tp, "get_theme_service", return_value=theme_service), \
|
||||
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
|
||||
patch.object(tp, "render_karaoke_frame", side_effect=slow_render) as render:
|
||||
threads = [threading.Thread(target=tp.render_translation_preview, args=("de",)) for _ in range(5)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert render.call_count == 1
|
||||
@@ -122,3 +122,228 @@ async def test_lyrics_worker_trigger_swallows_errors() -> None:
|
||||
with patch("backend.services.worker_service.WorkerService", return_value=ws):
|
||||
await _trigger_proactive_auto_correct("job-1", job_log) # must not raise
|
||||
job_log.warning.assert_called()
|
||||
|
||||
|
||||
# ---- de-duplication (lyrics trigger vs screens pre-apply race) ----
|
||||
|
||||
import google.api_core.exceptions as gexc # noqa: E402
|
||||
|
||||
|
||||
class _FakeBlob:
|
||||
def __init__(self, bucket, path):
|
||||
self.bucket, self.path = bucket, path
|
||||
self.generation = None
|
||||
|
||||
def upload_from_string(self, data, content_type=None, if_generation_match=None):
|
||||
current = self.bucket.objects.get(self.path)
|
||||
current_gen = current[0] if current else 0
|
||||
if if_generation_match is not None and if_generation_match != current_gen:
|
||||
raise gexc.PreconditionFailed("generation mismatch")
|
||||
self.bucket.next_gen += 1
|
||||
self.generation = self.bucket.next_gen
|
||||
self.bucket.objects[self.path] = (self.generation, data)
|
||||
|
||||
def download_as_bytes(self):
|
||||
return self.bucket.objects[self.path][1].encode()
|
||||
|
||||
def delete(self, if_generation_match=None):
|
||||
current = self.bucket.objects.get(self.path)
|
||||
if current is None:
|
||||
raise gexc.NotFound("gone")
|
||||
if if_generation_match is not None and if_generation_match != current[0]:
|
||||
raise gexc.PreconditionFailed("generation mismatch")
|
||||
del self.bucket.objects[self.path]
|
||||
|
||||
|
||||
class _FakeBucket:
|
||||
def __init__(self):
|
||||
self.objects: dict = {}
|
||||
self.next_gen = 100
|
||||
|
||||
def blob(self, path):
|
||||
return _FakeBlob(self, path)
|
||||
|
||||
def get_blob(self, path):
|
||||
if path not in self.objects:
|
||||
return None
|
||||
b = _FakeBlob(self, path)
|
||||
b.generation = self.objects[path][0]
|
||||
return b
|
||||
|
||||
def put_lease(self, job_id, acquired_at):
|
||||
import json as _json
|
||||
self.next_gen += 1
|
||||
self.objects[f"jobs/{job_id}/lyrics/auto_correct_inflight.json"] = (
|
||||
self.next_gen, _json.dumps({"acquired_at": acquired_at}))
|
||||
|
||||
|
||||
def _patch_with_bucket(service):
|
||||
p_set, p_st, p_jm, _p_svc, storage = _patch(service=service)
|
||||
bucket = _FakeBucket()
|
||||
storage.bucket = bucket
|
||||
storage.file_exists.side_effect = lambda p: p.endswith("corrections.json") or p in bucket.objects
|
||||
return p_set, p_st, p_jm, storage, bucket
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_calls_on_same_instance_share_one_run() -> None:
|
||||
"""Regression (job 96cf1100): the lyrics trigger and the screens pre-apply
|
||||
both called this within seconds and each ran the multi-model suggest."""
|
||||
import asyncio as _asyncio
|
||||
import threading
|
||||
|
||||
release = threading.Event()
|
||||
svc = MagicMock()
|
||||
|
||||
def _slow_suggest(**_kw):
|
||||
release.wait(5)
|
||||
return SimpleNamespace(suggestions=[1, 2, 3], model="m", elapsed_seconds=1.0)
|
||||
|
||||
svc.suggest.side_effect = _slow_suggest
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
first = _asyncio.create_task(process_proactive_auto_correct("job-dup"))
|
||||
await _asyncio.sleep(0.05)
|
||||
assert "jobs/job-dup/lyrics/auto_correct_inflight.json" in bucket.objects # lease held
|
||||
second = _asyncio.create_task(process_proactive_auto_correct("job-dup"))
|
||||
await _asyncio.sleep(0.05)
|
||||
release.set()
|
||||
r1, r2 = await _asyncio.gather(first, second)
|
||||
assert svc.suggest.call_count == 1
|
||||
assert r1 == r2 == {"status": "generated", "suggestions": 3}
|
||||
assert bucket.objects == {} # our lease released
|
||||
|
||||
# A later (non-concurrent) call isn't blocked by a leftover in-flight entry.
|
||||
await process_proactive_auto_correct("job-dup")
|
||||
assert svc.suggest.call_count == 2 # in prod this hits the service's own GCS cache
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_peer_instance_holding_lease_is_awaited_not_duplicated(monkeypatch) -> None:
|
||||
import time as _time
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
monkeypatch.setattr(w, "PEER_POLL_SECONDS", 0)
|
||||
svc = MagicMock()
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
bucket.put_lease("job-peer", _time.time()) # fresh lease held by another instance
|
||||
peer_cache = iter([None, None, [{"id": "s1"}, {"id": "s2"}]])
|
||||
with p_set, p_st, p_jm, \
|
||||
patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc), \
|
||||
patch("backend.services.auto_approval.executor._load_ai_suggestions",
|
||||
side_effect=lambda *_a: next(peer_cache)):
|
||||
result = await process_proactive_auto_correct("job-peer")
|
||||
assert result == {"status": "deduped", "suggestions": 2}
|
||||
svc.suggest.assert_not_called()
|
||||
assert "jobs/job-peer/lyrics/auto_correct_inflight.json" in bucket.objects # never released theirs
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_peer_lease_is_taken_over_with_generation_fence() -> None:
|
||||
svc = MagicMock()
|
||||
svc.suggest.return_value = SimpleNamespace(suggestions=[1], model="m", elapsed_seconds=1.0)
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
bucket.put_lease("job-stale", 0) # leftover from a crashed instance
|
||||
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
|
||||
result = await process_proactive_auto_correct("job-stale")
|
||||
assert result["status"] == "generated"
|
||||
svc.suggest.assert_called_once()
|
||||
assert bucket.objects == {}
|
||||
|
||||
|
||||
def test_stale_takeover_loses_to_a_concurrent_takeover() -> None:
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
bucket = _FakeBucket()
|
||||
bucket.put_lease("j", 0)
|
||||
storage = SimpleNamespace(bucket=bucket)
|
||||
real_get_blob = bucket.get_blob
|
||||
|
||||
def _get_blob_then_race(path):
|
||||
observed = real_get_blob(path)
|
||||
bucket.put_lease("j", 0) # another instance takes over after our read
|
||||
return observed
|
||||
|
||||
bucket.get_blob = _get_blob_then_race
|
||||
assert w._acquire_lease(storage, "j") == (False, None)
|
||||
|
||||
|
||||
def test_own_lease_after_lost_create_response_counts_as_held(monkeypatch) -> None:
|
||||
"""Upload retry after a lost response 412s on our own write: still ours."""
|
||||
import json as _json
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
bucket = _FakeBucket()
|
||||
storage = SimpleNamespace(bucket=bucket)
|
||||
monkeypatch.setattr(w.uuid, "uuid4", lambda: SimpleNamespace(hex="mytoken"))
|
||||
real_blob = bucket.blob
|
||||
|
||||
def _blob_lost_response(path):
|
||||
b = real_blob(path)
|
||||
orig = b.upload_from_string
|
||||
|
||||
def _upload(data, content_type=None, if_generation_match=None):
|
||||
orig(data, content_type=content_type, if_generation_match=if_generation_match)
|
||||
raise gexc.PreconditionFailed("retry of a create that already landed")
|
||||
|
||||
b.upload_from_string = _upload
|
||||
return b
|
||||
|
||||
bucket.blob = _blob_lost_response
|
||||
held, gen = w._acquire_lease(storage, "j")
|
||||
assert held and gen == bucket.objects["jobs/j/lyrics/auto_correct_inflight.json"][0]
|
||||
assert _json.loads(bucket.objects["jobs/j/lyrics/auto_correct_inflight.json"][1])["token"] == "mytoken"
|
||||
|
||||
|
||||
def test_release_never_deletes_a_lease_someone_else_took_over() -> None:
|
||||
import time as _time
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
bucket = _FakeBucket()
|
||||
storage = SimpleNamespace(bucket=bucket)
|
||||
held, gen = w._acquire_lease(storage, "j")
|
||||
assert held and gen is not None
|
||||
bucket.put_lease("j", _time.time()) # superseded (e.g. our run outlived the TTL)
|
||||
w._release_lease(storage, "j", gen)
|
||||
assert "jobs/j/lyrics/auto_correct_inflight.json" in bucket.objects
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_peer_failure_does_not_regenerate(monkeypatch) -> None:
|
||||
import time as _time
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
monkeypatch.setattr(w, "PEER_POLL_SECONDS", 0)
|
||||
svc = MagicMock()
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
bucket.put_lease("job-peer-fail", _time.time())
|
||||
lease = "jobs/job-peer-fail/lyrics/auto_correct_inflight.json"
|
||||
|
||||
def _no_cache(*_a):
|
||||
bucket.objects.pop(lease, None) # peer finishes (fails) without writing a cache
|
||||
return None
|
||||
|
||||
with p_set, p_st, p_jm, \
|
||||
patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc), \
|
||||
patch("backend.services.auto_approval.executor._load_ai_suggestions", side_effect=_no_cache):
|
||||
result = await process_proactive_auto_correct("job-peer-fail")
|
||||
assert result == {"status": "skipped", "reason": "peer_failed"}
|
||||
svc.suggest.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timed_out_run_keeps_its_lease(monkeypatch) -> None:
|
||||
from backend.workers import auto_correct_worker as w
|
||||
|
||||
svc = MagicMock()
|
||||
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
|
||||
|
||||
async def _timeout(*_a, **_k):
|
||||
raise TimeoutError()
|
||||
|
||||
monkeypatch.setattr(w, "_run_suggest", _timeout)
|
||||
with p_set, p_st, p_jm:
|
||||
result = await process_proactive_auto_correct("job-slow")
|
||||
assert result["status"] == "error"
|
||||
# suggest() may still be running in its thread: the lease must stay until TTL.
|
||||
assert "jobs/job-slow/lyrics/auto_correct_inflight.json" in bucket.objects
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Unit tests for backend.services.published_outputs_cleanup (shared by Edit + admin re-render)."""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from backend.services import published_outputs_cleanup as cleanup
|
||||
|
||||
|
||||
class TestSnapshot:
|
||||
def test_only_present_published_keys(self):
|
||||
state = {"youtube_url": "https://youtu.be/a", "brand_code": "NOMAD-1", "dropbox_link": None,
|
||||
"instrumental_selection": "clean"}
|
||||
assert cleanup.snapshot_published_outputs(state) == {"youtube_url": "https://youtu.be/a",
|
||||
"brand_code": "NOMAD-1"}
|
||||
|
||||
def test_none(self):
|
||||
assert cleanup.snapshot_published_outputs(None) == {}
|
||||
|
||||
|
||||
class TestYouTube:
|
||||
def test_video_id_parsing(self):
|
||||
assert cleanup.youtube_video_id("https://www.youtube.com/watch?v=abc123&t=3") == "abc123"
|
||||
assert cleanup.youtube_video_id("https://youtu.be/xyz") == "xyz"
|
||||
assert cleanup.youtube_video_id("https://example.com") is None
|
||||
|
||||
def test_skipped_without_url(self):
|
||||
assert cleanup.delete_youtube_video("j", None)["status"] == "skipped"
|
||||
|
||||
def test_unparseable_url_fails(self):
|
||||
assert cleanup.delete_youtube_video("j", "https://example.com/v")["status"] == "failed"
|
||||
|
||||
def _patched(self, configured=True, delete_ok=True, raises=None):
|
||||
yt = MagicMock(is_configured=configured)
|
||||
yt.get_credentials_dict.return_value = {"token": "t"}
|
||||
finalise = MagicMock()
|
||||
finalise.return_value.delete_youtube_video.return_value = delete_ok
|
||||
if raises:
|
||||
finalise.return_value.delete_youtube_video.side_effect = raises
|
||||
return (patch("backend.services.youtube_service.get_youtube_service", return_value=yt),
|
||||
patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", finalise), finalise)
|
||||
|
||||
def test_deletes(self):
|
||||
p1, p2, finalise = self._patched()
|
||||
with p1, p2:
|
||||
result = cleanup.delete_youtube_video("j", "https://www.youtube.com/watch?v=abc123")
|
||||
assert result == {"status": "success", "video_id": "abc123"}
|
||||
finalise.return_value.delete_youtube_video.assert_called_once_with("abc123")
|
||||
|
||||
def test_not_configured(self):
|
||||
p1, p2, _ = self._patched(configured=False)
|
||||
with p1, p2:
|
||||
assert cleanup.delete_youtube_video("j", "https://youtu.be/a")["status"] == "skipped"
|
||||
|
||||
def test_error_never_raises(self):
|
||||
p1, p2, _ = self._patched(raises=RuntimeError("quotaExceeded"))
|
||||
with p1, p2:
|
||||
result = cleanup.delete_youtube_video("j", "https://youtu.be/a")
|
||||
assert result["status"] == "error" and "quotaExceeded" in result["error"]
|
||||
|
||||
|
||||
class TestDropbox:
|
||||
def test_folder_path_matches_distribution_sanitisation(self):
|
||||
with patch("karaoke_gen.utils.sanitize_filename", side_effect=lambda s: s.replace("/", "_")):
|
||||
assert cleanup.dropbox_folder_path("/K", "NOMAD-1", "AC/DC", "T") == "/K/NOMAD-1 - AC_DC - T"
|
||||
|
||||
def test_skipped_without_brand_code_or_path(self):
|
||||
assert cleanup.delete_dropbox_folder("j", None, "NOMAD-1", "A", "T")["status"] == "skipped"
|
||||
assert cleanup.delete_dropbox_folder("j", "/K", None, "A", "T")["status"] == "skipped"
|
||||
|
||||
def test_deletes(self):
|
||||
dropbox = MagicMock(is_configured=True)
|
||||
dropbox.delete_folder.return_value = True
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=dropbox):
|
||||
result = cleanup.delete_dropbox_folder("j", "/K", "NOMAD-1", "Artist", "Title")
|
||||
assert result == {"status": "success", "path": "/K/NOMAD-1 - Artist - Title",
|
||||
"deleted": ["/K/NOMAD-1 - Artist - Title"]}
|
||||
dropbox.file_exists.assert_not_called() # names identical: no probing
|
||||
|
||||
def test_error(self):
|
||||
dropbox = MagicMock(is_configured=True)
|
||||
dropbox.delete_folder.side_effect = RuntimeError("boom")
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=dropbox):
|
||||
assert cleanup.delete_dropbox_folder("j", "/K", "NOMAD-1", "A", "T")["status"] == "error"
|
||||
|
||||
|
||||
class TestGDrive:
|
||||
def test_skipped_without_files(self):
|
||||
assert cleanup.delete_gdrive_files("j", None)["status"] == "skipped"
|
||||
|
||||
def _gdrive(self, results):
|
||||
gdrive = MagicMock(is_configured=True)
|
||||
gdrive.delete_files.return_value = results
|
||||
return gdrive
|
||||
|
||||
def test_deletes_and_cleans_mirror_by_default(self):
|
||||
gdrive = self._gdrive({"g1": True, "g2": True})
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=gdrive), \
|
||||
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mirror:
|
||||
result = cleanup.delete_gdrive_files("j", {"mp4": "g1", "mp4_720p": "g2"}, "NOMAD-1")
|
||||
assert result["status"] == "success"
|
||||
gdrive.delete_files.assert_called_once_with(["g1", "g2"])
|
||||
mirror.assert_called_once_with("NOMAD-1")
|
||||
|
||||
def test_keeps_mirror_when_asked(self):
|
||||
gdrive = self._gdrive({"g1": False})
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=gdrive), \
|
||||
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mirror:
|
||||
result = cleanup.delete_gdrive_files("j", {"mp4": "g1"}, "NOMAD-1", cleanup_mirror=False)
|
||||
assert result["status"] == "partial"
|
||||
mirror.assert_not_called()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Render worker: translated lyrics are prepared before render and passed to the encoder."""
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.encoding_errors import EncodingWorkerCapacityError
|
||||
|
||||
|
||||
def _job(translation_language):
|
||||
job = MagicMock()
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
job.input_media_gcs_path = "jobs/test/audio.flac"
|
||||
job.style_assets = {}
|
||||
job.style_params_gcs_path = None
|
||||
job.subtitle_offset_ms = 0
|
||||
job.prep_only = False
|
||||
job.state_data = {}
|
||||
job.file_urls = {}
|
||||
job.translation_language = translation_language
|
||||
return job
|
||||
|
||||
|
||||
async def _render_config(translation_language, prepared_path):
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = _job(translation_language)
|
||||
job_manager.transition_to_state.return_value = True
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.is_enabled = True
|
||||
# Stop right after the render is submitted
|
||||
encoding_service.render_video_on_gce = AsyncMock(
|
||||
side_effect=EncodingWorkerCapacityError("full", vm_name="vm", zone="z", code="ZONE_RESOURCE_POOL_EXHAUSTED")
|
||||
)
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = False
|
||||
settings = MagicMock()
|
||||
settings.gcs_bucket_name = "bucket"
|
||||
|
||||
with patch.object(rvw, "JobManager", return_value=job_manager), \
|
||||
patch.object(rvw, "StorageService", return_value=storage), \
|
||||
patch.object(rvw, "get_settings", return_value=settings), \
|
||||
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
|
||||
patch.object(rvw, "validate_worker_can_run", return_value=None), \
|
||||
patch.object(rvw, "get_encoding_service", return_value=encoding_service), \
|
||||
patch.object(rvw, "prepare_job_translations", return_value=prepared_path) as prepare:
|
||||
await rvw.process_render_video("test-job-id")
|
||||
|
||||
prepare.assert_called_once()
|
||||
return encoding_service.render_video_on_gce.call_args[0][1]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_translations_path_passed_to_encoder():
|
||||
config = await _render_config("es", "jobs/test-job-id/lyrics/translations.json")
|
||||
assert config["translations_gcs_path"] == "gs://bucket/jobs/test-job-id/lyrics/translations.json"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_translations_when_not_prepared():
|
||||
config = await _render_config(None, None)
|
||||
assert "translations_gcs_path" not in config
|
||||
@@ -205,3 +205,27 @@ class TestSystemStatusAdmin:
|
||||
assert admin["active_zone"] == "us-central1-a"
|
||||
# "n2c" family token → n2-highcpu-16 (inferred from the VM name).
|
||||
assert admin["active_machine_type"] == "n2-highcpu-16"
|
||||
|
||||
|
||||
class TestAudioSeparatorStatus:
|
||||
"""Separation runs in the audio-separation-job GPU Cloud Run Job; the
|
||||
standalone audio-separator service was shut down (2026-10-01), so the
|
||||
status must not depend on AUDIO_SEPARATOR_API_URL or call anything."""
|
||||
|
||||
def test_reports_ok_without_api_url(self, monkeypatch):
|
||||
from backend.api.routes.health import check_audio_separator_status
|
||||
|
||||
monkeypatch.delenv("AUDIO_SEPARATOR_API_URL", raising=False)
|
||||
status = check_audio_separator_status()
|
||||
assert status["available"] is True
|
||||
assert status["status"] == "ok"
|
||||
assert status["mode"] == "gpu_job"
|
||||
assert "version" in status
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint_matches_status_helper(self):
|
||||
from backend.api.routes.health import audio_separator_health
|
||||
|
||||
from backend.api.routes.health import check_audio_separator_status
|
||||
|
||||
assert await audio_separator_health() == check_audio_separator_status()
|
||||
@@ -133,13 +133,37 @@ def fake_domains(monkeypatch):
|
||||
return d
|
||||
|
||||
|
||||
class FakeDropbox:
|
||||
"""Stand-in for DropboxService recording folder creation."""
|
||||
|
||||
def __init__(self):
|
||||
self.is_configured = True
|
||||
self.ensured = []
|
||||
self.fail = None
|
||||
|
||||
def ensure_folder(self, path):
|
||||
if self.fail:
|
||||
raise self.fail
|
||||
self.ensured.append(path)
|
||||
return True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_dropbox(monkeypatch):
|
||||
d = FakeDropbox()
|
||||
monkeypatch.setattr(tas, "get_dropbox_service", lambda: d)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def patch_singletons(fake_storage, fake_domains, monkeypatch):
|
||||
def patch_singletons(fake_storage, fake_domains, fake_dropbox, monkeypatch):
|
||||
"""Point the service's tenant/theme singletons at the fake storage."""
|
||||
monkeypatch.setattr(tas, "get_tenant_service", lambda: TenantService(storage=fake_storage))
|
||||
monkeypatch.setattr(tas, "get_theme_service", lambda: ThemeService(storage=fake_storage))
|
||||
# Ensure logo gs:// url is deterministic
|
||||
monkeypatch.setattr(tas.settings, "gcs_bucket_name", "test-bucket", raising=False)
|
||||
monkeypatch.setattr(tas.settings, "default_brand_prefix", "NOMAD", raising=False)
|
||||
monkeypatch.setattr(tas.settings, "default_private_brand_prefix", "NOMADNP", raising=False)
|
||||
return fake_storage
|
||||
|
||||
|
||||
@@ -331,7 +355,7 @@ def test_update_tenant_full_theme_and_config(fake_storage):
|
||||
}
|
||||
updated = tas.update_tenant(
|
||||
"randy-vild",
|
||||
config_updates={"name": "Randy Vild Deluxe", "defaults": {"brand_prefix": "RVD"}},
|
||||
config_updates={"name": "Randy Vild Deluxe", "defaults": {"dropbox_path": "/K/RV", "brand_prefix": "RVD"}},
|
||||
style_params=new_style,
|
||||
assets={"kbg.jpg": (b"replacement", "jpg")},
|
||||
storage=fake_storage,
|
||||
@@ -582,3 +606,135 @@ def test_delete_reports_storage_failure(fake_storage, monkeypatch):
|
||||
monkeypatch.setattr(fake_storage, "delete_folder", lambda prefix: 0) # GCS failure swallowed
|
||||
with pytest.raises(tas.TenantProvisioningError, match="retry"):
|
||||
tas.delete_tenant("randy-vild", storage=fake_storage)
|
||||
|
||||
|
||||
# --- Dropbox delivery (path + brand prefix + folder creation) -----------------
|
||||
|
||||
|
||||
def test_create_creates_dropbox_folder_and_normalizes(fake_storage, fake_dropbox):
|
||||
config = tas.create_tenant(
|
||||
name="Randy Vild",
|
||||
dropbox_path=" MediaUnsynced/Karaoke/Tracks-RandyVild/ ",
|
||||
brand_prefix="rvild",
|
||||
storage=fake_storage,
|
||||
)
|
||||
assert config.defaults.dropbox_path == "/MediaUnsynced/Karaoke/Tracks-RandyVild"
|
||||
assert config.defaults.brand_prefix == "RVILD"
|
||||
assert config.features.dropbox_upload is True
|
||||
assert fake_dropbox.ensured == ["/MediaUnsynced/Karaoke/Tracks-RandyVild"]
|
||||
|
||||
|
||||
def test_create_download_only_does_not_touch_dropbox(fake_storage, fake_dropbox):
|
||||
tas.create_tenant(name="Solo Client", storage=fake_storage)
|
||||
assert fake_dropbox.ensured == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path,prefix",
|
||||
[("/Karaoke/Tracks-X", None), (None, "XYZ")],
|
||||
)
|
||||
def test_create_requires_path_and_prefix_together(fake_storage, path, prefix):
|
||||
with pytest.raises(tas.TenantValidationError, match="both a Dropbox path and a brand prefix"):
|
||||
tas.create_tenant(name="Half Set", dropbox_path=path, brand_prefix=prefix, storage=fake_storage)
|
||||
assert "tenants/half-set/config.json" not in fake_storage.blobs
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", ["R", "1ABC", "RV-ILD", "TOOLONGPREFIX1"])
|
||||
def test_create_rejects_bad_brand_prefix(fake_storage, prefix):
|
||||
with pytest.raises(tas.TenantValidationError, match="Brand prefix"):
|
||||
tas.create_tenant(name="Bad Prefix", dropbox_path="/K/T", brand_prefix=prefix, storage=fake_storage)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", ["NOMAD", "nomadnp"])
|
||||
def test_create_rejects_reserved_brand_prefix(fake_storage, prefix):
|
||||
with pytest.raises(tas.TenantValidationError, match="reserved"):
|
||||
tas.create_tenant(name="Sneaky", dropbox_path="/K/T", brand_prefix=prefix, storage=fake_storage)
|
||||
|
||||
|
||||
def test_create_rejects_brand_prefix_used_by_other_tenant(fake_storage):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
with pytest.raises(tas.TenantConflictError, match="randy-vild"):
|
||||
tas.create_tenant(name="Copycat", dropbox_path="/K/CC", brand_prefix="RVILD", storage=fake_storage)
|
||||
|
||||
|
||||
def test_create_fails_before_any_write_when_folder_creation_fails(fake_storage, fake_dropbox):
|
||||
fake_dropbox.fail = RuntimeError("insufficient_space")
|
||||
with pytest.raises(tas.TenantProvisioningError, match="insufficient_space"):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
assert "tenants/randy-vild/config.json" not in fake_storage.blobs
|
||||
|
||||
|
||||
def test_create_fails_when_dropbox_not_configured(fake_storage, fake_dropbox):
|
||||
fake_dropbox.is_configured = False
|
||||
with pytest.raises(tas.TenantProvisioningError, match="isn't configured"):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
|
||||
|
||||
def test_update_enables_dropbox_delivery(fake_storage, fake_dropbox):
|
||||
tas.create_tenant(name="Randy Vild", storage=fake_storage)
|
||||
updated = tas.update_tenant(
|
||||
"randy-vild",
|
||||
config_updates={
|
||||
"defaults": {"dropbox_path": "/MediaUnsynced/Karaoke/Tracks-RandyVild", "brand_prefix": "rvild"},
|
||||
# a stale client flag must not win over the path
|
||||
"features": {"dropbox_upload": False},
|
||||
},
|
||||
storage=fake_storage,
|
||||
)
|
||||
assert updated.defaults.dropbox_path == "/MediaUnsynced/Karaoke/Tracks-RandyVild"
|
||||
assert updated.defaults.brand_prefix == "RVILD"
|
||||
assert updated.features.dropbox_upload is True
|
||||
assert fake_dropbox.ensured == ["/MediaUnsynced/Karaoke/Tracks-RandyVild"]
|
||||
|
||||
|
||||
def test_update_prefix_only_keeps_path_and_skips_folder(fake_storage, fake_dropbox):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
fake_dropbox.ensured.clear()
|
||||
updated = tas.update_tenant(
|
||||
"randy-vild", config_updates={"defaults": {"brand_prefix": "RVD"}}, storage=fake_storage
|
||||
)
|
||||
assert updated.defaults.dropbox_path == "/K/RV"
|
||||
assert updated.defaults.brand_prefix == "RVD"
|
||||
assert fake_dropbox.ensured == [] # path unchanged → no Dropbox call
|
||||
|
||||
|
||||
def test_update_clearing_both_disables_dropbox(fake_storage):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
updated = tas.update_tenant(
|
||||
"randy-vild",
|
||||
config_updates={"defaults": {"dropbox_path": None, "brand_prefix": None}},
|
||||
storage=fake_storage,
|
||||
)
|
||||
assert updated.defaults.dropbox_path is None
|
||||
assert updated.features.dropbox_upload is False
|
||||
|
||||
|
||||
def test_update_rejects_path_without_prefix(fake_storage):
|
||||
tas.create_tenant(name="Randy Vild", storage=fake_storage)
|
||||
with pytest.raises(tas.TenantValidationError):
|
||||
tas.update_tenant(
|
||||
"randy-vild", config_updates={"defaults": {"dropbox_path": "/K/RV"}}, storage=fake_storage
|
||||
)
|
||||
|
||||
|
||||
def test_update_keeping_own_prefix_is_not_a_conflict(fake_storage):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
updated = tas.update_tenant(
|
||||
"randy-vild",
|
||||
config_updates={"defaults": {"dropbox_path": "/K/RV2", "brand_prefix": "RVILD"}},
|
||||
storage=fake_storage,
|
||||
)
|
||||
assert updated.defaults.dropbox_path == "/K/RV2"
|
||||
|
||||
|
||||
def test_list_tenants_includes_brand_prefix(fake_storage):
|
||||
tas.create_tenant(name="Randy Vild", dropbox_path="/K/RV", brand_prefix="RVILD", storage=fake_storage)
|
||||
assert tas.list_tenants(storage=fake_storage)[0]["brand_prefix"] == "RVILD"
|
||||
|
||||
|
||||
def test_update_features_only_cannot_desync_dropbox_flag(fake_storage):
|
||||
tas.create_tenant(name="Randy Vild", storage=fake_storage)
|
||||
updated = tas.update_tenant(
|
||||
"randy-vild", config_updates={"features": {"dropbox_upload": True}}, storage=fake_storage
|
||||
)
|
||||
assert updated.features.dropbox_upload is False # no path → flag stays off
|
||||
@@ -0,0 +1,385 @@
|
||||
"""
|
||||
Tests for re-rendering a finished tenant track with the tenant's current theme.
|
||||
|
||||
Covers validation, the service (theme re-snapshot, atomic claim, artifact
|
||||
cleanup, screens-worker trigger + rollback), the POST /api/jobs/{id}/rerender
|
||||
route (ownership, tenant allowlist), and the encoding-worker id keying that
|
||||
stops a re-run from getting the previous run's cached render/encode back.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderConflictError,
|
||||
RerenderError,
|
||||
ThemeRerenderService,
|
||||
validate_rerender,
|
||||
)
|
||||
from backend.workers.supersede import encoding_worker_job_id
|
||||
|
||||
|
||||
def _job(**overrides):
|
||||
fields = dict(
|
||||
job_id="job123",
|
||||
status="complete",
|
||||
tenant_id="randy-vild",
|
||||
user_email="randy@example.com",
|
||||
theme_id="randy-vild",
|
||||
color_overrides={},
|
||||
outputs_deleted_at=None,
|
||||
prep_only=False,
|
||||
finalise_only=False,
|
||||
state_data={"instrumental_selection": "custom"},
|
||||
file_urls={"lyrics": {"corrections": "jobs/job123/lyrics/corrections.json"}},
|
||||
)
|
||||
fields.update(overrides)
|
||||
return SimpleNamespace(**fields)
|
||||
|
||||
|
||||
class TestValidateRerender:
|
||||
def test_valid_tenant_job(self):
|
||||
assert validate_rerender(_job()) is None
|
||||
|
||||
@pytest.mark.parametrize("overrides, fragment", [
|
||||
({"tenant_id": None}, "portal tracks"),
|
||||
({"status": "rendering_video"}, "Only finished tracks"),
|
||||
({"outputs_deleted_at": "2026-09-29T18:47:13Z"}, "outputs were deleted"),
|
||||
({"theme_id": None}, "wasn't made from a theme"),
|
||||
({"prep_only": True}, "can't be re-rendered"),
|
||||
({"state_data": {}}, "instrumental selection"),
|
||||
({"file_urls": {}}, "reviewed lyrics"),
|
||||
({"state_data": {"instrumental_selection": "clean", "dropbox_link": "https://db"}}, "Dropbox folder"),
|
||||
({"state_data": {"instrumental_selection": "clean", "youtube_url": "https://yt"}}, "published"),
|
||||
({"state_data": {"instrumental_selection": "clean", "gdrive_files": {"mp4": "x"}}}, "published"),
|
||||
])
|
||||
def test_rejections(self, overrides, fragment):
|
||||
assert fragment in validate_rerender(_job(**overrides))
|
||||
|
||||
|
||||
def _service(claim_status="complete", trigger_ok=True):
|
||||
"""ThemeRerenderService wired to a fake Firestore transaction + storage."""
|
||||
job_manager = MagicMock()
|
||||
doc_ref = MagicMock()
|
||||
snapshot = MagicMock(exists=True)
|
||||
snapshot.to_dict.return_value = {"status": claim_status}
|
||||
doc_ref.get.return_value = snapshot
|
||||
job_manager.firestore.db.collection.return_value.document.return_value = doc_ref
|
||||
storage = MagicMock()
|
||||
worker_service = MagicMock()
|
||||
worker_service.trigger_screens_worker = AsyncMock(return_value=trigger_ok)
|
||||
return ThemeRerenderService(job_manager=job_manager, storage=storage), doc_ref, storage, worker_service
|
||||
|
||||
|
||||
def _passthrough_transactional(fn):
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patched_deps():
|
||||
prepare = MagicMock(return_value=(
|
||||
"jobs/job123/style/style_params.json",
|
||||
{"karaoke_background": "themes/randy-vild/assets/bg-new.jpg"},
|
||||
None,
|
||||
))
|
||||
with patch("backend.api.routes.file_upload._prepare_theme_for_job", prepare), \
|
||||
patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional):
|
||||
yield prepare
|
||||
|
||||
|
||||
class TestThemeRerenderService:
|
||||
@pytest.mark.asyncio
|
||||
async def test_resnapshots_theme_claims_and_triggers_screens(self, patched_deps):
|
||||
service, doc_ref, storage, worker_service = _service()
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="randy@example.com")
|
||||
|
||||
patched_deps.assert_called_once_with("job123", "randy-vild", None)
|
||||
transaction.update.assert_called_once()
|
||||
update = transaction.update.call_args.args[1]
|
||||
assert update["status"] == "lyrics_complete"
|
||||
assert update["state_data.regen_restore_status"] == "review_complete"
|
||||
assert update["style_params_gcs_path"] == "jobs/job123/style/style_params.json"
|
||||
assert update["style_assets"] == {"karaoke_background": "themes/randy-vild/assets/bg-new.jpg"}
|
||||
assert update["theme_id"] == "randy-vild"
|
||||
for key in ("screens_progress", "render_progress", "video_progress", "encoding_progress"):
|
||||
assert update[f"state_data.{key}"] is DELETE_FIELD
|
||||
assert update["file_urls.screens"] is DELETE_FIELD
|
||||
assert update["file_urls.videos.with_vocals"] is DELETE_FIELD
|
||||
|
||||
deleted = {c.args[0] for c in storage.delete_file.call_args_list}
|
||||
assert "jobs/job123/screens/title.mov" in deleted
|
||||
assert "jobs/job123/screens/end.png" in deleted
|
||||
assert "jobs/job123/videos/with_vocals.mkv" in deleted
|
||||
assert all(c.kwargs.get("ignore_missing") for c in storage.delete_file.call_args_list)
|
||||
|
||||
worker_service.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_passes_color_overrides(self, patched_deps):
|
||||
service, _, _, worker_service = _service()
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(_job(color_overrides={"sung": "#fff"}), theme_id="t", requested_by="x")
|
||||
patched_deps.assert_called_once_with("job123", "t", {"sung": "#fff"})
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conflict_when_job_no_longer_complete(self, patched_deps):
|
||||
"""A double-click: the second claim sees the job already re-rendering."""
|
||||
service, _, storage, worker_service = _service(claim_status="lyrics_complete")
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
with pytest.raises(RerenderConflictError):
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="x")
|
||||
|
||||
transaction.update.assert_not_called()
|
||||
storage.delete_file.assert_not_called()
|
||||
worker_service.trigger_screens_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restores_complete_when_trigger_fails(self, patched_deps):
|
||||
service, _, _, worker_service = _service(trigger_ok=False)
|
||||
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
with pytest.raises(RerenderError) as exc:
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="x")
|
||||
|
||||
assert exc.value.status_code == 503
|
||||
restore = service.job_manager.update_job.call_args.args[1]
|
||||
assert restore["status"] == "complete"
|
||||
assert restore["state_data.regen_restore_status"] is DELETE_FIELD
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_job_rejected_before_any_work(self, patched_deps):
|
||||
service, _, storage, _ = _service()
|
||||
with pytest.raises(RerenderError):
|
||||
await service.start(_job(tenant_id=None), theme_id="t", requested_by="x")
|
||||
patched_deps.assert_not_called()
|
||||
storage.delete_file.assert_not_called()
|
||||
|
||||
|
||||
class TestRerenderReviewFixes:
|
||||
@pytest.mark.asyncio
|
||||
async def test_deletes_old_title_end_movs_from_finals(self, patched_deps):
|
||||
"""The encoder globs **/*Title*.mov — an old finals MOV would be spliced in."""
|
||||
service, _, storage, worker_service = _service()
|
||||
storage.list_files.return_value = [
|
||||
"jobs/job123/finals/Randy Vild - What Goes Up (Title).mov",
|
||||
"jobs/job123/finals/Randy Vild - What Goes Up (End).mov",
|
||||
"jobs/job123/finals/title_mov.mov",
|
||||
"jobs/job123/finals/end_mov.mov",
|
||||
"jobs/job123/finals/lossy_4k_mp4.mp4",
|
||||
"jobs/job123/finals/lossless_4k_mkv.mkv",
|
||||
]
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="x")
|
||||
|
||||
storage.list_files.assert_called_once_with("jobs/job123/finals/")
|
||||
deleted = {c.args[0] for c in storage.delete_file.call_args_list}
|
||||
assert "jobs/job123/finals/Randy Vild - What Goes Up (Title).mov" in deleted
|
||||
assert "jobs/job123/finals/Randy Vild - What Goes Up (End).mov" in deleted
|
||||
assert "jobs/job123/finals/title_mov.mov" in deleted
|
||||
assert "jobs/job123/finals/end_mov.mov" in deleted
|
||||
assert "jobs/job123/finals/lossy_4k_mp4.mp4" not in deleted
|
||||
assert "jobs/job123/finals/lossless_4k_mkv.mkv" not in deleted
|
||||
|
||||
def test_failed_rerender_is_rerenderable(self):
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "custom",
|
||||
"theme_rerender": {"theme_id": "randy-vild"}})
|
||||
assert validate_rerender(job) is None
|
||||
|
||||
def test_failed_ordinary_job_is_not_rerenderable(self):
|
||||
assert "Only finished tracks" in validate_rerender(_job(status="failed"))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claims_failed_rerender(self, patched_deps):
|
||||
service, _, _, worker_service = _service(claim_status="failed")
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "custom",
|
||||
"theme_rerender": {"theme_id": "randy-vild"}})
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(job, theme_id="randy-vild", requested_by="x")
|
||||
transaction.update.assert_called_once()
|
||||
assert transaction.update.call_args.args[1]["error_message"] is None
|
||||
worker_service.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
|
||||
|
||||
class TestDropboxArchivedTenantJobs:
|
||||
"""Tenants like randy-vild archive to Dropbox (RVILD-0001 - Artist - Title)."""
|
||||
|
||||
def test_dropbox_archived_job_with_brand_code_is_rerenderable(self):
|
||||
job = _job(state_data={"instrumental_selection": "custom",
|
||||
"dropbox_link": "https://db", "brand_code": "RVILD-0001"})
|
||||
assert validate_rerender(job) is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_marker_records_brand_code_to_reuse(self, patched_deps):
|
||||
service, _, _, worker_service = _service()
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
job = _job(state_data={"instrumental_selection": "custom",
|
||||
"dropbox_link": "https://db", "brand_code": "RVILD-0001"})
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(job, theme_id="randy-vild", requested_by="x")
|
||||
marker = transaction.update.call_args.args[1]["state_data.theme_rerender"]
|
||||
assert marker["brand_code"] == "RVILD-0001"
|
||||
|
||||
def test_rerender_brand_code(self):
|
||||
from backend.services.theme_rerender_service import rerender_brand_code
|
||||
assert rerender_brand_code(_job(state_data={"theme_rerender": {"brand_code": "RVILD-0001"}})) == "RVILD-0001"
|
||||
assert rerender_brand_code(_job(state_data={"brand_code": "RVILD-0001"})) is None
|
||||
assert rerender_brand_code(_job(state_data=None)) is None
|
||||
|
||||
def test_orchestrator_keeps_brand_code_during_rerender(self):
|
||||
"""Refresh the existing Dropbox folder instead of allocating RVILD-0002."""
|
||||
from backend.workers.video_worker_orchestrator import create_orchestrator_config_from_job
|
||||
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist = "A"
|
||||
job.title = "T"
|
||||
job.keep_brand_code = None
|
||||
job.state_data = {"instrumental_selection": "custom", "brand_code": "RVILD-0001",
|
||||
"theme_rerender": {"brand_code": "RVILD-0001"}}
|
||||
job.file_urls = {}
|
||||
config = create_orchestrator_config_from_job(job, temp_dir="/tmp/x")
|
||||
assert config.keep_brand_code == "RVILD-0001"
|
||||
|
||||
|
||||
class TestEncodingWorkerJobId:
|
||||
def test_generation_zero_keeps_plain_job_id(self):
|
||||
assert encoding_worker_job_id("job123", 0) == "job123"
|
||||
|
||||
def test_generation_suffixes_job_id(self):
|
||||
assert encoding_worker_job_id("job123", 3) == "job123_g3"
|
||||
|
||||
def test_orchestrator_config_captures_generation(self):
|
||||
from backend.workers.video_worker_orchestrator import create_orchestrator_config_from_job
|
||||
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist = "A"
|
||||
job.title = "T"
|
||||
job.state_data = {"worker_generation": 4, "instrumental_selection": "clean"}
|
||||
job.file_urls = {}
|
||||
config = create_orchestrator_config_from_job(job, temp_dir="/tmp/x")
|
||||
assert config.worker_generation == 4
|
||||
|
||||
|
||||
# --- Route ---------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
from backend.main import app
|
||||
yield TestClient(app), app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def _auth(email="randy@example.com", is_admin=False):
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN if is_admin else UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="Valid",
|
||||
user_email=email,
|
||||
is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def _call(client, auth, job, tenant, start=None):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
async def override():
|
||||
return auth
|
||||
|
||||
app.dependency_overrides[require_auth] = override
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
tenant_service = MagicMock()
|
||||
tenant_service.get_tenant_config.return_value = tenant
|
||||
start = start or AsyncMock()
|
||||
with patch("backend.api.routes.jobs.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.tenant_service.get_tenant_service", return_value=tenant_service), \
|
||||
patch.object(ThemeRerenderService, "start", start):
|
||||
return test_client.post(f"/api/jobs/{job.job_id}/rerender"), start
|
||||
|
||||
|
||||
def _tenant(allowed=True, active=True):
|
||||
tenant = MagicMock()
|
||||
tenant.is_active = active
|
||||
tenant.is_email_allowed.return_value = allowed
|
||||
tenant.defaults.locked_theme = "randy-vild"
|
||||
tenant.defaults.theme_id = None
|
||||
tenant.id = "randy-vild"
|
||||
return tenant
|
||||
|
||||
|
||||
class TestRerenderRoute:
|
||||
def test_owner_starts_rerender_with_tenant_theme(self, client):
|
||||
job = _job()
|
||||
resp, start = _call(client, _auth(), job, _tenant())
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["theme_id"] == "randy-vild"
|
||||
start.assert_awaited_once()
|
||||
assert start.await_args.kwargs["theme_id"] == "randy-vild"
|
||||
assert start.await_args.kwargs["requested_by"] == "randy@example.com"
|
||||
|
||||
def test_non_owner_forbidden(self, client):
|
||||
resp, start = _call(client, _auth(email="someone@else.com"), _job(), _tenant())
|
||||
assert resp.status_code == 403
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_owner_removed_from_allowlist_forbidden(self, client):
|
||||
resp, start = _call(client, _auth(), _job(), _tenant(allowed=False))
|
||||
assert resp.status_code == 403
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_admin_allowed_on_any_job(self, client):
|
||||
resp, start = _call(client, _auth(email="admin@nomadkaraoke.com", is_admin=True), _job(), _tenant(allowed=False))
|
||||
assert resp.status_code == 200
|
||||
start.assert_awaited_once()
|
||||
|
||||
def test_consumer_job_rejected(self, client):
|
||||
resp, start = _call(client, _auth(), _job(tenant_id=None), _tenant())
|
||||
assert resp.status_code == 400
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_inactive_tenant_rejected(self, client):
|
||||
resp, start = _call(client, _auth(), _job(), _tenant(active=False))
|
||||
assert resp.status_code == 400
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_conflict_maps_to_409(self, client):
|
||||
start = AsyncMock(side_effect=RerenderConflictError("already"))
|
||||
resp, _ = _call(client, _auth(), _job(), _tenant(), start=start)
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
class TestRetryAfterFailedRerender:
|
||||
def test_retry_reruns_rerender_when_screens_missing(self, client):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
async def override():
|
||||
return _auth()
|
||||
|
||||
app.dependency_overrides[require_auth] = override
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "custom",
|
||||
"theme_rerender": {"theme_id": "randy-vild"}})
|
||||
job.error_details = {"stage": "screens"}
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
start = AsyncMock()
|
||||
with patch("backend.api.routes.jobs.job_manager", job_manager), \
|
||||
patch("backend.api.routes.jobs.JobManager", return_value=job_manager), \
|
||||
patch.object(ThemeRerenderService, "start", start):
|
||||
resp = test_client.post("/api/jobs/job123/retry")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["retry_stage"] == "theme_rerender"
|
||||
assert start.await_args.kwargs["theme_id"] == "randy-vild"
|
||||
@@ -1222,8 +1222,42 @@ class TestVideoWorkerOrchestratorDistribution:
|
||||
await orchestrator._upload_to_youtube()
|
||||
|
||||
mock_service.upload_video.assert_called_once()
|
||||
assert mock_service.upload_video.call_args.kwargs["title"] == "Test Artist - Test Title (Karaoke)"
|
||||
assert orchestrator.result.youtube_url == "https://youtube.com/watch?v=video123"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_to_youtube_labels_translated_video(self):
|
||||
"""A video showing translated lyrics says so in its YouTube title + description."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
video_file = os.path.join(temp_dir, "test.mp4")
|
||||
with open(video_file, "w") as f:
|
||||
f.write("dummy video")
|
||||
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Manel",
|
||||
title="Benvolgut",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_youtube_upload=True,
|
||||
youtube_credentials={"token": "test"},
|
||||
translation_language_name="English",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.final_video_lossy = video_file
|
||||
|
||||
with patch.object(orchestrator, "_get_youtube_service") as mock_get:
|
||||
mock_service = MagicMock()
|
||||
mock_service.upload_video.return_value = ("v", "https://youtube.com/watch?v=v")
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
await orchestrator._upload_to_youtube()
|
||||
|
||||
kwargs = mock_service.upload_video.call_args.kwargs
|
||||
assert kwargs["title"] == "Manel - Benvolgut (With Translation into English) (Karaoke)"
|
||||
assert "translated lyrics (English)" in kwargs["description"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_to_dropbox(self):
|
||||
"""Test Dropbox upload."""
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
Regression: a successful render must clear ``outputs_deleted_at``.
|
||||
|
||||
The edit flow (and admin "delete outputs") sets ``outputs_deleted_at``; the
|
||||
frontend hides every download while it is set. The flag used to be cleared only
|
||||
when the orchestrator uploaded to YouTube/Dropbox/GDrive, so an edited tenant job
|
||||
(which never distributes anywhere) re-rendered fresh finals but kept showing no
|
||||
download buttons forever (job 2579a1ea, randy-vild, 2026-09-29).
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers import video_worker
|
||||
|
||||
|
||||
def _orchestrator_result(**overrides):
|
||||
fields = dict(
|
||||
success=True,
|
||||
error_message=None,
|
||||
brand_code=None,
|
||||
youtube_url=None,
|
||||
youtube_upload_queued=False,
|
||||
dropbox_link=None,
|
||||
gdrive_files={},
|
||||
distribution_warnings=[],
|
||||
final_video=None,
|
||||
final_video_mkv=None,
|
||||
final_video_lossy=None,
|
||||
final_video_720p=None,
|
||||
final_with_vocals_mp4=None,
|
||||
final_karaoke_cdg_zip=None,
|
||||
final_karaoke_txt_zip=None,
|
||||
title_mov=None,
|
||||
end_mov=None,
|
||||
portrait_video=None,
|
||||
)
|
||||
fields.update(overrides)
|
||||
return SimpleNamespace(**fields)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_render_clears_outputs_deleted_without_distribution():
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist = "Randy Vild"
|
||||
job.title = "What Goes Up"
|
||||
job.tenant_id = "randy-vild"
|
||||
job.enable_youtube_upload = False
|
||||
job.is_private = False
|
||||
job.organised_dir_rclone_root = None
|
||||
job.edit_count = 1
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
orchestrator = MagicMock()
|
||||
orchestrator.run = AsyncMock(return_value=_orchestrator_result())
|
||||
|
||||
style_config = MagicMock()
|
||||
style_config.get_cdg_styles.return_value = None
|
||||
|
||||
with patch.object(video_worker, "JobManager", return_value=job_manager), \
|
||||
patch.object(video_worker, "StorageService", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "setup_job_logging", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "_validate_prerequisites", return_value=True), \
|
||||
patch("backend.services.job_health_service.validate_worker_can_run", return_value=None), \
|
||||
patch.object(video_worker, "_setup_working_directory", new=AsyncMock()), \
|
||||
patch.object(video_worker, "load_style_config", new=AsyncMock(return_value=style_config)), \
|
||||
patch("backend.workers.video_worker_orchestrator.create_orchestrator_config_from_job", return_value=MagicMock()), \
|
||||
patch("backend.workers.video_worker_orchestrator.VideoWorkerOrchestrator", return_value=orchestrator), \
|
||||
patch.object(video_worker, "_handle_native_distribution", new=AsyncMock()), \
|
||||
patch.object(video_worker, "_upload_results", new=AsyncMock()), \
|
||||
patch.object(video_worker, "_store_video_processing_metadata"):
|
||||
ok = await video_worker.generate_video_orchestrated("job123")
|
||||
|
||||
assert ok is True
|
||||
payloads = [c.args[1] for c in job_manager.update_job.call_args_list]
|
||||
cleared = [p for p in payloads if "outputs_deleted_at" in p]
|
||||
assert cleared, f"no update cleared outputs_deleted_at; updates were {payloads}"
|
||||
assert cleared[0]["outputs_deleted_at"] is None
|
||||
assert cleared[0]["outputs_deleted_by"] is None
|
||||
@@ -3,9 +3,12 @@ import pytest
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.youtube_description import (
|
||||
YOUTUBE_TITLE_MAX,
|
||||
build_youtube_tags,
|
||||
build_youtube_title,
|
||||
hashtagify,
|
||||
render_youtube_description,
|
||||
translated_language_name,
|
||||
)
|
||||
|
||||
|
||||
@@ -109,3 +112,35 @@ class TestBuildTags:
|
||||
tags = build_youtube_tags("A" * 300, "B" * 300)
|
||||
total = sum(len(t) + 1 for t in tags)
|
||||
assert total <= 460
|
||||
|
||||
|
||||
class TestTranslationLabel:
|
||||
"""Published videos with translated lyrics say so (Andrew: like the tempo label)."""
|
||||
|
||||
def test_only_a_successful_translation_counts(self):
|
||||
assert translated_language_name({"lyrics_translation": {"language": "es", "status": "translated"}}) == "Spanish"
|
||||
assert translated_language_name({"lyrics_translation": {"language": "es", "status": "failed"}}) is None
|
||||
assert translated_language_name({"lyrics_translation": {"language": "es", "status": "same_language"}}) is None
|
||||
assert translated_language_name({}) is None
|
||||
assert translated_language_name(None) is None
|
||||
|
||||
def test_untranslated_title_unchanged(self):
|
||||
assert build_youtube_title("Manel", "Benvolgut") == "Manel - Benvolgut (Karaoke)"
|
||||
|
||||
def test_translated_title_label_before_karaoke(self):
|
||||
assert (
|
||||
build_youtube_title("Manel", "Benvolgut", "English")
|
||||
== "Manel - Benvolgut (With Translation into English) (Karaoke)"
|
||||
)
|
||||
|
||||
def test_long_title_truncates_song_not_label(self):
|
||||
out = build_youtube_title("A Very Long Artist Name Indeed", "An Extremely Long Song Title That Goes On And On", "Portuguese")
|
||||
assert len(out) <= YOUTUBE_TITLE_MAX
|
||||
assert out.endswith(" ... (With Translation into Portuguese) (Karaoke)")
|
||||
assert out.startswith("A Very Long Artist Name Indeed - ")
|
||||
|
||||
def test_description_notice(self):
|
||||
desc = render_youtube_description("Manel", "Benvolgut", template="Body", translation_language_name="English")
|
||||
assert desc.startswith("This karaoke video includes translated lyrics (English) beneath each line.")
|
||||
assert desc.endswith("Body")
|
||||
assert "translation" not in render_youtube_description("Manel", "Benvolgut", template="Body")
|
||||
@@ -267,15 +267,57 @@ class TestUpdateJobYouTubeUrl:
|
||||
# (which would clobber a concurrently-changed sibling like brand_code).
|
||||
assert "state_data" not in payload
|
||||
|
||||
def test_handles_missing_job(self):
|
||||
"""Should not raise when job not found."""
|
||||
def test_missing_job_raises(self):
|
||||
"""A missing job must surface as a failure, so the processor flags the
|
||||
queue entry needs_attention instead of silently losing the URL."""
|
||||
from backend.workers.youtube_queue_processor import _update_job_youtube_url
|
||||
|
||||
mock_job_manager = Mock()
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.JobManager', return_value=mock_job_manager):
|
||||
# Should not raise
|
||||
_update_job_youtube_url("nonexistent", "https://youtube.com/watch?v=abc")
|
||||
with pytest.raises(RuntimeError, match="not found"):
|
||||
_update_job_youtube_url("nonexistent", "https://youtube.com/watch?v=abc")
|
||||
|
||||
mock_job_manager.update_job.assert_not_called()
|
||||
|
||||
def test_update_failure_propagates(self):
|
||||
from backend.workers.youtube_queue_processor import _update_job_youtube_url
|
||||
|
||||
mock_job_manager = Mock()
|
||||
mock_job_manager.get_job.return_value = Mock(state_data={})
|
||||
mock_job_manager.update_job.side_effect = RuntimeError("firestore down")
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.JobManager', return_value=mock_job_manager):
|
||||
with pytest.raises(RuntimeError, match="firestore down"):
|
||||
_update_job_youtube_url("job-123", "https://youtube.com/watch?v=abc")
|
||||
|
||||
|
||||
class TestProcessSingleUploadTranslationLabel:
|
||||
"""Queued uploads label translated videos exactly like the live upload path."""
|
||||
|
||||
def test_translated_job_title_and_description_labelled(self, tmp_path):
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from backend.workers.youtube_queue_processor import _process_single_upload
|
||||
|
||||
job = SimpleNamespace(
|
||||
job_id="job-tr", artist="Manel", title="Benvolgut",
|
||||
state_data={"lyrics_translation": {"language": "en", "status": "translated"}},
|
||||
)
|
||||
youtube = MagicMock()
|
||||
youtube.upload_video.return_value = ("vid", "https://youtube.com/watch?v=vid")
|
||||
settings = SimpleNamespace(default_youtube_description="Body")
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.JobManager') as jm, \
|
||||
patch('backend.workers.youtube_queue_processor.StorageService'), \
|
||||
patch('backend.workers.youtube_queue_processor._download_video_from_gcs', return_value=str(tmp_path / "v.mkv")), \
|
||||
patch('backend.workers.youtube_queue_processor._download_thumbnail_from_gcs', return_value=None), \
|
||||
patch('backend.workers.youtube_queue_processor._create_youtube_service', return_value=youtube):
|
||||
jm.return_value.get_job.return_value = job
|
||||
url = asyncio.run(_process_single_upload("job-tr", {}, MagicMock(), settings))
|
||||
|
||||
assert url == "https://youtube.com/watch?v=vid"
|
||||
kwargs = youtube.upload_video.call_args.kwargs
|
||||
assert kwargs["title"] == "Manel - Benvolgut (With Translation into English) (Karaoke)"
|
||||
assert kwargs["description"].startswith("This karaoke video includes translated lyrics (English)")
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "We couldn't find your uploaded instrumental. The upload may not have finished. Please try again.",
|
||||
"uploadDurationMismatchCancelled": "The instrumental ({instrumental_duration}s) doesn't line up with the song audio ({audio_duration}s), so it may be the wrong file for this song. This job has been cancelled and your credit refunded. Please check the files and submit again.",
|
||||
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead.",
|
||||
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment."
|
||||
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment.",
|
||||
"adminRerenderRetryAdminOnly": "This track is being re-rendered by our team, so it can only be retried by an admin. Please contact support and we'll finish it for you."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "تعذر العثور على ملف الموسيقى الآلية الذي قمت برفعه. قد لا يكون الرفع قد اكتمل بعد. يُرجى المحاولة مرة أخرى.",
|
||||
"uploadDurationMismatchCancelled": "لا تتطابق مدة المسار الموسيقي ({instrumental_duration} ثانية) مع مدة صوت الأغنية ({audio_duration} ثانية)، لذا قد يكون الملف غير صحيح لهذه الأغنية. تم إلغاء هذه المهمة واسترداد رصيدك. يُرجى التحقق من الملفات وإعادة المحاولة.",
|
||||
"instrumentalUploadTooLarge": "حجم هذا الملف الموسيقي هو {size_mb} ميجابايت، وهو ما يتجاوز الحد المسموح به البالغ {max_mb} ميجابايت. يُرجى رفع نسخة بصيغة FLAC أو MP3 بدلاً من ذلك.",
|
||||
"instrumentalConformUnavailable": "لم نتمكن من معالجة المقطع الموسيقي الخاص بك الآن. يُرجى محاولة الإرسال مجدداً بعد لحظات."
|
||||
"instrumentalConformUnavailable": "لم نتمكن من معالجة المقطع الموسيقي الخاص بك الآن. يُرجى محاولة الإرسال مجدداً بعد لحظات.",
|
||||
"adminRerenderRetryAdminOnly": "يعمل فريقنا على إعادة تصيير هذا المسار، لذا لا يمكن إعادة المحاولة إلا من قِبل مسؤول. يُرجى التواصل مع الدعم وسنكمله لك."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "المهمة غير موجودة",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "No hem pogut trobar l'instrumental que has pujat. És possible que la pujada no s'hagi completat. Si us plau, torna-ho a intentar.",
|
||||
"uploadDurationMismatchCancelled": "L'instrumental ({instrumental_duration}s) no coincideix amb l'àudio de la cançó ({audio_duration}s), per la qual cosa podria ser el fitxer equivocat per a aquesta cançó. Aquesta tasca s'ha cancel·lat i se t'ha reemborsat el crèdit. Comprova els fitxers i torna-ho a enviar.",
|
||||
"instrumentalUploadTooLarge": "Aquest fitxer instrumental fa {size_mb} MB, que supera el límit de {max_mb} MB. Si us plau, penja una versió en FLAC o MP3 en comptes d'això.",
|
||||
"instrumentalConformUnavailable": "No hem pogut processar el teu instrumental ara mateix. Si us plau, torna-ho a enviar d'aquí a un moment."
|
||||
"instrumentalConformUnavailable": "No hem pogut processar el teu instrumental ara mateix. Si us plau, torna-ho a enviar d'aquí a un moment.",
|
||||
"adminRerenderRetryAdminOnly": "Aquesta pista l'està tornant a renderitzar el nostre equip, així que només la pot reintentar un administrador. Posa't en contacte amb el servei de suport i te l'acabarem."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tasca no trobada",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nepodařilo se najít tvůj nahraný instrumentál. Nahrávání možná nebylo dokončeno. Zkus to prosím znovu.",
|
||||
"uploadDurationMismatchCancelled": "Instrumentální stopa ({instrumental_duration}s) časově nesedí se zvukem skladby ({audio_duration}s), takže může jít o nesprávný soubor pro tuto skladbu. Tato úloha byla zrušena a tvůj kredit byl vrácen. Zkontroluj prosím soubory a odešli je znovu.",
|
||||
"instrumentalUploadTooLarge": "Tento instrumentální soubor má {size_mb} MB, což překračuje limit {max_mb} MB. Nahraj prosím místo toho verzi ve formátu FLAC nebo MP3.",
|
||||
"instrumentalConformUnavailable": "Právě se nám nepodařilo zpracovat tvůj instrumentál. Zkus to prosím za chvíli odeslat znovu."
|
||||
"instrumentalConformUnavailable": "Právě se nám nepodařilo zpracovat tvůj instrumentál. Zkus to prosím za chvíli odeslat znovu.",
|
||||
"adminRerenderRetryAdminOnly": "Tuto skladbu právě znovu renderuje náš tým, takže ji může znovu spustit pouze administrátor. Kontaktuj prosím podporu a my to pro tebe dokončíme."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha nebyla nalezena",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Vi kunne ikke finde din uploadede instrumental. Uploaden blev muligvis ikke fuldført. Prøv venligst igen.",
|
||||
"uploadDurationMismatchCancelled": "Instrumentalsporet ({instrumental_duration}s) stemmer ikke overens med sangens lydspor ({audio_duration}s), så det er muligvis den forkerte fil til denne sang. Denne opgave er blevet annulleret, og din kredit er blevet refunderet. Tjek venligst filerne, og indsend igen.",
|
||||
"instrumentalUploadTooLarge": "Denne instrumentalfil er på {size_mb} MB, hvilket overskrider grænsen på {max_mb} MB. Upload venligst en FLAC- eller MP3-version i stedet.",
|
||||
"instrumentalConformUnavailable": "Vi kunne ikke behandle dit instrumentalspor lige nu. Prøv venligst at indsende igen om et øjeblik."
|
||||
"instrumentalConformUnavailable": "Vi kunne ikke behandle dit instrumentalspor lige nu. Prøv venligst at indsende igen om et øjeblik.",
|
||||
"adminRerenderRetryAdminOnly": "Dette track bliver renderet igen af vores team, så det kun kan genstartes af en administrator. Kontakt venligst support, så gør vi det færdigt for dig."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet blev ikke fundet",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Wir konnten dein hochgeladenes Instrumental nicht finden. Der Upload wurde möglicherweise nicht abgeschlossen. Bitte versuche es erneut.",
|
||||
"uploadDurationMismatchCancelled": "Das Instrumental ({instrumental_duration}s) stimmt zeitlich nicht mit dem Song-Audio ({audio_duration}s) überein, daher handelt es sich möglicherweise um die falsche Datei für diesen Song. Dieser Auftrag wurde abgebrochen und dein Guthaben erstattet. Bitte überprüfe die Dateien und reiche den Auftrag erneut ein.",
|
||||
"instrumentalUploadTooLarge": "Diese Instrumental-Datei ist {size_mb} MB groß, was über dem Limit von {max_mb} MB liegt. Bitte lade stattdessen eine FLAC- oder MP3-Version hoch.",
|
||||
"instrumentalConformUnavailable": "Wir konnten dein Instrumental gerade nicht verarbeiten. Bitte versuche es in einem Moment noch einmal einzureichen."
|
||||
"instrumentalConformUnavailable": "Wir konnten dein Instrumental gerade nicht verarbeiten. Bitte versuche es in einem Moment noch einmal einzureichen.",
|
||||
"adminRerenderRetryAdminOnly": "Dieser Track wird von unserem Team neu gerendert, daher kann er nur von einem Admin erneut gestartet werden. Bitte kontaktiere den Support, und wir stellen ihn für dich fertig."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Δεν μπορέσαμε να βρούμε το ορχηστρικό που μεταφόρτωσες. Η μεταφόρτωση ενδέχεται να μην έχει ολοκληρωθεί. Δοκίμασε ξανά.",
|
||||
"uploadDurationMismatchCancelled": "Το ορχηστρικό ({instrumental_duration}s) δεν ταιριάζει σε διάρκεια με τον ήχο του τραγουδιού ({audio_duration}s), οπότε μπορεί να είναι λάθος αρχείο για αυτό το τραγούδι. Αυτή η εργασία ακυρώθηκε και η πίστωσή σου επιστράφηκε. Παρακαλούμε έλεγξε τα αρχεία και υπόβαλε ξανά.",
|
||||
"instrumentalUploadTooLarge": "Αυτό το ορχηστρικό αρχείο είναι {size_mb} MB, το οποίο υπερβαίνει το όριο των {max_mb} MB. Παρακαλώ ανέβασε μια έκδοση FLAC ή MP3 αντ' αυτού.",
|
||||
"instrumentalConformUnavailable": "Δεν μπορέσαμε να επεξεργαστούμε το ορχηστρικό σου αυτή τη στιγμή. Δοκίμασε να υποβάλεις ξανά σε λίγο."
|
||||
"instrumentalConformUnavailable": "Δεν μπορέσαμε να επεξεργαστούμε το ορχηστρικό σου αυτή τη στιγμή. Δοκίμασε να υποβάλεις ξανά σε λίγο.",
|
||||
"adminRerenderRetryAdminOnly": "Αυτό το κομμάτι υποβάλλεται σε εκ νέου απόδοση από την ομάδα μας, επομένως μόνο ένας διαχειριστής μπορεί να επαναλάβει τη διαδικασία. Επικοινώνησε με την υποστήριξη και θα το ολοκληρώσουμε για εσένα."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Η εργασία δεν βρέθηκε",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "We couldn't find your uploaded instrumental. The upload may not have finished. Please try again.",
|
||||
"uploadDurationMismatchCancelled": "The instrumental ({instrumental_duration}s) doesn't line up with the song audio ({audio_duration}s), so it may be the wrong file for this song. This job has been cancelled and your credit refunded. Please check the files and submit again.",
|
||||
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead.",
|
||||
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment."
|
||||
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment.",
|
||||
"adminRerenderRetryAdminOnly": "This track is being re-rendered by our team, so it can only be retried by an admin. Please contact support and we'll finish it for you."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "No pudimos encontrar el instrumental que subiste. Es posible que la subida no haya finalizado. Por favor, inténtalo de nuevo.",
|
||||
"uploadDurationMismatchCancelled": "El instrumental ({instrumental_duration}s) no coincide con el audio de la canción ({audio_duration}s), por lo que podría ser el archivo incorrecto para esta canción. Este trabajo ha sido cancelado y tu crédito ha sido reembolsado. Por favor, revisa los archivos y vuelve a enviarlos.",
|
||||
"instrumentalUploadTooLarge": "Este archivo instrumental tiene {size_mb} MB, lo que supera el límite de {max_mb} MB. Por favor, sube una versión en FLAC o MP3 en su lugar.",
|
||||
"instrumentalConformUnavailable": "No pudimos procesar tu instrumental en este momento. Por favor, intenta enviarlo de nuevo en un momento."
|
||||
"instrumentalConformUnavailable": "No pudimos procesar tu instrumental en este momento. Por favor, intenta enviarlo de nuevo en un momento.",
|
||||
"adminRerenderRetryAdminOnly": "Esta pista está siendo rerenderizada por nuestro equipo, por lo que solo un administrador puede reintentarla. Por favor, contacta con soporte y la terminaremos por ti."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Emme löytäneet lataamaasi instrumentaaliraitaa. Lataus ei ehkä ole valmistunut. Yritä uudelleen.",
|
||||
"uploadDurationMismatchCancelled": "Taustaraita ({instrumental_duration}s) ei täsmää kappaleen ääniraidan ({audio_duration}s) kanssa, joten se saattaa olla väärä tiedosto tälle kappaleelle. Tämä työ on peruutettu ja krediittisi on palautettu. Tarkista tiedostot ja lähetä uudelleen.",
|
||||
"instrumentalUploadTooLarge": "Tämä instrumentaalitiedosto on {size_mb} MB, mikä ylittää {max_mb} MB:n rajan. Lataa sen sijaan FLAC- tai MP3-versio.",
|
||||
"instrumentalConformUnavailable": "Emme voineet käsitellä taustaraitaasi juuri nyt. Yritä lähettää uudelleen hetken kuluttua."
|
||||
"instrumentalConformUnavailable": "Emme voineet käsitellä taustaraitaasi juuri nyt. Yritä lähettää uudelleen hetken kuluttua.",
|
||||
"adminRerenderRetryAdminOnly": "Tiimimme renderöi tätä kappaletta uudelleen, joten vain ylläpitäjä voi käynnistää sen uudelleen. Ota yhteyttä tukeen, niin viimeistelemme sen puolestasi."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Työtä ei löytynyt",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nous n'avons pas trouvé ton instrumentale téléversée. Le téléversement n'est peut-être pas terminé. Réessaie.",
|
||||
"uploadDurationMismatchCancelled": "L'instrumental ({instrumental_duration}s) ne correspond pas à l'audio du morceau ({audio_duration}s), il s'agit donc peut-être du mauvais fichier pour cette chanson. Cette tâche a été annulée et ton crédit a été remboursé. Vérifie les fichiers et réessaie.",
|
||||
"instrumentalUploadTooLarge": "Ce fichier instrumental fait {size_mb} Mo, ce qui dépasse la limite de {max_mb} Mo. Téléverse plutôt une version FLAC ou MP3.",
|
||||
"instrumentalConformUnavailable": "Nous n'avons pas pu traiter ton instrumental à l'instant. Réessaie de le soumettre dans un instant."
|
||||
"instrumentalConformUnavailable": "Nous n'avons pas pu traiter ton instrumental à l'instant. Réessaie de le soumettre dans un instant.",
|
||||
"adminRerenderRetryAdminOnly": "Cette piste fait l'objet d'un nouveau rendu par notre équipe, elle ne peut donc être relancée que par un administrateur. Contacte le support et nous la terminerons pour toi."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tâche introuvable",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "לא הצלחנו למצוא את הפלייבק שהעליתם. ייתכן שההעלאה לא הושלמה. אנא נסו שוב.",
|
||||
"uploadDurationMismatchCancelled": "הפלייבק ({instrumental_duration} שניות) אינו תואם לקובץ השמע של השיר ({audio_duration} שניות), ולכן ייתכן שמדובר בקובץ שגוי עבור שיר זה. משימה זו בוטלה והקרדיט שלך הוחזר. נא לבדוק את הקבצים ולשלוח שוב.",
|
||||
"instrumentalUploadTooLarge": "קובץ הפלייבק הזה הוא בגודל {size_mb} MB, שחורג מהמגבלה של {max_mb} MB. נא להעלות גרסת FLAC או MP3 במקום זאת.",
|
||||
"instrumentalConformUnavailable": "לא הצלחנו לעבד את הפלייבק שלך כרגע. אנא נסה לשלוח שוב בעוד רגע."
|
||||
"instrumentalConformUnavailable": "לא הצלחנו לעבד את הפלייבק שלך כרגע. אנא נסה לשלוח שוב בעוד רגע.",
|
||||
"adminRerenderRetryAdminOnly": "הרצועה הזו מרונדרת מחדש על ידי הצוות שלנו, ולכן רק מנהל מערכת יכול לנסות שוב. אנא צרו קשר עם התמיכה ונסיים זאת עבורכם."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "המשימה לא נמצאה",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "हमें तुम्हारा अपलोड किया गया इंस्ट्रूमेंटल नहीं मिला। हो सकता है कि अपलोड पूरा न हुआ हो। कृपया फिर से कोशिश करो।",
|
||||
"uploadDurationMismatchCancelled": "इंस्ट्रुमेंटल ({instrumental_duration}s) गाने के ऑडियो ({audio_duration}s) से मेल नहीं खा रहा है, इसलिए हो सकता है कि यह इस गाने के लिए गलत फ़ाइल हो। यह जॉब रद्द कर दिया गया है और तुम्हारा क्रेडिट रिफ़ंड कर दिया गया है। कृपया फ़ाइलों की जाँच करो और फिर से सबमिट करो।",
|
||||
"instrumentalUploadTooLarge": "यह इंस्ट्रुमेंटल फ़ाइल {size_mb} MB की है, जो {max_mb} MB की सीमा से ज़्यादा है। कृपया इसके बजाय FLAC या MP3 वर्शन अपलोड करो।",
|
||||
"instrumentalConformUnavailable": "हम अभी तुम्हारा इंस्ट्रुमेंटल प्रोसेस नहीं कर पाए। कृपया थोड़ी देर बाद फिर से सबमिट करने की कोशिश करो।"
|
||||
"instrumentalConformUnavailable": "हम अभी तुम्हारा इंस्ट्रुमेंटल प्रोसेस नहीं कर पाए। कृपया थोड़ी देर बाद फिर से सबमिट करने की कोशिश करो।",
|
||||
"adminRerenderRetryAdminOnly": "यह ट्रैक हमारी टीम द्वारा री-रेंडर किया जा रहा है, इसलिए इसे केवल एडमिन ही री-ट्राई कर सकता है। कृपया सपोर्ट से संपर्क करो और हम इसे तुम्हारे लिए पूरा कर देंगे।"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "जॉब नहीं मिली",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nismo uspjeli pronaći tvoj preneseni instrumental. Prijenos možda nije dovršen. Pokušaj ponovno.",
|
||||
"uploadDurationMismatchCancelled": "Instrumental ({instrumental_duration}s) se ne podudara s audiozapisom pjesme ({audio_duration}s), pa je možda riječ o pogrešnoj datoteci za ovu pjesmu. Ovaj je zadatak otkazan, a tvoj je kredit vraćen. Provjeri datoteke i pošalji ponovno.",
|
||||
"instrumentalUploadTooLarge": "Ova instrumentalna datoteka ima {size_mb} MB, što premašuje ograničenje od {max_mb} MB. Umjesto toga učitaj FLAC ili MP3 verziju.",
|
||||
"instrumentalConformUnavailable": "Trenutačno nismo uspjeli obraditi tvoj instrumental. Pokušaj ponovno poslati za koji trenutak."
|
||||
"instrumentalConformUnavailable": "Trenutačno nismo uspjeli obraditi tvoj instrumental. Pokušaj ponovno poslati za koji trenutak.",
|
||||
"adminRerenderRetryAdminOnly": "Ovu pjesmu ponovno renderira naš tim, pa je može ponovno pokrenuti samo administrator. Javi se podršci i dovršit ćemo je za tebe."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Zadatak nije pronađen",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nem találtuk a feltöltött hangszeres sávot. Lehet, hogy a feltöltés nem fejeződött be. Kérlek, próbáld újra.",
|
||||
"uploadDurationMismatchCancelled": "Az instrumentális sáv ({instrumental_duration} mp) nem vág egybe a dal hanganyagával ({audio_duration} mp), ezért előfordulhat, hogy nem a megfelelő fájl tartozik ehhez a dalhoz. A feladat törölve lett, és a kreditedet visszatérítettük. Kérjük, ellenőrizd a fájlokat, és küldd be újra.",
|
||||
"instrumentalUploadTooLarge": "Ez az instrumentális fájl {size_mb} MB méretű, ami meghaladja a {max_mb} MB-os limitet. Kérlek, tölts fel helyette egy FLAC vagy MP3 verziót.",
|
||||
"instrumentalConformUnavailable": "Nem sikerült most feldolgozni a zenei alapodat. Kérlek, próbáld meg újra beküldeni egy pillanat múlva."
|
||||
"instrumentalConformUnavailable": "Nem sikerült most feldolgozni a zenei alapodat. Kérlek, próbáld meg újra beküldeni egy pillanat múlva.",
|
||||
"adminRerenderRetryAdminOnly": "Ezt a számot a csapatunk éppen újrarendereli, ezért csak egy adminisztrátor indíthatja újra. Kérjük, lépj kapcsolatba az ügyfélszolgálattal, és befejezzük neked."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "A feladat nem található",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Kami tidak dapat menemukan instrumental yang Anda unggah. Pengunggahan mungkin belum selesai. Silakan coba lagi.",
|
||||
"uploadDurationMismatchCancelled": "Audio instrumental ({instrumental_duration} detik) tidak selaras dengan audio lagu ({audio_duration} detik), sehingga mungkin ini bukan file yang tepat untuk lagu ini. Proses ini telah dibatalkan dan kredit Anda telah dikembalikan. Silakan periksa file Anda dan kirimkan kembali.",
|
||||
"instrumentalUploadTooLarge": "File instrumental ini berukuran {size_mb} MB, yang melebihi batas {max_mb} MB. Silakan unggah versi FLAC atau MP3 sebagai gantinya.",
|
||||
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental Anda barusan. Silakan coba kirimkan lagi beberapa saat lagi."
|
||||
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental Anda barusan. Silakan coba kirimkan lagi beberapa saat lagi.",
|
||||
"adminRerenderRetryAdminOnly": "Trek ini sedang dirender ulang oleh tim kami, sehingga hanya dapat dicoba ulang oleh admin. Silakan hubungi tim dukungan dan kami akan menyelesaikannya untuk Anda."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugas tidak ditemukan",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Non siamo riusciti a trovare la base strumentale caricata. Il caricamento potrebbe non essere stato completato. Riprova.",
|
||||
"uploadDurationMismatchCancelled": "La base strumentale ({instrumental_duration}s) non coincide con l'audio del brano ({audio_duration}s), quindi potrebbe trattarsi del file sbagliato per questo brano. Questo lavoro è stato annullato e il tuo credito è stato rimborsato. Controlla i file e invia di nuovo.",
|
||||
"instrumentalUploadTooLarge": "Questo file strumentale è di {size_mb} MB, che supera il limite di {max_mb} MB. Carica invece una versione in FLAC o MP3.",
|
||||
"instrumentalConformUnavailable": "Non siamo riusciti a elaborare la tua base strumentale in questo momento. Riprova a inviarla tra qualche istante."
|
||||
"instrumentalConformUnavailable": "Non siamo riusciti a elaborare la tua base strumentale in questo momento. Riprova a inviarla tra qualche istante.",
|
||||
"adminRerenderRetryAdminOnly": "Questa traccia è in fase di re-rendering da parte del nostro team, quindi può essere riavviata solo da un amministratore. Contatta l'assistenza e la completeremo per te."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Lavoro non trovato",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "アップロードされたインスト音源が見つかりませんでした。アップロードが完了していない可能性があります。もう一度お試しください。",
|
||||
"uploadDurationMismatchCancelled": "インスト音源({instrumental_duration}秒)の長さが楽曲音源({audio_duration}秒)と一致しないため、この曲とは異なるファイルの可能性があります。このジョブはキャンセルされ、クレジットは返却されました。ファイルをご確認のうえ、再度送信してください。",
|
||||
"instrumentalUploadTooLarge": "このインスト音源ファイルは{size_mb} MBで、上限の{max_mb} MBを超えています。代わりにFLACまたはMP3形式のファイルをアップロードしてください。",
|
||||
"instrumentalConformUnavailable": "インスト音源を処理できませんでした。少し時間をおいてから、もう一度送信してください。"
|
||||
"instrumentalConformUnavailable": "インスト音源を処理できませんでした。少し時間をおいてから、もう一度送信してください。",
|
||||
"adminRerenderRetryAdminOnly": "このトラックは現在当チームにて再レンダリング中のため、管理者のみ再試行できます。サポートまでお問い合わせいただければ、こちらで処理を完了いたします。"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ジョブが見つかりません",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "업로드한 반주 파일을 찾을 수 없습니다. 업로드가 완료되지 않았을 수 있습니다. 다시 시도해 주세요.",
|
||||
"uploadDurationMismatchCancelled": "반주({instrumental_duration}초)의 길이가 원곡 오디오({audio_duration}초)와 일치하지 않아 이 곡에 맞는 파일이 아닐 수 있습니다. 해당 작업은 취소되었으며 크레딧이 환불되었습니다. 파일을 확인하신 후 다시 제출해 주세요.",
|
||||
"instrumentalUploadTooLarge": "이 반주 파일의 용량은 {size_mb} MB로 제한 용량인 {max_mb} MB를 초과했습니다. 대신 FLAC 또는 MP3 버전으로 업로드해 주세요.",
|
||||
"instrumentalConformUnavailable": "방금 반주 음원을 처리하지 못했습니다. 잠시 후 다시 제출해 주세요."
|
||||
"instrumentalConformUnavailable": "방금 반주 음원을 처리하지 못했습니다. 잠시 후 다시 제출해 주세요.",
|
||||
"adminRerenderRetryAdminOnly": "이 트랙은 현재 저희 팀에서 재렌더링 중이므로 관리자만 다시 시도할 수 있습니다. 지원팀에 문의해 주시면 저희가 작업을 마무리해 드리겠습니다."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "작업을 찾을 수 없습니다",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Kami tidak dapat mencari instrumental yang anda muat naik. Proses muat naik mungkin belum selesai. Sila cuba lagi.",
|
||||
"uploadDurationMismatchCancelled": "Instrumental ({instrumental_duration}s) tidak sepadan dengan audio lagu ({audio_duration}s), jadi ia mungkin fail yang salah untuk lagu ini. Tugasan ini telah dibatalkan dan kredit anda telah dikembalikan. Sila semak fail tersebut dan hantar semula.",
|
||||
"instrumentalUploadTooLarge": "Fail instrumental ini bersaiz {size_mb} MB, iaitu melebihi had {max_mb} MB. Sila muat naik versi FLAC atau MP3 sebagai ganti.",
|
||||
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental anda sebentar tadi. Sila cuba hantar semula sebentar lagi."
|
||||
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental anda sebentar tadi. Sila cuba hantar semula sebentar lagi.",
|
||||
"adminRerenderRetryAdminOnly": "Trek ini sedang dirender semula oleh pasukan kami, jadi ia hanya boleh dicuba semula oleh pentadbir. Sila hubungi pihak sokongan dan kami akan menyelesaikannya untuk anda."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugasan tidak dijumpai",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Vi fant ikke den opplastede instrumentalen din. Det kan hende opplastingen ikke ble fullført. Prøv igjen.",
|
||||
"uploadDurationMismatchCancelled": "Instrumentalsporet ({instrumental_duration}s) stemmer ikke overens med sanglyden ({audio_duration}s), så det kan være feil fil for denne sangen. Denne jobben har blitt kansellert og kreditten din er refundert. Vennligst sjekk filene og send inn på nytt.",
|
||||
"instrumentalUploadTooLarge": "Denne instrumentalfilen er på {size_mb} MB, noe som er over grensen på {max_mb} MB. Vennligst last opp en FLAC- eller MP3-versjon i stedet.",
|
||||
"instrumentalConformUnavailable": "Vi kunne ikke behandle instrumentalen din akkurat nå. Prøv å sende inn på nytt om et øyeblikk."
|
||||
"instrumentalConformUnavailable": "Vi kunne ikke behandle instrumentalen din akkurat nå. Prøv å sende inn på nytt om et øyeblikk.",
|
||||
"adminRerenderRetryAdminOnly": "Dette sporet rendres på nytt av teamet vårt, så det kan kun prøves på nytt av en administrator. Ta kontakt med kundestøtte, så fullfører vi det for deg."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobben ble ikke funnet",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "We konden je geüploade instrumentale track niet vinden. De upload is mogelijk niet voltooid. Probeer het opnieuw.",
|
||||
"uploadDurationMismatchCancelled": "De instrumentale track ({instrumental_duration}s) komt niet overeen met de audio van het nummer ({audio_duration}s), dus het is mogelijk het verkeerde bestand voor dit nummer. Deze opdracht is geannuleerd en je tegoed is teruggestort. Controleer de bestanden en dien de aanvraag opnieuw in.",
|
||||
"instrumentalUploadTooLarge": "Dit instrumentale bestand is {size_mb} MB, wat de limiet van {max_mb} MB overschrijdt. Upload in plaats daarvan een FLAC- of MP3-versie.",
|
||||
"instrumentalConformUnavailable": "We konden je instrumental zojuist niet verwerken. Probeer het over een ogenblik opnieuw in te dienen."
|
||||
"instrumentalConformUnavailable": "We konden je instrumental zojuist niet verwerken. Probeer het over een ogenblik opnieuw in te dienen.",
|
||||
"adminRerenderRetryAdminOnly": "Dit nummer wordt opnieuw gerenderd door ons team, dus alleen een beheerder kan dit opnieuw proberen. Neem contact op met support en we maken het voor je af."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Taak niet gevonden",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nie udało się znaleźć Twojego przesłanego podkładu instrumentalnego. Przesyłanie mogło się nie zakończyć. Spróbuj ponownie.",
|
||||
"uploadDurationMismatchCancelled": "Wersja instrumentalna ({instrumental_duration}s) nie zgadza się z plikiem audio utworu ({audio_duration}s), więc może to być niewłaściwy plik dla tej piosenki. To zadanie zostało anulowane, a Twój kredyt zwrócony. Sprawdź pliki i prześlij je ponownie.",
|
||||
"instrumentalUploadTooLarge": "Ten plik instrumentalny ma {size_mb} MB, co przekracza limit {max_mb} MB. Prześlij zamiast tego wersję FLAC lub MP3.",
|
||||
"instrumentalConformUnavailable": "Nie udało nam się teraz przetworzyć Twojego podkładu instrumentalnego. Spróbuj przesłać go ponownie za chwilę."
|
||||
"instrumentalConformUnavailable": "Nie udało nam się teraz przetworzyć Twojego podkładu instrumentalnego. Spróbuj przesłać go ponownie za chwilę.",
|
||||
"adminRerenderRetryAdminOnly": "Ten utwór jest ponownie renderowany przez nasz zespół, więc tylko administrator może ponowić próbę. Skontaktuj się ze wsparciem, a dokończymy to dla Ciebie."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Nie znaleziono zadania",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Não conseguimos encontrar o instrumental enviado. O upload pode não ter sido concluído. Tente novamente.",
|
||||
"uploadDurationMismatchCancelled": "O instrumental ({instrumental_duration}s) não coincide com o áudio da música ({audio_duration}s), portanto pode ser o arquivo errado para esta música. Esta tarefa foi cancelada e seu crédito foi reembolsado. Por favor, verifique os arquivos e envie novamente.",
|
||||
"instrumentalUploadTooLarge": "Este arquivo instrumental tem {size_mb} MB, o que ultrapassa o limite de {max_mb} MB. Por favor, envie uma versão em FLAC ou MP3 em vez disso.",
|
||||
"instrumentalConformUnavailable": "Não conseguimos processar seu instrumental agora. Por favor, tente enviar novamente em alguns instantes."
|
||||
"instrumentalConformUnavailable": "Não conseguimos processar seu instrumental agora. Por favor, tente enviar novamente em alguns instantes.",
|
||||
"adminRerenderRetryAdminOnly": "Esta faixa está sendo renderizada novamente pela nossa equipe, então só um administrador pode tentar novamente. Entre em contato com o suporte e nós a finalizaremos para você."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job não encontrado",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nu am putut găsi instrumentalul încărcat. Este posibil ca încărcarea să nu se fi finalizat. Te rugăm să încerci din nou.",
|
||||
"uploadDurationMismatchCancelled": "Instrumentalul ({instrumental_duration}s) nu se potrivește cu fișierul audio al melodiei ({audio_duration}s), așa că este posibil să fie fișierul greșit pentru această melodie. Această sarcină a fost anulată, iar creditul tău a fost rambursat. Te rugăm să verifici fișierele și să trimiți din nou.",
|
||||
"instrumentalUploadTooLarge": "Acest fișier instrumental are {size_mb} MB, ceea ce depășește limita de {max_mb} MB. Te rugăm să încarci în schimb o versiune FLAC sau MP3.",
|
||||
"instrumentalConformUnavailable": "Nu am putut procesa instrumentalul tău chiar acum. Te rugăm să încerci să trimiți din nou peste câteva momente."
|
||||
"instrumentalConformUnavailable": "Nu am putut procesa instrumentalul tău chiar acum. Te rugăm să încerci să trimiți din nou peste câteva momente.",
|
||||
"adminRerenderRetryAdminOnly": "Această piesă este randată din nou de echipa noastră, așa că poate fi reîncercată doar de un administrator. Te rugăm să contactezi echipa de asistență și o vom finaliza pentru tine."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobul nu a fost găsit",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Мы не смогли найти твой загруженный инструментал. Возможно, загрузка не завершилась. Попробуй ещё раз.",
|
||||
"uploadDurationMismatchCancelled": "Длительность инструментала ({instrumental_duration} с) не совпадает с длительностью аудио песни ({audio_duration} с), поэтому, возможно, для этой песни выбран не тот файл. Задача отменена, а твой кредит возвращен. Пожалуйста, проверь файлы и отправь снова.",
|
||||
"instrumentalUploadTooLarge": "Этот файл инструментала весит {size_mb} МБ, что превышает лимит в {max_mb} МБ. Пожалуйста, загрузи вместо него версию в формате FLAC или MP3.",
|
||||
"instrumentalConformUnavailable": "Нам не удалось обработать твой инструментал прямо сейчас. Пожалуйста, попробуй отправить снова чуть позже."
|
||||
"instrumentalConformUnavailable": "Нам не удалось обработать твой инструментал прямо сейчас. Пожалуйста, попробуй отправить снова чуть позже.",
|
||||
"adminRerenderRetryAdminOnly": "Этот трек сейчас повторно рендерится нашей командой, поэтому перезапустить его может только администратор. Пожалуйста, свяжись с поддержкой, и мы всё доделаем."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Задача не найдена",
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"instrumentalUploadMissing": "Nenašli sme tvoj nahraný inštrumentál. Nahrávanie sa pravdepodobne nedokončilo. Skús to, prosím, znova.",
|
||||
"uploadDurationMismatchCancelled": "Inštrumentálna stopa ({instrumental_duration}s) sa nezhoduje so zvukom skladby ({audio_duration}s), takže môže ísť o nesprávny súbor pre túto skladbu. Táto úloha bola zrušená a tvoj kredit bol vrátený. Prosím, skontroluj súbory a odošli ich znova.",
|
||||
"instrumentalUploadTooLarge": "Tento inštrumentálny súbor má {size_mb} MB, čo prekračuje limit {max_mb} MB. Namiesto toho prosím nahraj verziu vo formáte FLAC alebo MP3.",
|
||||
"instrumentalConformUnavailable": "Nepodarilo sa nám práve spracovať tvoj inštrumentál. Skús to, prosím, o chvíľu odoslať znova."
|
||||
"instrumentalConformUnavailable": "Nepodarilo sa nám práve spracovať tvoj inštrumentál. Skús to, prosím, o chvíľu odoslať znova.",
|
||||
"adminRerenderRetryAdminOnly": "Túto skladbu práve nanovo renderuje náš tím, takže ju môže znova spustiť iba administrátor. Kontaktuj, prosím, podporu a my to pre teba dokončíme."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha sa nenašla",
|
||||
|
||||
Loaded 100 of 249 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user