mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 17:38:25 +09:00
Compare commits
No files matched your search
@@ -0,0 +1,42 @@
|
||||
# karaoke-gen backend environment — copy to .env and adjust.
|
||||
#
|
||||
# NOTE: scripts/run-backend-local.sh --with-emulators sets all the required
|
||||
# variables itself; you only need a .env for optional API keys or overrides.
|
||||
# None of the keys below are required to boot the backend locally.
|
||||
|
||||
# --- Core (defaults shown are what run-backend-local.sh uses in emulator mode) ---
|
||||
# ENVIRONMENT=development
|
||||
# GOOGLE_CLOUD_PROJECT=test-project
|
||||
# GCS_BUCKET_NAME=test-bucket
|
||||
# FIRESTORE_COLLECTION=test-jobs
|
||||
# ADMIN_TOKENS=local-dev-token
|
||||
# PORT=8000
|
||||
# FRONTEND_URL=http://localhost:3000
|
||||
|
||||
# --- Emulators (set automatically by run-backend-local.sh --with-emulators) ---
|
||||
# FIRESTORE_EMULATOR_HOST=127.0.0.1:8080
|
||||
# STORAGE_EMULATOR_HOST=http://127.0.0.1:4443
|
||||
|
||||
# --- Audio separation (pick one; without either, jobs stall at separation) ---
|
||||
# Local CPU/GPU separation via the audio-separator package. Models are
|
||||
# downloaded into this directory on first use (~2GB). CPU works but is slow.
|
||||
# MODEL_DIR=./models
|
||||
# ...or point at a remote audio-separator API service:
|
||||
# AUDIO_SEPARATOR_API_URL=
|
||||
|
||||
# --- Lyrics transcription ---
|
||||
# The lyrics worker reads AUDIOSHAKE_API_TOKEN (not AUDIOSHAKE_API_KEY).
|
||||
# Without it, transcription falls back to local Whisper if installed
|
||||
# (poetry install --extras local-whisper).
|
||||
# AUDIOSHAKE_API_TOKEN=
|
||||
|
||||
# --- Lyrics sources (optional; improves reference lyrics) ---
|
||||
# GENIUS_API_KEY=
|
||||
# SPOTIFY_COOKIE_SP_DC=
|
||||
|
||||
# --- Email (optional; without it, emails are logged to the console) ---
|
||||
# POSTMARK_SERVER_TOKEN=
|
||||
|
||||
# --- Payments (optional; only needed to exercise payment endpoints) ---
|
||||
# STRIPE_SECRET_KEY=
|
||||
# STRIPE_WEBHOOK_SECRET=
|
||||
@@ -515,12 +515,35 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build frontend into the package
|
||||
# The Next.js static export (karaoke_gen/nextjs_frontend/out) is gitignored
|
||||
# (#876) and bundled into the wheel via pyproject `include`. Build it here,
|
||||
# BEFORE `poetry build`, so the wheel contains the CLI local-review UI.
|
||||
# node_modules is already installed above, so this just builds + copies.
|
||||
# `make build-frontend` fails loudly if the frontend build fails.
|
||||
run: make build-frontend
|
||||
|
||||
- name: Build package
|
||||
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
|
||||
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
|
||||
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
|
||||
run: poetry build --format wheel
|
||||
|
||||
- name: Verify frontend is bundled in the wheel
|
||||
# Guard against silently shipping a frontend-less wheel.
|
||||
run: python scripts/verify_wheel_frontend.py dist/*.whl
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
pip install dist/*.whl
|
||||
@@ -833,6 +856,25 @@ jobs:
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build frontend into the package
|
||||
# The Next.js static export (karaoke_gen/nextjs_frontend/out) is gitignored
|
||||
# (#876) and bundled into the wheel via pyproject `include`. Build it here,
|
||||
# BEFORE `poetry build`, so the shipped wheel contains the CLI local-review
|
||||
# UI. node_modules is already installed above, so this just builds + copies.
|
||||
# `make build-frontend` fails loudly if the frontend build fails.
|
||||
run: make build-frontend
|
||||
|
||||
- name: Build package
|
||||
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
|
||||
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
|
||||
@@ -841,6 +883,10 @@ jobs:
|
||||
# source (the GCE encoding worker pulls the wheel from GCS).
|
||||
run: poetry build --format wheel
|
||||
|
||||
- name: Verify frontend is bundled in the wheel
|
||||
# Loud guard against shipping a frontend-less wheel to PyPI / the GCE worker.
|
||||
run: python scripts/verify_wheel_frontend.py dist/*.whl
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -1172,7 +1218,11 @@ jobs:
|
||||
echo "GCS deployment complete"
|
||||
|
||||
- name: Install Firestore client
|
||||
run: pip install google-cloud-firestore
|
||||
# Pinned to the app's version. google-cloud-firestore 2.29.0 (2026-08-24)
|
||||
# percent-encodes the default database id, so the config read below fails
|
||||
# with "400 Invalid database id %28default%29" — an unpinned install broke
|
||||
# every backend deploy after 2.29.0 shipped. Keep in sync with pyproject.
|
||||
run: pip install 'google-cloud-firestore==2.26.0'
|
||||
|
||||
- name: Read Firestore config
|
||||
id: config
|
||||
@@ -1871,7 +1921,7 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,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-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
|
||||
@@ -53,7 +53,11 @@ jobs:
|
||||
import os, sys, datetime, boto3
|
||||
|
||||
BUCKET = os.environ["BUCKET"]
|
||||
# (label, prefix, max_age_hours)
|
||||
# (label, prefix, max_age_hours, require_suffix)
|
||||
# require_suffix: only objects with this key suffix count toward
|
||||
# freshness (None = any object). git-repos/ requires ".bundle" so the
|
||||
# always-written manifest.json can't mark the prefix fresh when every
|
||||
# bundle failed / nothing was bundled — 0 bundles then reads as stale.
|
||||
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
|
||||
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
|
||||
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
|
||||
@@ -61,10 +65,11 @@ jobs:
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
|
||||
# files and secrets DO upload to S3 nightly, so they stay at 36h.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 192),
|
||||
("GCS job files", "gcs/job-files/", 36),
|
||||
("Encrypted secrets", "secrets/", 36),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192),
|
||||
("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/", 36, ".bundle"),
|
||||
]
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
@@ -75,10 +80,12 @@ jobs:
|
||||
# operates per-page, which silently breaks "newest across all pages"
|
||||
# queries on prefixes with >1000 objects (e.g. firestore/ has ~22k).
|
||||
paginator = s3.get_paginator("list_objects_v2")
|
||||
for label, prefix, max_hours in TARGETS:
|
||||
for label, prefix, max_hours, require_suffix in TARGETS:
|
||||
latest = None
|
||||
for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
if require_suffix and not obj["Key"].endswith(require_suffix):
|
||||
continue
|
||||
if latest is None or obj["LastModified"] > latest:
|
||||
latest = obj["LastModified"]
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
name: PyPI prune reminder
|
||||
|
||||
# PyPI caps total *project* size at 10 GB. karaoke-gen auto-publishes a ~62 MiB
|
||||
# wheel on every merge to main (~3 GB/month), so the project refills the cap
|
||||
# every few months and `poetry publish` then fails with "Project size too large".
|
||||
#
|
||||
# PyPI has NO deletion API (upload tokens are upload-only), so this can't
|
||||
# auto-delete. Instead it runs monthly, computes the retention plan
|
||||
# (scripts/prune_pypi_releases.py), and opens/updates a single tracking issue
|
||||
# containing a paste-into-browser-console snippet you run on your logged-in PyPI
|
||||
# releases page to actually prune. No secrets are stored.
|
||||
#
|
||||
# See docs/PYPI-STORAGE-PRUNE.md.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# 09:00 UTC on the 1st of each month.
|
||||
- cron: "0 9 1 * *"
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
prune-reminder:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PROJECT: karaoke-gen
|
||||
KEEP_DAYS: "60"
|
||||
# Only nag once the project crosses this watermark — pruning holds it at
|
||||
# ~4-7 GB, and there are always old releases to consolidate, so without a
|
||||
# threshold this would open an issue every month for no real reason. 7 GB
|
||||
# leaves ~1 month of ~3 GB/month growth before the 10 GB cap.
|
||||
NAG_THRESHOLD_GB: "7"
|
||||
ISSUE_TITLE: "🧹 PyPI storage prune due: karaoke-gen"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Compute prune plan
|
||||
id: plan
|
||||
run: |
|
||||
python scripts/prune_pypi_releases.py \
|
||||
--project "$PROJECT" --keep-days "$KEEP_DAYS" \
|
||||
--format markdown --output plan.md
|
||||
python scripts/prune_pypi_releases.py \
|
||||
--project "$PROJECT" --keep-days "$KEEP_DAYS" \
|
||||
--format json --output plan.json
|
||||
python - <<'PY' >> "$GITHUB_OUTPUT"
|
||||
import json, os
|
||||
d = json.load(open("plan.json"))
|
||||
threshold = float(os.environ["NAG_THRESHOLD_GB"])
|
||||
should_nag = d["delete_count"] > 0 and d["current_gb"] >= threshold
|
||||
print(f"delete_count={d['delete_count']}")
|
||||
print(f"reclaimable_gb={d['reclaimable_gb']:.2f}")
|
||||
print(f"current_gb={d['current_gb']:.2f}")
|
||||
print(f"should_nag={'true' if should_nag else 'false'}")
|
||||
PY
|
||||
|
||||
- name: Job summary
|
||||
run: cat plan.md >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Open or update tracking issue
|
||||
if: steps.plan.outputs.should_nag == 'true'
|
||||
run: |
|
||||
# Search by a stable ASCII substring (emoji in search queries is
|
||||
# flaky); the exact-title jq filter below is the real dedupe guard.
|
||||
existing=$(gh issue list --repo "$GITHUB_REPOSITORY" \
|
||||
--state open --search "PyPI storage prune due in:title" \
|
||||
--json number,title \
|
||||
--jq "map(select(.title == \"$ISSUE_TITLE\")) | .[0].number // empty")
|
||||
note="🔁 Refreshed $(date -u +%Y-%m-%d): ${{ steps.plan.outputs.delete_count }} releases prunable, ~${{ steps.plan.outputs.reclaimable_gb }} GB reclaimable (project at ${{ steps.plan.outputs.current_gb }} GB)."
|
||||
if [ -n "$existing" ]; then
|
||||
echo "Updating existing issue #$existing"
|
||||
gh issue edit "$existing" --repo "$GITHUB_REPOSITORY" --body-file plan.md
|
||||
gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" --body "$note"
|
||||
else
|
||||
echo "Creating new tracking issue"
|
||||
gh issue create --repo "$GITHUB_REPOSITORY" \
|
||||
--title "$ISSUE_TITLE" --body-file plan.md
|
||||
fi
|
||||
@@ -28,6 +28,9 @@ frontend/.swc/
|
||||
frontend/.turbo/
|
||||
frontend/build/
|
||||
frontend/dist/
|
||||
# Generated Next.js static export copied into the Python package at build time (#876).
|
||||
# Bundled into the wheel via pyproject `include`; must not be tracked in git.
|
||||
karaoke_gen/nextjs_frontend/out/
|
||||
|
||||
# Next.js specific
|
||||
frontend/*.tsbuildinfo
|
||||
|
||||
@@ -57,4 +57,7 @@ regexes = [
|
||||
# Firebase / GCP client API keys — public by design (identify the project,
|
||||
# access is gated by Firebase Security Rules).
|
||||
'''AIzaSy[A-Za-z0-9_-]{33}''',
|
||||
|
||||
# Documented local-development placeholder token (CONTRIBUTING.md, dev scripts)
|
||||
'''local-dev-token''',
|
||||
]
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
# Contributing to karaoke-gen
|
||||
|
||||
Thanks for your interest in contributing! This guide focuses on getting a
|
||||
working **local development environment with no Google Cloud credentials or
|
||||
paid API keys** — everything runs against local emulators.
|
||||
|
||||
## What runs locally (no credentials needed)
|
||||
|
||||
| Component | Local story |
|
||||
|-----------|-------------|
|
||||
| FastAPI backend | Runs directly via uvicorn |
|
||||
| Firestore | Google's Firestore emulator |
|
||||
| Cloud Storage | [fake-gcs-server](https://github.com/fsouza/fake-gcs-server) (Docker) |
|
||||
| Background workers (audio, lyrics, screens, video…) | Run as local subprocesses / in-process tasks |
|
||||
| Audio separation | Local CPU/GPU via `audio-separator` (set `MODEL_DIR`; models download on first use) |
|
||||
| Lyrics transcription | Local Whisper (`poetry install --extras local-whisper`); AudioShake used only if you set a token |
|
||||
| Login (magic links) | Printed to the backend console instead of emailed |
|
||||
| Signed URLs (review audio, downloads, uploads) | Rewritten to plain emulator URLs |
|
||||
| Frontend (Next.js) | `npm run dev`, pointed at the local backend |
|
||||
|
||||
Things that do NOT run locally: payments (Stripe), production email
|
||||
(Postmark), YouTube/Drive/Dropbox distribution, and the `flacfetch`
|
||||
URL-download service — **jobs from URLs won't process locally; use file
|
||||
upload instead.**
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.12/3.13 + [Poetry](https://python-poetry.org/)
|
||||
- Node.js 20+ (for the frontend)
|
||||
- Docker (for the GCS emulator)
|
||||
- Java 21+ and the Google Cloud SDK with the Firestore emulator:
|
||||
`gcloud components install cloud-firestore-emulator`
|
||||
(no login/account needed — the emulator runs entirely offline)
|
||||
- ffmpeg (`brew install ffmpeg` / `apt install ffmpeg`)
|
||||
|
||||
## Backend quickstart
|
||||
|
||||
```bash
|
||||
poetry install # heavy: torch etc, ~10 min first time
|
||||
./scripts/run-backend-local.sh --with-emulators
|
||||
```
|
||||
|
||||
This starts the Firestore emulator (port 8080), fake-gcs-server (port 4443),
|
||||
creates the bucket, seeds a default theme (`scripts/seed-local-data.py`), and
|
||||
runs the backend at <http://localhost:8000> (API docs at `/docs`).
|
||||
|
||||
Optional API keys go in `.env` (see `.env.example`) — none are required to boot.
|
||||
|
||||
### Try it
|
||||
|
||||
```bash
|
||||
# Health
|
||||
curl http://localhost:8000/api/health
|
||||
|
||||
# Create a job from a local audio file (admin token is "local-dev-token")
|
||||
curl -X POST http://localhost:8000/api/jobs/upload \
|
||||
-H 'Authorization: Bearer local-dev-token' \
|
||||
-F "file=@/path/to/song.flac" -F "artist=Some Artist" -F "title=Some Song"
|
||||
|
||||
# Watch it process; when status hits awaiting_review, open the review UI
|
||||
curl http://localhost:8000/api/jobs/<job_id> -H 'Authorization: Bearer local-dev-token'
|
||||
```
|
||||
|
||||
For audio separation to run, set `MODEL_DIR` (e.g. `MODEL_DIR=./models`) —
|
||||
separation models (~2 GB) are downloaded on first use. Without it the job
|
||||
fails at the separation step with a clear error.
|
||||
|
||||
## Frontend quickstart
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
NEXT_PUBLIC_API_URL=http://localhost:8000 npx next dev
|
||||
```
|
||||
|
||||
Then open <http://localhost:3000>. To log in, enter any email address — the
|
||||
magic link is printed in the **backend** console (look for `EMAIL TO:`); open
|
||||
that link in your browser.
|
||||
|
||||
### Review UI without running the full pipeline
|
||||
|
||||
If you're working on the lyrics review UI specifically, there's a fixtures
|
||||
harness that serves real correction data through the review API shape without
|
||||
processing any audio:
|
||||
|
||||
```bash
|
||||
python scripts/review_test_fixtures.py # serves on :8765
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
make test # everything (backend + frontend)
|
||||
make test-backend # backend only (unit + emulator tests)
|
||||
```
|
||||
|
||||
Emulator-backed integration tests live in `backend/tests/emulator/` and use
|
||||
the same two emulators as the local dev setup.
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Keep PRs focused; include tests for behavior changes.
|
||||
- Run `make test` before pushing — CI runs the same suite.
|
||||
- Bump `tool.poetry.version` in `pyproject.toml` for code changes.
|
||||
- CI must pass before merge; a maintainer will review from there.
|
||||
|
||||
See `docs/DEVELOPMENT.md` for deeper docs (architecture, deployment,
|
||||
observability) — most of that file concerns the production GCP deployment,
|
||||
which contributors don't need.
|
||||
@@ -675,4 +675,6 @@ MIT
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Contributions are welcome! Please see our contributing guidelines.
|
||||
Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) — the whole
|
||||
backend runs locally against emulators with no Google Cloud credentials or
|
||||
paid API keys required.
|
||||
+248
-25
@@ -7,7 +7,9 @@ Handles:
|
||||
- Admin-only operations
|
||||
- Audio search cache management
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Tuple, List, Optional, Any, Dict
|
||||
|
||||
@@ -91,6 +93,10 @@ class JobUpdateRequest(BaseModel):
|
||||
youtube_description_template: Optional[str] = None
|
||||
customer_email: Optional[str] = None
|
||||
customer_notes: Optional[str] = None
|
||||
# Review autonomy: "auto" (skip review when confident) | "always_review"
|
||||
review_mode: Optional[str] = None
|
||||
# Backing-vocals preference: "auto" | "clean" | "review"
|
||||
backing_preference: Optional[str] = None
|
||||
|
||||
# Editable boolean fields
|
||||
enable_cdg: Optional[bool] = None
|
||||
@@ -127,6 +133,8 @@ EDITABLE_JOB_FIELDS = {
|
||||
"non_interactive",
|
||||
"prep_only",
|
||||
"is_private",
|
||||
"review_mode",
|
||||
"backing_preference",
|
||||
}
|
||||
|
||||
|
||||
@@ -153,10 +161,23 @@ async def get_admin_stats_overview(
|
||||
- Credit statistics
|
||||
- Beta program stats
|
||||
"""
|
||||
# The Firestore streaming below is synchronous; run it in a worker thread so
|
||||
# it can't block the event loop and stall every other request on this instance.
|
||||
return await asyncio.to_thread(_compute_admin_stats_overview, user_service.db, exclude_test)
|
||||
|
||||
|
||||
# Field masks for the overview stats streams. Job documents carry large payloads
|
||||
# (state_data, timeline, corrections — ~100MB across the collection), so streaming
|
||||
# full documents just to count statuses takes ~15-20s; with these masks it's ~1s.
|
||||
_OVERVIEW_USER_FIELDS = ["email", "last_login_at", "credit_transactions"]
|
||||
_OVERVIEW_JOB_FIELDS = ["user_email", "created_at", "status"]
|
||||
|
||||
|
||||
def _compute_admin_stats_overview(db, exclude_test: bool) -> AdminStatsOverview:
|
||||
"""Synchronous stats computation — called via asyncio.to_thread from the route."""
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud.firestore_v1 import aggregation
|
||||
|
||||
db = user_service.db
|
||||
now = datetime.utcnow()
|
||||
seven_days_ago = now - timedelta(days=7)
|
||||
thirty_days_ago = now - timedelta(days=30)
|
||||
@@ -180,20 +201,37 @@ async def get_admin_stats_overview(
|
||||
|
||||
if exclude_test:
|
||||
# When excluding test data, we must stream and filter in Python
|
||||
# because Firestore doesn't support "not ends with" queries
|
||||
# because Firestore doesn't support "not ends with" queries.
|
||||
# The two streams are independent, so run them concurrently.
|
||||
|
||||
# Stream all users and filter
|
||||
all_users = []
|
||||
users_fetched = 0
|
||||
for doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
|
||||
users_fetched += 1
|
||||
user_data = doc.to_dict()
|
||||
email = user_data.get("email", "")
|
||||
if not is_test_email(email):
|
||||
all_users.append(user_data)
|
||||
def _stream_users():
|
||||
users, fetched = [], 0
|
||||
for doc in users_collection.select(_OVERVIEW_USER_FIELDS).limit(USERS_STREAM_LIMIT).stream():
|
||||
fetched += 1
|
||||
user_data = doc.to_dict()
|
||||
if not is_test_email(user_data.get("email", "")):
|
||||
users.append(user_data)
|
||||
return users, fetched
|
||||
|
||||
def _stream_jobs():
|
||||
jobs, fetched = [], 0
|
||||
for doc in jobs_collection.select(_OVERVIEW_JOB_FIELDS).limit(JOBS_STREAM_LIMIT).stream():
|
||||
fetched += 1
|
||||
job_data = doc.to_dict()
|
||||
if not is_test_email(job_data.get("user_email", "")):
|
||||
jobs.append(job_data)
|
||||
return jobs, fetched
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
users_future = executor.submit(_stream_users)
|
||||
jobs_future = executor.submit(_stream_jobs)
|
||||
all_users, users_fetched = users_future.result()
|
||||
all_jobs, jobs_fetched = jobs_future.result()
|
||||
|
||||
if users_fetched >= USERS_STREAM_LIMIT:
|
||||
logger.warning(f"Users stream hit limit ({USERS_STREAM_LIMIT}), stats may be incomplete")
|
||||
if jobs_fetched >= JOBS_STREAM_LIMIT:
|
||||
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
|
||||
|
||||
# Calculate user stats from filtered list
|
||||
total_users = len(all_users)
|
||||
@@ -216,19 +254,6 @@ async def get_admin_stats_overview(
|
||||
if amount > 0:
|
||||
total_credits_issued_30d += amount
|
||||
|
||||
# Stream all jobs and filter by user_email
|
||||
all_jobs = []
|
||||
jobs_fetched = 0
|
||||
for doc in jobs_collection.limit(JOBS_STREAM_LIMIT).stream():
|
||||
jobs_fetched += 1
|
||||
job_data = doc.to_dict()
|
||||
user_email = job_data.get("user_email", "")
|
||||
if not is_test_email(user_email):
|
||||
all_jobs.append(job_data)
|
||||
|
||||
if jobs_fetched >= JOBS_STREAM_LIMIT:
|
||||
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
|
||||
|
||||
# Calculate job stats from filtered list
|
||||
total_jobs = len(all_jobs)
|
||||
jobs_last_7d = sum(
|
||||
@@ -313,7 +338,7 @@ async def get_admin_stats_overview(
|
||||
total_credits_issued_30d = 0
|
||||
try:
|
||||
users_fetched = 0
|
||||
for user_doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
|
||||
for user_doc in users_collection.select(["credit_transactions"]).limit(USERS_STREAM_LIMIT).stream():
|
||||
users_fetched += 1
|
||||
user_data = user_doc.to_dict()
|
||||
transactions = user_data.get("credit_transactions", [])
|
||||
@@ -948,6 +973,44 @@ async def update_job(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Reassigning a job to an email with no account would orphan it (the user
|
||||
# couldn't log in to see it, and impersonation would 404) — so normalize the
|
||||
# email and auto-create the account if needed.
|
||||
user_created_email = None
|
||||
if isinstance(updates.get("user_email"), str):
|
||||
normalized_email = updates["user_email"].strip().lower()
|
||||
if not normalized_email or "@" not in normalized_email:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="user_email must be a valid email address"
|
||||
)
|
||||
updates["user_email"] = normalized_email
|
||||
user_service = get_user_service()
|
||||
if not user_service.get_user(normalized_email):
|
||||
user_service.get_or_create_user(normalized_email)
|
||||
user_created_email = normalized_email
|
||||
logger.info(
|
||||
f"Admin {admin_email} reassigned job {job_id} to {normalized_email} — "
|
||||
f"no account existed, created one"
|
||||
)
|
||||
|
||||
# The executor treats any value other than "auto" as an enforcement blocker,
|
||||
# so a typo (e.g. "always-review") would silently force human review.
|
||||
if "review_mode" in updates and updates["review_mode"] not in ("auto", "always_review"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail='review_mode must be "auto" or "always_review"',
|
||||
)
|
||||
|
||||
# backing_preference likewise gates the instrumental decision — reject typos.
|
||||
if "backing_preference" in updates and updates["backing_preference"] not in (
|
||||
"auto", "clean", "review",
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail='backing_preference must be "auto", "clean", or "review"',
|
||||
)
|
||||
|
||||
# Check if we're toggling is_private from False to True on a completed job
|
||||
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
|
||||
toggling_to_private = (
|
||||
@@ -997,6 +1060,8 @@ async def update_job(
|
||||
)
|
||||
|
||||
message = f"Successfully updated {len(updates)} field(s)"
|
||||
if user_created_email:
|
||||
message += f". Created new user account for {user_created_email}."
|
||||
if auto_deleted:
|
||||
message += ". Existing outputs were auto-deleted (job set to private)."
|
||||
|
||||
@@ -1835,6 +1900,133 @@ async def delete_job_outputs(
|
||||
)
|
||||
|
||||
|
||||
class OrphanedOutputsCleanupRequest(BaseModel):
|
||||
"""Explicit targets for cleaning up distributed outputs whose owning job doc no
|
||||
longer exists (e.g. a job deleted before its outputs were cleaned up)."""
|
||||
youtube_video_id: Optional[str] = None
|
||||
dropbox_folder_path: Optional[str] = None
|
||||
gdrive_file_ids: List[str] = []
|
||||
mirror_filename_prefix: Optional[str] = None # e.g. "NOMAD-1583 - Mazzy Star"
|
||||
|
||||
|
||||
@router.post("/orphaned-outputs/cleanup")
|
||||
async def cleanup_orphaned_outputs(
|
||||
req: OrphanedOutputsCleanupRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
) -> dict:
|
||||
"""
|
||||
Delete distributed outputs that no longer have an owning job doc (admin only).
|
||||
|
||||
The per-job cleanup endpoints (delete-outputs, cleanup-distribution) all require
|
||||
the job document to resolve file IDs and paths. When a job was deleted while its
|
||||
outputs were still published (the pre-fix DELETE /api/jobs/{id} behavior), those
|
||||
outputs are orphaned and must be targeted explicitly:
|
||||
|
||||
- youtube_video_id: YouTube video to delete (bare video ID)
|
||||
- dropbox_folder_path: full Dropbox folder path to delete
|
||||
- gdrive_file_ids: Google Drive file IDs to delete (from upload logs)
|
||||
- mirror_filename_prefix: "NOMAD-#### - Artist..." prefix for kjbox GCS mirror
|
||||
objects (masters + vocals guides); must include artist text so it can't match
|
||||
another track sharing a recycled brand code
|
||||
|
||||
Returns per-service results; each requested service reports success/failed/error.
|
||||
"""
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
if not any([req.youtube_video_id, req.dropbox_folder_path, req.gdrive_file_ids, req.mirror_filename_prefix]):
|
||||
raise HTTPException(status_code=400, detail="No cleanup targets specified")
|
||||
|
||||
if req.mirror_filename_prefix:
|
||||
from backend.services.nomad_master_mirror import is_safe_track_filename_prefix
|
||||
|
||||
if not is_safe_track_filename_prefix(req.mirror_filename_prefix):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
f"Unsafe mirror_filename_prefix {req.mirror_filename_prefix!r}: must be "
|
||||
f"'NOMAD-#### - Artist...' (brand code plus artist text) so it cannot "
|
||||
f"match another track sharing a recycled brand code"
|
||||
),
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_email} cleaning up orphaned outputs: "
|
||||
f"youtube={req.youtube_video_id}, dropbox={req.dropbox_folder_path}, "
|
||||
f"gdrive={req.gdrive_file_ids}, mirror_prefix={req.mirror_filename_prefix}"
|
||||
)
|
||||
results: Dict[str, Any] = {}
|
||||
|
||||
if req.youtube_video_id:
|
||||
try:
|
||||
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(req.youtube_video_id)
|
||||
results["youtube"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"video_id": req.youtube_video_id,
|
||||
}
|
||||
else:
|
||||
results["youtube"] = {"status": "failed", "reason": "YouTube credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned YouTube video {req.youtube_video_id}: {e}", exc_info=True)
|
||||
results["youtube"] = {"status": "error", "error": str(e)}
|
||||
|
||||
if req.dropbox_folder_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
success = dropbox.delete_folder(req.dropbox_folder_path)
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": req.dropbox_folder_path,
|
||||
}
|
||||
else:
|
||||
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned Dropbox folder {req.dropbox_folder_path}: {e}", exc_info=True)
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
if req.gdrive_file_ids:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
delete_results = gdrive.delete_files(req.gdrive_file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results,
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned GDrive files {req.gdrive_file_ids}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
|
||||
if req.mirror_filename_prefix:
|
||||
try:
|
||||
from backend.services.nomad_master_mirror import NomadMasterMirror
|
||||
|
||||
counts = NomadMasterMirror().delete_track_objects_by_filename_prefix(req.mirror_filename_prefix)
|
||||
results["mirror"] = {"status": "success", **counts}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting orphaned mirror objects for {req.mirror_filename_prefix}: {e}", exc_info=True)
|
||||
results["mirror"] = {"status": "error", "error": str(e)}
|
||||
|
||||
logger.info(f"Orphaned-outputs cleanup by {admin_email} complete: {results}")
|
||||
return {"status": "complete", "results": results}
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
|
||||
async def get_job_completion_message(
|
||||
job_id: str,
|
||||
@@ -2977,6 +3169,37 @@ async def get_user_payments(
|
||||
return service.get_user_payment_history(email)
|
||||
|
||||
|
||||
@router.get("/users/{email}/emails")
|
||||
async def get_user_emails(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List every email ever sent to a user (Postmark + our persisted log)."""
|
||||
from backend.services.postmark_admin_service import get_postmark_admin_service
|
||||
service = get_postmark_admin_service()
|
||||
return service.get_user_email_history(email)
|
||||
|
||||
|
||||
@router.get("/emails/{message_id}")
|
||||
async def get_email_detail(
|
||||
message_id: str,
|
||||
source: str = "postmark",
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Full detail for a single email — rendered HTML + delivery metadata.
|
||||
|
||||
``source=log`` reads our persisted copy directly (for mail older than
|
||||
Postmark's ~45-day retention); otherwise Postmark is queried with a
|
||||
fallback to the stored log.
|
||||
"""
|
||||
from backend.services.postmark_admin_service import get_postmark_admin_service
|
||||
service = get_postmark_admin_service()
|
||||
result = service.get_email_detail(message_id, source=source)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Email not found")
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/payments/{session_id}")
|
||||
async def get_payment_detail(
|
||||
session_id: str,
|
||||
|
||||
@@ -55,7 +55,7 @@ from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from pathlib import Path
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -143,6 +143,10 @@ class AudioSearchRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# 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'")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
@@ -803,9 +807,12 @@ async def search_audio(
|
||||
auto_download=body.auto_download,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -17,6 +17,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.i18n import get_full_locale_from_request
|
||||
from backend.services.auth_service import AuthResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -257,6 +258,9 @@ class BulkSettings(BaseModel):
|
||||
is_private: bool = False
|
||||
skip_audio_edit: bool = True
|
||||
skip_customization: bool = True
|
||||
# Full-auto review (workstream C): batch default autonomy + backing preference.
|
||||
review_mode: str = "auto"
|
||||
backing_preference: str = "auto"
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
@@ -341,6 +345,8 @@ async def bulk_submit(
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
review_mode=body.settings.review_mode,
|
||||
backing_preference=body.settings.backing_preference,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
@@ -348,6 +354,7 @@ async def bulk_submit(
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
request_metadata=request_metadata,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
try:
|
||||
job = job_manager.create_job(job_create, is_admin=is_admin)
|
||||
|
||||
@@ -10,13 +10,14 @@ Supports two upload flows:
|
||||
- Client uploads files directly to GCS using signed URLs (no size limit)
|
||||
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import os
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
from typing import Optional, List, Dict, Any, Tuple, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -44,7 +45,7 @@ from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -184,6 +185,10 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Audio editing
|
||||
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
|
||||
|
||||
# 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'")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
"""Response from creating a job from URL."""
|
||||
@@ -242,19 +247,35 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
prep_only: bool = Field(False, description="Stop after review phase, don't run finalisation")
|
||||
keep_brand_code: Optional[str] = Field(None, description="Preserve existing brand code instead of generating new one")
|
||||
|
||||
# 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'")
|
||||
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
# Bulk-upload grouping: jobs created from the same tenant bulk batch share a
|
||||
# batch_id (stamped into state_data) so they can be grouped/filtered later.
|
||||
batch_id: Optional[str] = Field(None, description="Groups jobs created together in one tenant bulk batch")
|
||||
|
||||
# Upload mechanism. "signed_put" (default) returns single-shot signed PUT
|
||||
# URLs; "resumable" returns GCS resumable session URIs that support chunked
|
||||
# uploads with mid-file resume after interruptions (flaky connections).
|
||||
upload_mode: Literal["signed_put", "resumable"] = Field(
|
||||
"signed_put", description="'signed_put' (default) or 'resumable'"
|
||||
)
|
||||
|
||||
|
||||
class SignedUploadUrl(BaseModel):
|
||||
"""Signed URL for uploading a file."""
|
||||
"""Signed URL (or resumable session URI) for uploading a file."""
|
||||
file_type: str = Field(..., description="Type of file this URL is for")
|
||||
gcs_path: str = Field(..., description="The GCS path where file will be stored")
|
||||
upload_url: str = Field(..., description="Signed URL to PUT the file to")
|
||||
upload_url: str = Field(..., description="Signed URL to PUT the file to, or a resumable session URI")
|
||||
content_type: str = Field(..., description="Content-Type header to use when uploading")
|
||||
resumable: bool = Field(False, description="True when upload_url is a GCS resumable session URI")
|
||||
|
||||
|
||||
class CreateJobWithUploadUrlsResponse(BaseModel):
|
||||
@@ -453,6 +474,9 @@ async def upload_and_create_job(
|
||||
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
|
||||
# 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'"),
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
|
||||
# Audio editing
|
||||
@@ -681,10 +705,15 @@ async def upload_and_create_job(
|
||||
request_metadata=request_metadata,
|
||||
# Non-interactive mode
|
||||
non_interactive=non_interactive,
|
||||
# Review autonomy + backing-vocals preference (full-auto review)
|
||||
review_mode=review_mode,
|
||||
backing_preference=backing_preference,
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -799,8 +828,10 @@ async def upload_and_create_job(
|
||||
update_data['style_assets'] = style_assets
|
||||
if 'style_params' in style_assets:
|
||||
update_data['style_params_gcs_path'] = style_assets['style_params']
|
||||
elif theme_style_assets:
|
||||
# Theme style assets (no custom uploads)
|
||||
elif theme_style_assets or theme_style_params_path:
|
||||
# Theme style assets (no custom uploads). A theme may have style
|
||||
# params but no asset files (e.g. the minimal local-dev seed theme),
|
||||
# so the params path must be written even when the assets dict is empty.
|
||||
update_data['style_assets'] = theme_style_assets
|
||||
if theme_style_params_path:
|
||||
update_data['style_params_gcs_path'] = theme_style_params_path
|
||||
@@ -1266,9 +1297,13 @@ async def create_job_with_upload_urls(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -1281,6 +1316,11 @@ async def create_job_with_upload_urls(
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
# Stamp bulk-batch grouping so jobs created together can be grouped/filtered later.
|
||||
if body.batch_id:
|
||||
job_manager.update_state_data(job_id, 'batch_id', body.batch_id)
|
||||
job_manager.update_state_data(job_id, 'created_from', 'tenant-bulk')
|
||||
|
||||
logger.info(f"Created job {job_id} for {body.artist} - {body.title} (signed URL upload flow)")
|
||||
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
@@ -1298,27 +1338,50 @@ async def create_job_with_upload_urls(
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
|
||||
|
||||
# Generate signed upload URLs for each file
|
||||
upload_urls = []
|
||||
for file_info in body.files:
|
||||
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
|
||||
|
||||
# Generate signed upload URL (valid for 60 minutes)
|
||||
signed_url = storage_service.generate_signed_upload_url(
|
||||
gcs_path,
|
||||
content_type=file_info.content_type,
|
||||
expiration_minutes=60
|
||||
)
|
||||
|
||||
upload_urls.append(SignedUploadUrl(
|
||||
file_type=file_info.file_type,
|
||||
gcs_path=gcs_path,
|
||||
upload_url=signed_url,
|
||||
content_type=file_info.content_type
|
||||
))
|
||||
|
||||
logger.info(f"Generated signed upload URL for {file_info.file_type}: {gcs_path}")
|
||||
|
||||
# Generate upload URLs for each file. Two modes:
|
||||
# - "signed_put" (default): single-shot signed PUT URL — simple, but an
|
||||
# interrupted upload restarts the whole file.
|
||||
# - "resumable": GCS resumable session URI — the client uploads in chunks
|
||||
# with Content-Range and can resume mid-file after any interruption
|
||||
# (network switch, sleep, reload). Sessions are created with the
|
||||
# caller's Origin so GCS handles CORS on the session itself.
|
||||
use_resumable = body.upload_mode == "resumable"
|
||||
request_origin = request.headers.get("Origin") if use_resumable else None
|
||||
|
||||
def _build_upload_urls() -> list:
|
||||
urls = []
|
||||
for file_info in body.files:
|
||||
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
|
||||
if use_resumable:
|
||||
upload_url = storage_service.create_resumable_upload_session(
|
||||
gcs_path,
|
||||
content_type=file_info.content_type,
|
||||
origin=request_origin,
|
||||
)
|
||||
else:
|
||||
# Signed PUT URL (valid for 60 minutes)
|
||||
upload_url = storage_service.generate_signed_upload_url(
|
||||
gcs_path,
|
||||
content_type=file_info.content_type,
|
||||
expiration_minutes=60
|
||||
)
|
||||
urls.append(SignedUploadUrl(
|
||||
file_type=file_info.file_type,
|
||||
gcs_path=gcs_path,
|
||||
upload_url=upload_url,
|
||||
content_type=file_info.content_type,
|
||||
resumable=use_resumable,
|
||||
))
|
||||
logger.info(
|
||||
f"Generated {'resumable session' if use_resumable else 'signed upload URL'} "
|
||||
f"for {file_info.file_type}: {gcs_path}"
|
||||
)
|
||||
return urls
|
||||
|
||||
# Resumable session creation makes a network round-trip to GCS per file;
|
||||
# run off the event loop. (Signed URLs sign locally but share the path.)
|
||||
upload_urls = await asyncio.to_thread(_build_upload_urls)
|
||||
|
||||
return CreateJobWithUploadUrlsResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
@@ -1894,9 +1957,13 @@ async def create_job_from_url(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -2202,6 +2269,8 @@ async def create_finalise_only_job(
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -901,10 +901,41 @@ async def recover_stuck_jobs(
|
||||
if _repark_stalled_render(job_manager, job_id):
|
||||
reparked.append(job_id)
|
||||
|
||||
# --- REVIEW_COMPLETE with no render started: lost render trigger ---
|
||||
# Both the human complete-review endpoint (fire-and-forget task) and the
|
||||
# auto-approval executor can lose the render trigger (e.g. Cloud Tasks
|
||||
# enqueue failure). Without this, the job sits at review_complete forever
|
||||
# with no error and no Retry button. Re-trigger is idempotent (worker
|
||||
# generation fence + status validation).
|
||||
# REVIEW_COMPLETE is a transient state (render normally starts in seconds),
|
||||
# so the population is tiny — scan it all (no limit, which could otherwise
|
||||
# return only fresh jobs and starve stalled ones) and cap re-triggers per
|
||||
# tick to bound the blast radius.
|
||||
render_retriggered = []
|
||||
rc_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.REVIEW_COMPLETE.value)
|
||||
).stream()
|
||||
for doc in rc_query:
|
||||
if len(render_retriggered) >= RENDER_RETRIGGERS_PER_TICK:
|
||||
break
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if not _review_complete_stalled(job):
|
||||
continue
|
||||
logger.warning(f"[job:{job_id}] REVIEW_COMPLETE stalled >10 min with no render — re-triggering")
|
||||
try:
|
||||
if await worker_service.trigger_render_video_worker(job_id):
|
||||
render_retriggered.append(job_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)}"
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)} "
|
||||
f"render_retriggered={len(render_retriggered)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
@@ -923,9 +954,38 @@ async def recover_stuck_jobs(
|
||||
"download_timed_out_jobs": download_timed_out,
|
||||
"reparked_render_jobs": reparked,
|
||||
"reparked_render_count": len(reparked),
|
||||
"render_retriggered_jobs": render_retriggered,
|
||||
"render_retriggered_count": len(render_retriggered),
|
||||
}
|
||||
|
||||
|
||||
REVIEW_COMPLETE_STALL_SECONDS = 10 * 60 # render normally starts within seconds
|
||||
RENDER_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
|
||||
|
||||
|
||||
def _review_complete_stalled(job) -> bool:
|
||||
"""True when a REVIEW_COMPLETE job has sat >10 min with no render underway.
|
||||
|
||||
``render_progress`` is cleared on review completion and (re)written by the
|
||||
render worker — its absence plus a stale ``updated_at`` means the trigger
|
||||
was lost.
|
||||
"""
|
||||
if (job.state_data or {}).get("render_progress"):
|
||||
return False
|
||||
updated_at = getattr(job, "updated_at", None)
|
||||
if updated_at is None:
|
||||
return False
|
||||
from datetime import datetime, timezone as _tz
|
||||
now = datetime.now(_tz.utc)
|
||||
if updated_at.tzinfo is None:
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
age = (now - updated_at).total_seconds()
|
||||
except TypeError:
|
||||
return False
|
||||
return age > REVIEW_COMPLETE_STALL_SECONDS
|
||||
|
||||
|
||||
# Torrent sources whose downloads are worth auto-retrying over a long window —
|
||||
# they fail transiently when a rare release has few/intermittent seeders or the
|
||||
# private tracker is briefly unreachable. Non-torrent sources (YouTube/Spotify/
|
||||
|
||||
+91
-42
@@ -39,7 +39,7 @@ from backend.services.tracing import add_span_attribute
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
@@ -164,6 +164,7 @@ async def create_job(
|
||||
user_email=user_email,
|
||||
is_private=request.is_private or False,
|
||||
credits=credits,
|
||||
locale=get_full_locale_from_request(http_request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
@@ -812,27 +813,53 @@ async def delete_job(
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete"))
|
||||
|
||||
# Recycle any unreturned brand code before deleting the job record
|
||||
# If the job still has published outputs (brand code allocated, outputs never
|
||||
# cleaned up), delete the distributed files BEFORE deleting the job record.
|
||||
# The brand code is recycled inside the cleanup only once Dropbox + GDrive are
|
||||
# confirmed clean: recycling while files remain in the public share hands the
|
||||
# same NOMAD-#### to a future job and creates duplicate brand codes (NOMAD-1583
|
||||
# incident, 2026-08-29). If cleanup fails, the code stays allocated — a sequence
|
||||
# gap the GDrive validator surfaces, which is safe and recoverable.
|
||||
state_data = job.state_data or {}
|
||||
brand_code = state_data.get('brand_code')
|
||||
if brand_code:
|
||||
if not job.outputs_deleted_at:
|
||||
logger.warning(
|
||||
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
|
||||
f"were not cleaned up first. Brand code will be recycled but "
|
||||
f"distributed files (GDrive/Dropbox/YouTube) may be orphaned."
|
||||
distribution_cleanup = None
|
||||
if brand_code and not job.outputs_deleted_at:
|
||||
if not delete_files:
|
||||
# Published outputs cannot be preserved when their job record is
|
||||
# deleted — the record holds the only file IDs/paths needed to ever
|
||||
# clean them up or reconcile the brand code.
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t(locale, "jobs.deletePublishedRequiresFiles"),
|
||||
)
|
||||
logger.warning(
|
||||
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
|
||||
f"were not cleaned up first — running distribution cleanup before delete."
|
||||
)
|
||||
distribution_cleanup = _run_distribution_cleanup(job_id, job)
|
||||
incomplete = [
|
||||
svc for svc in ("youtube", "dropbox", "gdrive")
|
||||
if distribution_cleanup.get(svc, {}).get("status") in ("failed", "partial", "error")
|
||||
]
|
||||
if incomplete:
|
||||
# Keep the job record: it holds the file IDs/paths needed to retry.
|
||||
# Deleting it anyway would orphan the remaining published files with
|
||||
# no way to resolve them later (NOMAD-1583 incident).
|
||||
logger.error(
|
||||
f"Aborting delete of job {job_id}: distribution cleanup incomplete "
|
||||
f"for {incomplete} — {distribution_cleanup}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=t(locale, "jobs.cleanupFailed", services=", ".join(incomplete)),
|
||||
)
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"Recycled brand code {brand_code} before deleting job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
|
||||
job_manager.delete_job(job_id, delete_files=delete_files)
|
||||
|
||||
return {"status": "success", "message": f"Job {job_id} deleted"}
|
||||
response = {"status": "success", "message": f"Job {job_id} deleted"}
|
||||
if distribution_cleanup is not None:
|
||||
response["distribution_cleanup"] = distribution_cleanup
|
||||
return response
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -2164,41 +2191,23 @@ async def get_worker_logs(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{job_id}/cleanup-distribution")
|
||||
async def cleanup_distribution(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_job: bool = True,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
) -> dict:
|
||||
def _run_distribution_cleanup(job_id: str, job) -> dict:
|
||||
"""
|
||||
Clean up all distributed content for a job (YouTube, Dropbox, Google Drive).
|
||||
Delete a job's distributed outputs (YouTube video, Dropbox folder, Google Drive
|
||||
files, kjbox GCS mirror objects) and recycle its brand code once Dropbox AND
|
||||
GDrive are confirmed clean.
|
||||
|
||||
This admin-only endpoint is designed for E2E test cleanup. It:
|
||||
1. Deletes YouTube video (if uploaded)
|
||||
2. Deletes Dropbox folder (if uploaded)
|
||||
3. Deletes Google Drive files (if uploaded)
|
||||
4. Optionally deletes the job itself
|
||||
|
||||
Args:
|
||||
job_id: Job ID to clean up
|
||||
delete_job: If True, also delete the job after cleaning up distribution
|
||||
|
||||
Returns:
|
||||
Cleanup results for each service
|
||||
Shared by the admin cleanup-distribution endpoint and job deletion. Deleting a
|
||||
job whose outputs are still published MUST run this first: recycling the brand
|
||||
code while the files remain in the public share hands the same NOMAD-#### to a
|
||||
future job and creates duplicate brand codes (NOMAD-1583 incident, 2026-08-29).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
state_data = job.state_data or {}
|
||||
results = {
|
||||
"job_id": job_id,
|
||||
"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"},
|
||||
"job_deleted": False
|
||||
}
|
||||
|
||||
# Clean up YouTube
|
||||
@@ -2357,6 +2366,41 @@ async def cleanup_distribution(
|
||||
f"collisions with leftover GDrive files."
|
||||
)
|
||||
|
||||
|
||||
return results
|
||||
|
||||
|
||||
@router.post("/{job_id}/cleanup-distribution")
|
||||
async def cleanup_distribution(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_job: bool = True,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
) -> dict:
|
||||
"""
|
||||
Clean up all distributed content for a job (YouTube, Dropbox, Google Drive).
|
||||
|
||||
This admin-only endpoint is designed for E2E test cleanup. It:
|
||||
1. Deletes YouTube video (if uploaded)
|
||||
2. Deletes Dropbox folder (if uploaded)
|
||||
3. Deletes Google Drive files (if uploaded)
|
||||
4. Optionally deletes the job itself
|
||||
|
||||
Args:
|
||||
job_id: Job ID to clean up
|
||||
delete_job: If True, also delete the job after cleaning up distribution
|
||||
|
||||
Returns:
|
||||
Cleanup results for each service
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
results = _run_distribution_cleanup(job_id, job)
|
||||
results["job_deleted"] = False
|
||||
|
||||
# Delete the job if requested
|
||||
if delete_job:
|
||||
try:
|
||||
@@ -2385,6 +2429,8 @@ class CreateFromSearchRequest(BaseModel):
|
||||
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
|
||||
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'")
|
||||
|
||||
@validator('display_artist', 'display_title')
|
||||
def strip_whitespace(cls, v):
|
||||
@@ -2540,7 +2586,10 @@ async def create_job_from_search(
|
||||
audio_search_title=session_title,
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
tenant_id=tenant_id,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
+672
-152
@@ -19,10 +19,10 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Optional, Set, Tuple
|
||||
from typing import Dict, Any, List, Literal, Optional, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
@@ -210,6 +210,156 @@ def _get_audio_hash(job_id: str) -> str:
|
||||
return hashlib.md5(job_id.encode()).hexdigest()
|
||||
|
||||
|
||||
def _preview_error_marker_path(job_id: str, preview_hash: str) -> str:
|
||||
"""GCS marker written when a background preview encode fails permanently.
|
||||
|
||||
The status-poll endpoint reports it so the review UI can stop polling and
|
||||
show a real error. GCS (not memory) because polls may hit a different
|
||||
Cloud Run instance than the one running the encode task.
|
||||
"""
|
||||
return f"jobs/{job_id}/previews/{preview_hash}.error.json"
|
||||
|
||||
|
||||
def _record_preview_video(job_id: str, preview_hash: str, gcs_path: str) -> None:
|
||||
if job_id not in _preview_videos:
|
||||
_preview_videos[job_id] = {}
|
||||
_preview_videos[job_id][preview_hash] = gcs_path
|
||||
|
||||
|
||||
def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
|
||||
"""Download corrections/audio/styles for a preview render into temp_dir.
|
||||
|
||||
Returns (correction_result, audio_path, output_config). Blocking (GCS
|
||||
downloads) — shared by the preview endpoint and the local-encode fallback.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
with create_span("download-corrections-and-audio") as download_span:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
corrections_path = os.path.join(temp_dir, "corrections.json")
|
||||
storage.download_file(corrections_gcs, corrections_path)
|
||||
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
storage.download_file(job.input_media_gcs_path, audio_path)
|
||||
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
|
||||
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
add_span_event("corrections_loaded")
|
||||
|
||||
with create_span("load-styles") as styles_span:
|
||||
styles_path, _ = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=logger,
|
||||
)
|
||||
styles_span.set_attribute("styles_path", styles_path)
|
||||
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
output_config = OutputConfig(
|
||||
output_styles_json=styles_path,
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
video_resolution="360p",
|
||||
is_duet=is_duet,
|
||||
)
|
||||
return correction_result, audio_path, output_config
|
||||
|
||||
|
||||
def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
"""Render the full 360p preview locally and upload it to GCS.
|
||||
|
||||
Blocking (downloads + ffmpeg) — call via asyncio.to_thread. Used when GCE
|
||||
preview encoding is disabled and as the fallback when it fails.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
correction_result, audio_path, output_config = _prepare_preview_inputs(
|
||||
job=job, temp_dir=temp_dir, storage=storage, is_duet=is_duet
|
||||
)
|
||||
|
||||
with create_span("render-preview-video-local") as render_span:
|
||||
render_span.set_attribute("resolution", "360p")
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
correction_result=correction_result,
|
||||
updated_data=updated_data,
|
||||
output_config=output_config,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
logger=logger,
|
||||
ass_only=False,
|
||||
)
|
||||
preview_hash = result["preview_hash"]
|
||||
video_path = result["video_path"]
|
||||
add_span_event("render_complete")
|
||||
|
||||
with create_span("upload-preview-video") as upload_span:
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
storage.upload_file(video_path, preview_gcs_path)
|
||||
upload_span.set_attribute("gcs_path", preview_gcs_path)
|
||||
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
return preview_hash
|
||||
|
||||
|
||||
async def _encode_preview_in_background(
|
||||
job,
|
||||
preview_hash: str,
|
||||
encode_kwargs: Dict[str, Any],
|
||||
updated_data: Dict[str, Any],
|
||||
is_duet: bool,
|
||||
) -> None:
|
||||
"""Run the GCE preview encode without holding the HTTP request open.
|
||||
|
||||
Cold-starting a fallback encoder VM can take 2-3 minutes — longer than
|
||||
Cloudflare's ~100s edge timeout — so POST /preview-video returns as soon
|
||||
as the ASS is uploaded and the browser polls the /status endpoint, which
|
||||
reports ready once the mp4 exists in GCS. On GCE failure this falls back
|
||||
to a local render; if that also fails an error marker is written so the
|
||||
poll can surface the failure instead of spinning until its timeout.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
encoding_service = get_encoding_service()
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
|
||||
with job_log_context(job_id, worker="preview"):
|
||||
try:
|
||||
with create_span("gce-preview-encoding", {"job_id": job_id, "preview_hash": preview_hash}) as gce_span:
|
||||
gce_result = await encoding_service.encode_preview_video(**encode_kwargs)
|
||||
gce_span.set_attribute("gce_status", gce_result.get("status"))
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
logger.info(f"Job {job_id}: Preview generated via GCE: {preview_hash}")
|
||||
return
|
||||
except Exception as gce_error:
|
||||
logger.warning(f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}")
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(_render_preview_locally, job, updated_data, is_duet)
|
||||
logger.info(f"Job {job_id}: Preview generated locally after GCE failure: {preview_hash}")
|
||||
except Exception as local_error:
|
||||
logger.error(
|
||||
f"Job {job_id}: Preview generation failed (GCE and local fallback): {local_error}",
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
storage.upload_json(
|
||||
_preview_error_marker_path(job_id, preview_hash),
|
||||
{"error": str(local_error)},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Job {job_id}: Failed to write preview error marker")
|
||||
|
||||
|
||||
# Cross-job search endpoint MUST be registered before {job_id} routes
|
||||
# to avoid FastAPI matching "sessions" as a job_id path parameter.
|
||||
@router.get("/sessions/search")
|
||||
@@ -237,9 +387,159 @@ async def ping(job_id: str):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def _dev_audio_proxy_enabled() -> bool:
|
||||
"""True when the backend should proxy review audio bytes instead of returning
|
||||
GCS signed URLs. Enabled via ``REVIEW_AUDIO_PROXY=1`` on a LOCAL dev backend
|
||||
that lacks URL-signing credentials (plain user ADC can't sign). Never set in
|
||||
prod — prod keeps the lighter signed-URL/redirect path.
|
||||
"""
|
||||
return os.environ.get("REVIEW_AUDIO_PROXY", "").lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def _dev_audio_url(job_id: str, gcs_path: Optional[str], base_url: str = "") -> Optional[str]:
|
||||
"""Build an ABSOLUTE dev-proxy URL for a review audio/image artifact.
|
||||
|
||||
The URL is used directly as an ``<audio>``/``<img>`` src by the frontend, which
|
||||
resolves relative URLs against the page origin (localhost:3000), not the API host.
|
||||
So we must return the full backend URL (``request.base_url``, e.g. http://127.0.0.1:8000/).
|
||||
"""
|
||||
if not gcs_path:
|
||||
return None
|
||||
from urllib.parse import quote
|
||||
return f"{base_url.rstrip('/')}/api/review/{job_id}/dev-audio?path={quote(gcs_path, safe='')}"
|
||||
|
||||
|
||||
def _reconstruct_post_ai_segments(
|
||||
raw_segments: List[Dict[str, Any]],
|
||||
edit_log: Optional[Dict[str, Any]],
|
||||
) -> Optional[List[Dict[str, Any]]]:
|
||||
"""Reconstruct the "post-AI, pre-human" lyrics state for replay.
|
||||
|
||||
Forward-replays the reviewer's edit log onto the RAW transcription
|
||||
(``corrections.json`` corrected_segments), applying only the accepted AI
|
||||
suggestion ops and STOPPING at the first manual op. The result is what the
|
||||
reviewer saw right after the AI auto-corrections were applied but before they
|
||||
made any manual edits — so a "Post-AI" toggle vs the final state makes the
|
||||
human's manual edits obvious (e.g. cleaning up an AI self-conflict that inserted
|
||||
a duplicate word).
|
||||
|
||||
Best-effort: ops that can't be applied are skipped rather than raising. Returns
|
||||
None if there's no edit log (nothing to reconstruct) or no manual edits at all
|
||||
(post-AI == final, so a toggle would be pointless).
|
||||
"""
|
||||
import copy
|
||||
|
||||
if not edit_log:
|
||||
return None
|
||||
entries = edit_log.get("entries") or []
|
||||
if not any(e.get("operation") and not str(e["operation"]).startswith("ai_suggestion") for e in entries):
|
||||
return None # no manual edits → nothing to distinguish
|
||||
|
||||
segments = copy.deepcopy(raw_segments)
|
||||
|
||||
def _find(word_id):
|
||||
for seg in segments:
|
||||
words = seg.get("words") or []
|
||||
for i, w in enumerate(words):
|
||||
if w.get("id") == word_id:
|
||||
return seg, words, i
|
||||
return None, None, None
|
||||
|
||||
_new_id = [0]
|
||||
|
||||
def _gen_id():
|
||||
_new_id[0] += 1
|
||||
return f"postai_{_new_id[0]}"
|
||||
|
||||
for e in entries:
|
||||
op = e.get("operation") or ""
|
||||
if not op.startswith("ai_suggestion"):
|
||||
break # reached the human's manual edits — stop
|
||||
if op != "ai_suggestion_accept":
|
||||
continue # run/reject/undo: not an applied change
|
||||
details = e.get("details") or {}
|
||||
sub_op = details.get("op") or "replace"
|
||||
before_ids = e.get("word_ids_before") or []
|
||||
text_after = (e.get("text_after") or "").strip()
|
||||
anchor_id = before_ids[0] if before_ids else None
|
||||
seg, words, idx = (_find(anchor_id) if anchor_id else (None, None, None))
|
||||
|
||||
def _make_words(text, start, end):
|
||||
# Split the replacement/insertion text into individual words, distributing
|
||||
# the [start, end] span evenly so multi-word replacements get distinct
|
||||
# timestamps (not all crammed into one slot with identical timing).
|
||||
toks = text.split()
|
||||
n = len(toks) or 1
|
||||
if end is None or start is None or end < start:
|
||||
end = start
|
||||
step = (end - start) / n
|
||||
out = []
|
||||
for i, tok in enumerate(toks):
|
||||
ws = start + i * step
|
||||
we = start + (i + 1) * step
|
||||
out.append({"id": _gen_id(), "text": tok, "start_time": ws, "end_time": we,
|
||||
"ai_corrected": True, "original_text": ""})
|
||||
return out
|
||||
|
||||
try:
|
||||
if sub_op == "replace":
|
||||
if words is not None:
|
||||
# word_ids_before may span MULTIPLE words (e.g.
|
||||
# 'quite a picket fence' -> 'white picket fences'). Replace the
|
||||
# whole contiguous span with the space-split replacement text,
|
||||
# spreading the original span's [start,end] across the new words.
|
||||
id_set = set(before_ids)
|
||||
span = [k for k, w in enumerate(words) if w.get("id") in id_set]
|
||||
if span:
|
||||
lo, hi = min(span), max(span)
|
||||
s0 = words[lo].get("start_time", 0.0)
|
||||
e0 = words[hi].get("end_time", s0)
|
||||
words[lo:hi + 1] = _make_words(text_after, s0, e0) if text_after else []
|
||||
elif sub_op in ("insert_after", "insert_before", "insert"):
|
||||
if words is not None:
|
||||
at = idx if sub_op == "insert_before" else idx + 1
|
||||
anchor = words[idx]
|
||||
a_s = anchor.get("start_time", 0.0)
|
||||
a_e = anchor.get("end_time", a_s)
|
||||
words[at:at] = _make_words(text_after, a_s, a_e)
|
||||
elif sub_op in ("delete", "remove", "adlib_removal"):
|
||||
if words is not None:
|
||||
id_set = set(before_ids)
|
||||
seg["words"] = [w for w in words if w.get("id") not in id_set]
|
||||
except Exception:
|
||||
continue # best-effort
|
||||
|
||||
# Refresh each segment's joined text for display.
|
||||
for seg in segments:
|
||||
seg["text"] = " ".join((w.get("text") or "") for w in (seg.get("words") or [])).strip()
|
||||
return segments
|
||||
|
||||
|
||||
def _load_edit_log(job, storage) -> Optional[Dict[str, Any]]:
|
||||
"""Load the reviewer's persisted edit log for replay, or None if absent.
|
||||
|
||||
Prefers the ``state_data.last_edit_log_path`` pointer written by the
|
||||
submit-edit-log endpoint; the file lives at
|
||||
``jobs/{job_id}/lyrics/edit_log_{session_id}.json`` and holds ordered,
|
||||
typed ops (``ai_suggestion_accept/reject`` vs manual ``word_*``/``timing_change``).
|
||||
"""
|
||||
try:
|
||||
path = (job.state_data or {}).get('last_edit_log_path')
|
||||
if not path:
|
||||
return None
|
||||
if not storage.file_exists(path):
|
||||
return None
|
||||
return storage.download_json(path)
|
||||
except Exception as e: # never let replay fail on a missing/corrupt log
|
||||
logger.warning(f"Job {job.job_id}: could not load edit_log for replay: {e}")
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/{job_id}/correction-data")
|
||||
async def get_correction_data(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
replay: bool = False,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
@@ -252,6 +552,15 @@ 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
|
||||
|
||||
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
|
||||
review UI can be re-opened read-only for a completed job. It skips the
|
||||
AWAITING_REVIEW/IN_REVIEW status gate and the AWAITING_REVIEW→IN_REVIEW
|
||||
transition side-effect, and additionally attaches the reviewer's ordered
|
||||
``edit_log`` (AI-accept/reject/manual ops) under ``replay``. Purely read-only;
|
||||
used for the fully-automated-review recording program. See
|
||||
docs/archive/2026-08-25-full-auto-review-design.md.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
@@ -260,12 +569,29 @@ async def get_correction_data(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
if replay and auth_info[1] != "full":
|
||||
# Replay reopens completed jobs; restrict to authenticated admin/owner,
|
||||
# never anonymous review-token links.
|
||||
raise HTTPException(status_code=403, detail="Replay mode requires admin/owner authentication")
|
||||
|
||||
if not replay and job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
# Server-side pre-apply ON LOAD (C2 completeness): jobs processed before the
|
||||
# screens_worker pre-apply shipped (or whose cache landed after that gate) reach
|
||||
# this endpoint without a pre_applied marker, so the review UI would still run its
|
||||
# on-load client-side apply (the visible ~4s "uncorrected -> corrected" flicker).
|
||||
# Apply here from an EXISTING cache only (generate_on_miss=False so the page never
|
||||
# blocks on a multi-model LLM call). Best-effort + idempotent: a no-op when the
|
||||
# job was already pre-applied, already human-edited, or has no cache. The direct
|
||||
# corrections_updated path below then serves the freshly-written corrected state.
|
||||
if not replay:
|
||||
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
|
||||
await ensure_and_pre_apply(job_id, generate_on_miss=False)
|
||||
|
||||
# Check for updated corrections first (from previous review sessions where user edited lyrics)
|
||||
# This mirrors the logic in render_video_worker.py to ensure consistency
|
||||
corrections_updated_gcs = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
@@ -314,18 +640,25 @@ async def get_correction_data(
|
||||
clean_url = stems.get('instrumental_clean')
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
|
||||
# Build instrumental options with transcoded signed URLs (OGG Opus)
|
||||
# Build instrumental options with transcoded signed URLs (OGG Opus).
|
||||
# In local dev without signing creds, use same-origin byte-proxy URLs.
|
||||
instrumental_options = []
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
|
||||
signed_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
if _dev_audio_proxy_enabled():
|
||||
_base = str(request.base_url)
|
||||
if clean_url:
|
||||
signed_urls['clean'] = _dev_audio_url(job_id, clean_url, _base)
|
||||
if backing_url:
|
||||
signed_urls['with_backing'] = _dev_audio_url(job_id, backing_url, _base)
|
||||
else:
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
if clean_url:
|
||||
instrumental_options.append({
|
||||
@@ -348,23 +681,55 @@ async def get_correction_data(
|
||||
backing_vocals_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
corrections_data['backing_vocals_analysis'] = backing_vocals_analysis
|
||||
|
||||
# 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
|
||||
# backing_preference — the same decision the executor / complete endpoint use.
|
||||
from backend.config import get_settings as _get_settings
|
||||
from backend.services.auto_approval.instrumental import auto_approval_summary
|
||||
corrections_data['auto_approval'] = auto_approval_summary(job, _get_settings())
|
||||
|
||||
# Get waveform URL if available
|
||||
analysis_files = job.file_urls.get('analysis', {})
|
||||
waveform_url = analysis_files.get('backing_vocals_waveform')
|
||||
if waveform_url:
|
||||
corrections_data['backing_vocals_waveform_url'] = storage.generate_signed_url(
|
||||
waveform_url, expiration_minutes=120
|
||||
corrections_data['backing_vocals_waveform_url'] = (
|
||||
_dev_audio_url(job_id, waveform_url, str(request.base_url)) if _dev_audio_proxy_enabled()
|
||||
else storage.generate_signed_url(waveform_url, expiration_minutes=120)
|
||||
)
|
||||
|
||||
# Transition to IN_REVIEW if not already
|
||||
if job.status == JobStatus.AWAITING_REVIEW:
|
||||
# Transition to IN_REVIEW if not already (never in replay — read-only)
|
||||
if not replay and job.status == JobStatus.AWAITING_REVIEW:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User opened combined review interface"
|
||||
)
|
||||
|
||||
logger.info(f"Job {job_id}: Serving correction data with instrumental options for combined review")
|
||||
# Replay: attach the reviewer's ordered edit_log so the UI can show the
|
||||
# sequence of actions (AI-accept/reject/manual/timing) beside the final state.
|
||||
if replay:
|
||||
edit_log = _load_edit_log(job, storage)
|
||||
post_ai_segments = None
|
||||
try:
|
||||
raw_data = storage.download_json(f"jobs/{job_id}/lyrics/corrections.json")
|
||||
post_ai_segments = _reconstruct_post_ai_segments(
|
||||
raw_data.get('corrected_segments', []), edit_log
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: could not reconstruct post-AI segments: {e}")
|
||||
corrections_data['replay'] = {
|
||||
'is_replay': True,
|
||||
'job_status': str(job.status),
|
||||
'instrumental_selection': job.state_data.get('instrumental_selection'),
|
||||
'edit_log': edit_log,
|
||||
# Present only when the reviewer made manual edits — lets the UI offer a
|
||||
# "Post-AI (pre-human)" toggle vs the final state.
|
||||
'post_ai_segments': post_ai_segments,
|
||||
'has_manual_edits': post_ai_segments is not None,
|
||||
}
|
||||
|
||||
logger.info(f"Job {job_id}: Serving correction data (replay={replay}) for combined review")
|
||||
return corrections_data
|
||||
|
||||
except Exception as e:
|
||||
@@ -372,6 +737,15 @@ async def get_correction_data(
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/vocals")
|
||||
async def get_vocals_audio(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the vocals audio file for playback."""
|
||||
return await _stream_audio(job_id, stem="vocals")
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
async def get_audio_with_hash(
|
||||
job_id: str,
|
||||
@@ -392,7 +766,7 @@ async def get_audio_no_hash(
|
||||
return await _stream_audio(job_id)
|
||||
|
||||
|
||||
async def _stream_audio(job_id: str):
|
||||
async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"] = "input"):
|
||||
"""
|
||||
Redirect to a signed GCS URL for audio playback in the review interface.
|
||||
|
||||
@@ -407,12 +781,57 @@ async def _stream_audio(job_id: str):
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
audio_gcs_path = None
|
||||
if stem == "input":
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
elif stem == "vocals":
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
# Stem keys vary by separation model. We want the full vocal mix
|
||||
# (lead + backing) so every word can be lined up against the waveform:
|
||||
# - "vocals" : full vocal from a 2-stem split (rare)
|
||||
# - "vocals_clean" : full vocal from the primary vocal/instrumental
|
||||
# split (present on essentially all cloud jobs)
|
||||
# - "lead_vocals" : last-resort fallback (misses backing lines)
|
||||
# Use .get() so a missing key yields a clean 404 below, not a KeyError/500.
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals"):
|
||||
if stems.get(key):
|
||||
audio_gcs_path = stems[key]
|
||||
break
|
||||
if not audio_gcs_path:
|
||||
# Audio separation is decoupled from the lyrics-review critical path, so a
|
||||
# user can open review before the vocal stems have been uploaded (the stem
|
||||
# arrives a minute or two later). Signal "not ready yet, retry" with a 202
|
||||
# so the frontend polls instead of treating it as a terminal 404.
|
||||
# state_data.audio_complete is set both when separation finishes and when
|
||||
# it's skipped entirely (existing-instrumental jobs), so a missing stem
|
||||
# with audio_complete=True really is a permanent 404.
|
||||
if stem == "vocals" and not job.state_data.get("audio_complete", False):
|
||||
logger.info(f"Job {job_id}: Vocal stem not yet available (separation in progress), returning 202")
|
||||
return Response(status_code=202, headers={"Retry-After": "15"})
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
transcoding = AudioTranscodingService()
|
||||
|
||||
if stem == "vocals":
|
||||
# Proxy the vocals bytes through the API rather than 302-redirecting to
|
||||
# a signed GCS URL. The waveform visualizer fetch()es + decodeAudioData()s
|
||||
# this (a cross-origin READ), and a cross-origin redirect makes the
|
||||
# browser send `Origin: null`, which the bucket CORS rejects. Serving
|
||||
# the (~3 MB) bytes from the API keeps it same-origin to api.* whose
|
||||
# CORS already allows the frontend. <audio> playback (stem="input")
|
||||
# doesn't need CORS, so it keeps the lighter redirect below.
|
||||
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
|
||||
logger.info(f"Job {job_id}: Proxying {len(audio_bytes)}B vocals audio for waveform")
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
if _dev_audio_proxy_enabled():
|
||||
# Local dev (no GCS URL-signing creds): proxy the bytes instead of
|
||||
# 302-redirecting to a signed URL. Prod (flag unset) is unchanged.
|
||||
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
|
||||
logger.info(f"Job {job_id}: [dev-proxy] streaming {len(audio_bytes)}B input audio")
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
@@ -422,6 +841,68 @@ async def _stream_audio(job_id: str):
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
|
||||
|
||||
|
||||
# In-memory cache of already-fetched/transcoded dev-audio bytes so HTTP Range
|
||||
# requests (seeking) don't re-transcode the whole file each time. Dev-only.
|
||||
_DEV_AUDIO_CACHE: Dict[str, Tuple[bytes, str]] = {}
|
||||
|
||||
|
||||
def _ranged_response(request: Request, data: bytes, content_type: str) -> Response:
|
||||
"""Serve ``data`` honoring an HTTP Range header (206) so <audio> can seek."""
|
||||
total = len(data)
|
||||
range_header = request.headers.get("range")
|
||||
headers = {"Accept-Ranges": "bytes"}
|
||||
if range_header and range_header.startswith("bytes="):
|
||||
try:
|
||||
spec = range_header.split("=", 1)[1].split(",")[0].strip()
|
||||
start_s, _, end_s = spec.partition("-")
|
||||
start = int(start_s) if start_s else 0
|
||||
end = int(end_s) if end_s else total - 1
|
||||
end = min(end, total - 1)
|
||||
if start > end or start >= total:
|
||||
return Response(status_code=416, headers={"Content-Range": f"bytes */{total}"})
|
||||
chunk = data[start:end + 1]
|
||||
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
|
||||
headers["Content-Length"] = str(len(chunk))
|
||||
return Response(content=chunk, status_code=206, media_type=content_type, headers=headers)
|
||||
except Exception:
|
||||
pass # fall through to full 200
|
||||
headers["Content-Length"] = str(total)
|
||||
return Response(content=data, media_type=content_type, headers=headers)
|
||||
|
||||
|
||||
@router.get("/{job_id}/dev-audio")
|
||||
async def get_dev_audio(job_id: str, path: str, request: Request):
|
||||
"""LOCAL-DEV ONLY audio/image byte proxy for replay when signing creds are absent.
|
||||
|
||||
Returns 404 unless ``REVIEW_AUDIO_PROXY`` is enabled, so it is inert in prod.
|
||||
No auth dependency (dev backend binds to localhost); it only ever serves bytes
|
||||
under ``jobs/{job_id}/`` so it can't be used to read arbitrary blobs. Supports
|
||||
HTTP Range so audio elements can seek.
|
||||
"""
|
||||
if not _dev_audio_proxy_enabled():
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
# Scope guard: only this job's own artifacts (path anchored under the job's
|
||||
# prefix), and no traversal. Localhost-dev-only, so this is belt-and-braces.
|
||||
if not path.startswith(f"jobs/{job_id}/") or ".." in path:
|
||||
raise HTTPException(status_code=400, detail="Invalid path")
|
||||
|
||||
try:
|
||||
cached = _DEV_AUDIO_CACHE.get(path)
|
||||
if cached is None:
|
||||
storage = StorageService()
|
||||
if path.lower().endswith(".png"):
|
||||
cached = (storage.download_bytes(path), "image/png")
|
||||
else:
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
cached = await AudioTranscodingService().get_review_audio_bytes_async(path)
|
||||
_DEV_AUDIO_CACHE[path] = cached
|
||||
data, content_type = cached
|
||||
return _ranged_response(request, data, content_type)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: [dev-proxy] error serving {path}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail="dev-audio proxy error")
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
@@ -459,6 +940,21 @@ async def complete_review(
|
||||
detail=t("en", "review.instrumentalSelectionRequired")
|
||||
)
|
||||
|
||||
# Per-screen skip (C1): a client that skipped the instrumental screen because
|
||||
# the backing decision was confidently auto-resolved sends "auto"; resolve it
|
||||
# from the stored verdict here so CLI/tenant clients get the skip for free.
|
||||
if instrumental_selection == "auto":
|
||||
from backend.config import get_settings as _get_settings
|
||||
from backend.services.auto_approval.instrumental import resolve_auto_instrumental
|
||||
resolved = resolve_auto_instrumental(job, _get_settings())
|
||||
if not resolved:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t("en", "review.instrumentalSelectionRequired"),
|
||||
)
|
||||
logger.info(f"Job {job_id}: Resolved instrumental_selection='auto' -> '{resolved}'")
|
||||
instrumental_selection = resolved
|
||||
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
# Allow "custom" for mute-region instrumentals or user-uploaded instrumentals
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
@@ -851,16 +1347,29 @@ async def add_lyrics(
|
||||
updated_result.metadata['audio_hash'] = audio_hash
|
||||
updated_result.metadata['artist'] = job.artist
|
||||
updated_result.metadata['title'] = job.title
|
||||
|
||||
|
||||
# The relevance filter may silently drop the new source during the
|
||||
# correction rerun. Surface that as a "rejected" outcome (without
|
||||
# persisting the no-op rerun) so the frontend can offer force-add.
|
||||
source_kept = source in (updated_result.reference_lyrics or {})
|
||||
if not source_kept:
|
||||
rejection = (updated_result.metadata.get("rejected_sources") or {}).get(source) or {}
|
||||
logger.info(
|
||||
f"Job {job_id}: Lyrics source '{source}' rejected by relevance filter "
|
||||
f"({rejection.get('matched_words')}/{rejection.get('total_words')} words matched)"
|
||||
)
|
||||
span.set_attribute("rejected", True)
|
||||
return {"status": "rejected", "rejection": rejection, "data": updated_result.to_dict()}
|
||||
|
||||
# Upload updated corrections back to GCS
|
||||
with create_span("upload-corrections") as upload_span:
|
||||
updated_data = updated_result.to_dict()
|
||||
storage.upload_json(corrections_gcs, updated_data)
|
||||
upload_span.set_attribute("gcs_path", corrections_gcs)
|
||||
|
||||
|
||||
logger.info(f"Job {job_id}: Successfully added lyrics source '{source}'")
|
||||
span.set_attribute("success", True)
|
||||
|
||||
|
||||
return {"status": "success", "data": updated_data}
|
||||
|
||||
except ValueError as e:
|
||||
@@ -1071,59 +1580,26 @@ async def generate_preview_video(
|
||||
with create_span("generate-preview-video", {"job_id": job_id, "use_gce": use_gce_preview}) as span:
|
||||
with job_log_context(job_id, worker="preview"):
|
||||
try:
|
||||
# Create temp directory for this preview operation
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# 1. Download original corrections.json (has full structure)
|
||||
with create_span("download-corrections-and-audio") as download_span:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
corrections_path = os.path.join(temp_dir, "corrections.json")
|
||||
storage.download_file(corrections_gcs, corrections_path)
|
||||
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 2. Download input audio
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
storage.download_file(job.input_media_gcs_path, audio_path)
|
||||
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
|
||||
|
||||
# 3. Load original as CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
add_span_event("corrections_loaded")
|
||||
|
||||
# 4. Get or create styles file for preview using unified style loader
|
||||
with create_span("load-styles") as styles_span:
|
||||
styles_path, _ = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=logger,
|
||||
if use_gce_preview:
|
||||
# GCE path: prepare inputs and generate ASS subtitles inline
|
||||
# (fast), then hand the video encode to a background task and
|
||||
# return immediately. Encoding can take minutes when a worker
|
||||
# VM cold-starts — longer than Cloudflare's ~100s edge timeout
|
||||
# — so the request must not wait for it; the frontend polls
|
||||
# the /status endpoint until the mp4 lands in GCS.
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Blocking work (GCS downloads, ASS generation) runs in a
|
||||
# worker thread so other requests on this instance don't
|
||||
# stall behind it.
|
||||
correction_result, audio_path, output_config = await asyncio.to_thread(
|
||||
_prepare_preview_inputs,
|
||||
job=job, temp_dir=temp_dir, storage=storage, is_duet=is_duet,
|
||||
)
|
||||
styles_span.set_attribute("styles_path", styles_path)
|
||||
|
||||
# 5. Set up output config for preview
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
output_config = OutputConfig(
|
||||
output_styles_json=styles_path,
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
video_resolution="360p",
|
||||
is_duet=is_duet,
|
||||
)
|
||||
|
||||
# 6. Generate preview (ASS-only if using GCE, or full video if local)
|
||||
preview_gcs_path = None
|
||||
|
||||
if use_gce_preview:
|
||||
# GCE path: Generate ASS only, then offload encoding to GCE
|
||||
try:
|
||||
with create_span("generate-ass-subtitles") as ass_span:
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
result = await asyncio.to_thread(
|
||||
CorrectionOperations.generate_preview_video,
|
||||
correction_result=correction_result,
|
||||
updated_data=updated_data,
|
||||
output_config=output_config,
|
||||
@@ -1138,94 +1614,95 @@ async def generate_preview_video(
|
||||
ass_span.set_attribute("ass_path", ass_path)
|
||||
add_span_event("ass_generated")
|
||||
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
|
||||
# The hash is deterministic over the correction data, so
|
||||
# if this exact preview already exists (e.g. the user
|
||||
# retried after a dropped connection) skip encoding.
|
||||
if storage.file_exists(preview_gcs_path):
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
span.set_attribute("preview_cache_hit", True)
|
||||
logger.info(f"Job {job_id}: Preview cache hit: {preview_hash}")
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
# Upload ASS to GCS
|
||||
with create_span("upload-ass-to-gcs") as upload_ass_span:
|
||||
ass_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.ass"
|
||||
storage.upload_file(ass_path, ass_gcs_path)
|
||||
upload_ass_span.set_attribute("ass_gcs_path", ass_gcs_path)
|
||||
|
||||
# Call GCE encoding service
|
||||
with create_span("gce-preview-encoding") as gce_span:
|
||||
bucket_name = settings.gcs_bucket_name
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
# A stale error marker from an earlier failed attempt at
|
||||
# this same hash would make the status poll fail instantly.
|
||||
storage.delete_file(
|
||||
_preview_error_marker_path(job_id, preview_hash),
|
||||
ignore_missing=True,
|
||||
)
|
||||
|
||||
# Get background image and font from style assets if available
|
||||
style_assets = job.style_assets or {}
|
||||
bucket_name = settings.gcs_bucket_name
|
||||
style_assets = job.style_assets or {}
|
||||
|
||||
# Only use background image if user explicitly requested it
|
||||
# Default is black background for faster preview generation (~10s vs ~30-60s)
|
||||
background_image_gcs_path = None
|
||||
if use_background_image:
|
||||
for key in ["karaoke_background", "style_karaoke_background"]:
|
||||
if key in style_assets:
|
||||
background_image_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
gce_span.set_attribute("background_image", background_image_gcs_path)
|
||||
break
|
||||
gce_span.set_attribute("use_background_image", use_background_image)
|
||||
|
||||
font_gcs_path = None
|
||||
for key in ["font", "style_font"]:
|
||||
# Only use background image if user explicitly requested it.
|
||||
# Default is black background for faster preview generation.
|
||||
background_image_gcs_path = None
|
||||
if use_background_image:
|
||||
for key in ["karaoke_background", "style_karaoke_background"]:
|
||||
if key in style_assets:
|
||||
font_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
gce_span.set_attribute("font", font_gcs_path)
|
||||
background_image_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
break
|
||||
span.set_attribute("use_background_image", use_background_image)
|
||||
|
||||
gce_result = await encoding_service.encode_preview_video(
|
||||
job_id=f"preview_{job_id}_{preview_hash}",
|
||||
ass_gcs_path=f"gs://{bucket_name}/{ass_gcs_path}",
|
||||
audio_gcs_path=f"gs://{bucket_name}/{job.input_media_gcs_path}",
|
||||
output_gcs_path=f"gs://{bucket_name}/{preview_gcs_path}",
|
||||
background_color="black",
|
||||
background_image_gcs_path=background_image_gcs_path,
|
||||
font_gcs_path=font_gcs_path,
|
||||
font_gcs_path = None
|
||||
for key in ["font", "style_font"]:
|
||||
if key in style_assets:
|
||||
font_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
|
||||
break
|
||||
|
||||
encode_kwargs = {
|
||||
"job_id": f"preview_{job_id}_{preview_hash}",
|
||||
"ass_gcs_path": f"gs://{bucket_name}/{ass_gcs_path}",
|
||||
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
|
||||
"output_gcs_path": f"gs://{bucket_name}/{preview_gcs_path}",
|
||||
"background_color": "black",
|
||||
"background_image_gcs_path": background_image_gcs_path,
|
||||
"font_gcs_path": font_gcs_path,
|
||||
}
|
||||
task = asyncio.create_task(
|
||||
_encode_preview_in_background(
|
||||
job=job,
|
||||
preview_hash=preview_hash,
|
||||
encode_kwargs=encode_kwargs,
|
||||
updated_data=updated_data,
|
||||
is_duet=is_duet,
|
||||
)
|
||||
gce_span.set_attribute("gce_status", gce_result.get("status"))
|
||||
add_span_event("gce_encoding_complete")
|
||||
)
|
||||
_background_tasks.add(task)
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
logger.info(f"Job {job_id}: Preview generated via GCE: {preview_hash}")
|
||||
logger.info(f"Job {job_id}: Preview encode running in background: {preview_hash}")
|
||||
return {"status": "generating", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError:
|
||||
raise
|
||||
except Exception as gce_error:
|
||||
# Fall back to local encoding if GCE fails
|
||||
# Fall back to synchronous local encoding if GCE setup fails
|
||||
logger.warning(
|
||||
f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}"
|
||||
f"Job {job_id}: GCE preview setup failed, falling back to local: {gce_error}"
|
||||
)
|
||||
span.set_attribute("gce_fallback", True)
|
||||
use_gce_preview = False # Fall through to local encoding below
|
||||
|
||||
if not use_gce_preview:
|
||||
# Local path: Generate full preview video locally
|
||||
with create_span("render-preview-video-local") as render_span:
|
||||
render_span.set_attribute("resolution", "360p")
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
correction_result=correction_result,
|
||||
updated_data=updated_data,
|
||||
output_config=output_config,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
logger=logger,
|
||||
ass_only=False, # Generate full video locally
|
||||
)
|
||||
preview_hash = result["preview_hash"]
|
||||
video_path = result["video_path"]
|
||||
add_span_event("render_complete")
|
||||
# Local path (GCE preview disabled, or GCE setup failed): render
|
||||
# the full preview synchronously — no cold-start problem, but slow.
|
||||
preview_hash = await asyncio.to_thread(
|
||||
_render_preview_locally, job, updated_data, is_duet
|
||||
)
|
||||
|
||||
# Upload preview video to GCS
|
||||
with create_span("upload-preview-video") as upload_span:
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
storage.upload_file(video_path, preview_gcs_path)
|
||||
upload_span.set_attribute("gcs_path", preview_gcs_path)
|
||||
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
span.set_attribute("success", True)
|
||||
|
||||
# Store the GCS path for serving
|
||||
if job_id not in _preview_videos:
|
||||
_preview_videos[job_id] = {}
|
||||
_preview_videos[job_id][preview_hash] = preview_gcs_path
|
||||
|
||||
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
span.set_attribute("success", True)
|
||||
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError as timing_err:
|
||||
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
|
||||
@@ -1282,6 +1759,41 @@ async def get_preview_video(
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/preview-video/{preview_hash}/status")
|
||||
async def get_preview_video_status(
|
||||
job_id: str,
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Poll the state of a background preview encode.
|
||||
|
||||
POST /preview-video returns {"status": "generating"} immediately and the
|
||||
encode runs in a background task (_encode_preview_in_background). The
|
||||
browser polls this endpoint until the mp4 appears in GCS. GCS is the
|
||||
source of truth so polls work regardless of which Cloud Run instance
|
||||
they hit.
|
||||
"""
|
||||
storage = StorageService()
|
||||
|
||||
if storage.file_exists(f"jobs/{job_id}/previews/{preview_hash}.mp4"):
|
||||
return {"status": "ready", "preview_hash": preview_hash}
|
||||
|
||||
marker_path = _preview_error_marker_path(job_id, preview_hash)
|
||||
if storage.file_exists(marker_path):
|
||||
message = None
|
||||
try:
|
||||
message = storage.download_json(marker_path).get("error")
|
||||
except Exception:
|
||||
logger.warning(f"Job {job_id}: Unreadable preview error marker {marker_path}")
|
||||
return {
|
||||
"status": "error",
|
||||
"preview_hash": preview_hash,
|
||||
"message": message or t("en", "review.previewVideoGenerationError", error="encoding failed"),
|
||||
}
|
||||
|
||||
return {"status": "generating", "preview_hash": preview_hash}
|
||||
|
||||
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
@@ -1345,6 +1857,7 @@ async def get_annotation_stats(
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
async def get_instrumental_analysis(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
@@ -1374,21 +1887,28 @@ async def get_instrumental_analysis(
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
|
||||
# Build audio URLs with transcoded signed access (OGG Opus, parallel)
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if job.input_media_gcs_path:
|
||||
url_tasks['original'] = transcoding.get_review_audio_url_async(job.input_media_gcs_path, expiration_minutes=120)
|
||||
if backing_vocals_path:
|
||||
url_tasks['backing_vocals'] = transcoding.get_review_audio_url_async(backing_vocals_path, expiration_minutes=120)
|
||||
|
||||
# Build audio URLs with transcoded signed access (OGG Opus, parallel).
|
||||
# In local dev without signing creds, use same-origin byte-proxy URLs.
|
||||
audio_url_sources = {
|
||||
'clean': clean_url,
|
||||
'with_backing': backing_url,
|
||||
'original': job.input_media_gcs_path,
|
||||
'backing_vocals': backing_vocals_path,
|
||||
}
|
||||
audio_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
if _dev_audio_proxy_enabled():
|
||||
_base = str(request.base_url)
|
||||
for key, src in audio_url_sources.items():
|
||||
if src:
|
||||
audio_urls[key] = _dev_audio_url(job_id, src, _base)
|
||||
else:
|
||||
url_tasks = {
|
||||
key: transcoding.get_review_audio_url_async(src, expiration_minutes=120)
|
||||
for key, src in audio_url_sources.items() if src
|
||||
}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
# Format response to match InstrumentalAnalysis type
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Authenticated tenant bulk-upload endpoints.
|
||||
|
||||
Separate from ``tenant.py`` (which is public config only): these require a
|
||||
tenant session and gate on the ``bulk_upload`` feature flag.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import List
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.services.auth_service import AuthResult
|
||||
from pathlib import Path
|
||||
|
||||
from backend.services.tenant_bulk import analyze_filenames
|
||||
from backend.services.tenant_bulk.analyze import AUDIO_EXTENSIONS, default_generate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/tenant/bulk", tags=["tenant-bulk"])
|
||||
|
||||
# Mirror consumer Bulk Mode's cap to bound LLM cost and upload load. Counts
|
||||
# audio files (candidate tracks), not incidental non-audio files a folder pick
|
||||
# may include (cover art, etc.), so an image-heavy folder isn't falsely blocked.
|
||||
MAX_AUDIO_FILES = 100
|
||||
# Absolute payload guard so a single request can't send an unbounded list.
|
||||
MAX_FILENAMES = 2000
|
||||
|
||||
|
||||
class BulkAnalyzeRequest(BaseModel):
|
||||
filenames: List[str] = Field(
|
||||
..., description="Filenames from the operator's folder pick (no paths needed)"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_bulk_filenames(
|
||||
request: Request,
|
||||
body: BulkAnalyzeRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Analyse a list of filenames into proposed Mixed/Instrumental job rows.
|
||||
|
||||
Pure analysis: filenames only, no uploads, no audio, no state written.
|
||||
Returns ``{rows, unpaired, ignored}`` for an editable review table.
|
||||
"""
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if not tenant_config:
|
||||
raise HTTPException(
|
||||
status_code=403, detail="Bulk upload is only available on tenant portals"
|
||||
)
|
||||
if not getattr(tenant_config.features, "bulk_upload", False):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="Bulk upload is not enabled for this portal"
|
||||
)
|
||||
|
||||
filenames = [f for f in (body.filenames or []) if f and f.strip()]
|
||||
if not filenames:
|
||||
raise HTTPException(status_code=400, detail="No filenames provided")
|
||||
if len(filenames) > MAX_FILENAMES:
|
||||
raise HTTPException(status_code=400, detail="Too many files in request")
|
||||
audio_count = sum(
|
||||
1 for f in filenames if Path(f).suffix.lower() in AUDIO_EXTENSIONS
|
||||
)
|
||||
if audio_count > MAX_AUDIO_FILES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Too many tracks ({audio_count}). Please submit at most {MAX_AUDIO_FILES} at a time.",
|
||||
)
|
||||
|
||||
# The LLM pass is a blocking Vertex call; run it off the event loop. It only
|
||||
# fires for files the regex could not pair, and analyze_filenames falls back
|
||||
# to the regex result if the model errors — so this never hard-fails.
|
||||
def _run() -> dict:
|
||||
return analyze_filenames(filenames, generate=default_generate).to_dict()
|
||||
|
||||
analysis = await asyncio.to_thread(_run)
|
||||
logger.info(
|
||||
"tenant-bulk analyze: tenant=%s files=%d rows=%d unpaired=%d ignored=%d",
|
||||
tenant_config.id,
|
||||
len(filenames),
|
||||
len(analysis["rows"]),
|
||||
len(analysis["unpaired"]),
|
||||
len(analysis["ignored"]),
|
||||
)
|
||||
return analysis
|
||||
@@ -36,7 +36,8 @@ def _mask_email(email: str) -> str:
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request, Header
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.config import is_production
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.models.user import (
|
||||
UserRole,
|
||||
@@ -48,6 +49,8 @@ from backend.models.user import (
|
||||
ResendFromTokenResponse,
|
||||
AddCreditsRequest,
|
||||
AddCreditsResponse,
|
||||
AdminCreateUserRequest,
|
||||
AdminCreateUserResponse,
|
||||
UserListResponse,
|
||||
UserFeedback,
|
||||
UserFeedbackRequest,
|
||||
@@ -272,8 +275,10 @@ async def send_magic_link(
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Check if email service is configured
|
||||
if not email_service.is_configured():
|
||||
# Check if email service is configured. In development the console provider
|
||||
# logs the magic link to the backend console instead of emailing it, so
|
||||
# contributors can log in locally without a Postmark token.
|
||||
if not email_service.is_configured() and is_production():
|
||||
logger.error("Email service not configured - cannot send magic links")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
@@ -438,10 +443,22 @@ async def verify_magic_link(
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
|
||||
|
||||
# Persist user's locale preference (from Accept-Language header)
|
||||
if locale and locale != (user.locale or "en"):
|
||||
# Persist user's locale preference (from Accept-Language header).
|
||||
# `locale` is narrowed to en/es/de for email rendering; `ui_locale` is the
|
||||
# full UI language (any of 33) so admins know what language to communicate in.
|
||||
ui_locale = get_full_locale_from_request(http_request)
|
||||
has_accept_language = bool(http_request.headers.get("accept-language"))
|
||||
locale_updates = {}
|
||||
# Only touch locale when the client actually sent an Accept-Language header —
|
||||
# otherwise get_locale_from_request()'s "en" default would clobber a user's
|
||||
# real stored locale on token-only logins (e.g. magic-link scanners).
|
||||
if has_accept_language and locale and locale != (user.locale or "en"):
|
||||
locale_updates["locale"] = locale
|
||||
if ui_locale and ui_locale != user.ui_locale:
|
||||
locale_updates["ui_locale"] = ui_locale
|
||||
if locale_updates:
|
||||
try:
|
||||
user_service.update_user(user.email, locale=locale)
|
||||
user_service.update_user(user.email, **locale_updates)
|
||||
except Exception:
|
||||
pass # Non-critical — don't block login
|
||||
|
||||
@@ -801,6 +818,7 @@ async def create_checkout(
|
||||
@router.post("/made-for-you/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_made_for_you_checkout(
|
||||
request: MadeForYouCheckoutRequest,
|
||||
http_request: Request,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
):
|
||||
"""
|
||||
@@ -825,6 +843,7 @@ async def create_made_for_you_checkout(
|
||||
source_type=request.source_type,
|
||||
youtube_url=request.youtube_url,
|
||||
notes=request.notes,
|
||||
locale=get_full_locale_from_request(http_request),
|
||||
)
|
||||
|
||||
if not success or not checkout_url:
|
||||
@@ -1008,6 +1027,8 @@ async def _handle_made_for_you_order(
|
||||
brand_prefix=dist.brand_prefix,
|
||||
discord_webhook_url=dist.discord_webhook_url,
|
||||
youtube_description=dist.youtube_description,
|
||||
# UI language the customer ordered in (captured at checkout, admin-only signal)
|
||||
locale=metadata.get("locale") or None,
|
||||
)
|
||||
# Made-for-you jobs are created by admin (via Stripe webhook) - bypass rate limits
|
||||
job = job_manager.create_job(job_create, is_admin=True)
|
||||
@@ -1758,6 +1779,10 @@ class UserDetailResponse(BaseModel):
|
||||
display_name: Optional[str] = None
|
||||
is_active: bool = True
|
||||
email_verified: bool = False
|
||||
# Language: `locale` is the email locale (en/es/de); `ui_locale` is the full UI
|
||||
# language (any of 33) the user browses in — what admins should communicate in.
|
||||
locale: Optional[str] = None
|
||||
ui_locale: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
last_login_at: Optional[str] = None
|
||||
@@ -1922,6 +1947,7 @@ async def get_user_detail(
|
||||
"artist": job_data.get("artist"),
|
||||
"title": job_data.get("title"),
|
||||
"created_at": created_at_str,
|
||||
"locale": job_data.get("locale"),
|
||||
})
|
||||
|
||||
# Get active sessions with details
|
||||
@@ -1958,6 +1984,8 @@ async def get_user_detail(
|
||||
display_name=user.display_name,
|
||||
is_active=user.is_active,
|
||||
email_verified=user.email_verified,
|
||||
locale=user.locale,
|
||||
ui_locale=user.ui_locale,
|
||||
created_at=user.created_at.isoformat() if user.created_at else None,
|
||||
updated_at=user.updated_at.isoformat() if user.updated_at else None,
|
||||
last_login_at=user.last_login_at.isoformat() if user.last_login_at else None,
|
||||
@@ -1978,6 +2006,68 @@ async def get_user_detail(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/users", response_model=AdminCreateUserResponse, status_code=201)
|
||||
async def admin_create_user(
|
||||
request: AdminCreateUserRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Create a user account directly (admin only).
|
||||
|
||||
Use this to set up an account for someone who has never logged in, so you can
|
||||
grant them credits, submit jobs on their behalf, or impersonate them. The user
|
||||
can later log in normally via magic link with the same email.
|
||||
|
||||
Users created this way with initial credits do NOT receive the automatic
|
||||
welcome credit on first login (welcome_credits_granted is set to prevent
|
||||
double-granting).
|
||||
"""
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
email = request.email.strip().lower()
|
||||
|
||||
if request.initial_credits < 0 or request.initial_credits > 1000:
|
||||
raise HTTPException(status_code=400, detail="initial_credits must be between 0 and 1000")
|
||||
|
||||
if user_service.get_user(email):
|
||||
raise HTTPException(status_code=409, detail=f"User {email} already exists")
|
||||
|
||||
user = user_service.get_or_create_user(email)
|
||||
|
||||
extra_updates = {}
|
||||
if request.display_name and request.display_name.strip():
|
||||
extra_updates["display_name"] = request.display_name.strip()
|
||||
|
||||
if request.initial_credits > 0:
|
||||
success, new_balance, message = user_service.add_credits(
|
||||
email=email,
|
||||
amount=request.initial_credits,
|
||||
reason=request.credit_reason,
|
||||
admin_email=admin_id,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(status_code=500, detail=f"User created but adding credits failed: {message}")
|
||||
user.credits = new_balance
|
||||
# Admin-granted starter credits replace the automatic welcome credit
|
||||
extra_updates["welcome_credits_granted"] = True
|
||||
|
||||
if extra_updates:
|
||||
user_service.update_user(email, **extra_updates)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_id} created user {_mask_email(email)} "
|
||||
f"(initial_credits={request.initial_credits})"
|
||||
)
|
||||
|
||||
return AdminCreateUserResponse(
|
||||
status="success",
|
||||
email=email,
|
||||
credits=user.credits,
|
||||
message=f"Created user {email}"
|
||||
+ (f" with {request.initial_credits} credit(s)" if request.initial_credits > 0 else ""),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/credits", response_model=AddCreditsResponse)
|
||||
async def add_credits_to_user(
|
||||
request: AddCreditsRequest,
|
||||
|
||||
@@ -4,9 +4,14 @@ Configuration management for the karaoke generation backend.
|
||||
import os
|
||||
import logging
|
||||
from typing import Optional, Dict
|
||||
from dotenv import load_dotenv
|
||||
from pydantic_settings import BaseSettings
|
||||
from google.cloud import secretmanager
|
||||
|
||||
# Load .env for local development (no-op when absent, e.g. in Cloud Run).
|
||||
# Must run before the Settings class body below, which reads os.getenv at
|
||||
# class-definition time. Real environment variables take precedence.
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -118,6 +123,29 @@ class Settings(BaseSettings):
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Auto-approval ENFORCEMENT: when the auto-approval scorer is fully confident
|
||||
# (see backend/services/auto_approval/), skip the combined review screens and
|
||||
# go straight to render. Scoring + verdict recording happen on every job
|
||||
# regardless of this flag; it only gates actually skipping the human.
|
||||
# Per-job opt-out via Job.review_mode="always_review". Kill switch: false.
|
||||
auto_approval_enforce_enabled: bool = os.getenv(
|
||||
"AUTO_APPROVAL_ENFORCE_ENABLED", "true"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Backing decider ENFORCEMENT (Phase 2B): allow a confident WITH_BACKING
|
||||
# verdict from the 3-stem decider to auto-select the with-backing
|
||||
# instrumental. Shadow-validated 2026-08-28/29 (20-job corpus + live
|
||||
# batteries + human review pass: 10/11 pick agreement, the one
|
||||
# auto-eligible job shipped identically to the human) -> default ON.
|
||||
# Default lives HERE, not per-environment env vars, because the executor
|
||||
# runs in BOTH the backend service and the audio-separation Cloud Run Job
|
||||
# (independent env; a service-only env flip left the audio_worker trigger
|
||||
# reading false). Kill switch: set false in ci.yml backend deploy env
|
||||
# AND infrastructure audio-separation-job envs (or revert this default).
|
||||
auto_approval_backing_keep_enabled: bool = os.getenv(
|
||||
"AUTO_APPROVAL_BACKING_KEEP_ENABLED", "true"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Match judge — artist/title formatting + match-acceptance for the job
|
||||
# submission flow. Deterministic + catalog layers always run; the light AI
|
||||
# layer (Vertex Gemini Flash) fires only when those aren't confident.
|
||||
@@ -149,6 +177,11 @@ class Settings(BaseSettings):
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
enable_cloud_tasks: bool = os.getenv("ENABLE_CLOUD_TASKS", "false").lower() in ("true", "1", "yes")
|
||||
gcp_region: str = os.getenv("GCP_REGION", "us-central1")
|
||||
# ALL Cloud Tasks queues live in us-central1, but workers running in other
|
||||
# regions (the GPU audio-separation-job sets GCP_REGION to its GPU region)
|
||||
# must still enqueue to the real queue location — building queue paths from
|
||||
# gcp_region 404s from those workers ("Queue does not exist").
|
||||
cloud_tasks_region: str = os.getenv("CLOUD_TASKS_REGION", "us-central1")
|
||||
|
||||
# Cloud Run Jobs (for long-running video encoding)
|
||||
# When enabled AND enable_cloud_tasks is true, video worker uses Cloud Run Jobs
|
||||
|
||||
@@ -92,6 +92,37 @@ def get_locale_from_request(request: Request) -> str:
|
||||
return DEFAULT_LOCALE
|
||||
|
||||
|
||||
def get_full_locale_from_request(request: Request) -> str | None:
|
||||
"""Extract the user's actual UI language tag from Accept-Language.
|
||||
|
||||
Unlike :func:`get_locale_from_request`, this does NOT narrow to the 3
|
||||
email-supported locales (en/es/de). It returns the primary language subtag
|
||||
of the first entry in the header (e.g. ``pt``, ``ja``, ``zh``) so the admin
|
||||
UI can show the real language a customer was using the product in.
|
||||
|
||||
Returns the lowercased language subtag, or ``None`` if the header is absent
|
||||
or unparseable.
|
||||
"""
|
||||
accept_lang = request.headers.get("accept-language", "")
|
||||
|
||||
for part in accept_lang.split(","):
|
||||
# Each part looks like "en-US;q=0.9" — take the language-region token
|
||||
# before the quality factor, then the primary subtag before any region.
|
||||
segments = part.split(";")
|
||||
token = segments[0].strip()
|
||||
if not token or token == "*":
|
||||
continue
|
||||
# Skip ranges the client explicitly rejects with q=0.
|
||||
if any(seg.strip().lower().replace(" ", "") in ("q=0", "q=0.0", "q=0.00", "q=0.000")
|
||||
for seg in segments[1:]):
|
||||
continue
|
||||
lang = token.split("-")[0].strip().lower()
|
||||
if lang.isalpha() and len(lang) >= 2:
|
||||
return lang
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_locale_prefix(locale: str) -> str:
|
||||
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
|
||||
if locale not in SUPPORTED_LOCALES:
|
||||
|
||||
+2
-1
@@ -10,7 +10,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings, validate_production_config
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -203,6 +203,7 @@ app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename
|
||||
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
app.include_router(tenant_bulk.router) # Tenant bulk-upload filename analysis (router has /api prefix)
|
||||
|
||||
|
||||
# Exception handlers
|
||||
|
||||
+50
-3
@@ -144,7 +144,10 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.LYRICS_COMPLETE: [JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
# Post-parallel processing (screens + backing vocals analysis)
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
# GENERATING_SCREENS -> REVIEW_COMPLETE is the auto-approval path: when the
|
||||
# scorer is fully confident the review screens are skipped entirely (no
|
||||
# review token / "ready for review" notification is ever issued).
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.APPLYING_PADDING: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
|
||||
# Combined human review flow (lyrics + instrumental selection)
|
||||
@@ -272,9 +275,29 @@ class Job(BaseModel):
|
||||
user_email: Optional[str] = None # Email for notifications
|
||||
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
|
||||
|
||||
# Review autonomy level. "auto" (default): skip the combined review screens
|
||||
# whenever the auto-approval scorer is fully confident, falling back to human
|
||||
# review otherwise. "always_review": every job stops at the review screens.
|
||||
# (Distinct from legacy non_interactive, which is CLI packaging/upload
|
||||
# semantics and never gated the cloud review flow.)
|
||||
review_mode: str = "auto"
|
||||
|
||||
# Backing-vocals preference chosen up-front at submission. "auto" (default):
|
||||
# retain backing vocals wherever the 3-stem decider is confident it's safe,
|
||||
# else fall through to human review. "clean": always use the clean
|
||||
# instrumental (never retain backing). "review": always let a human pick the
|
||||
# instrumental. Consumed by the auto-approval instrumental decision.
|
||||
backing_preference: str = "auto"
|
||||
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
|
||||
|
||||
# UI language the job was submitted in (primary Accept-Language subtag, e.g.
|
||||
# "pt", "ja", "zh"). Any of the 33 supported UI locales — NOT narrowed to the
|
||||
# 3 email locales. Admin-only signal for support/intervention. None for jobs
|
||||
# created before this field existed or where the header was absent.
|
||||
locale: Optional[str] = None
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
@@ -551,7 +574,13 @@ class JobCreate(BaseModel):
|
||||
webhook_url: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
|
||||
|
||||
# "auto" (default) = skip review screens when the auto-approval scorer is
|
||||
# fully confident; "always_review" = always stop at the review screens.
|
||||
review_mode: str = "auto"
|
||||
# "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"
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
@@ -631,6 +660,10 @@ class JobCreate(BaseModel):
|
||||
# Tenant scoping for white-label portals ("" = consumer, "vocalstar"/etc = tenant)
|
||||
tenant_id: str = "" # Tenant ID for job scoping
|
||||
|
||||
# UI language the job was submitted in (primary Accept-Language subtag, e.g.
|
||||
# "pt", "ja"). Set by the API endpoint from the request header; admin-only.
|
||||
locale: Optional[str] = None
|
||||
|
||||
@validator('url')
|
||||
def validate_url(cls, v):
|
||||
"""Validate URL is not empty."""
|
||||
@@ -638,6 +671,20 @@ class JobCreate(BaseModel):
|
||||
raise ValueError("Field cannot be empty string")
|
||||
return v.strip() if isinstance(v, str) else v
|
||||
|
||||
@validator('review_mode')
|
||||
def _normalize_review_mode(cls, v):
|
||||
"""Coerce an out-of-set value to the fail-safe default (always_review =
|
||||
more human oversight), so a typo can never silently skip review. The
|
||||
executor already treats any non-"auto" value as an enforcement blocker."""
|
||||
return v if v in ("auto", "always_review") else "always_review"
|
||||
|
||||
@validator('backing_preference')
|
||||
def _normalize_backing_preference(cls, v):
|
||||
"""Coerce an out-of-set value to the default. Every creation route passes
|
||||
the client value straight through, so this is the single choke point that
|
||||
keeps a typo from reaching the instrumental decision as an unknown value."""
|
||||
return v if v in ("auto", "clean", "review") else "auto"
|
||||
|
||||
@validator('artist', 'title')
|
||||
def normalize_artist_title(cls, v):
|
||||
"""Normalize artist/title text to standardize Unicode characters.
|
||||
|
||||
@@ -53,6 +53,10 @@ class TenantFeatures(BaseModel):
|
||||
True, description="Enable audio search (flacfetch integration)"
|
||||
)
|
||||
file_upload: bool = Field(True, description="Enable direct file upload")
|
||||
bulk_upload: bool = Field(
|
||||
True,
|
||||
description="Enable bulk folder upload (drop a folder of tracks, auto-pair Mixed/Instrumental)",
|
||||
)
|
||||
youtube_url: bool = Field(True, description="Enable YouTube URL input")
|
||||
|
||||
# Distribution options
|
||||
|
||||
+25
-2
@@ -10,7 +10,7 @@ Supports:
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from typing import Optional, List, Dict
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class UserRole(str, Enum):
|
||||
@@ -91,9 +91,16 @@ class User(BaseModel):
|
||||
# Optional profile fields for future use
|
||||
display_name: Optional[str] = None
|
||||
|
||||
# i18n locale preference (set from Accept-Language on login, used for emails/push)
|
||||
# i18n locale preference (set from Accept-Language on login, used for emails/push).
|
||||
# Narrowed to the 3 email-supported locales (en/es/de) — do NOT widen, email
|
||||
# rendering depends on it.
|
||||
locale: Optional[str] = None
|
||||
|
||||
# Actual UI language the user browses in (primary Accept-Language subtag, any
|
||||
# of the 33 supported locales, e.g. "pt", "ja"). Captured on login and job
|
||||
# creation. Admin-only signal so support knows what language to communicate in.
|
||||
ui_locale: Optional[str] = None
|
||||
|
||||
# Push notification subscriptions (Web Push API)
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
@@ -250,6 +257,22 @@ class AddCreditsResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class AdminCreateUserRequest(BaseModel):
|
||||
"""Admin request to create a user account directly."""
|
||||
email: EmailStr
|
||||
display_name: Optional[str] = None
|
||||
initial_credits: int = 0
|
||||
credit_reason: str = "admin_grant"
|
||||
|
||||
|
||||
class AdminCreateUserResponse(BaseModel):
|
||||
"""Response after admin creates a user."""
|
||||
status: str
|
||||
email: str
|
||||
credits: int
|
||||
message: str
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
"""Response for listing users (admin only)."""
|
||||
users: List[UserPublic]
|
||||
|
||||
@@ -101,35 +101,43 @@ class AudioAnalysisService:
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
gcs_waveform_destination: str,
|
||||
) -> tuple[AnalysisResult, str]:
|
||||
gcs_lead_vocals_path: Optional[str] = None,
|
||||
gcs_vocals_path: Optional[str] = None,
|
||||
) -> tuple[AnalysisResult, str, Optional[dict]]:
|
||||
"""
|
||||
Analyze backing vocals and generate a waveform image.
|
||||
|
||||
Analyze backing vocals, generate a waveform image, and (when the lead
|
||||
and full-vocals stems are provided) compute the 3-stem comparison
|
||||
signals for the backing-vocals decider.
|
||||
|
||||
This method:
|
||||
1. Downloads the audio file from GCS
|
||||
2. Runs analysis using AudioAnalyzer
|
||||
3. Generates waveform image using WaveformGenerator
|
||||
4. Uploads the waveform image to GCS
|
||||
5. Returns analysis result and waveform GCS path
|
||||
|
||||
5. Optionally downloads lead_vocals + vocals stems and runs
|
||||
compare_stems (best-effort — a failure yields a comparison dict
|
||||
with ``error`` set, never an exception)
|
||||
|
||||
Args:
|
||||
gcs_audio_path: Path to the audio file in GCS
|
||||
gcs_audio_path: Path to the backing-vocals audio file in GCS
|
||||
job_id: Job ID for logging
|
||||
gcs_waveform_destination: Where to upload the waveform image in GCS
|
||||
|
||||
gcs_lead_vocals_path: Optional GCS path of the lead_vocals stem
|
||||
gcs_vocals_path: Optional GCS path of the full vocals stem
|
||||
|
||||
Returns:
|
||||
Tuple of (AnalysisResult, waveform_gcs_path)
|
||||
Tuple of (AnalysisResult, waveform_gcs_path, stem_comparison dict or None)
|
||||
"""
|
||||
logger.info(f"[{job_id}] Analyzing and generating waveform: {gcs_audio_path}")
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
|
||||
# Run analysis
|
||||
result = self.analyzer.analyze(local_audio_path)
|
||||
|
||||
|
||||
# Generate waveform
|
||||
local_waveform_path = os.path.join(temp_dir, "waveform.png")
|
||||
self.waveform_generator.generate(
|
||||
@@ -139,19 +147,64 @@ class AudioAnalysisService:
|
||||
show_time_axis=True,
|
||||
silence_threshold_db=self.analyzer.silence_threshold_db,
|
||||
)
|
||||
|
||||
|
||||
# Upload waveform to GCS
|
||||
self.storage_service.upload_file(
|
||||
local_waveform_path,
|
||||
gcs_waveform_destination
|
||||
)
|
||||
|
||||
|
||||
comparison: Optional[dict] = None
|
||||
if gcs_lead_vocals_path and gcs_vocals_path:
|
||||
comparison = self._compare_stems(
|
||||
job_id, temp_dir, local_audio_path,
|
||||
gcs_lead_vocals_path, gcs_vocals_path,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[{job_id}] Analysis and waveform generation complete. "
|
||||
f"Waveform uploaded to: {gcs_waveform_destination}"
|
||||
)
|
||||
|
||||
return result, gcs_waveform_destination
|
||||
|
||||
return result, gcs_waveform_destination, comparison
|
||||
|
||||
def _compare_stems(
|
||||
self,
|
||||
job_id: str,
|
||||
temp_dir: str,
|
||||
local_backing_path: str,
|
||||
gcs_lead_vocals_path: str,
|
||||
gcs_vocals_path: str,
|
||||
) -> Optional[dict]:
|
||||
"""Download lead + vocals stems and run the 3-stem comparison.
|
||||
|
||||
Best-effort: returns None when the extra stems can't even be
|
||||
downloaded; compare_stems itself reports internal failures via the
|
||||
``error`` field rather than raising.
|
||||
"""
|
||||
from karaoke_gen.instrumental_review.stem_comparison import compare_stems
|
||||
|
||||
try:
|
||||
local_lead = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
local_vocals = os.path.join(temp_dir, "vocals.flac")
|
||||
self.storage_service.download_file(gcs_lead_vocals_path, local_lead)
|
||||
self.storage_service.download_file(gcs_vocals_path, local_vocals)
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] stem comparison skipped (download failed): {e}")
|
||||
return None
|
||||
comparison = compare_stems(
|
||||
local_backing_path,
|
||||
local_lead,
|
||||
local_vocals,
|
||||
silence_threshold_db=self.analyzer.silence_threshold_db,
|
||||
)
|
||||
logger.info(
|
||||
f"[{job_id}] Stem comparison: coverage_ratio={comparison.coverage_ratio}, "
|
||||
f"corr_backing_vocals={comparison.corr_backing_vocals}, "
|
||||
f"lead_overlap={comparison.lead_overlap_fraction}, "
|
||||
f"flat_fraction={comparison.flat_fraction}, error={comparison.error}"
|
||||
)
|
||||
return comparison.to_dict()
|
||||
|
||||
def get_waveform_data(
|
||||
self,
|
||||
|
||||
@@ -137,6 +137,34 @@ class AudioTranscodingService:
|
||||
self.get_review_audio_url, source_gcs_path, expiration_minutes
|
||||
)
|
||||
|
||||
def get_review_audio_bytes(self, source_gcs_path: str) -> tuple[bytes, str]:
|
||||
"""Return (bytes, content_type) of the transcoded review audio.
|
||||
|
||||
Used to proxy the audio through the API instead of 302-redirecting to a
|
||||
signed GCS URL. The waveform visualizer fetch()es + decodeAudioData()s
|
||||
this, which is a cross-origin read; a redirect to storage.googleapis.com
|
||||
makes the browser send `Origin: null` on the redirected request, which
|
||||
the bucket CORS rejects. Proxying keeps it same-origin to the API (which
|
||||
sets the right CORS headers). The transcoded OGG is small (~3 MB), well
|
||||
under Cloud Run's 32 MB response cap.
|
||||
|
||||
Falls back to the original (FLAC) source if transcoding fails, mirroring
|
||||
get_review_audio_url, so a transient ffmpeg/cache error doesn't blank the
|
||||
waveform while the source still exists. (A very long FLAC could exceed
|
||||
Cloud Run's 32 MB cap on that rare fallback path — the frontend then just
|
||||
hides the waveform, which is acceptable degradation.)
|
||||
"""
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_gcs_path)
|
||||
return self.storage.download_bytes(cache_path), "audio/ogg"
|
||||
except Exception as e:
|
||||
logger.warning(f"Transcoding failed for {source_gcs_path}, serving source audio: {e}")
|
||||
return self.storage.download_bytes(source_gcs_path), "audio/flac"
|
||||
|
||||
async def get_review_audio_bytes_async(self, source_gcs_path: str) -> tuple[bytes, str]:
|
||||
"""Async wrapper around get_review_audio_bytes via asyncio.to_thread."""
|
||||
return await asyncio.to_thread(self.get_review_audio_bytes, source_gcs_path)
|
||||
|
||||
def prepare_review_audio_for_job(self, job) -> list[str]:
|
||||
"""
|
||||
Transcode all review audio files for a job (eager transcoding).
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Auto-approvability scoring + review-diff analysis.
|
||||
|
||||
Shared, pure building blocks for the "fully-automated review" program:
|
||||
- ``scorer`` — decide whether a job's lyrics/backing decisions are safe to
|
||||
auto-approve (used in shadow mode first, then as the real gate).
|
||||
- ``lyrics_diff`` — reconstruct exactly what a human changed during review by
|
||||
diffing ``corrections.json`` against ``corrections_updated.json``.
|
||||
|
||||
See ``docs/archive/2026-08-25-full-auto-review-design.md``.
|
||||
"""
|
||||
|
||||
from backend.services.auto_approval.models import (
|
||||
AutoApprovabilityVerdict,
|
||||
BackingResult,
|
||||
BackingVerdict,
|
||||
LyricsResult,
|
||||
LyricsVerdict,
|
||||
)
|
||||
from backend.services.auto_approval.scorer import (
|
||||
SCORER_VERSION,
|
||||
score_backing,
|
||||
score_job,
|
||||
score_lyrics,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AutoApprovabilityVerdict",
|
||||
"BackingResult",
|
||||
"BackingVerdict",
|
||||
"LyricsResult",
|
||||
"LyricsVerdict",
|
||||
"SCORER_VERSION",
|
||||
"score_backing",
|
||||
"score_job",
|
||||
"score_lyrics",
|
||||
]
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Server-side application of AI auto-correct suggestions.
|
||||
|
||||
Faithful port of the review UI's auto-apply (frontend
|
||||
``lib/lyrics-review/utils/autoCorrectApply.ts`` + ``autoCorrectConflicts.ts`` +
|
||||
``useAutoCorrect.acceptAll``): the UI auto-applies every pending suggestion on
|
||||
load (conflict groups resolved by consensus → confidence), so a human reviewer
|
||||
always starts from the post-AI state. When a job is auto-approved without a
|
||||
human, this module produces that same post-AI state server-side.
|
||||
|
||||
Everything here is pure (dict in, dict out); any anomaly is reported so the
|
||||
caller can fall back to human review rather than ship a suspect result.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
Segment = Dict[str, Any]
|
||||
Suggestion = Dict[str, Any]
|
||||
|
||||
_WORD_SPLIT_RE = re.compile(r"\s+")
|
||||
_TOKEN_NORM_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _new_word_id() -> str:
|
||||
return uuid.uuid4().hex[:8]
|
||||
|
||||
|
||||
def _rebuild_text(words: List[Dict[str, Any]]) -> str:
|
||||
return " ".join(w.get("text", "") for w in words)
|
||||
|
||||
|
||||
def pick_accept_all_winners(suggestions: List[Suggestion]) -> List[str]:
|
||||
"""Winner ids for accept-all: one per conflict group (highest consensus,
|
||||
then confidence); non-conflicting suggestions all win. Original order."""
|
||||
best_of_group: Dict[str, Suggestion] = {}
|
||||
for s in suggestions:
|
||||
group = s.get("conflict_group")
|
||||
if not group:
|
||||
continue
|
||||
current = best_of_group.get(group)
|
||||
if (
|
||||
current is None
|
||||
or (s.get("consensus") or 0) > (current.get("consensus") or 0)
|
||||
or (
|
||||
(s.get("consensus") or 0) == (current.get("consensus") or 0)
|
||||
and (s.get("confidence") or 0) > (current.get("confidence") or 0)
|
||||
)
|
||||
):
|
||||
best_of_group[group] = s
|
||||
return [
|
||||
s["id"]
|
||||
for s in suggestions
|
||||
if not s.get("conflict_group")
|
||||
or best_of_group.get(s["conflict_group"], {}).get("id") == s.get("id")
|
||||
]
|
||||
|
||||
|
||||
def _find_segment_with_words(
|
||||
segments: List[Segment], word_ids: List[str]
|
||||
) -> Optional[Tuple[int, List[int]]]:
|
||||
if not word_ids:
|
||||
# all([]) is vacuously True — an empty/missing word_ids must read as
|
||||
# not-found, not as "matches the first segment".
|
||||
return None
|
||||
for i, seg in enumerate(segments):
|
||||
words = seg.get("words") or []
|
||||
indices = []
|
||||
for wid in word_ids:
|
||||
idx = next((j for j, w in enumerate(words) if w.get("id") == wid), -1)
|
||||
indices.append(idx)
|
||||
if all(x >= 0 for x in indices):
|
||||
return i, indices
|
||||
return None
|
||||
|
||||
|
||||
def is_suggestion_stale(segments: List[Segment], suggestion: Suggestion) -> bool:
|
||||
"""Stale when the target words no longer exist in one segment, contiguously."""
|
||||
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
|
||||
if not found:
|
||||
return True
|
||||
_, indices = found
|
||||
s = sorted(indices)
|
||||
return any(s[i] != s[i - 1] + 1 for i in range(1, len(s)))
|
||||
|
||||
|
||||
def _distribute_timings(
|
||||
n: int, start: Optional[float], end: Optional[float]
|
||||
) -> List[Tuple[Optional[float], Optional[float]]]:
|
||||
if n <= 0:
|
||||
return []
|
||||
if start is None or end is None or end <= start:
|
||||
return [(start, end)] * n
|
||||
step = (end - start) / n
|
||||
return [(start + i * step, start + (i + 1) * step) for i in range(n)]
|
||||
|
||||
|
||||
def _copy_segments(segments: List[Segment]) -> List[Segment]:
|
||||
return [{**s, "words": [dict(w) for w in (s.get("words") or [])]} for s in segments]
|
||||
|
||||
|
||||
def apply_suggestion(
|
||||
segments: List[Segment], suggestion: Suggestion
|
||||
) -> Optional[List[Segment]]:
|
||||
"""Apply one suggestion; returns new segments or None when stale."""
|
||||
if is_suggestion_stale(segments, suggestion):
|
||||
return None
|
||||
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
|
||||
if not found:
|
||||
return None
|
||||
seg_index, word_indices = found
|
||||
span_start = min(word_indices)
|
||||
span_end = max(word_indices)
|
||||
|
||||
result = _copy_segments(segments)
|
||||
seg = result[seg_index]
|
||||
words = seg["words"]
|
||||
op = suggestion.get("op")
|
||||
new_text = suggestion.get("new_text") or ""
|
||||
|
||||
if op == "insert_after":
|
||||
anchor = words[span_end]
|
||||
nxt = words[span_end + 1] if span_end + 1 < len(words) else None
|
||||
new_texts = [t for t in _WORD_SPLIT_RE.split(new_text) if t]
|
||||
window_start = anchor.get("end_time")
|
||||
if (
|
||||
nxt is not None
|
||||
and nxt.get("start_time") is not None
|
||||
and window_start is not None
|
||||
and nxt["start_time"] > window_start
|
||||
):
|
||||
window_end: Optional[float] = nxt["start_time"]
|
||||
elif window_start is not None:
|
||||
window_end = window_start + 0.5 * len(new_texts)
|
||||
else:
|
||||
window_end = None
|
||||
timings = _distribute_timings(len(new_texts), window_start, window_end)
|
||||
new_words = [
|
||||
{
|
||||
"id": _new_word_id(),
|
||||
"text": text,
|
||||
"start_time": t[0],
|
||||
"end_time": t[1],
|
||||
"confidence": 1,
|
||||
"created_during_correction": True,
|
||||
"ai_corrected": True,
|
||||
# Inserted words have no source transcription -> synthetic timing.
|
||||
"timing_estimated": True,
|
||||
"correction_span_id": suggestion.get("id"),
|
||||
}
|
||||
for text, t in zip(new_texts, timings)
|
||||
]
|
||||
words[span_end + 1 : span_end + 1] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
return result
|
||||
|
||||
removed = words[span_start : span_end + 1]
|
||||
|
||||
if op == "delete":
|
||||
del words[span_start : span_start + len(removed)]
|
||||
if not words:
|
||||
del result[seg_index]
|
||||
else:
|
||||
seg["text"] = _rebuild_text(words)
|
||||
seg["start_time"] = words[0].get("start_time")
|
||||
seg["end_time"] = words[-1].get("end_time")
|
||||
return result
|
||||
|
||||
# replace
|
||||
new_texts = [t for t in _WORD_SPLIT_RE.split(new_text) if t]
|
||||
timings = _distribute_timings(
|
||||
len(new_texts),
|
||||
removed[0].get("start_time") if removed else None,
|
||||
removed[-1].get("end_time") if removed else None,
|
||||
)
|
||||
# >1 replacement word forces an even split of one range -> estimated timing.
|
||||
timing_estimated = len(new_texts) > 1
|
||||
original_span_text = suggestion.get("original_text") or _rebuild_text(removed)
|
||||
new_words = []
|
||||
for i, (text, t) in enumerate(zip(new_texts, timings)):
|
||||
w = {
|
||||
"id": _new_word_id(),
|
||||
"text": text,
|
||||
"start_time": t[0],
|
||||
"end_time": t[1],
|
||||
"confidence": 1,
|
||||
"created_during_correction": True,
|
||||
"ai_corrected": True,
|
||||
"timing_estimated": timing_estimated,
|
||||
"correction_span_id": suggestion.get("id"),
|
||||
}
|
||||
if i == 0:
|
||||
w["original_text"] = original_span_text
|
||||
new_words.append(w)
|
||||
words[span_start : span_start + len(removed)] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
return result
|
||||
|
||||
|
||||
def apply_all_suggestions(
|
||||
segments: List[Segment], suggestions: List[Suggestion]
|
||||
) -> Dict[str, Any]:
|
||||
"""Accept-all with conflict resolution, mirroring the UI's on-load auto-apply.
|
||||
|
||||
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids"}``.
|
||||
"""
|
||||
winners = set(pick_accept_all_winners(suggestions))
|
||||
current = segments
|
||||
applied: List[str] = []
|
||||
rejected: List[str] = []
|
||||
stale: List[str] = []
|
||||
for s in suggestions:
|
||||
sid = s.get("id") or ""
|
||||
if sid not in winners:
|
||||
rejected.append(sid)
|
||||
continue
|
||||
result = apply_suggestion(current, s)
|
||||
if result is None:
|
||||
stale.append(sid)
|
||||
continue
|
||||
current = result
|
||||
applied.append(sid)
|
||||
return {
|
||||
"segments": current,
|
||||
"applied_ids": applied,
|
||||
"rejected_ids": rejected,
|
||||
"stale_ids": stale,
|
||||
}
|
||||
|
||||
|
||||
def build_applied_segments(
|
||||
corrections: Dict[str, Any], ai_suggestions: Optional[List[Suggestion]]
|
||||
) -> Dict[str, Any]:
|
||||
"""Apply the AI suggestions to a corrections payload with the safety gates.
|
||||
|
||||
Shared by the executor (auto-complete) and the review-gate pre-apply. Returns
|
||||
``{"aborted": <reason>}`` on any anomaly (caller falls back to human review /
|
||||
client-side apply), else ``{"segments", "applied_ids", "rejected_ids"}``.
|
||||
"""
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if not segments:
|
||||
return {"aborted": "no_segments"}
|
||||
|
||||
result = apply_all_suggestions(segments, ai_suggestions or [])
|
||||
if result["stale_ids"]:
|
||||
# Nothing edits segments between generation and now, so staleness means
|
||||
# the cache doesn't match this corrections.json -> don't trust the apply.
|
||||
return {"aborted": f"stale_suggestions:{len(result['stale_ids'])}"}
|
||||
|
||||
new_segments = result["segments"]
|
||||
if not new_segments or any(not (s.get("words") or []) for s in new_segments):
|
||||
return {"aborted": "empty_segments_after_apply"}
|
||||
|
||||
duplicates = find_suspicious_duplicates(new_segments, corrections.get("reference_lyrics"))
|
||||
if duplicates:
|
||||
# P1 signature: overlapping suggestions doubled a word ("you're you're").
|
||||
return {"aborted": f"duplicate_words:{','.join(duplicates[:5])}"}
|
||||
|
||||
return {
|
||||
"segments": new_segments,
|
||||
"applied_ids": result["applied_ids"],
|
||||
"rejected_ids": result["rejected_ids"],
|
||||
}
|
||||
|
||||
|
||||
def _norm_token(text: str) -> str:
|
||||
return _TOKEN_NORM_RE.sub("", (text or "").lower())
|
||||
|
||||
|
||||
def find_suspicious_duplicates(
|
||||
segments: List[Segment], reference_lyrics: Optional[Dict[str, Any]] = None
|
||||
) -> List[str]:
|
||||
"""Adjacent identical words that no reference supports (P1 self-conflict
|
||||
signature — e.g. two overlapping suggestions both adding "you're" produced
|
||||
"fire, you're you're gasoline"). Returns the offending tokens."""
|
||||
ref_texts: List[str] = []
|
||||
for ref in (reference_lyrics or {}).values():
|
||||
for ref_seg in ref.get("segments") or []:
|
||||
ref_texts.append(" ".join(
|
||||
_norm_token(t) for t in _WORD_SPLIT_RE.split(ref_seg.get("text") or "") if t
|
||||
))
|
||||
ref_blob = "\n".join(ref_texts)
|
||||
|
||||
offenders: List[str] = []
|
||||
for seg in segments:
|
||||
words = seg.get("words") or []
|
||||
for i in range(1, len(words)):
|
||||
a = _norm_token(words[i - 1].get("text") or "")
|
||||
b = _norm_token(words[i].get("text") or "")
|
||||
if a and a == b:
|
||||
# A doubled word is fine when a reference genuinely repeats it.
|
||||
if f"{a} {a}" in ref_blob:
|
||||
continue
|
||||
offenders.append(a)
|
||||
return offenders
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Auto-approval executor: complete the combined review without a human when safe.
|
||||
|
||||
Called from two places (covering both orderings of audio vs lyrics completion):
|
||||
- ``screens_worker`` just before it would transition to AWAITING_REVIEW
|
||||
(trigger="screens_worker", job still GENERATING_SCREENS), and
|
||||
- ``audio_worker`` after stems + backing analysis land, when the job is already
|
||||
sitting in AWAITING_REVIEW (trigger="audio_worker").
|
||||
|
||||
Every call scores the job and records the verdict in
|
||||
``processing_metadata.auto_approval`` (so shadow data accumulates on every job).
|
||||
Enforcement — actually skipping the review screens — happens only when ALL of:
|
||||
- the feature flag is on and the job's ``review_mode`` is "auto" (the default);
|
||||
- the job is not a made-for-you order (the human QC pass is part of that
|
||||
product);
|
||||
- the job is ELIGIBLE: with a user-supplied instrumental (tenant bulk uploads,
|
||||
the existing-instrumental upload option, mute-region edits) there is no
|
||||
instrumental decision to make, so confident lyrics alone qualify and the
|
||||
selection is "custom" — mirroring the human tenant complete-review flow.
|
||||
Otherwise the scorer's ``overall_auto`` must be True (confident lyrics AND a
|
||||
non-subjective backing decision);
|
||||
- audio separation is complete and the required instrumental exists (clean or
|
||||
with-backing stem; the video worker validates custom sources itself).
|
||||
|
||||
The enforce path replicates exactly what a human clicking "Complete Review"
|
||||
does after the UI's on-load auto-apply: apply the cached AI suggestions
|
||||
(conflict groups resolved identically), save ``corrections_updated.json``,
|
||||
store the instrumental selection, clear worker progress keys, transition to
|
||||
REVIEW_COMPLETE and trigger the render worker.
|
||||
|
||||
FAIL-SAFE: any anomaly (stale suggestions, duplicate-word artifacts, missing
|
||||
data, exceptions) aborts enforcement and the job proceeds to normal human
|
||||
review. Auto-approval must never be the reason a job fails.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.auto_approval.instrumental import (
|
||||
backing_decision,
|
||||
has_custom_instrumental,
|
||||
)
|
||||
from backend.services.auto_approval.models import LyricsVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CORRECTIONS_PATH = "jobs/{job_id}/lyrics/corrections.json"
|
||||
CORRECTIONS_UPDATED_PATH = "jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
AUTO_CORRECT_CACHE_PREFIX = "jobs/{job_id}/lyrics/auto_correct_cache/"
|
||||
|
||||
REVIEW_MODE_AUTO = "auto"
|
||||
REVIEW_MODE_ALWAYS_REVIEW = "always_review"
|
||||
|
||||
|
||||
def _load_ai_suggestions(storage, job_id: str) -> Optional[List[Dict[str, Any]]]:
|
||||
"""The proactive auto-correct cache the review UI would auto-apply on load."""
|
||||
try:
|
||||
prefix = AUTO_CORRECT_CACHE_PREFIX.format(job_id=job_id)
|
||||
for cache_path in sorted(storage.list_files(prefix)):
|
||||
cached = storage.download_json(cache_path)
|
||||
suggestions = cached.get("suggestions")
|
||||
if isinstance(suggestions, list):
|
||||
return suggestions
|
||||
except Exception as e:
|
||||
logger.info(f"[job:{job_id}] auto-approval: no auto-correct cache readable ({e})")
|
||||
return None
|
||||
|
||||
|
||||
def _enforcement_blockers(job, settings) -> List[str]:
|
||||
"""Why this job may not be ENFORCED (shadow scoring still happens)."""
|
||||
blockers: List[str] = []
|
||||
if not settings.auto_approval_enforce_enabled:
|
||||
blockers.append("flag_disabled")
|
||||
review_mode = getattr(job, "review_mode", REVIEW_MODE_AUTO) or REVIEW_MODE_AUTO
|
||||
if review_mode != REVIEW_MODE_AUTO:
|
||||
blockers.append(f"review_mode:{review_mode}")
|
||||
if getattr(job, "made_for_you", False):
|
||||
blockers.append("made_for_you")
|
||||
return blockers
|
||||
|
||||
|
||||
async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any]:
|
||||
"""Score the job, record the verdict, and auto-complete the review if safe.
|
||||
|
||||
Returns a small status dict; ``{"outcome": "auto_completed"}`` means the
|
||||
review screens were skipped and the render worker has been triggered.
|
||||
Never raises.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_approval.scorer import score_job
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
outcome: Dict[str, Any] = {"outcome": "skipped"}
|
||||
try:
|
||||
settings = get_settings()
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
return {"outcome": "no_job"}
|
||||
|
||||
# Only act on the two known launch points; a human already in the
|
||||
# editor (IN_REVIEW) or any other state is out of scope.
|
||||
if trigger == "screens_worker":
|
||||
expected_statuses = (JobStatus.GENERATING_SCREENS,)
|
||||
else:
|
||||
expected_statuses = (JobStatus.AWAITING_REVIEW,)
|
||||
if job.status not in expected_statuses:
|
||||
return {"outcome": "wrong_status", "status": str(job.status)}
|
||||
if job.state_data.get("instrumental_selection"):
|
||||
return {"outcome": "already_selected"}
|
||||
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
return {"outcome": "no_corrections"}
|
||||
corrections = storage.download_json(corrections_path)
|
||||
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
state_data = job.state_data or {}
|
||||
backing_analysis = state_data.get("backing_vocals_analysis")
|
||||
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)
|
||||
blockers = _enforcement_blockers(job, settings)
|
||||
custom_instrumental = has_custom_instrumental(job)
|
||||
backing_preference = getattr(job, "backing_preference", "auto") or "auto"
|
||||
backing_keep_enabled = getattr(settings, "auto_approval_backing_keep_enabled", False)
|
||||
# Single source of truth for the instrumental decision (shared with the
|
||||
# complete-review "auto" resolver and the per-screen-skip UI summary).
|
||||
decision = backing_decision(
|
||||
backing_verdict=verdict.backing.verdict.value,
|
||||
backing_non_subjective=verdict.backing.non_subjective,
|
||||
backing_preference=backing_preference,
|
||||
backing_keep_enabled=backing_keep_enabled,
|
||||
custom_instrumental=custom_instrumental,
|
||||
)
|
||||
keep_backing = decision["keep_backing"]
|
||||
|
||||
# Eligibility: confident lyrics AND a resolvable instrumental decision.
|
||||
# With a user-supplied instrumental the backing decision is moot, so
|
||||
# confident lyrics alone qualify (selection="custom").
|
||||
lyrics_auto = verdict.lyrics.verdict == LyricsVerdict.AUTO
|
||||
if custom_instrumental:
|
||||
eligible = lyrics_auto
|
||||
enforcement_basis = "lyrics_only_custom_instrumental"
|
||||
else:
|
||||
eligible = lyrics_auto and decision["ok"]
|
||||
enforcement_basis = (
|
||||
"overall_auto"
|
||||
if backing_preference == "auto"
|
||||
else f"lyrics_auto_backing_pref:{backing_preference}"
|
||||
)
|
||||
|
||||
# Stem / audio blockers (the instrumental the selection needs must exist).
|
||||
if not audio_complete:
|
||||
blockers.append("audio_incomplete")
|
||||
elif custom_instrumental:
|
||||
# User-supplied instrumental -> "custom"; the video worker validates
|
||||
# the custom source itself, no separated-stem requirements.
|
||||
pass
|
||||
elif keep_backing:
|
||||
# Confident-keep (3-stem decider) selects the with-backing
|
||||
# instrumental — gated shadow-first behind its own flag.
|
||||
if not backing_keep_enabled:
|
||||
blockers.append("backing_keep_disabled")
|
||||
if not stems.get("instrumental_with_backing"):
|
||||
blockers.append("no_with_backing_stem")
|
||||
elif not stems.get("instrumental_clean"):
|
||||
# Clean selection (auto-clean verdict OR backing_preference="clean").
|
||||
blockers.append("no_clean_stem")
|
||||
|
||||
payload = verdict.to_dict()
|
||||
payload.update({
|
||||
"mode": "shadow", # flipped to "enforce" only when we actually enforce
|
||||
"enforcement_eligible": eligible and not blockers,
|
||||
"enforcement_basis": enforcement_basis,
|
||||
"custom_instrumental": custom_instrumental,
|
||||
"backing_preference": backing_preference,
|
||||
"resolved_instrumental_selection": decision["selection"],
|
||||
"trigger": trigger,
|
||||
"enforcement_blockers": blockers,
|
||||
"audio_complete_at_scoring": audio_complete,
|
||||
"backing_analysis_available": backing_analysis is not None,
|
||||
"ai_suggestions_available": ai_suggestions is not None,
|
||||
"scored_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
|
||||
summary = (
|
||||
f"auto-approval [{trigger}]: eligible={eligible} ({enforcement_basis}) "
|
||||
f"lyrics={verdict.lyrics.verdict.value}/{verdict.lyrics.tier} "
|
||||
f"backing={verdict.backing.verdict.value} blockers={blockers or 'none'} "
|
||||
f"(scorer v{verdict.scorer_version})"
|
||||
)
|
||||
logger.info(f"[job:{job_id}] {summary}")
|
||||
|
||||
if not eligible or blockers:
|
||||
payload["outcome"] = "review"
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
return {"outcome": "review", "overall_auto": verdict.overall_auto,
|
||||
"blockers": blockers}
|
||||
|
||||
# ---- ENFORCE: complete the review exactly like a human would ----
|
||||
# The status gate above used a snapshot read. Re-read now so a human who
|
||||
# opened the editor in the meantime (AWAITING_REVIEW -> IN_REVIEW) is not
|
||||
# overwritten — IN_REVIEW -> REVIEW_COMPLETE is a legal transition and
|
||||
# would otherwise pass validation mid-edit.
|
||||
fresh = job_manager.get_job(job_id)
|
||||
if (
|
||||
not fresh
|
||||
or fresh.status not in expected_statuses
|
||||
or (fresh.state_data or {}).get("instrumental_selection")
|
||||
):
|
||||
payload["outcome"] = "aborted"
|
||||
payload["abort_reason"] = "state_changed_during_enforce"
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
return {"outcome": "aborted", "reason": "state_changed_during_enforce"}
|
||||
|
||||
applied_info = _build_auto_corrections(
|
||||
job_id, corrections, ai_suggestions or [], storage
|
||||
)
|
||||
if applied_info.get("aborted"):
|
||||
payload["outcome"] = "aborted"
|
||||
payload["abort_reason"] = applied_info["aborted"]
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
logger.warning(
|
||||
f"[job:{job_id}] auto-approval aborted -> human review "
|
||||
f"({applied_info['aborted']})"
|
||||
)
|
||||
return {"outcome": "aborted", "reason": applied_info["aborted"]}
|
||||
|
||||
# Instrumental selection resolved by the shared decision: user-supplied
|
||||
# instrumental -> "custom"; otherwise the non-subjective backing verdict
|
||||
# (or the user's backing_preference) picks the separated stem.
|
||||
selection = decision["selection"] or ("with_backing" if keep_backing else "clean")
|
||||
job_manager.update_state_data(job_id, "instrumental_selection", selection)
|
||||
|
||||
# Clear worker progress keys so downstream workers run fresh (mirrors
|
||||
# complete_review — idempotency keys would otherwise skip re-runs).
|
||||
progress_keys = ["render_progress", "video_progress", "encoding_progress"]
|
||||
job_manager.delete_state_data_keys(job_id, progress_keys)
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.REVIEW_COMPLETE,
|
||||
progress=70,
|
||||
message=(
|
||||
"Auto-approved: lyrics verified against synced references and "
|
||||
+ (
|
||||
"using your provided instrumental"
|
||||
if custom_instrumental
|
||||
else (
|
||||
"clear backing vocals retained"
|
||||
if keep_backing
|
||||
else "no audible backing vocals"
|
||||
)
|
||||
)
|
||||
+ " — skipping review, rendering video"
|
||||
),
|
||||
)
|
||||
|
||||
# Record the verdict AFTER the transition so the metadata never claims
|
||||
# auto-completion for a job that in fact fell back to human review.
|
||||
payload["mode"] = "enforce"
|
||||
payload["outcome"] = "auto_completed"
|
||||
payload["applied_suggestions"] = len(applied_info.get("applied_ids") or [])
|
||||
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
|
||||
|
||||
from backend.services.worker_service import get_worker_service
|
||||
await get_worker_service().trigger_render_video_worker(job_id)
|
||||
|
||||
logger.info(f"[job:{job_id}] auto-approval COMPLETED review "
|
||||
f"(applied {payload['applied_suggestions']} AI suggestions)")
|
||||
return {"outcome": "auto_completed"}
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] auto-approval failed non-fatally: {e}", exc_info=True)
|
||||
try:
|
||||
from backend.services.job_manager import JobManager
|
||||
JobManager().update_processing_metadata(job_id, "auto_approval", {
|
||||
"outcome": "error",
|
||||
"error": str(e),
|
||||
"trigger": trigger,
|
||||
"scored_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
return {"outcome": "error", "error": str(e)}
|
||||
|
||||
|
||||
def _build_auto_corrections(
|
||||
job_id: str,
|
||||
corrections: Dict[str, Any],
|
||||
ai_suggestions: List[Dict[str, Any]],
|
||||
storage,
|
||||
) -> Dict[str, Any]:
|
||||
"""Apply the AI suggestions and save corrections_updated.json.
|
||||
|
||||
Returns ``{"aborted": <reason>}`` on any anomaly (caller falls back to
|
||||
human review), else ``{"applied_ids": [...]}``.
|
||||
"""
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
|
||||
result = build_applied_segments(corrections, ai_suggestions)
|
||||
if result.get("aborted"):
|
||||
return {"aborted": result["aborted"]}
|
||||
|
||||
updated = dict(corrections)
|
||||
updated["corrected_segments"] = result["segments"]
|
||||
metadata = dict(updated.get("metadata") or {})
|
||||
metadata["auto_approval"] = {
|
||||
"auto_approved": True,
|
||||
"applied_suggestion_ids": result["applied_ids"],
|
||||
"rejected_suggestion_ids": result["rejected_ids"],
|
||||
"applied_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
updated["metadata"] = metadata
|
||||
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
storage.upload_json(updated_path, updated)
|
||||
|
||||
from backend.services.job_manager import JobManager
|
||||
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
|
||||
logger.info(
|
||||
f"[job:{job_id}] auto-approval saved corrections_updated.json "
|
||||
f"({len(result['applied_ids'])} suggestions applied, "
|
||||
f"{len(result['rejected_ids'])} conflict-losers rejected)"
|
||||
)
|
||||
return {"applied_ids": result["applied_ids"]}
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Single source of truth for the auto instrumental-selection decision.
|
||||
|
||||
The backing decision is derived in three places that MUST agree:
|
||||
- the executor, when auto-completing a job (live verdict object);
|
||||
- ``POST /review/{id}/complete`` when a client sends ``instrumental_selection="auto"``
|
||||
(reads the stored ``processing_metadata.auto_approval`` verdict);
|
||||
- the ``/correction-data`` response summary the frontend uses to decide whether to
|
||||
show the instrumental screen at all (per-screen skip, C1).
|
||||
|
||||
``backing_decision`` is a pure function over primitives so all three can call it with
|
||||
either the live verdict or the persisted dict. It also folds in the user's up-front
|
||||
``backing_preference`` (C3): ``clean`` forces a clean instrumental, ``review`` suppresses
|
||||
the auto backing decision so a human always picks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
BACKING_PREFERENCE_AUTO = "auto" # retain backing vocals where confidently safe (default)
|
||||
BACKING_PREFERENCE_CLEAN = "clean" # always use the clean instrumental
|
||||
BACKING_PREFERENCE_REVIEW = "review" # always let a human pick the instrumental
|
||||
VALID_BACKING_PREFERENCES = (
|
||||
BACKING_PREFERENCE_AUTO,
|
||||
BACKING_PREFERENCE_CLEAN,
|
||||
BACKING_PREFERENCE_REVIEW,
|
||||
)
|
||||
|
||||
|
||||
def has_custom_instrumental(job) -> bool:
|
||||
"""True when the user supplied their own instrumental (tenant bulk uploads,
|
||||
the upload flow's existing-instrumental option, or a mute-region edit).
|
||||
|
||||
For these jobs there is NO instrumental decision to make — the human
|
||||
complete-review flow submits ``instrumental_selection="custom"``.
|
||||
"""
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
return bool(
|
||||
getattr(job, "existing_instrumental_gcs_path", None)
|
||||
or stems.get("custom_instrumental")
|
||||
)
|
||||
|
||||
|
||||
def backing_decision(
|
||||
*,
|
||||
backing_verdict: Optional[str],
|
||||
backing_non_subjective: bool,
|
||||
backing_preference: Optional[str],
|
||||
backing_keep_enabled: bool,
|
||||
custom_instrumental: bool,
|
||||
) -> Dict[str, Any]:
|
||||
"""Resolve the instrumental decision from a (live or stored) backing verdict.
|
||||
|
||||
Returns ``{"ok": bool, "selection": Optional[str], "keep_backing": bool}``:
|
||||
- ``ok`` — the instrumental can be auto-selected (no human needed for this half).
|
||||
- ``selection`` — "custom" | "clean" | "with_backing" | None (None ⇒ human must pick).
|
||||
- ``keep_backing`` — informational: the confident verdict is a with-backing keep
|
||||
(used by the executor to require the with-backing stem).
|
||||
"""
|
||||
if custom_instrumental:
|
||||
return {"ok": True, "selection": "custom", "keep_backing": False}
|
||||
|
||||
pref = backing_preference or BACKING_PREFERENCE_AUTO
|
||||
if pref == BACKING_PREFERENCE_CLEAN:
|
||||
# User asked to always strip backing vocals.
|
||||
return {"ok": True, "selection": "clean", "keep_backing": False}
|
||||
if pref == BACKING_PREFERENCE_REVIEW:
|
||||
# User asked to always decide the instrumental themselves.
|
||||
return {"ok": False, "selection": None, "keep_backing": False}
|
||||
|
||||
# pref == auto: rely on the non-subjective backing verdict.
|
||||
if not backing_non_subjective:
|
||||
return {"ok": False, "selection": None, "keep_backing": False}
|
||||
if backing_verdict == "with_backing":
|
||||
# Confident 3-stem keep — gated shadow-first behind its own flag.
|
||||
if not backing_keep_enabled:
|
||||
return {"ok": False, "selection": None, "keep_backing": True}
|
||||
return {"ok": True, "selection": "with_backing", "keep_backing": True}
|
||||
# Confident CLEAN ("no audible backing").
|
||||
return {"ok": True, "selection": "clean", "keep_backing": False}
|
||||
|
||||
|
||||
def auto_approval_summary(job, settings) -> Dict[str, Any]:
|
||||
"""Compact block for the ``/correction-data`` response (C1 per-screen skip).
|
||||
|
||||
Reads the stored ``processing_metadata.auto_approval`` verdict + the job's
|
||||
``backing_preference`` and tells the frontend whether each review half is
|
||||
confidently resolved (so it can skip that screen).
|
||||
"""
|
||||
aa = (getattr(job, "processing_metadata", None) or {}).get("auto_approval") or {}
|
||||
backing = aa.get("backing") or {}
|
||||
lyrics = aa.get("lyrics") or {}
|
||||
custom = has_custom_instrumental(job)
|
||||
|
||||
# ``always_review`` (or any non-"auto" review_mode) means the user asked to
|
||||
# see every screen — no half is ever "confident" enough to skip.
|
||||
review_mode = getattr(job, "review_mode", "auto") or "auto"
|
||||
if review_mode != "auto":
|
||||
return {
|
||||
"backing": {"verdict": backing.get("verdict"), "confident": False, "resolved_selection": None},
|
||||
"lyrics": {"verdict": lyrics.get("verdict"), "confident": False},
|
||||
"custom_instrumental": custom,
|
||||
"verdict_present": bool(aa),
|
||||
}
|
||||
|
||||
decision = backing_decision(
|
||||
backing_verdict=backing.get("verdict"),
|
||||
backing_non_subjective=bool(backing.get("non_subjective")),
|
||||
backing_preference=getattr(job, "backing_preference", BACKING_PREFERENCE_AUTO),
|
||||
backing_keep_enabled=bool(getattr(settings, "auto_approval_backing_keep_enabled", False)),
|
||||
custom_instrumental=custom,
|
||||
)
|
||||
selection = _selection_with_stem_check(job, decision["selection"])
|
||||
return {
|
||||
"backing": {
|
||||
"verdict": backing.get("verdict"),
|
||||
"confident": selection is not None,
|
||||
"resolved_selection": selection,
|
||||
},
|
||||
"lyrics": {
|
||||
"verdict": lyrics.get("verdict"),
|
||||
"confident": lyrics.get("verdict") == "auto",
|
||||
},
|
||||
"custom_instrumental": custom,
|
||||
"verdict_present": bool(aa),
|
||||
}
|
||||
|
||||
|
||||
def _selection_with_stem_check(job, selection: Optional[str]) -> Optional[str]:
|
||||
"""None out a separated-stem selection when that stem isn't present, so the
|
||||
complete endpoint never persists an instrumental the render worker can't use
|
||||
(mirrors the executor's no_*_stem blockers). "custom" is validated elsewhere."""
|
||||
if selection in ("clean", "with_backing"):
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
stem_key = "instrumental_with_backing" if selection == "with_backing" else "instrumental_clean"
|
||||
if not stems.get(stem_key):
|
||||
return None
|
||||
return selection
|
||||
|
||||
|
||||
def resolve_auto_instrumental(job, settings) -> Optional[str]:
|
||||
"""Map a client's ``instrumental_selection="auto"`` to a concrete selection
|
||||
from the stored verdict, or None when it isn't confidently resolvable."""
|
||||
return auto_approval_summary(job, settings)["backing"]["resolved_selection"]
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Reconstruct exactly what a human changed during lyrics review.
|
||||
|
||||
Diffs the raw transcription (``corrections.json`` -> ``corrected_segments``) against
|
||||
the reviewer's final result (``corrections_updated.json`` -> ``corrected_segments``).
|
||||
Because production runs with auto-correction disabled, the original ``corrected_segments``
|
||||
IS the raw AudioShake transcription, so this diff is *exactly* the set of manual edits
|
||||
Andrew made — the ground truth the recording corpus is built on.
|
||||
|
||||
Words carry stable ``id``s, BUT the review UI assigns a NEW id when a word's text is
|
||||
replaced (rather than mutating in place). It preserves the word's start/end time and line,
|
||||
though — so a text correction shows up as a delete+insert at the *same timing*. We recover
|
||||
those as ``replacements`` by pairing a deletion with an insertion sharing (line, start, end).
|
||||
|
||||
The diff is keyed on word id and yields:
|
||||
- ``replacements`` — a word swapped for another at the same time/line (`Carl` → `Karl`);
|
||||
the common case for mis-transcribed words
|
||||
- ``text_edits`` — same id, changed text (in-place edit; rare)
|
||||
- ``timing_changes`` — same id, moved start/end (a sync nudge)
|
||||
- ``deletions`` — a word removed with no same-timing replacement (adlib/dupe/etc.)
|
||||
- ``insertions`` — a word added with no same-timing original
|
||||
- ``segmentation`` — line count changed or a word moved between lines (split/merge/rewrap)
|
||||
|
||||
See ``docs/archive/2026-08-25-full-auto-review-design.md``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
# Minimum start/end move (seconds) to count as a deliberate timing change, not float noise.
|
||||
TIMING_EPSILON = 0.005
|
||||
# Max start/end difference (seconds) to treat a delete+insert as an in-place replacement.
|
||||
REPLACE_TIMING_EPSILON = 0.02
|
||||
|
||||
|
||||
@dataclass
|
||||
class TextEdit:
|
||||
word_id: str
|
||||
original_text: str
|
||||
final_text: str
|
||||
segment_index: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class TimingChange:
|
||||
word_id: str
|
||||
text: str
|
||||
original_start: Optional[float]
|
||||
original_end: Optional[float]
|
||||
final_start: Optional[float]
|
||||
final_end: Optional[float]
|
||||
start_delta: Optional[float]
|
||||
end_delta: Optional[float]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Replacement:
|
||||
"""A word swapped for another at the same time/line (mis-transcription fix)."""
|
||||
|
||||
original_word_id: str
|
||||
final_word_id: str
|
||||
original_text: str
|
||||
final_text: str
|
||||
segment_index: int
|
||||
start_time: Optional[float]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WordRef:
|
||||
word_id: str
|
||||
text: str
|
||||
segment_index: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class SegmentMove:
|
||||
"""A word that stayed but moved to a different line (split/merge/rewrap)."""
|
||||
|
||||
word_id: str
|
||||
text: str
|
||||
original_segment_index: int
|
||||
final_segment_index: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class LyricsDiff:
|
||||
has_changes: bool = False
|
||||
total_changes: int = 0
|
||||
original_segment_count: int = 0
|
||||
final_segment_count: int = 0
|
||||
original_word_count: int = 0
|
||||
final_word_count: int = 0
|
||||
segmentation_changed: bool = False
|
||||
replacements: List[Replacement] = field(default_factory=list)
|
||||
text_edits: List[TextEdit] = field(default_factory=list)
|
||||
timing_changes: List[TimingChange] = field(default_factory=list)
|
||||
deletions: List[WordRef] = field(default_factory=list)
|
||||
insertions: List[WordRef] = field(default_factory=list)
|
||||
segment_moves: List[SegmentMove] = field(default_factory=list)
|
||||
# The UI-recorded WordCorrection list from corrections_updated.json (supplementary).
|
||||
ui_recorded_corrections: int = 0
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _index_words(segments: List[Dict[str, Any]]) -> Tuple[Dict[str, Dict[str, Any]], int]:
|
||||
"""Return {word_id: {text,start,end,segment_index}} and total word count."""
|
||||
by_id: Dict[str, Dict[str, Any]] = {}
|
||||
count = 0
|
||||
for seg_index, seg in enumerate(segments or []):
|
||||
for word in seg.get("words") or []:
|
||||
wid = word.get("id")
|
||||
count += 1
|
||||
if not wid:
|
||||
continue
|
||||
by_id[wid] = {
|
||||
"text": (word.get("text") or "").strip(),
|
||||
"start": word.get("start_time"),
|
||||
"end": word.get("end_time"),
|
||||
"segment_index": seg_index,
|
||||
}
|
||||
return by_id, count
|
||||
|
||||
|
||||
def _delta(a: Optional[float], b: Optional[float]) -> Optional[float]:
|
||||
if a is None or b is None:
|
||||
return None
|
||||
return round(b - a, 4)
|
||||
|
||||
|
||||
def compute_lyrics_diff(
|
||||
original_data: Dict[str, Any],
|
||||
updated_data: Optional[Dict[str, Any]],
|
||||
) -> LyricsDiff:
|
||||
"""Diff raw transcription against the reviewer's final result.
|
||||
|
||||
``original_data``: parsed ``corrections.json``.
|
||||
``updated_data``: parsed ``corrections_updated.json`` (or ``None`` if the job was
|
||||
never edited — yields an empty diff).
|
||||
"""
|
||||
orig_segments = original_data.get("corrected_segments") or []
|
||||
orig_by_id, orig_count = _index_words(orig_segments)
|
||||
|
||||
diff = LyricsDiff(
|
||||
original_segment_count=len(orig_segments),
|
||||
original_word_count=orig_count,
|
||||
)
|
||||
|
||||
if not updated_data or "corrected_segments" not in updated_data:
|
||||
# No human edits recorded — final == raw transcription.
|
||||
diff.final_segment_count = len(orig_segments)
|
||||
diff.final_word_count = orig_count
|
||||
return diff
|
||||
|
||||
final_segments = updated_data.get("corrected_segments") or []
|
||||
final_by_id, final_count = _index_words(final_segments)
|
||||
diff.final_segment_count = len(final_segments)
|
||||
diff.final_word_count = final_count
|
||||
diff.ui_recorded_corrections = len(updated_data.get("corrections") or [])
|
||||
|
||||
orig_ids = set(orig_by_id)
|
||||
final_ids = set(final_by_id)
|
||||
|
||||
deleted_ids = sorted(orig_ids - final_ids)
|
||||
inserted_ids = sorted(final_ids - orig_ids)
|
||||
|
||||
# Pair delete+insert at the same line & timing into replacements (mis-transcription
|
||||
# fixes: the UI re-keys the word but keeps its slot). One-to-one, greedy.
|
||||
unmatched_inserts = list(inserted_ids)
|
||||
for did in deleted_ids:
|
||||
o = orig_by_id[did]
|
||||
match = None
|
||||
for iid in unmatched_inserts:
|
||||
f = final_by_id[iid]
|
||||
if (
|
||||
o["segment_index"] == f["segment_index"]
|
||||
and o["start"] is not None and f["start"] is not None
|
||||
and abs((o["start"] or 0) - (f["start"] or 0)) <= REPLACE_TIMING_EPSILON
|
||||
and abs((o["end"] or 0) - (f["end"] or 0)) <= REPLACE_TIMING_EPSILON
|
||||
):
|
||||
match = iid
|
||||
break
|
||||
if match is not None:
|
||||
f = final_by_id[match]
|
||||
unmatched_inserts.remove(match)
|
||||
diff.replacements.append(
|
||||
Replacement(
|
||||
original_word_id=did,
|
||||
final_word_id=match,
|
||||
original_text=o["text"],
|
||||
final_text=f["text"],
|
||||
segment_index=f["segment_index"],
|
||||
start_time=f["start"],
|
||||
)
|
||||
)
|
||||
else:
|
||||
diff.deletions.append(WordRef(did, o["text"], o["segment_index"]))
|
||||
|
||||
for iid in unmatched_inserts:
|
||||
w = final_by_id[iid]
|
||||
diff.insertions.append(WordRef(iid, w["text"], w["segment_index"]))
|
||||
|
||||
for wid in sorted(orig_ids & final_ids):
|
||||
o = orig_by_id[wid]
|
||||
f = final_by_id[wid]
|
||||
|
||||
if o["text"] != f["text"]:
|
||||
diff.text_edits.append(
|
||||
TextEdit(wid, o["text"], f["text"], f["segment_index"])
|
||||
)
|
||||
|
||||
start_d = _delta(o["start"], f["start"])
|
||||
end_d = _delta(o["end"], f["end"])
|
||||
if (start_d is not None and abs(start_d) > TIMING_EPSILON) or (
|
||||
end_d is not None and abs(end_d) > TIMING_EPSILON
|
||||
):
|
||||
diff.timing_changes.append(
|
||||
TimingChange(
|
||||
word_id=wid,
|
||||
text=f["text"],
|
||||
original_start=o["start"],
|
||||
original_end=o["end"],
|
||||
final_start=f["start"],
|
||||
final_end=f["end"],
|
||||
start_delta=start_d,
|
||||
end_delta=end_d,
|
||||
)
|
||||
)
|
||||
|
||||
if o["segment_index"] != f["segment_index"]:
|
||||
diff.segment_moves.append(
|
||||
SegmentMove(wid, f["text"], o["segment_index"], f["segment_index"])
|
||||
)
|
||||
|
||||
diff.segmentation_changed = bool(
|
||||
diff.segment_moves
|
||||
or diff.original_segment_count != diff.final_segment_count
|
||||
)
|
||||
diff.total_changes = (
|
||||
len(diff.replacements)
|
||||
+ len(diff.text_edits)
|
||||
+ len(diff.timing_changes)
|
||||
+ len(diff.deletions)
|
||||
+ len(diff.insertions)
|
||||
+ len(diff.segment_moves)
|
||||
)
|
||||
diff.has_changes = diff.total_changes > 0
|
||||
return diff
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Data models for the auto-approvability scorer.
|
||||
|
||||
These are plain dataclasses (JSON-serializable via ``asdict``) so the verdict can
|
||||
be logged into ``processing_metadata`` and written into the offline recording
|
||||
corpus without pulling in extra dependencies.
|
||||
|
||||
See ``docs/archive/2026-08-25-full-auto-review-design.md`` for the design.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class LyricsVerdict(str, Enum):
|
||||
"""Whether the lyrics look safe to auto-approve without human review."""
|
||||
|
||||
AUTO = "auto" # confident the synced lyrics are already correct
|
||||
REVIEW = "review" # needs a human
|
||||
|
||||
|
||||
class BackingVerdict(str, Enum):
|
||||
"""Backing-vocals decision confidence."""
|
||||
|
||||
CLEAN = "clean" # non-subjective: no backing vocals to retain -> clean
|
||||
WITH_BACKING = "with_backing" # (reserved) confidently retain
|
||||
REVIEW = "review" # subjective -> needs a human listen
|
||||
|
||||
|
||||
@dataclass
|
||||
class LyricsSignals:
|
||||
"""The quantitative signals extracted from ``corrections.json``."""
|
||||
|
||||
total_words: int = 0
|
||||
anchor_word_count: int = 0
|
||||
gap_word_count: int = 0
|
||||
anchor_word_fraction: float = 0.0
|
||||
uncorrected_gap_fraction: float = 0.0
|
||||
corrections_made: int = 0
|
||||
anchor_sequences_count: int = 0
|
||||
gap_sequences_count: int = 0
|
||||
# Reference-lyrics agreement
|
||||
accepted_reference_sources: List[str] = field(default_factory=list)
|
||||
best_reference_relevance: float = 0.0
|
||||
strong_reference_sources: int = 0
|
||||
has_synced_reference: bool = False
|
||||
# Guards
|
||||
correction_actually_ran: bool = False
|
||||
# AI auto-correct suggestions (auto-applied on review load — see corpus SYNTHESIS):
|
||||
# gap words COVERED by a suggestion get fixed before a human would ever look,
|
||||
# so post-AI confidence keys off the UNCOVERED remainder, not the raw gap count.
|
||||
ai_suggestions_available: bool = False
|
||||
ai_suggestion_count: int = 0
|
||||
ai_full_consensus_count: int = 0
|
||||
gap_words_covered_by_ai: int = 0
|
||||
uncovered_gap_word_count: int = 0
|
||||
uncovered_gap_fraction: float = 0.0
|
||||
# Gating class: non-lexical vocalization sections (Pattern 3 — never fully auto)
|
||||
vocalization_word_count: int = 0
|
||||
vocalization_max_run: int = 0
|
||||
long_vocalization_word_count: int = 0
|
||||
has_vocalization_section: bool = False
|
||||
# Gating class: phantom/hallucinated lines with absurd durations (Pattern 8)
|
||||
max_word_duration_s: float = 0.0
|
||||
absurd_duration_word_count: int = 0
|
||||
suspicious_parenthetical_count: int = 0
|
||||
has_phantom_signature: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackingSignals:
|
||||
"""The quantitative signals extracted from ``backing_vocals_analysis``."""
|
||||
|
||||
analysis_present: bool = False
|
||||
has_audible_content: bool = True
|
||||
audible_percentage: float = 0.0
|
||||
segment_count: int = 0
|
||||
loud_segment_count: int = 0
|
||||
peak_amplitude_db: Optional[float] = None
|
||||
recommended_selection: Optional[str] = None
|
||||
# 3-stem comparison (backing vs lead vs full vocals) — present on jobs
|
||||
# analyzed since the Phase-2B backing decider; absent before that.
|
||||
comparison_present: bool = False
|
||||
coverage_ratio: float = 0.0
|
||||
corr_backing_vocals: float = 0.0
|
||||
corr_backing_lead: float = 0.0
|
||||
lead_overlap_fraction: float = 0.0
|
||||
lead_audible_fraction: float = 0.0
|
||||
backing_audible_fraction: float = 0.0
|
||||
backing_median_db: Optional[float] = None
|
||||
lead_median_db: Optional[float] = None
|
||||
backing_db_std: float = 0.0
|
||||
flat_fraction: float = 0.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class LyricsResult:
|
||||
verdict: LyricsVerdict
|
||||
tier: str # short label, e.g. "synced-perfect", "high-anchor", "needs-review"
|
||||
signals: LyricsSignals
|
||||
reasons: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BackingResult:
|
||||
verdict: BackingVerdict
|
||||
non_subjective: bool # True only when the decision has no taste component
|
||||
signals: BackingSignals
|
||||
reasons: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoApprovabilityVerdict:
|
||||
"""Combined shadow verdict for a job.
|
||||
|
||||
``overall_auto`` is intentionally the *conjunction* of a confident lyrics
|
||||
verdict and a non-subjective backing decision — the narrow, safe intersection
|
||||
Andrew asked to start with. Anything less stays in human review.
|
||||
"""
|
||||
|
||||
lyrics: LyricsResult
|
||||
backing: BackingResult
|
||||
overall_auto: bool
|
||||
scorer_version: str
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
# Convert Enum members to their plain string values so the dict is safe
|
||||
# for both json.dumps and Firestore writes.
|
||||
return asdict(
|
||||
self,
|
||||
dict_factory=lambda pairs: {
|
||||
k: (v.value if isinstance(v, Enum) else v) for k, v in pairs
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Server-side pre-apply of AI corrections BEFORE the review-ready notification.
|
||||
|
||||
Andrew's directive (2026-08-29): *"apply the ai-generated lyrics corrections and any
|
||||
post-ai heuristic fixes before the user ever sees the notification/button saying the
|
||||
lyrics review is ready ... it should all be done server-side and loaded as a single
|
||||
load event when the lyrics review page launches."*
|
||||
|
||||
Called from ``screens_worker`` for review-bound jobs (i.e. when the executor did NOT
|
||||
auto-complete the whole job), just before the AWAITING_REVIEW transition. It applies
|
||||
the same cached suggestions the review UI would auto-apply on load, using the same
|
||||
machinery the executor uses (``apply.build_applied_segments``), and writes
|
||||
``corrections_updated.json`` with a ``pre_applied`` marker so the ``/correction-data``
|
||||
endpoint serves the already-corrected state in a single load — eliminating the
|
||||
in-browser auto-apply race.
|
||||
|
||||
BEST-EFFORT: never raises, bounded. On any miss (proactive disabled, cache absent,
|
||||
LLM outage, sanity-check abort) it simply does nothing and the review UI falls back to
|
||||
its existing client-side on-load auto-apply. Auto-approval must never strand a job.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CORRECTIONS_PATH = "jobs/{job_id}/lyrics/corrections.json"
|
||||
CORRECTIONS_UPDATED_PATH = "jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
|
||||
async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) -> Dict[str, Any]:
|
||||
"""Ensure the suggestion cache exists, apply it, and persist the pre-applied
|
||||
corrections with a ``pre_applied`` marker. Returns a small status dict; never
|
||||
raises.
|
||||
|
||||
``generate_on_miss`` (default True, the screens_worker path): when the proactive
|
||||
cache is absent, generate it synchronously (bounded) before applying. The
|
||||
``/correction-data`` load path passes False — it only applies an EXISTING cache
|
||||
so a review page never blocks on a multi-model LLM call; a cache-miss there
|
||||
falls through to the UI's own client-side apply.
|
||||
"""
|
||||
try:
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
from backend.services.auto_approval.executor import _load_ai_suggestions
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
settings = get_settings()
|
||||
storage = StorageService()
|
||||
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
return {"outcome": "skipped", "reason": "no_corrections"}
|
||||
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
if storage.file_exists(updated_path):
|
||||
# Already applied once (executor auto-complete, a prior pre-apply run,
|
||||
# or a human edit). Never clobber existing corrections_updated.json.
|
||||
try:
|
||||
existing = storage.download_json(updated_path)
|
||||
if ((existing.get("metadata") or {}).get("auto_approval")):
|
||||
return {"outcome": "skipped", "reason": "already_applied"}
|
||||
except Exception:
|
||||
pass
|
||||
return {"outcome": "skipped", "reason": "corrections_updated_exists"}
|
||||
|
||||
corrections = storage.download_json(corrections_path)
|
||||
|
||||
# 1) Ensure the proactive suggestion cache exists (generate on miss, unless
|
||||
# the caller — e.g. the load-time path — asked to only apply an existing
|
||||
# cache so the request doesn't block on an LLM call).
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
if ai_suggestions is None and generate_on_miss and settings.auto_correct_proactive_enabled:
|
||||
logger.info(f"[job:{job_id}] pre-apply: cache miss, generating suggestions synchronously")
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
await process_proactive_auto_correct(job_id) # bounded (180s) + best-effort
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
|
||||
if ai_suggestions is None:
|
||||
# Unknown suggestion set (proactive disabled or generation failed) —
|
||||
# do NOT mark pre_applied; let the UI run its client-side apply.
|
||||
return {"outcome": "skipped", "reason": "no_suggestions_cache"}
|
||||
|
||||
# 2) Apply with the executor's sanity gates.
|
||||
result = build_applied_segments(corrections, ai_suggestions)
|
||||
if result.get("aborted"):
|
||||
logger.info(f"[job:{job_id}] pre-apply aborted ({result['aborted']}) — UI will apply client-side")
|
||||
return {"outcome": "skipped", "reason": result["aborted"]}
|
||||
|
||||
# 3) Persist corrections_updated.json with the pre_applied marker + the
|
||||
# suggestions themselves (so the review panel renders applied state).
|
||||
updated = dict(corrections)
|
||||
updated["corrected_segments"] = result["segments"]
|
||||
metadata = dict(updated.get("metadata") or {})
|
||||
metadata["auto_approval"] = {
|
||||
"pre_applied": True,
|
||||
"applied_suggestion_ids": result["applied_ids"],
|
||||
"rejected_suggestion_ids": result["rejected_ids"],
|
||||
"suggestions": ai_suggestions,
|
||||
"applied_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
updated["metadata"] = metadata
|
||||
# Create-only write: we only reach here when corrections_updated.json was
|
||||
# absent at the check above, so if_generation_match=0 makes the write atomic —
|
||||
# a concurrent writer (executor auto-complete, or an edit submission) that
|
||||
# created it in the meantime wins and we don't clobber their (newer) state.
|
||||
try:
|
||||
from google.api_core.exceptions import PreconditionFailed
|
||||
except Exception: # pragma: no cover - google libs always present in prod
|
||||
PreconditionFailed = () # type: ignore[assignment]
|
||||
try:
|
||||
storage.upload_json(updated_path, updated, if_generation_match=0)
|
||||
except PreconditionFailed:
|
||||
logger.info(f"[job:{job_id}] pre-apply raced a concurrent write — theirs wins")
|
||||
return {"outcome": "skipped", "reason": "raced_concurrent_write"}
|
||||
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
|
||||
|
||||
logger.info(
|
||||
f"[job:{job_id}] pre-apply saved corrections_updated.json "
|
||||
f"({len(result['applied_ids'])} applied, {len(result['rejected_ids'])} rejected) "
|
||||
"before review notification"
|
||||
)
|
||||
return {"outcome": "pre_applied", "applied": len(result["applied_ids"])}
|
||||
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fatal
|
||||
logger.warning(f"[job:{job_id}] pre-apply failed non-fatally: {e}", exc_info=True)
|
||||
return {"outcome": "error", "error": str(e)}
|
||||
@@ -0,0 +1,600 @@
|
||||
"""Auto-approvability scorer.
|
||||
|
||||
Pure functions that decide, from signals that already exist on every job, whether
|
||||
a job's lyrics look safe to auto-approve without human review, and whether the
|
||||
backing-vocals decision is non-subjective.
|
||||
|
||||
This module runs **in shadow mode**: ``screens_worker`` computes + records the
|
||||
verdict in ``processing_metadata.auto_approval_shadow`` just before every job goes
|
||||
to human review, so verdicts can be validated against real review outcomes before
|
||||
the scorer is allowed to gate. See
|
||||
``docs/archive/2026-08-25-full-auto-review-design.md`` (+ session-4 update).
|
||||
|
||||
Design notes / traps handled here:
|
||||
- In production, auto-correction is DISABLED, so ``corrections.json`` always reports
|
||||
``corrections_made == 0`` and ``confidence == 1.0`` regardless of lyric quality
|
||||
(``controller.py`` uncorrected path). We therefore NEVER treat those two fields as
|
||||
positive evidence. Confidence comes from anchor coverage against reference lyrics,
|
||||
gap words left *uncovered* by the auto-applied AI suggestions, reference-source
|
||||
agreement, and the absence of the never-auto gating signatures.
|
||||
- ``anchor_sequences`` and ``gap_sequences`` are still computed when correction is
|
||||
disabled, so anchor/gap coverage is available on every prod job.
|
||||
- The review UI auto-applies the (pre-generated) AI suggestions on load, so a gap
|
||||
word covered by a suggestion is fixed before any human would look — raw gap
|
||||
counts alone do NOT separate AI-solved jobs from human-needed ones (2026-08-27
|
||||
20-job corpus calibration).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.auto_approval.models import (
|
||||
AutoApprovabilityVerdict,
|
||||
BackingResult,
|
||||
BackingSignals,
|
||||
BackingVerdict,
|
||||
LyricsResult,
|
||||
LyricsSignals,
|
||||
LyricsVerdict,
|
||||
)
|
||||
|
||||
SCORER_VERSION = "0.3.0"
|
||||
|
||||
# --- Lyrics thresholds (deliberately conservative; the safe intersection first) ---
|
||||
# The AUTO tier requires a synced reference the transcription matches with ZERO
|
||||
# unresolved gaps. Empirically (job 79c4f60c "Clarity", 2026-08), a single gap word
|
||||
# on an otherwise 99.6%-anchored track was a genuine mis-transcription the reviewer
|
||||
# fixed ("I" -> "High"): a gap word is by definition a word with no confident reference
|
||||
# match, i.e. exactly where errors hide. So we do not tolerate any gaps for AUTO.
|
||||
MIN_TOTAL_WORDS = 10
|
||||
AUTO_MIN_ANCHOR_FRACTION = 0.99
|
||||
AUTO_MAX_GAP_FRACTION = 0.0
|
||||
# The "ai-resolved" AUTO tier accounts for the auto-applied AI corrections: raw gap
|
||||
# words that an AI suggestion covers get fixed on load before any human would look,
|
||||
# so confidence keys off the UNCOVERED remainder (corpus 2026-08-27: raw gap counts
|
||||
# do NOT separate AI-solved jobs from human-needed ones; uncovered gaps + the
|
||||
# never-auto gates + an anchor floor do).
|
||||
AI_RESOLVED_MIN_ANCHOR_FRACTION = 0.90
|
||||
AI_RESOLVED_MAX_UNCOVERED_FRACTION = 0.02
|
||||
AI_RESOLVED_MAX_UNCOVERED_WORDS = 6
|
||||
# A looser "near-miss" band, recorded for calibration but still sent to review.
|
||||
NEARMISS_MIN_ANCHOR_FRACTION = 0.95
|
||||
NEARMISS_MAX_GAP_FRACTION = 0.05
|
||||
|
||||
# --- Gating class: non-lexical vocalization sections (Pattern 3; never fully auto) ---
|
||||
# AudioShake mistimes da-da-dun / oh-oh / woo-woo sections badly (wrong count, rhythm,
|
||||
# segmentation); the correct grouping is a musical interpretation not recoverable from
|
||||
# its output (corpus jobs b5a7b8aa, a4dcaa21, 8f2305ee). Detect and route to a human.
|
||||
VOCALIZATION_TOKENS = frozenset({
|
||||
"da", "dun", "dum", "la", "na", "nah", "oh", "ooh", "oohs", "ah", "ahh", "aah",
|
||||
"woo", "whoa", "woah", "yeah", "hey", "ba", "bah", "doo", "dee", "di", "mm",
|
||||
"mmm", "hmm", "sha", "bop", "pa", "ra", "ta",
|
||||
})
|
||||
# A run of this many consecutive vocalization words = a vocalization section.
|
||||
VOCALIZATION_MIN_RUN = 5
|
||||
# A single sung vocalization rarely lasts this long; a multi-second "Ooh"/"da" almost
|
||||
# always means AudioShake lumped many short vocalizations into one (10.1s/4.0s examples).
|
||||
LONG_VOCALIZATION_DURATION_S = 3.5
|
||||
VERY_LONG_VOCALIZATION_DURATION_S = 6.0
|
||||
|
||||
# --- Gating class: phantom/hallucinated lines (Pattern 8) ---
|
||||
# Real sung words basically never span this long; corpus phantoms were 7.4s and 4.8s.
|
||||
ABSURD_WORD_DURATION_S = 5.0
|
||||
# Short parenthetical lines ("(I'm sorry)") stretched over multiple seconds are the
|
||||
# classic phantom signature.
|
||||
PHANTOM_PARENTHETICAL_DURATION_S = 4.0
|
||||
PHANTOM_PARENTHETICAL_MAX_WORDS = 4
|
||||
|
||||
# --- Backing thresholds ---
|
||||
# Only "there is literally no audible backing content" is treated as non-subjective.
|
||||
# A tiny non-zero floor absorbs separation noise but stays extremely conservative.
|
||||
NON_SUBJECTIVE_MAX_AUDIBLE_PCT = 0.5 # percent
|
||||
LOUD_SEGMENT_DB = -20.0
|
||||
|
||||
# --- 3-stem backing decider thresholds (Phase 2B) ---
|
||||
# Calibrated on the 20-job replay-review corpus signals (private
|
||||
# validate_backing_decider.py — rerun after ANY change here). Corpus rules:
|
||||
# pink present -> KEEP (the human under-keeps; every with_backing pick was
|
||||
# correct), EXCEPT the "pink but don't keep" modes below.
|
||||
#
|
||||
# Backing-stem-IS-the-lead (1d45b286 — catastrophic if kept): the backing stem
|
||||
# tracks the whole vocal line while the real lead stem is comparatively
|
||||
# sparse. Corpus values: covR 0.94 / corr 0.95 / backing 60% audible vs lead
|
||||
# 18%. The coverage comparison (backing > lead) is the decisive discriminator:
|
||||
# the nearest genuine keep (33453fa0) hits covR 0.77 / corr 0.86 but its
|
||||
# backing coverage (28%) sits well BELOW its lead coverage (34%).
|
||||
BACKING_IS_LEAD_MIN_COVERAGE_RATIO = 0.80
|
||||
BACKING_IS_LEAD_MIN_CORR = 0.80
|
||||
# Noise-floor pink (95d8e844, grungegaze): a fuzzy mix pushes the backing
|
||||
# stem's noise floor just above the -40 dB threshold, producing widespread
|
||||
# near-threshold "pink" that does not correlate with the vocal line (corpus:
|
||||
# median -38.6 dB over 30% of the track, corr -0.23). Genuine quiet harmonies
|
||||
# (d508adb6: -38.1 dB but only 1% audible; 44622ffa: -35.9 dB, 11%) are sparse.
|
||||
# Marginal either way per the corpus -> REVIEW, never a confident verdict.
|
||||
NOISE_FLOOR_MAX_MEDIAN_DB = -35.0
|
||||
NOISE_FLOOR_MIN_AUDIBLE_FRACTION = 0.15
|
||||
NOISE_FLOOR_MAX_CORR = 0.05
|
||||
# Lead bleed (ae0cd7e8): tiny audible content riding entirely on lead
|
||||
# activity. The corpus bleed case is already caught by the near-silent rule;
|
||||
# this catches slightly-larger blobs. Deliberately NARROW (overlap >= 0.95):
|
||||
# d508adb6's genuine harmonies overlap the lead 0.89 and must stay keepable.
|
||||
BLEED_MAX_AUDIBLE_PCT = 3.0
|
||||
BLEED_MIN_LEAD_OVERLAP = 0.95
|
||||
|
||||
_TOKEN_STRIP_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _count_ids(sequences: List[Dict[str, Any]]) -> int:
|
||||
total = 0
|
||||
for seq in sequences or []:
|
||||
ids = seq.get("transcribed_word_ids")
|
||||
if ids:
|
||||
total += len(ids)
|
||||
return total
|
||||
|
||||
|
||||
def _is_vocalization_token(text: str) -> bool:
|
||||
"""True if a word looks like a non-lexical vocalization ("Da-", "dun,", "Woo-woo")."""
|
||||
t = _TOKEN_STRIP_RE.sub("", (text or "").lower())
|
||||
if not t:
|
||||
return False
|
||||
parts = [p for p in t.split("-") if p]
|
||||
return bool(parts) and all(p in VOCALIZATION_TOKENS for p in parts)
|
||||
|
||||
|
||||
def _word_duration(word: Dict[str, Any]) -> float:
|
||||
start = word.get("start_time")
|
||||
end = word.get("end_time")
|
||||
if isinstance(start, (int, float)) and isinstance(end, (int, float)) and end > start:
|
||||
return float(end) - float(start)
|
||||
return 0.0
|
||||
|
||||
|
||||
def _extract_gating_signals(
|
||||
correction_data: Dict[str, Any],
|
||||
) -> Tuple[int, int, int, bool, float, int, int, bool]:
|
||||
"""Scan corrected_segments for the two never-auto gating classes.
|
||||
|
||||
Returns (vocalization_word_count, vocalization_max_run, long_vocalization_word_count,
|
||||
has_vocalization_section, max_word_duration_s, absurd_duration_word_count,
|
||||
suspicious_parenthetical_count, has_phantom_signature).
|
||||
"""
|
||||
voc_count = 0
|
||||
max_run = 0
|
||||
run = 0 # runs continue across segment boundaries (consecutive vocalization lines)
|
||||
long_voc = 0
|
||||
very_long_voc = 0
|
||||
max_duration = 0.0
|
||||
absurd = 0
|
||||
suspicious_paren = 0
|
||||
|
||||
for seg in correction_data.get("corrected_segments") or []:
|
||||
words = seg.get("words") or []
|
||||
for word in words:
|
||||
duration = _word_duration(word)
|
||||
max_duration = max(max_duration, duration)
|
||||
if duration > ABSURD_WORD_DURATION_S:
|
||||
absurd += 1
|
||||
if _is_vocalization_token(word.get("text") or ""):
|
||||
voc_count += 1
|
||||
run += 1
|
||||
max_run = max(max_run, run)
|
||||
if duration >= VERY_LONG_VOCALIZATION_DURATION_S:
|
||||
very_long_voc += 1
|
||||
long_voc += 1
|
||||
elif duration >= LONG_VOCALIZATION_DURATION_S:
|
||||
long_voc += 1
|
||||
else:
|
||||
run = 0
|
||||
|
||||
# Phantom signature: a short parenthetical line stretched over several seconds
|
||||
# (e.g. three "(I'm sorry)" lines, one 7.4s — corpus job 33453fa0).
|
||||
seg_text = (seg.get("text") or "").strip()
|
||||
if (
|
||||
seg_text.startswith("(")
|
||||
and seg_text.endswith(")")
|
||||
and 0 < len(words) <= PHANTOM_PARENTHETICAL_MAX_WORDS
|
||||
):
|
||||
seg_start, seg_end = seg.get("start_time"), seg.get("end_time")
|
||||
if (
|
||||
isinstance(seg_start, (int, float))
|
||||
and isinstance(seg_end, (int, float))
|
||||
and seg_end - seg_start >= PHANTOM_PARENTHETICAL_DURATION_S
|
||||
):
|
||||
suspicious_paren += 1
|
||||
|
||||
has_vocalization_section = (
|
||||
max_run >= VOCALIZATION_MIN_RUN or long_voc >= 2 or very_long_voc >= 1
|
||||
)
|
||||
has_phantom_signature = absurd >= 1 or suspicious_paren >= 1
|
||||
return (
|
||||
voc_count,
|
||||
max_run,
|
||||
long_voc,
|
||||
has_vocalization_section,
|
||||
round(max_duration, 3),
|
||||
absurd,
|
||||
suspicious_paren,
|
||||
has_phantom_signature,
|
||||
)
|
||||
|
||||
|
||||
def _total_words(correction_data: Dict[str, Any]) -> int:
|
||||
meta = correction_data.get("metadata") or {}
|
||||
if isinstance(meta.get("total_words"), int) and meta["total_words"] > 0:
|
||||
return meta["total_words"]
|
||||
# Fallback: count from corrected_segments
|
||||
total = 0
|
||||
for seg in correction_data.get("corrected_segments") or []:
|
||||
total += len(seg.get("words") or [])
|
||||
return total
|
||||
|
||||
|
||||
def _gap_word_ids(correction_data: Dict[str, Any]) -> set:
|
||||
ids: set = set()
|
||||
for seq in correction_data.get("gap_sequences") or []:
|
||||
ids.update(seq.get("transcribed_word_ids") or [])
|
||||
return ids
|
||||
|
||||
|
||||
def extract_lyrics_signals(
|
||||
correction_data: Dict[str, Any],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
) -> LyricsSignals:
|
||||
"""Pull the quantitative lyrics signals out of a ``corrections.json`` dict.
|
||||
|
||||
``ai_suggestions`` is the (pre-generated) auto-correct suggestion list — the
|
||||
ones the review UI auto-applies on load. When provided, gap coverage is
|
||||
computed against it: a gap word touched by a suggestion will be fixed before
|
||||
any human looks, so only the *uncovered* gaps carry residual risk.
|
||||
"""
|
||||
meta = correction_data.get("metadata") or {}
|
||||
total_words = _total_words(correction_data)
|
||||
|
||||
anchor_words = _count_ids(correction_data.get("anchor_sequences"))
|
||||
gap_words = _count_ids(correction_data.get("gap_sequences"))
|
||||
|
||||
suggestion_word_ids: set = set()
|
||||
full_consensus = 0
|
||||
for sug in ai_suggestions or []:
|
||||
suggestion_word_ids.update(sug.get("word_ids") or [])
|
||||
total_models = sug.get("total_models")
|
||||
if (
|
||||
isinstance(total_models, int)
|
||||
and total_models >= 2
|
||||
and sug.get("consensus") == total_models
|
||||
):
|
||||
full_consensus += 1
|
||||
gap_ids = _gap_word_ids(correction_data)
|
||||
covered = len(gap_ids & suggestion_word_ids)
|
||||
uncovered = max(0, gap_words - covered)
|
||||
uncovered_fraction = min(1.0, uncovered / total_words) if total_words else 1.0
|
||||
|
||||
anchor_fraction = min(1.0, anchor_words / total_words) if total_words else 0.0
|
||||
gap_fraction = min(1.0, gap_words / total_words) if total_words else 1.0
|
||||
|
||||
reference_lyrics = correction_data.get("reference_lyrics") or {}
|
||||
accepted_sources = list(reference_lyrics.keys())
|
||||
|
||||
has_synced = False
|
||||
for src in accepted_sources:
|
||||
src_meta = ((reference_lyrics.get(src) or {}).get("metadata")) or {}
|
||||
if src_meta.get("is_synced"):
|
||||
has_synced = True
|
||||
break
|
||||
|
||||
# Relevance of accepted sources isn't stored directly; rejected_sources carries it.
|
||||
# Use it only to compute a best-observed relevance for context, never as a gate.
|
||||
best_relevance = 0.0
|
||||
rejected = meta.get("rejected_sources") or {}
|
||||
for info in rejected.values():
|
||||
rel = info.get("relevance")
|
||||
if isinstance(rel, (int, float)):
|
||||
best_relevance = max(best_relevance, float(rel))
|
||||
|
||||
agentic_routing = meta.get("agentic_routing")
|
||||
correction_type = meta.get("correction_type")
|
||||
correction_actually_ran = (
|
||||
agentic_routing not in (None, "disabled") and correction_type != "none"
|
||||
)
|
||||
|
||||
(
|
||||
voc_count,
|
||||
voc_max_run,
|
||||
long_voc,
|
||||
has_voc_section,
|
||||
max_duration,
|
||||
absurd,
|
||||
suspicious_paren,
|
||||
has_phantom,
|
||||
) = _extract_gating_signals(correction_data)
|
||||
|
||||
return LyricsSignals(
|
||||
total_words=total_words,
|
||||
anchor_word_count=anchor_words,
|
||||
gap_word_count=gap_words,
|
||||
anchor_word_fraction=round(anchor_fraction, 4),
|
||||
uncorrected_gap_fraction=round(gap_fraction, 4),
|
||||
corrections_made=int(correction_data.get("corrections_made") or 0),
|
||||
anchor_sequences_count=len(correction_data.get("anchor_sequences") or []),
|
||||
gap_sequences_count=len(correction_data.get("gap_sequences") or []),
|
||||
accepted_reference_sources=accepted_sources,
|
||||
best_reference_relevance=round(best_relevance, 4),
|
||||
strong_reference_sources=len(accepted_sources),
|
||||
has_synced_reference=has_synced,
|
||||
correction_actually_ran=correction_actually_ran,
|
||||
ai_suggestions_available=ai_suggestions is not None,
|
||||
ai_suggestion_count=len(ai_suggestions or []),
|
||||
ai_full_consensus_count=full_consensus,
|
||||
gap_words_covered_by_ai=covered,
|
||||
uncovered_gap_word_count=uncovered,
|
||||
uncovered_gap_fraction=round(uncovered_fraction, 4),
|
||||
vocalization_word_count=voc_count,
|
||||
vocalization_max_run=voc_max_run,
|
||||
long_vocalization_word_count=long_voc,
|
||||
has_vocalization_section=has_voc_section,
|
||||
max_word_duration_s=max_duration,
|
||||
absurd_duration_word_count=absurd,
|
||||
suspicious_parenthetical_count=suspicious_paren,
|
||||
has_phantom_signature=has_phantom,
|
||||
)
|
||||
|
||||
|
||||
def score_lyrics(
|
||||
correction_data: Dict[str, Any],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
) -> LyricsResult:
|
||||
"""Decide whether the lyrics look safe to auto-approve."""
|
||||
s = extract_lyrics_signals(correction_data, ai_suggestions)
|
||||
reasons: List[str] = []
|
||||
|
||||
if s.total_words < MIN_TOTAL_WORDS:
|
||||
reasons.append(
|
||||
f"only {s.total_words} words (< {MIN_TOTAL_WORDS}); too little signal to trust"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "too-few-words", s, reasons)
|
||||
|
||||
# Never-auto gating classes: these override everything, including a perfect
|
||||
# anchor/gap profile — the transcription can be "anchored" yet still wrong in
|
||||
# ways only a human can judge (Pattern 3) or plainly hallucinated (Pattern 8).
|
||||
if s.has_vocalization_section:
|
||||
reasons.append(
|
||||
f"non-lexical vocalization section detected ({s.vocalization_word_count} "
|
||||
f"vocalization words, longest run {s.vocalization_max_run}, "
|
||||
f"{s.long_vocalization_word_count} multi-second) — timing/grouping is a "
|
||||
"musical judgement; never fully auto"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "vocalization-gate", s, reasons)
|
||||
|
||||
if s.has_phantom_signature:
|
||||
reasons.append(
|
||||
f"phantom-line signature: {s.absurd_duration_word_count} words > "
|
||||
f"{ABSURD_WORD_DURATION_S:.0f}s (max {s.max_word_duration_s:.1f}s), "
|
||||
f"{s.suspicious_parenthetical_count} multi-second short parenthetical lines"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "phantom-gate", s, reasons)
|
||||
|
||||
if not s.accepted_reference_sources:
|
||||
reasons.append("no reference lyrics survived the relevance filter")
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "no-reference", s, reasons)
|
||||
|
||||
auto_ok = (
|
||||
s.has_synced_reference
|
||||
and s.anchor_word_fraction >= AUTO_MIN_ANCHOR_FRACTION
|
||||
and s.uncorrected_gap_fraction <= AUTO_MAX_GAP_FRACTION
|
||||
)
|
||||
if auto_ok:
|
||||
reasons.append(
|
||||
f"synced reference present; anchor coverage {s.anchor_word_fraction:.1%} "
|
||||
f">= {AUTO_MIN_ANCHOR_FRACTION:.0%}; zero unresolved gap words"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.AUTO, "synced-perfect", s, reasons)
|
||||
|
||||
# AI-resolved tier: the auto-applied suggestions cover (almost) every gap word,
|
||||
# anchoring is high, and no never-auto gate fired. What remains uncovered is a
|
||||
# handful of words with no confident reference match — empirically adlib/benign.
|
||||
ai_resolved_ok = (
|
||||
s.ai_suggestions_available
|
||||
and s.has_synced_reference
|
||||
and s.anchor_word_fraction >= AI_RESOLVED_MIN_ANCHOR_FRACTION
|
||||
and s.uncovered_gap_fraction <= AI_RESOLVED_MAX_UNCOVERED_FRACTION
|
||||
and s.uncovered_gap_word_count <= AI_RESOLVED_MAX_UNCOVERED_WORDS
|
||||
)
|
||||
if ai_resolved_ok:
|
||||
reasons.append(
|
||||
f"synced reference; anchor {s.anchor_word_fraction:.1%} >= "
|
||||
f"{AI_RESOLVED_MIN_ANCHOR_FRACTION:.0%}; {s.gap_word_count} gap words of "
|
||||
f"which {s.gap_words_covered_by_ai} covered by auto-applied AI suggestions, "
|
||||
f"{s.uncovered_gap_word_count} uncovered ({s.uncovered_gap_fraction:.1%})"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.AUTO, "ai-resolved", s, reasons)
|
||||
|
||||
# Not auto — classify why, for calibration.
|
||||
if (
|
||||
s.anchor_word_fraction >= NEARMISS_MIN_ANCHOR_FRACTION
|
||||
and s.uncorrected_gap_fraction <= NEARMISS_MAX_GAP_FRACTION
|
||||
):
|
||||
tier = "near-miss"
|
||||
if not s.has_synced_reference:
|
||||
reasons.append("high anchor coverage but NO synced reference (unsynced only)")
|
||||
else:
|
||||
reasons.append(
|
||||
f"anchor coverage {s.anchor_word_fraction:.1%} / gap "
|
||||
f"{s.uncorrected_gap_fraction:.1%} close but below AUTO thresholds"
|
||||
)
|
||||
else:
|
||||
tier = "needs-review"
|
||||
reasons.append(
|
||||
f"anchor coverage {s.anchor_word_fraction:.1%}, unresolved-gap fraction "
|
||||
f"{s.uncorrected_gap_fraction:.1%} ({s.gap_sequences_count} gaps)"
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, tier, s, reasons)
|
||||
|
||||
|
||||
def extract_backing_signals(backing_analysis: Optional[Dict[str, Any]]) -> BackingSignals:
|
||||
"""Pull backing-vocals signals out of ``state_data.backing_vocals_analysis``."""
|
||||
if not backing_analysis:
|
||||
return BackingSignals(analysis_present=False)
|
||||
# A FAILED analysis stores has_audible_content=None + analysis_error; that
|
||||
# must never read as "no audible content" (which would wrongly auto-select
|
||||
# clean). Treat it as no-analysis -> review.
|
||||
if backing_analysis.get("analysis_error") or backing_analysis.get("has_audible_content") is None:
|
||||
return BackingSignals(analysis_present=False)
|
||||
|
||||
segments = backing_analysis.get("audible_segments") or []
|
||||
loud = 0
|
||||
peak: Optional[float] = None
|
||||
for seg in segments:
|
||||
avg_db = seg.get("avg_amplitude_db")
|
||||
if isinstance(avg_db, (int, float)) and avg_db > LOUD_SEGMENT_DB:
|
||||
loud += 1
|
||||
pk = seg.get("peak_amplitude_db")
|
||||
if isinstance(pk, (int, float)):
|
||||
peak = pk if peak is None else max(peak, pk)
|
||||
|
||||
signals = BackingSignals(
|
||||
analysis_present=True,
|
||||
has_audible_content=bool(backing_analysis.get("has_audible_content", True)),
|
||||
audible_percentage=float(backing_analysis.get("audible_percentage", 0.0) or 0.0),
|
||||
segment_count=len(segments),
|
||||
loud_segment_count=loud,
|
||||
peak_amplitude_db=peak,
|
||||
recommended_selection=backing_analysis.get("recommended_selection"),
|
||||
)
|
||||
|
||||
# 3-stem comparison (Phase 2B). A comparison that errored is treated as
|
||||
# absent — never as evidence in either direction.
|
||||
comparison = backing_analysis.get("stem_comparison") or {}
|
||||
if comparison and not comparison.get("error"):
|
||||
def _num(key: str, default: float = 0.0) -> float:
|
||||
value = comparison.get(key)
|
||||
return float(value) if isinstance(value, (int, float)) else default
|
||||
|
||||
signals.comparison_present = True
|
||||
signals.coverage_ratio = _num("coverage_ratio")
|
||||
signals.corr_backing_vocals = _num("corr_backing_vocals")
|
||||
signals.corr_backing_lead = _num("corr_backing_lead")
|
||||
signals.lead_overlap_fraction = _num("lead_overlap_fraction")
|
||||
signals.lead_audible_fraction = _num("lead_audible_fraction")
|
||||
signals.backing_audible_fraction = _num("backing_audible_fraction")
|
||||
signals.backing_db_std = _num("backing_db_std")
|
||||
signals.flat_fraction = _num("flat_fraction")
|
||||
backing_median = comparison.get("backing_median_db")
|
||||
lead_median = comparison.get("lead_median_db")
|
||||
if isinstance(backing_median, (int, float)):
|
||||
signals.backing_median_db = float(backing_median)
|
||||
if isinstance(lead_median, (int, float)):
|
||||
signals.lead_median_db = float(lead_median)
|
||||
return signals
|
||||
|
||||
|
||||
def score_backing(backing_analysis: Optional[Dict[str, Any]]) -> BackingResult:
|
||||
"""Decide whether the backing-vocals call is non-subjective (no audible backing)."""
|
||||
s = extract_backing_signals(backing_analysis)
|
||||
reasons: List[str] = []
|
||||
|
||||
if not s.analysis_present:
|
||||
reasons.append("no backing-vocals analysis on the job")
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
non_subjective_clean = (
|
||||
not s.has_audible_content
|
||||
or (s.audible_percentage <= NON_SUBJECTIVE_MAX_AUDIBLE_PCT and s.loud_segment_count == 0)
|
||||
)
|
||||
if non_subjective_clean:
|
||||
reasons.append(
|
||||
"no audible backing vocals detected"
|
||||
if not s.has_audible_content
|
||||
else f"near-silent backing ({s.audible_percentage:.2f}% audible, no loud segments)"
|
||||
)
|
||||
return BackingResult(BackingVerdict.CLEAN, True, s, reasons)
|
||||
|
||||
# Audible backing exists. Without the 3-stem comparison the clean-vs-with
|
||||
# call stays a human judgement (pre-Phase-2B jobs, or comparison failed).
|
||||
if not s.comparison_present:
|
||||
reasons.append(
|
||||
f"audible backing present ({s.audible_percentage:.1f}%, {s.segment_count} segments, "
|
||||
f"{s.loud_segment_count} loud) but no 3-stem comparison available — "
|
||||
"retain-or-not needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# -- "pink but don't keep" mode 1: the backing stem IS the lead --
|
||||
# (separation misclassified a quiet/reverby lead; keeping it would put the
|
||||
# lead vocal back into the karaoke track — the worst possible output.)
|
||||
if (
|
||||
s.coverage_ratio >= BACKING_IS_LEAD_MIN_COVERAGE_RATIO
|
||||
and s.corr_backing_vocals >= BACKING_IS_LEAD_MIN_CORR
|
||||
and s.backing_audible_fraction > s.lead_audible_fraction
|
||||
):
|
||||
reasons.append(
|
||||
f"backing stem appears to BE the lead vocal: covers "
|
||||
f"{s.coverage_ratio:.0%} of the vocal line with envelope correlation "
|
||||
f"{s.corr_backing_vocals:.2f}, and is more present than the lead stem "
|
||||
f"({s.backing_audible_fraction:.0%} vs {s.lead_audible_fraction:.0%} "
|
||||
"audible) — keeping it would re-insert the lead; needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# -- mode 2: noise-floor pink (lo-fi/fuzzy mix) --
|
||||
if (
|
||||
s.backing_median_db is not None
|
||||
and s.backing_median_db <= NOISE_FLOOR_MAX_MEDIAN_DB
|
||||
and s.backing_audible_fraction >= NOISE_FLOOR_MIN_AUDIBLE_FRACTION
|
||||
and s.corr_backing_vocals <= NOISE_FLOOR_MAX_CORR
|
||||
):
|
||||
reasons.append(
|
||||
f"widespread near-threshold backing (median "
|
||||
f"{s.backing_median_db:.1f} dB over {s.backing_audible_fraction:.0%} "
|
||||
f"of the track) uncorrelated with the vocal line "
|
||||
f"({s.corr_backing_vocals:.2f}) — noise-floor signature; marginal "
|
||||
"either way, needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# -- mode 3: lead bleed (small blobs riding entirely on lead activity) --
|
||||
if (
|
||||
s.audible_percentage <= BLEED_MAX_AUDIBLE_PCT
|
||||
and s.lead_overlap_fraction >= BLEED_MIN_LEAD_OVERLAP
|
||||
):
|
||||
reasons.append(
|
||||
f"sparse backing ({s.audible_percentage:.1f}%) almost entirely "
|
||||
f"overlapping lead activity ({s.lead_overlap_fraction:.0%}) — "
|
||||
"likely lead bleed, not harmony; needs a human listen"
|
||||
)
|
||||
return BackingResult(BackingVerdict.REVIEW, False, s, reasons)
|
||||
|
||||
# Real pink harmony remains -> KEEP. Corpus: the human under-keeps (every
|
||||
# with_backing pick was right, 2 of 8 clean picks were wrong); with the
|
||||
# three don't-keep modes carved out above, retaining is the non-subjective
|
||||
# default ("retain backing vocals where possible").
|
||||
reasons.append(
|
||||
f"clear backing-vocal content present ({s.audible_percentage:.1f}%, "
|
||||
f"{s.segment_count} segments, {s.loud_segment_count} loud; flat fraction "
|
||||
f"{s.flat_fraction:.0%}, vocal-line coverage {s.coverage_ratio:.0%}) with "
|
||||
"no lead-bleed / misclassified-lead / noise signature — retain"
|
||||
)
|
||||
return BackingResult(BackingVerdict.WITH_BACKING, True, s, reasons)
|
||||
|
||||
|
||||
def score_job(
|
||||
correction_data: Dict[str, Any],
|
||||
backing_analysis: Optional[Dict[str, Any]],
|
||||
ai_suggestions: Optional[List[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)
|
||||
backing = score_backing(backing_analysis)
|
||||
overall_auto = lyrics.verdict == LyricsVerdict.AUTO and backing.non_subjective
|
||||
return AutoApprovabilityVerdict(
|
||||
lyrics=lyrics,
|
||||
backing=backing,
|
||||
overall_auto=overall_auto,
|
||||
scorer_version=SCORER_VERSION,
|
||||
)
|
||||
@@ -0,0 +1,369 @@
|
||||
"""Deterministic auto-correct suggestion generators (no LLM).
|
||||
|
||||
Mechanical residual-edit classes from the 2026-08 20-job replay-review corpus,
|
||||
emitted as ordinary suggestions so they flow through the exact same paths as
|
||||
the LLM ones: shown in the review UI, auto-applied on load, applied server-side
|
||||
by the auto-approval executor, counted by the scorer's gap-coverage signal, and
|
||||
cached alongside the LLM output.
|
||||
|
||||
Pattern 4 — leading-connective over-insertion: AudioShake is too eager to
|
||||
insert a short connective ("And", "Oh", …) at a segment start. When that word
|
||||
is a gap word (no confident reference match) and no reference source's reading
|
||||
of the gap supports it, emit a delete (+ re-capitalize the next word).
|
||||
|
||||
Pattern 5 — reference-majority resolution: when a gap's transcription contains
|
||||
an implausible proper noun (capitalized mid-line token absent from every
|
||||
reference source) and >=2/3 of the reference sources agree on the same reading
|
||||
for that gap, replace the gap with the majority reading. The red-flag token is
|
||||
REQUIRED, not just preferred: the corpus shows plain 2/3-majority gaps that the
|
||||
human deliberately left alone (Miguel 6d0640fa "though"->"dog" and an
|
||||
explicit-lyrics rewrite), while the one edit he did make ("yo Mick," ->
|
||||
"Come here,") had the proper-noun signature.
|
||||
|
||||
Everything here is pure and conservative: no evidence -> no suggestion.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.auto_approval.scorer import _is_vocalization_token
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Short connectives/interjections AudioShake over-inserts at segment starts —
|
||||
# exactly the set documented in the corpus (Pattern 4: And / But / So / Oh / A).
|
||||
# Deliberately NOT the near-misses like "ah"/"yeah": those double as
|
||||
# vocalization tokens, where deleting the leading word is a musical judgement.
|
||||
# The reference check below does the real gating; this list only scopes
|
||||
# which leading words are candidates.
|
||||
LEADING_CONNECTIVES = frozenset({"and", "but", "so", "oh", "a"})
|
||||
|
||||
# P4/P5 confidences: high enough to auto-apply, below full LLM consensus so a
|
||||
# conflicting multi-model AI suggestion wins its conflict group.
|
||||
P4_CONFIDENCE = 0.9
|
||||
P5_CONFIDENCE = 0.85
|
||||
|
||||
# P5 size guards: never rewrite long spans deterministically.
|
||||
P5_MAX_GAP_WORDS = 6
|
||||
P5_MAX_READING_WORDS = 8
|
||||
# A red-flag token this similar to some reference token is a spelling/
|
||||
# transliteration variant ("Crick"~"Cricket", "Projectorinsky"~
|
||||
# "Projektorinski"), not an implausible name. The right fix there is the
|
||||
# LLM's (it handles proper-noun spelling well); the gap alignment is also
|
||||
# often skewed in exactly these cases, so the majority "reading" is junk
|
||||
# (corpus 507513ba aligned gap "Crick" to reference "and").
|
||||
P5_SPELLING_VARIANT_RATIO = 0.75
|
||||
|
||||
_TOKEN_NORM_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _norm(text: str) -> str:
|
||||
return _TOKEN_NORM_RE.sub("", (text or "").lower())
|
||||
|
||||
|
||||
def _norm_join(texts: List[str]) -> str:
|
||||
return " ".join(t for t in (_norm(x) for x in texts) if t)
|
||||
|
||||
|
||||
def _ref_word_streams(
|
||||
reference_lyrics: Dict[str, Any],
|
||||
) -> Dict[str, Tuple[List[str], Dict[str, int]]]:
|
||||
"""Per source: (ordered word texts, word_id -> position)."""
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]] = {}
|
||||
for source, ref in (reference_lyrics or {}).items():
|
||||
texts: List[str] = []
|
||||
index: Dict[str, int] = {}
|
||||
for seg in ref.get("segments") or []:
|
||||
for w in seg.get("words") or []:
|
||||
wid = w.get("id")
|
||||
if wid:
|
||||
index[wid] = len(texts)
|
||||
texts.append(w.get("text") or "")
|
||||
streams[source] = (texts, index)
|
||||
return streams
|
||||
|
||||
|
||||
def _gap_readings(
|
||||
gap: Dict[str, Any],
|
||||
anchors_by_id: Dict[str, Dict[str, Any]],
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
||||
) -> Dict[str, List[str]]:
|
||||
"""Each source's reading of the gap (raw word texts).
|
||||
|
||||
Prefer the gap's own per-source alignment. When a source aligned neither
|
||||
gap word (empty list — common), derive the reading from the reference
|
||||
stream around the surrounding anchors: the words strictly between the
|
||||
anchors when both aligned for that source, else the same-count window
|
||||
after the preceding (or before the following) anchor. A source with no
|
||||
usable anchor alignment contributes no reading.
|
||||
"""
|
||||
n = len(gap.get("transcribed_word_ids") or [])
|
||||
pre = anchors_by_id.get(gap.get("preceding_anchor_id") or "")
|
||||
fol = anchors_by_id.get(gap.get("following_anchor_id") or "")
|
||||
readings: Dict[str, List[str]] = {}
|
||||
for source, (texts, index) in streams.items():
|
||||
aligned_ids = (gap.get("reference_word_ids") or {}).get(source) or []
|
||||
aligned = [texts[index[i]] for i in aligned_ids if i in index]
|
||||
if aligned:
|
||||
readings[source] = aligned
|
||||
continue
|
||||
pre_ids = ((pre or {}).get("reference_word_ids") or {}).get(source) or []
|
||||
fol_ids = ((fol or {}).get("reference_word_ids") or {}).get(source) or []
|
||||
lo = index[pre_ids[-1]] + 1 if pre_ids and pre_ids[-1] in index else None
|
||||
hi = index[fol_ids[0]] if fol_ids and fol_ids[0] in index else None
|
||||
if lo is not None and hi is not None:
|
||||
if lo <= hi <= lo + n + 4:
|
||||
readings[source] = texts[lo:hi]
|
||||
elif lo is not None:
|
||||
readings[source] = texts[lo : lo + n]
|
||||
elif hi is not None:
|
||||
readings[source] = texts[max(0, hi - n) : hi]
|
||||
return readings
|
||||
|
||||
|
||||
def _word_maps(
|
||||
segments: List[Dict[str, Any]],
|
||||
) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, str]]:
|
||||
"""(word_id -> word dict, word_id -> segment_id) from the CURRENT segments."""
|
||||
words: Dict[str, Dict[str, Any]] = {}
|
||||
seg_of: Dict[str, str] = {}
|
||||
for seg in segments or []:
|
||||
for w in seg.get("words") or []:
|
||||
wid = w.get("id")
|
||||
if wid:
|
||||
words[wid] = w
|
||||
seg_of[wid] = seg.get("id") or ""
|
||||
return words, seg_of
|
||||
|
||||
|
||||
def _make_suggestion(
|
||||
*,
|
||||
op: str,
|
||||
word_ids: List[str],
|
||||
segment_ids: List[str],
|
||||
original_text: str,
|
||||
new_text: str,
|
||||
reason: str,
|
||||
category: str,
|
||||
confidence: float,
|
||||
) -> Dict[str, Any]:
|
||||
"""A suggestion dict shaped exactly like the LLM ones after validation."""
|
||||
return {
|
||||
"id": str(uuid.uuid4()),
|
||||
"op": op,
|
||||
"word_ids": word_ids,
|
||||
"segment_ids": segment_ids,
|
||||
"original_text": original_text,
|
||||
"new_text": new_text,
|
||||
"reason": reason,
|
||||
"category": category,
|
||||
"confidence": confidence,
|
||||
"models": ["deterministic"],
|
||||
"consensus": 1,
|
||||
"total_models": 1,
|
||||
"conflict_group": None,
|
||||
}
|
||||
|
||||
|
||||
def _capitalize(text: str) -> str:
|
||||
for i, ch in enumerate(text):
|
||||
if ch.isalpha():
|
||||
return text[:i] + ch.upper() + text[i + 1 :]
|
||||
return text
|
||||
|
||||
|
||||
def leading_connective_suggestions(
|
||||
segments: List[Dict[str, Any]],
|
||||
correction_data: Dict[str, Any],
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Pattern 4: delete an unsupported leading connective, re-capitalize next word."""
|
||||
gaps = correction_data.get("gap_sequences") or []
|
||||
anchors_by_id = {
|
||||
a.get("id"): a for a in correction_data.get("anchor_sequences") or [] if a.get("id")
|
||||
}
|
||||
gap_of_word: Dict[str, Dict[str, Any]] = {}
|
||||
for gap in gaps:
|
||||
for wid in gap.get("transcribed_word_ids") or []:
|
||||
gap_of_word[wid] = gap
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for seg in segments or []:
|
||||
words = seg.get("words") or []
|
||||
if len(words) < 3:
|
||||
continue
|
||||
first = words[0]
|
||||
wid = first.get("id")
|
||||
token = _norm(first.get("text") or "")
|
||||
if not wid or token not in LEADING_CONNECTIVES:
|
||||
continue
|
||||
gap = gap_of_word.get(wid)
|
||||
if gap is None:
|
||||
# A confidently reference-anchored leading word is legitimate.
|
||||
continue
|
||||
if _is_vocalization_token(words[1].get("text") or ""):
|
||||
# "Oh- whoa, ..." — a vocalization run, not an over-inserted
|
||||
# connective before a sentence; grouping there is musical judgement.
|
||||
continue
|
||||
readings = _gap_readings(gap, anchors_by_id, streams)
|
||||
if not readings:
|
||||
continue # no reference evidence either way -> leave it alone
|
||||
if any(token in {_norm(t) for t in reading} for reading in readings.values()):
|
||||
continue # some source supports the connective at this position
|
||||
seg_id = seg.get("id") or ""
|
||||
out.append(
|
||||
_make_suggestion(
|
||||
op="delete",
|
||||
word_ids=[wid],
|
||||
segment_ids=[seg_id],
|
||||
original_text=first.get("text") or "",
|
||||
new_text="",
|
||||
reason=(
|
||||
f'Removed leading "{first.get("text", "").strip()}" — the '
|
||||
"transcription inserted it at the line start but no reference "
|
||||
"source has it at this position"
|
||||
),
|
||||
category="mishearing",
|
||||
confidence=P4_CONFIDENCE,
|
||||
)
|
||||
)
|
||||
nxt = words[1]
|
||||
nxt_text = nxt.get("text") or ""
|
||||
capitalized = _capitalize(nxt_text)
|
||||
if nxt.get("id") and capitalized != nxt_text:
|
||||
out.append(
|
||||
_make_suggestion(
|
||||
op="replace",
|
||||
word_ids=[nxt.get("id")],
|
||||
segment_ids=[seg_id],
|
||||
original_text=nxt_text,
|
||||
new_text=capitalized,
|
||||
reason="Capitalized the new first word of the line",
|
||||
category="formatting",
|
||||
confidence=P4_CONFIDENCE,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _majority_reading(
|
||||
readings: Dict[str, List[str]], total_sources: int
|
||||
) -> Optional[List[str]]:
|
||||
"""The reading >=2/3 of ALL sources agree on (>=2 absolute), else None."""
|
||||
votes: Dict[str, List[List[str]]] = {}
|
||||
for reading in readings.values():
|
||||
if reading:
|
||||
votes.setdefault(_norm_join(reading), []).append(reading)
|
||||
if not votes:
|
||||
return None
|
||||
key, group = max(votes.items(), key=lambda kv: len(kv[1]))
|
||||
if not key or len(group) < 2 or len(group) * 3 < total_sources * 2:
|
||||
return None
|
||||
return group[0]
|
||||
|
||||
|
||||
def reference_majority_suggestions(
|
||||
segments: List[Dict[str, Any]],
|
||||
correction_data: Dict[str, Any],
|
||||
streams: Dict[str, Tuple[List[str], Dict[str, int]]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Pattern 5: replace an implausible-proper-noun gap with the >=2/3 majority reading."""
|
||||
words_by_id, seg_of = _word_maps(segments)
|
||||
anchors_by_id = {
|
||||
a.get("id"): a for a in correction_data.get("anchor_sequences") or [] if a.get("id")
|
||||
}
|
||||
all_ref_tokens = {
|
||||
_norm(t) for texts, _ in streams.values() for t in texts if _norm(t)
|
||||
}
|
||||
seg_first_word_ids = {
|
||||
(seg.get("words") or [{}])[0].get("id") for seg in segments or []
|
||||
}
|
||||
total_sources = len(streams)
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for gap in correction_data.get("gap_sequences") or []:
|
||||
gap_ids = gap.get("transcribed_word_ids") or []
|
||||
if not gap_ids or len(gap_ids) > P5_MAX_GAP_WORDS:
|
||||
continue
|
||||
gap_words = [words_by_id.get(i) for i in gap_ids]
|
||||
if any(w is None for w in gap_words):
|
||||
continue # a gap word no longer exists in the working segments
|
||||
# Red flag (REQUIRED): a capitalized mid-line token no reference knows.
|
||||
# A token merely SIMILAR to a reference token is a spelling variant,
|
||||
# not an implausible name — that's the LLM's fix, not ours.
|
||||
red_flag = None
|
||||
for wid, w in zip(gap_ids, gap_words):
|
||||
text = (w.get("text") or "").strip()
|
||||
norm = _norm(text)
|
||||
if not (
|
||||
text
|
||||
and text[0].isupper()
|
||||
and wid not in seg_first_word_ids
|
||||
and norm
|
||||
and norm not in all_ref_tokens
|
||||
):
|
||||
continue
|
||||
if any(
|
||||
difflib.SequenceMatcher(None, norm, ref).ratio()
|
||||
>= P5_SPELLING_VARIANT_RATIO
|
||||
for ref in all_ref_tokens
|
||||
):
|
||||
continue
|
||||
red_flag = text
|
||||
break
|
||||
if red_flag is None:
|
||||
continue
|
||||
readings = _gap_readings(gap, anchors_by_id, streams)
|
||||
majority = _majority_reading(readings, total_sources)
|
||||
if majority is None or len(majority) > P5_MAX_READING_WORDS:
|
||||
continue
|
||||
original = [w.get("text") or "" for w in gap_words]
|
||||
if _norm_join(majority) == _norm_join(original):
|
||||
continue
|
||||
segment_ids = sorted({seg_of.get(i, "") for i in gap_ids})
|
||||
out.append(
|
||||
_make_suggestion(
|
||||
op="replace",
|
||||
word_ids=list(gap_ids),
|
||||
segment_ids=segment_ids,
|
||||
original_text=" ".join(original),
|
||||
new_text=" ".join(majority).strip(),
|
||||
reason=(
|
||||
f'Transcription "{" ".join(original)}" contains "{red_flag}", '
|
||||
"which no reference source has; the majority of reference "
|
||||
f'sources read this as "{" ".join(majority).strip()}"'
|
||||
),
|
||||
category="mishearing",
|
||||
confidence=P5_CONFIDENCE,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def deterministic_suggestions(
|
||||
segments: List[Dict[str, Any]],
|
||||
reference_lyrics: Dict[str, Any],
|
||||
correction_data: Optional[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""All deterministic suggestions for the current working segments.
|
||||
|
||||
Needs the job's ``corrections.json`` dict for gap/anchor alignment; with
|
||||
none available (or on any internal error) it returns [] — deterministic
|
||||
fixes are an enhancement, never a failure mode.
|
||||
"""
|
||||
if not correction_data or not reference_lyrics:
|
||||
return []
|
||||
try:
|
||||
streams = _ref_word_streams(reference_lyrics)
|
||||
if not streams:
|
||||
return []
|
||||
return leading_connective_suggestions(
|
||||
segments, correction_data, streams
|
||||
) + reference_majority_suggestions(segments, correction_data, streams)
|
||||
except Exception:
|
||||
logger.warning("deterministic suggestion generation failed", exc_info=True)
|
||||
return []
|
||||
@@ -5,6 +5,7 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
@@ -14,6 +15,7 @@ from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.deterministic import deterministic_suggestions
|
||||
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
|
||||
from backend.services.auto_correct.prompts import (
|
||||
RESPONSE_SCHEMA,
|
||||
@@ -127,6 +129,84 @@ class AutoCorrectResult:
|
||||
cached: bool = False
|
||||
|
||||
|
||||
_NORM_TOKEN_RE = re.compile(r"^[^\w]+|[^\w]+$")
|
||||
|
||||
|
||||
def _norm_tokens(text: str) -> set:
|
||||
return {t for t in (_NORM_TOKEN_RE.sub("", w.lower()) for w in (text or "").split()) if t}
|
||||
|
||||
|
||||
def _assign_conflict_groups(result: list[Suggestion]) -> None:
|
||||
"""(Re)compute conflict groups over a suggestion list, in place.
|
||||
|
||||
Two rules union suggestions into a pick-at-most-one group:
|
||||
- Non-insert suggestions sharing any target word disagree about that span.
|
||||
- An ``insert_after`` whose inserted token(s) also appear in another
|
||||
suggestion's new_text targeting (or anchored on) the same word is the P1
|
||||
self-conflict signature — two overlapping suggestions both adding the
|
||||
same token (corpus f6439692: ``insert_after "fire" -> "you're"`` plus
|
||||
``replace "fire" -> "fire, you're"`` produced "you're you're"). Grouping
|
||||
them lets accept-all pick one winner instead of double-applying.
|
||||
A plain insert next to an edit with disjoint tokens stays independent.
|
||||
"""
|
||||
for s in result:
|
||||
s.conflict_group = None
|
||||
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
def union(a: int, b: int) -> None:
|
||||
parent[find(b)] = find(a)
|
||||
|
||||
by_word: dict[str, list[int]] = {}
|
||||
for i, s in enumerate(result):
|
||||
if s.op == "insert_after":
|
||||
continue
|
||||
for wid in s.word_ids:
|
||||
by_word.setdefault(wid, []).append(i)
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
union(overlapping[0], other)
|
||||
|
||||
for i, s in enumerate(result):
|
||||
if s.op != "insert_after" or not s.word_ids:
|
||||
continue
|
||||
anchor = s.word_ids[0]
|
||||
tokens = _norm_tokens(s.new_text)
|
||||
if not tokens:
|
||||
continue
|
||||
for j, r in enumerate(result):
|
||||
if j == i:
|
||||
continue
|
||||
anchored = (
|
||||
anchor in r.word_ids
|
||||
if r.op != "insert_after"
|
||||
else bool(r.word_ids) and r.word_ids[0] == anchor
|
||||
)
|
||||
if anchored and tokens & _norm_tokens(r.new_text):
|
||||
union(i, j)
|
||||
|
||||
roots: dict[int, list[int]] = {}
|
||||
for i in range(len(result)):
|
||||
roots.setdefault(find(i), []).append(i)
|
||||
for members in roots.values():
|
||||
if len(members) < 2:
|
||||
continue
|
||||
group = str(uuid.uuid4())
|
||||
for i in members:
|
||||
result[i].conflict_group = group
|
||||
|
||||
|
||||
def _sort_by_position(result: list[Suggestion], flat: list[tuple[str, str, str]]) -> None:
|
||||
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
|
||||
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
|
||||
|
||||
|
||||
class AutoCorrectService:
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
@@ -140,6 +220,7 @@ class AutoCorrectService:
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
settings: AutoCorrectSettings,
|
||||
correction_data: Optional[dict] = None,
|
||||
) -> AutoCorrectResult:
|
||||
if not segments:
|
||||
raise AutoCorrectServiceError("segments is empty")
|
||||
@@ -227,6 +308,9 @@ class AutoCorrectService:
|
||||
)
|
||||
|
||||
merged = self._merge(per_model, flat)
|
||||
merged = self._add_deterministic(
|
||||
merged, job_id, segments, reference_lyrics, correction_data, settings, flat
|
||||
)
|
||||
elapsed = time.time() - t0
|
||||
model_label = ", ".join(per_model.keys())
|
||||
logger.info(
|
||||
@@ -307,8 +391,10 @@ class AutoCorrectService:
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> str:
|
||||
# v2: deterministic suggestions (P4/P1/P5 fixers) joined the pipeline —
|
||||
# older cached results predate them, so they must not be served.
|
||||
payload = {
|
||||
"v": 1,
|
||||
"v": 2,
|
||||
"models": models,
|
||||
"settings": settings.to_dict(),
|
||||
"words": [[word_id, text] for word_id, text, _seg in flat],
|
||||
@@ -402,42 +488,78 @@ class AutoCorrectService:
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
|
||||
result = list(merged.values())
|
||||
|
||||
# Conflict groups: suggestions sharing any target word but not merged
|
||||
# above disagree about the same span — reviewer picks at most one.
|
||||
# (insert_after anchors are excluded: inserting after a word does not
|
||||
# conflict with editing that word.)
|
||||
by_word: dict[str, list[int]] = {}
|
||||
for i, s in enumerate(result):
|
||||
if s.op == "insert_after":
|
||||
continue
|
||||
for wid in s.word_ids:
|
||||
by_word.setdefault(wid, []).append(i)
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
parent[find(other)] = find(overlapping[0])
|
||||
roots: dict[int, list[int]] = {}
|
||||
for i in range(len(result)):
|
||||
roots.setdefault(find(i), []).append(i)
|
||||
for members in roots.values():
|
||||
if len(members) < 2:
|
||||
continue
|
||||
group = str(uuid.uuid4())
|
||||
for i in members:
|
||||
result[i].conflict_group = group
|
||||
|
||||
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
|
||||
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
|
||||
_assign_conflict_groups(result)
|
||||
_sort_by_position(result, flat)
|
||||
return result
|
||||
|
||||
def _add_deterministic(
|
||||
self,
|
||||
merged: list[Suggestion],
|
||||
job_id: str,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
correction_data: Optional[dict],
|
||||
settings: AutoCorrectSettings,
|
||||
flat: list[tuple[str, str, str]],
|
||||
) -> list[Suggestion]:
|
||||
"""Fold the deterministic (P4/P5) suggestions into the LLM set.
|
||||
|
||||
A deterministic suggestion identical to an LLM one just tags the
|
||||
existing suggestion; new ones are appended. Conflict groups are then
|
||||
recomputed over the combined set so a deterministic fix that disagrees
|
||||
with an LLM suggestion becomes a pick-one conflict, not a double-apply.
|
||||
"""
|
||||
if correction_data is None:
|
||||
# The proactive worker passes corrections.json in; the review-UI
|
||||
# route doesn't have it, so fetch it (best-effort) — it holds the
|
||||
# gap/anchor alignment the generators key off.
|
||||
try:
|
||||
path = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
storage = self._get_storage()
|
||||
if storage.bucket.blob(path).exists():
|
||||
correction_data = storage.download_json(path)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"auto-correct: corrections.json unavailable for %s; "
|
||||
"skipping deterministic suggestions", job_id, exc_info=True,
|
||||
)
|
||||
raw = deterministic_suggestions(segments, reference_lyrics, correction_data)
|
||||
deterministic = [
|
||||
Suggestion(**s)
|
||||
for s in raw
|
||||
if float(s.get("confidence", 0.0)) >= settings.min_confidence
|
||||
]
|
||||
if not deterministic:
|
||||
return merged
|
||||
|
||||
by_key = {
|
||||
(s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split())): s
|
||||
for s in merged
|
||||
}
|
||||
added = 0
|
||||
for s in deterministic:
|
||||
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
|
||||
existing = by_key.get(key)
|
||||
if existing is not None:
|
||||
# The deterministic generator counts as an agreeing source:
|
||||
# keeps the consensus == len(models) invariant, and lets an
|
||||
# LLM+deterministic agreement outrank a conflicting
|
||||
# single-model suggestion in winner selection.
|
||||
existing.models.append("deterministic")
|
||||
existing.consensus += 1
|
||||
existing.total_models += 1
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
continue
|
||||
merged.append(s)
|
||||
added += 1
|
||||
logger.info(
|
||||
"auto-correct deterministic job=%s generated=%d added=%d",
|
||||
job_id, len(deterministic), added,
|
||||
)
|
||||
_assign_conflict_groups(merged)
|
||||
_sort_by_position(merged, flat)
|
||||
return merged
|
||||
|
||||
# ---- internals ----
|
||||
|
||||
def _call_model(
|
||||
|
||||
@@ -10,9 +10,11 @@ Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
|
||||
import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, List
|
||||
from typing import NamedTuple, Optional, List
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
@@ -25,6 +27,18 @@ from karaoke_gen.utils import sanitize_filename
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SendResult(NamedTuple):
|
||||
"""Outcome of a provider send.
|
||||
|
||||
``message_id`` is the provider's unique id for the sent message (Postmark's
|
||||
``MessageID``) when available — used to link a send to its Postmark record and
|
||||
to dedupe the persisted ``email_log`` entry. ``None`` for providers that don't
|
||||
expose one (console/preview).
|
||||
"""
|
||||
success: bool
|
||||
message_id: Optional[str] = None
|
||||
|
||||
|
||||
class EmailProvider(ABC):
|
||||
"""Abstract base class for email providers."""
|
||||
|
||||
@@ -53,6 +67,32 @@ class EmailProvider(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def send_email_detailed(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str] = None,
|
||||
cc_emails: Optional[List[str]] = None,
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> SendResult:
|
||||
"""Send an email and report the provider message id when available.
|
||||
|
||||
Default implementation delegates to :meth:`send_email` and reports no
|
||||
message id. Providers that expose one (Postmark) override this.
|
||||
"""
|
||||
success = self.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
from_email_override=from_email_override,
|
||||
)
|
||||
return SendResult(success=success, message_id=None)
|
||||
|
||||
|
||||
class ConsoleEmailProvider(EmailProvider):
|
||||
"""
|
||||
@@ -133,6 +173,9 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
self.server_token = server_token
|
||||
self.from_email = from_email
|
||||
self.from_name = from_name
|
||||
# Postmark MessageID of the most recent successful send, so the email_log
|
||||
# chokepoint can link a persisted record to its Postmark message.
|
||||
self.last_message_id: Optional[str] = None
|
||||
|
||||
def send_email(
|
||||
self,
|
||||
@@ -144,6 +187,26 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> bool:
|
||||
return self.send_email_detailed(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
from_email_override=from_email_override,
|
||||
).success
|
||||
|
||||
def send_email_detailed(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str] = None,
|
||||
cc_emails: Optional[List[str]] = None,
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> SendResult:
|
||||
try:
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
@@ -176,7 +239,15 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
bcc_info = f" (BCC: {', '.join(bcc_emails)})" if bcc_emails else ""
|
||||
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via Postmark")
|
||||
return True
|
||||
# Capture Postmark's MessageID so the send can be linked to its
|
||||
# Postmark record and the persisted email_log entry deduped.
|
||||
message_id = None
|
||||
try:
|
||||
message_id = response.json().get("MessageID")
|
||||
except ValueError:
|
||||
pass
|
||||
self.last_message_id = message_id
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
|
||||
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
|
||||
try:
|
||||
@@ -187,11 +258,25 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
)
|
||||
except ValueError:
|
||||
logger.error(f"Postmark returned status {response.status_code}: {response.text[:200]}")
|
||||
return False
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
except requests.RequestException:
|
||||
logger.exception("Failed to send email via Postmark")
|
||||
return False
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
|
||||
# Query params that carry single-use auth/capability tokens (magic-link sign-in,
|
||||
# lyrics/instrumental review access, referral codes). We persist a redacted copy
|
||||
# so the admin email-history log never becomes a store of live credentials — the
|
||||
# email still renders faithfully, only the secret value is masked.
|
||||
_SENSITIVE_QUERY_PARAM = re.compile(r"([?&](?:token|ref|review_token|instrumental_token)=)[^&\"'\s<]+", re.IGNORECASE)
|
||||
|
||||
|
||||
def _redact_sensitive_tokens(content: Optional[str]) -> Optional[str]:
|
||||
"""Mask token/ref query-param values in email content before persistence."""
|
||||
if not content:
|
||||
return content
|
||||
return _SENSITIVE_QUERY_PARAM.sub(r"\1[REDACTED]", content)
|
||||
|
||||
|
||||
def _dedupe_emails(emails: List[str]) -> List[str]:
|
||||
@@ -275,7 +360,51 @@ class EmailService:
|
||||
(e.g. internal failure alerts) without a dedicated template method.
|
||||
Prefer a dedicated ``send_*`` template method for customer-facing mail.
|
||||
"""
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
from_email_override=from_email_override,
|
||||
email_type="raw",
|
||||
)
|
||||
|
||||
def _log_and_send(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str] = None,
|
||||
cc_emails: Optional[List[str]] = None,
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
email_type: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Single send chokepoint: dispatch via the provider, then persist a
|
||||
record of the send for the admin email-history view.
|
||||
|
||||
Every ``send_*`` template method routes through here so the persisted
|
||||
``email_log`` mirrors exactly what left the building. Persistence is
|
||||
strictly best-effort — a Firestore failure must never break or delay a
|
||||
real email send.
|
||||
"""
|
||||
# Categorize by the calling send_* method name (e.g. send_magic_link →
|
||||
# "magic_link") so the admin UI can group emails without threading an
|
||||
# explicit type through every template method.
|
||||
if email_type is None:
|
||||
try:
|
||||
caller = sys._getframe(1).f_code.co_name
|
||||
email_type = caller[len("send_"):] if caller.startswith("send_") else caller
|
||||
except Exception:
|
||||
email_type = None
|
||||
|
||||
# Dispatch via the provider's public send_email (as keyword args) so
|
||||
# callers/mocks that observe that method still see it. PostmarkEmailProvider
|
||||
# records the returned MessageID on ``last_message_id`` for us to link the
|
||||
# log entry.
|
||||
success = self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -285,6 +414,71 @@ class EmailService:
|
||||
from_email_override=from_email_override,
|
||||
)
|
||||
|
||||
# Only persist genuine outbound mail (Postmark). Console/preview providers
|
||||
# are dev/test only and have no real inbox to reflect.
|
||||
if success and isinstance(self.provider, PostmarkEmailProvider):
|
||||
try:
|
||||
self._record_sent_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
from_email=from_email_override or getattr(self.provider, "from_email", None),
|
||||
email_type=email_type,
|
||||
message_id=getattr(self.provider, "last_message_id", None),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to persist email_log record (the email itself was sent OK)"
|
||||
)
|
||||
|
||||
return success
|
||||
|
||||
def _record_sent_email(
|
||||
self,
|
||||
*,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str],
|
||||
cc_emails: Optional[List[str]],
|
||||
bcc_emails: Optional[List[str]],
|
||||
from_email: Optional[str],
|
||||
email_type: Optional[str],
|
||||
message_id: Optional[str],
|
||||
) -> None:
|
||||
"""Write one Firestore ``email_log`` doc mirroring a sent email.
|
||||
|
||||
Keyed by the Postmark MessageID when available (idempotent), else an
|
||||
auto-id. Stores the rendered HTML so the admin UI can show older mail
|
||||
after Postmark's ~45-day content retention expires — with single-use
|
||||
auth/capability tokens redacted so the log never holds live credentials.
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
db = FirestoreService().db
|
||||
doc = {
|
||||
"recipient": (to_email or "").strip().lower(),
|
||||
"recipient_raw": to_email,
|
||||
"cc": _dedupe_emails(cc_emails) if cc_emails else [],
|
||||
"bcc": _dedupe_emails(bcc_emails) if bcc_emails else [],
|
||||
"from_email": from_email,
|
||||
"subject": subject,
|
||||
"html_content": _redact_sensitive_tokens(html_content),
|
||||
"text_content": _redact_sensitive_tokens(text_content),
|
||||
"email_type": email_type,
|
||||
"message_stream": "outbound",
|
||||
"postmark_message_id": message_id,
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
collection = db.collection("email_log")
|
||||
if message_id:
|
||||
collection.document(message_id).set(doc)
|
||||
else:
|
||||
collection.add(doc)
|
||||
|
||||
def send_magic_link(
|
||||
self,
|
||||
email: str,
|
||||
@@ -378,7 +572,7 @@ class EmailService:
|
||||
© {self._get_year()} {brand_name}
|
||||
"""
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
email, subject, html_content, text_content, from_email_override=sender_email
|
||||
)
|
||||
|
||||
@@ -451,7 +645,7 @@ class EmailService:
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
return self._log_and_send(email, subject, html_content, text_content)
|
||||
|
||||
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
|
||||
"""
|
||||
@@ -593,7 +787,7 @@ class EmailService:
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
return self._log_and_send(email, subject, html_content, text_content)
|
||||
|
||||
def _get_year(self) -> int:
|
||||
"""Get current year for copyright notices."""
|
||||
@@ -973,7 +1167,7 @@ class EmailService:
|
||||
|
||||
cc_emails = ["gen@nomadkaraoke.com"] if cc_admin else None
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1050,7 +1244,7 @@ class EmailService:
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1150,7 +1344,7 @@ class EmailService:
|
||||
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1292,7 +1486,7 @@ class EmailService:
|
||||
f"If you have any questions, just reply to this email — we're happy to help."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1385,7 +1579,7 @@ class EmailService:
|
||||
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1527,7 +1721,7 @@ class EmailService:
|
||||
f"If you have any questions, just reply to this email — we're happy to help."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1577,7 +1771,7 @@ class EmailService:
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1670,7 +1864,7 @@ class EmailService:
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1780,7 +1974,7 @@ Open Job: {app_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1912,7 +2106,7 @@ View all feedback: {admin_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=admin_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -2027,7 +2221,7 @@ If the user looks legitimate, grant them credits from their admin page.
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email="andrew@beveridge.uk",
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -2082,7 +2276,7 @@ If the user looks legitimate, grant them credits from their admin page.
|
||||
|
||||
html_content = self._build_email_html(content, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
return self._log_and_send(
|
||||
to_email=email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
|
||||
@@ -200,8 +200,9 @@ class FirestoreService:
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'made_for_you', 'customer_email',
|
||||
'url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'made_for_you', 'customer_email', 'locale',
|
||||
'url', 'filename', 'existing_instrumental_gcs_path',
|
||||
'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
'state_data.audio_progress', 'state_data.lyrics_progress',
|
||||
|
||||
@@ -101,6 +101,10 @@ class JobManager:
|
||||
youtube_description_template=job_create.youtube_description_template, # video_worker reads this
|
||||
webhook_url=job_create.webhook_url,
|
||||
user_email=job_create.user_email,
|
||||
# Review autonomy ("auto" = skip review screens when confident)
|
||||
review_mode=job_create.review_mode,
|
||||
# Backing-vocals preference ("auto"=retain-where-safe | clean | review)
|
||||
backing_preference=job_create.backing_preference,
|
||||
# Distribution settings
|
||||
brand_prefix=job_create.brand_prefix,
|
||||
discord_webhook_url=job_create.discord_webhook_url,
|
||||
@@ -119,6 +123,8 @@ class JobManager:
|
||||
request_metadata=job_create.request_metadata,
|
||||
# Tenant scoping
|
||||
tenant_id=job_create.tenant_id,
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=job_create.locale,
|
||||
# Made-for-you order fields
|
||||
made_for_you=job_create.made_for_you,
|
||||
customer_email=job_create.customer_email,
|
||||
|
||||
@@ -14,6 +14,7 @@ Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding t
|
||||
here must never break the distribution pipeline — the nightly VM remains the safety net.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import storage
|
||||
@@ -23,6 +24,17 @@ from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# A single-track filename prefix must be a full public brand code PLUS at least part
|
||||
# of the artist name ("NOMAD-#### - X..."). Stricter than the by-brand deletes: when a
|
||||
# recycled brand code is shared by two tracks (orphaned files), this lets cleanup
|
||||
# target exactly one of them without touching the other.
|
||||
_TRACK_FILENAME_PREFIX_RE = re.compile(r"^NOMAD-\d{4,} - \S.*")
|
||||
|
||||
|
||||
def is_safe_track_filename_prefix(filename_prefix: Optional[str]) -> bool:
|
||||
"""True if the prefix is specific enough for a single-track mirror delete."""
|
||||
return bool(_TRACK_FILENAME_PREFIX_RE.match(filename_prefix or ""))
|
||||
|
||||
|
||||
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
|
||||
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
|
||||
@@ -162,6 +174,53 @@ class NomadMasterMirror:
|
||||
return deleted
|
||||
|
||||
|
||||
def delete_track_objects_by_filename_prefix(self, filename_prefix: str) -> dict:
|
||||
"""Delete mirror objects (720p masters + original-vocals guides) whose filename
|
||||
starts with ``filename_prefix`` — e.g. ``"NOMAD-1583 - Mazzy Star"``.
|
||||
|
||||
Used by orphaned-output cleanup when the owning job doc is gone and a recycled
|
||||
brand code is shared with a live track: the prefix must include artist text
|
||||
(enforced by ``_TRACK_FILENAME_PREFIX_RE``) so only the orphaned track's
|
||||
objects match, never the whole brand code. Matching is delimiter-bounded — the
|
||||
character after the prefix must be a space or ``.`` — so ``"NOMAD-1583 - Mazzy
|
||||
Star"`` can never match a different track named ``"NOMAD-1583 - Mazzy Starlight
|
||||
- ..."``. Raises ``ValueError`` for an unsafe prefix (callers validate with
|
||||
``is_safe_track_filename_prefix``); GCS errors stay best-effort.
|
||||
"""
|
||||
if not is_safe_track_filename_prefix(filename_prefix):
|
||||
raise ValueError(
|
||||
f"Unsafe mirror track prefix {filename_prefix!r} "
|
||||
f"(must look like 'NOMAD-#### - Artist...')"
|
||||
)
|
||||
|
||||
counts = {"masters_deleted": 0, "vocals_guides_deleted": 0}
|
||||
targets = [
|
||||
("masters_deleted", settings.nomad_master_gcs_prefix.strip("/")),
|
||||
("vocals_guides_deleted", settings.nomad_vocals_guide_gcs_prefix.strip("/")),
|
||||
]
|
||||
for key, gcs_prefix in targets:
|
||||
prefix = f"{gcs_prefix}/{filename_prefix}"
|
||||
try:
|
||||
for blob in self._bucket.list_blobs(prefix=prefix):
|
||||
remainder = blob.name[len(prefix):]
|
||||
if remainder and remainder[0] not in " .":
|
||||
# Prefix ends mid-word (a longer artist/title shares it) —
|
||||
# this object belongs to a different track.
|
||||
continue
|
||||
try:
|
||||
blob.delete()
|
||||
counts[key] += 1
|
||||
logger.info(
|
||||
"Removed orphaned mirror object gs://%s/%s",
|
||||
settings.divebar_files_bucket, blob.name,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
|
||||
except Exception as e: # noqa: BLE001 - never fatal to the caller
|
||||
logger.warning("Mirror track prefix-delete failed for %s: %s", prefix, e)
|
||||
return counts
|
||||
|
||||
|
||||
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
|
||||
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
|
||||
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Postmark admin service — email history for the admin user-detail view.
|
||||
|
||||
Surfaces "every email ever sent to a user" by merging two sources:
|
||||
|
||||
1. **Postmark Messages API** (``GET /messages/outbound``) — authoritative for the
|
||||
last ~45 days, with the exact rendered HTML and rich delivery metadata
|
||||
(delivered / opened / clicked / bounced).
|
||||
2. **Our Firestore ``email_log``** — every send persisted at send time (see
|
||||
``EmailService._record_sent_email``), so history survives beyond Postmark's
|
||||
45-day content retention.
|
||||
|
||||
The same per-server ``POSTMARK_SERVER_TOKEN`` used for sending is sufficient to
|
||||
read outbound message history (no separate Account API token needed).
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import requests
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
POSTMARK_API_BASE = "https://api.postmarkapp.com"
|
||||
EMAIL_LOG_COLLECTION = "email_log"
|
||||
|
||||
# Postmark's outbound list is paginated (count+offset, count max 500). We page
|
||||
# through until exhausted or the safety cap, so a user with a long history isn't
|
||||
# silently truncated at one batch.
|
||||
_PAGE_SIZE = 100
|
||||
_MAX_RECORDS = 500 # safety cap per source (admin view; avoids unbounded fetches)
|
||||
_HTTP_TIMEOUT = 12
|
||||
|
||||
|
||||
def _iso(value: Any) -> Optional[str]:
|
||||
"""Normalize a timestamp (datetime or str) to an ISO-8601 string."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.isoformat()
|
||||
return str(value)
|
||||
|
||||
|
||||
class PostmarkAdminService:
|
||||
"""Read-only email history queries for the admin UI."""
|
||||
|
||||
def __init__(self, server_token: Optional[str] = None):
|
||||
self.server_token = server_token if server_token is not None else os.getenv("POSTMARK_SERVER_TOKEN")
|
||||
self._db: Optional[firestore.Client] = None
|
||||
|
||||
# -- infra -------------------------------------------------------------
|
||||
@property
|
||||
def db(self) -> firestore.Client:
|
||||
# Lazy so the service can be constructed (and Postmark-only paths used)
|
||||
# without a Firestore client in contexts that don't need one.
|
||||
if self._db is None:
|
||||
self._db = firestore.Client()
|
||||
return self._db
|
||||
|
||||
def _postmark_headers(self) -> Dict[str, str]:
|
||||
return {
|
||||
"Accept": "application/json",
|
||||
"X-Postmark-Server-Token": self.server_token or "",
|
||||
}
|
||||
|
||||
# -- Postmark queries --------------------------------------------------
|
||||
def _fetch_postmark_messages(self, email: str) -> List[Dict[str, Any]]:
|
||||
"""List outbound Postmark messages sent to ``email`` (best-effort, paginated)."""
|
||||
if not self.server_token:
|
||||
return []
|
||||
|
||||
messages: List[Dict[str, Any]] = []
|
||||
offset = 0
|
||||
while len(messages) < _MAX_RECORDS:
|
||||
try:
|
||||
resp = requests.get(
|
||||
f"{POSTMARK_API_BASE}/messages/outbound",
|
||||
headers=self._postmark_headers(),
|
||||
params={"recipient": email, "count": _PAGE_SIZE, "offset": offset},
|
||||
timeout=_HTTP_TIMEOUT,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
logger.warning(
|
||||
"Postmark outbound list returned %s for recipient=%s: %s",
|
||||
resp.status_code, email, resp.text[:200],
|
||||
)
|
||||
break
|
||||
body = resp.json()
|
||||
batch = body.get("Messages", []) or []
|
||||
except (requests.RequestException, ValueError):
|
||||
logger.exception("Failed to fetch Postmark outbound messages for %s", email)
|
||||
break
|
||||
|
||||
messages.extend(batch)
|
||||
total = body.get("TotalCount", 0)
|
||||
offset += _PAGE_SIZE
|
||||
# Stop when this batch was short or we've read everything Postmark has.
|
||||
if len(batch) < _PAGE_SIZE or offset >= total:
|
||||
break
|
||||
|
||||
if len(messages) >= _MAX_RECORDS:
|
||||
logger.info("Postmark history for %s capped at %d records", email, _MAX_RECORDS)
|
||||
|
||||
summaries = []
|
||||
for m in messages:
|
||||
summaries.append({
|
||||
"message_id": m.get("MessageID"),
|
||||
"source": "postmark",
|
||||
"subject": m.get("Subject"),
|
||||
"to": ", ".join(m.get("Recipients") or []) or email,
|
||||
"from_email": m.get("From"),
|
||||
"sent_at": _iso(m.get("ReceivedAt")),
|
||||
"status": m.get("Status"),
|
||||
# Postmark tags map to our email_type when we set them; not used yet.
|
||||
"email_type": (m.get("Metadata") or {}).get("email_type"),
|
||||
"has_stored_html": False,
|
||||
})
|
||||
return summaries
|
||||
|
||||
def _fetch_log_docs(self, email: str) -> List[Dict[str, Any]]:
|
||||
"""Read persisted email_log docs for ``email`` (best-effort)."""
|
||||
recipient = (email or "").strip().lower()
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(EMAIL_LOG_COLLECTION)
|
||||
.where(filter=FieldFilter("recipient", "==", recipient))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(_MAX_RECORDS)
|
||||
)
|
||||
docs = list(query.stream())
|
||||
except Exception:
|
||||
# Missing composite index or emulator quirk — degrade gracefully.
|
||||
logger.exception("Failed to read email_log for %s", email)
|
||||
return []
|
||||
|
||||
out = []
|
||||
for doc in docs:
|
||||
data = doc.to_dict() or {}
|
||||
out.append({
|
||||
"doc_id": doc.id,
|
||||
"message_id": data.get("postmark_message_id"),
|
||||
"source": "log",
|
||||
"subject": data.get("subject"),
|
||||
"to": data.get("recipient_raw") or data.get("recipient"),
|
||||
"from_email": data.get("from_email"),
|
||||
"sent_at": _iso(data.get("created_at")),
|
||||
"status": None,
|
||||
"email_type": data.get("email_type"),
|
||||
"has_stored_html": bool(data.get("html_content")),
|
||||
})
|
||||
return out
|
||||
|
||||
# -- public API --------------------------------------------------------
|
||||
def get_user_email_history(self, email: str) -> Dict[str, Any]:
|
||||
"""Merged, de-duplicated list of emails sent to ``email`` (newest first)."""
|
||||
postmark = self._fetch_postmark_messages(email)
|
||||
logged = self._fetch_log_docs(email)
|
||||
|
||||
# Postmark wins for a message present in both (richer status); note that we
|
||||
# also have stored HTML so the UI can fall back after the 45-day window.
|
||||
by_id: Dict[str, Dict[str, Any]] = {}
|
||||
logged_by_mid: Dict[str, Dict[str, Any]] = {
|
||||
d["message_id"]: d for d in logged if d.get("message_id")
|
||||
}
|
||||
for pm in postmark:
|
||||
mid = pm.get("message_id")
|
||||
if mid and mid in logged_by_mid:
|
||||
pm["has_stored_html"] = True
|
||||
if mid:
|
||||
by_id[mid] = pm
|
||||
|
||||
merged = list(by_id.values())
|
||||
for d in logged:
|
||||
mid = d.get("message_id")
|
||||
if mid and mid in by_id:
|
||||
continue # already represented by the Postmark summary
|
||||
merged.append(d)
|
||||
|
||||
merged.sort(key=lambda x: x.get("sent_at") or "", reverse=True)
|
||||
return {
|
||||
"email": email,
|
||||
"count": len(merged),
|
||||
"postmark_available": bool(self.server_token),
|
||||
"emails": merged,
|
||||
}
|
||||
|
||||
def _log_doc_to_detail(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"message_id": data.get("postmark_message_id"),
|
||||
"source": "log",
|
||||
"subject": data.get("subject"),
|
||||
"from_email": data.get("from_email"),
|
||||
"to": data.get("recipient_raw") or data.get("recipient"),
|
||||
"cc": data.get("cc") or [],
|
||||
"bcc": data.get("bcc") or [],
|
||||
"sent_at": _iso(data.get("created_at")),
|
||||
"email_type": data.get("email_type"),
|
||||
"message_stream": data.get("message_stream"),
|
||||
"html_body": data.get("html_content"),
|
||||
"text_body": data.get("text_content"),
|
||||
"status": None,
|
||||
"events": [],
|
||||
}
|
||||
|
||||
def _fetch_log_detail_by_message_id(self, message_id: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
snap = self.db.collection(EMAIL_LOG_COLLECTION).document(message_id).get()
|
||||
if snap.exists:
|
||||
return self._log_doc_to_detail(snap.to_dict() or {})
|
||||
except Exception:
|
||||
logger.exception("email_log fallback lookup failed for %s", message_id)
|
||||
return None
|
||||
|
||||
def get_email_detail(self, message_id: str, source: str = "postmark") -> Optional[Dict[str, Any]]:
|
||||
"""Full detail for one email — rendered HTML + delivery metadata.
|
||||
|
||||
``source="log"`` reads our Firestore record directly (for messages older
|
||||
than Postmark's retention). Otherwise we query Postmark and fall back to
|
||||
the Firestore log on 404/unavailable.
|
||||
"""
|
||||
if source == "log":
|
||||
return self._fetch_log_detail_by_message_id(message_id)
|
||||
|
||||
if self.server_token:
|
||||
try:
|
||||
resp = requests.get(
|
||||
f"{POSTMARK_API_BASE}/messages/outbound/{message_id}/details",
|
||||
headers=self._postmark_headers(),
|
||||
timeout=_HTTP_TIMEOUT,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return self._postmark_detail(resp.json())
|
||||
logger.info(
|
||||
"Postmark message %s details returned %s; trying stored log",
|
||||
message_id, resp.status_code,
|
||||
)
|
||||
except (requests.RequestException, ValueError):
|
||||
logger.exception("Failed to fetch Postmark details for %s", message_id)
|
||||
|
||||
# Fallback: our persisted copy (older than 45 days, or Postmark down).
|
||||
return self._fetch_log_detail_by_message_id(message_id)
|
||||
|
||||
def _postmark_detail(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Shape a Postmark message-details payload for the admin modal."""
|
||||
events = []
|
||||
opened = 0
|
||||
clicked = 0
|
||||
bounced_detail = None
|
||||
delivered_at = None
|
||||
for ev in data.get("MessageEvents", []) or []:
|
||||
etype = ev.get("Type")
|
||||
events.append({
|
||||
"type": etype,
|
||||
"received_at": _iso(ev.get("ReceivedAt")),
|
||||
"details": ev.get("Details") or {},
|
||||
})
|
||||
if etype == "Delivered":
|
||||
delivered_at = _iso(ev.get("ReceivedAt"))
|
||||
elif etype == "Opened":
|
||||
opened += 1
|
||||
elif etype in ("LinkClicked", "Clicked"):
|
||||
clicked += 1
|
||||
elif etype == "Bounced":
|
||||
bounced_detail = ev.get("Details") or {}
|
||||
|
||||
# Derive a coarse status from events when present.
|
||||
status = data.get("Status")
|
||||
if bounced_detail:
|
||||
status = "Bounced"
|
||||
elif delivered_at:
|
||||
status = "Delivered"
|
||||
|
||||
return {
|
||||
"message_id": data.get("MessageID"),
|
||||
"source": "postmark",
|
||||
"subject": data.get("Subject"),
|
||||
"from_email": data.get("From"),
|
||||
"to": ", ".join(data.get("Recipients") or []) or data.get("To"),
|
||||
"cc": data.get("Cc"),
|
||||
"bcc": data.get("Bcc"),
|
||||
"sent_at": _iso(data.get("ReceivedAt")),
|
||||
"message_stream": data.get("MessageStream"),
|
||||
"html_body": data.get("HtmlBody"),
|
||||
"text_body": data.get("TextBody"),
|
||||
"status": status,
|
||||
"delivered_at": delivered_at,
|
||||
"open_count": opened,
|
||||
"click_count": clicked,
|
||||
"bounce": bounced_detail,
|
||||
"events": events,
|
||||
}
|
||||
|
||||
|
||||
_postmark_admin_service: Optional[PostmarkAdminService] = None
|
||||
|
||||
|
||||
def get_postmark_admin_service() -> PostmarkAdminService:
|
||||
"""Get the global Postmark admin service instance."""
|
||||
global _postmark_admin_service
|
||||
if _postmark_admin_service is None:
|
||||
_postmark_admin_service = PostmarkAdminService()
|
||||
return _postmark_admin_service
|
||||
@@ -64,7 +64,20 @@ class StorageService:
|
||||
except Exception as e:
|
||||
logger.error(f"Error downloading file {source_path}: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def download_bytes(self, source_path: str) -> bytes:
|
||||
"""Download an object from GCS fully into memory. Only use for small
|
||||
objects (e.g. transcoded review audio); large files should stream."""
|
||||
try:
|
||||
blob = self.bucket.blob(source_path)
|
||||
return blob.download_as_bytes()
|
||||
except NotFound:
|
||||
logger.warning(f"Object not found downloading {source_path}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error downloading bytes {source_path}: {e}")
|
||||
raise
|
||||
|
||||
def copy_blob(self, source_path: str, destination_path: str) -> str:
|
||||
"""Server-side copy of a blob within the bucket (no download/upload)."""
|
||||
try:
|
||||
@@ -100,12 +113,70 @@ class StorageService:
|
||||
A signed URL that accepts PUT requests with the file content
|
||||
"""
|
||||
return self._generate_signed_url_internal(blob_path, "PUT", expiration_minutes, content_type)
|
||||
|
||||
|
||||
def create_resumable_upload_session(
|
||||
self,
|
||||
blob_path: str,
|
||||
content_type: str = "application/octet-stream",
|
||||
origin: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Create a GCS resumable upload session and return its session URI.
|
||||
|
||||
Unlike a signed PUT URL (single-shot: any interruption restarts the whole
|
||||
file), a resumable session accepts chunked uploads with Content-Range and
|
||||
supports querying the persisted offset after a failure, so clients on
|
||||
flaky connections can resume mid-file with no wasted bandwidth. Session
|
||||
URIs are unauthenticated capability tokens valid for ~1 week.
|
||||
|
||||
Args:
|
||||
blob_path: The destination path in GCS.
|
||||
content_type: Content type fixed at session creation.
|
||||
origin: Browser Origin that will upload. When set, GCS answers CORS
|
||||
preflights on the session URI for that origin itself — no bucket
|
||||
CORS config is needed for the chunk PUTs.
|
||||
|
||||
Returns:
|
||||
The resumable session URI the client PUTs chunks to.
|
||||
"""
|
||||
try:
|
||||
blob = self.bucket.blob(blob_path)
|
||||
session_uri = blob.create_resumable_upload_session(
|
||||
content_type=content_type,
|
||||
origin=origin,
|
||||
)
|
||||
logger.info(f"Created resumable upload session for {blob_path} (origin={origin})")
|
||||
return session_uri
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating resumable upload session for {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def _generate_signed_url_internal(self, blob_path: str, method: str, expiration_minutes: int = 60, content_type: Optional[str] = None) -> str:
|
||||
"""Internal method to generate signed URLs for GET or PUT operations."""
|
||||
import google.auth
|
||||
from google.auth.transport import requests
|
||||
|
||||
|
||||
# Local development against fake-gcs-server: real URL signing requires
|
||||
# service-account credentials, which contributors don't have. The emulator
|
||||
# serves objects unauthenticated, so return a plain emulator URL instead.
|
||||
emulator_host = os.getenv("STORAGE_EMULATOR_HOST")
|
||||
if emulator_host:
|
||||
from urllib.parse import quote
|
||||
|
||||
base = emulator_host.rstrip("/")
|
||||
if method == "GET":
|
||||
url = f"{base}/download/storage/v1/b/{self.bucket.name}/o/{quote(blob_path, safe='')}?alt=media"
|
||||
else:
|
||||
# fake-gcs-server treats a PUT with X-Goog signature params as a
|
||||
# signed-URL upload without validating the signature. Requires the
|
||||
# server to run with -public-host matching this host.
|
||||
url = (
|
||||
f"{base}/{self.bucket.name}/{quote(blob_path)}"
|
||||
"?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Signature=local-dev"
|
||||
)
|
||||
logger.info(f"Generated emulator {method} URL for {blob_path} (STORAGE_EMULATOR_HOST set)")
|
||||
return url
|
||||
|
||||
try:
|
||||
blob = self.bucket.blob(blob_path)
|
||||
|
||||
@@ -217,14 +288,28 @@ class StorageService:
|
||||
logger.error(f"Error checking file existence {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
def upload_json(self, destination_path: str, data: Dict[str, Any]) -> str:
|
||||
"""Upload a JSON object to GCS."""
|
||||
def upload_json(
|
||||
self,
|
||||
destination_path: str,
|
||||
data: Dict[str, Any],
|
||||
if_generation_match: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Upload a JSON object to GCS.
|
||||
|
||||
``if_generation_match=0`` makes the write a create-only operation: GCS raises
|
||||
``PreconditionFailed`` (412) if the object already exists, so concurrent
|
||||
writers can't clobber each other. Callers that need this must handle the
|
||||
exception.
|
||||
"""
|
||||
try:
|
||||
blob = self.bucket.blob(destination_path)
|
||||
blob.content_type = "application/json"
|
||||
upload_kwargs = {"content_type": "application/json"}
|
||||
if if_generation_match is not None:
|
||||
upload_kwargs["if_generation_match"] = if_generation_match
|
||||
blob.upload_from_string(
|
||||
json.dumps(data, indent=2, ensure_ascii=False),
|
||||
content_type="application/json"
|
||||
**upload_kwargs,
|
||||
)
|
||||
logger.info(f"Uploaded JSON to gs://{settings.gcs_bucket_name}/{destination_path}")
|
||||
return destination_path
|
||||
|
||||
@@ -185,6 +185,7 @@ class StripeService:
|
||||
notes: Optional[str] = None,
|
||||
success_url: Optional[str] = None,
|
||||
cancel_url: Optional[str] = None,
|
||||
locale: Optional[str] = None,
|
||||
) -> Tuple[bool, Optional[str], str]:
|
||||
"""
|
||||
Create a Stripe Checkout session for a made-for-you order.
|
||||
@@ -228,6 +229,9 @@ class StripeService:
|
||||
if notes:
|
||||
# Truncate notes to fit Stripe's 500 char limit per metadata value
|
||||
metadata['notes'] = notes[:500] if len(notes) > 500 else notes
|
||||
if locale:
|
||||
# UI language the customer ordered in — surfaced admin-side on the job
|
||||
metadata['locale'] = locale
|
||||
|
||||
# Build checkout session params
|
||||
session_params = {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Tenant bulk-upload helpers.
|
||||
|
||||
Filename analysis for the tenant portal "bulk upload" flow: pairs Mixed vs
|
||||
Instrumental audio files and extracts Artist/Title from filenames so an operator
|
||||
can review/fix an editable table before submitting many karaoke jobs at once.
|
||||
"""
|
||||
|
||||
from backend.services.tenant_bulk.analyze import (
|
||||
BulkAnalysis,
|
||||
IgnoredFile,
|
||||
ProposedRow,
|
||||
UnpairedFile,
|
||||
analyze_filenames,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BulkAnalysis",
|
||||
"IgnoredFile",
|
||||
"ProposedRow",
|
||||
"UnpairedFile",
|
||||
"analyze_filenames",
|
||||
]
|
||||
@@ -0,0 +1,480 @@
|
||||
"""Filename analysis for tenant bulk upload.
|
||||
|
||||
Turns a flat list of filenames (as a browser folder-pick produces) into a set of
|
||||
proposed karaoke jobs: each pairs a **Mixed** audio file (the full song, has
|
||||
vocals) with its **Instrumental** counterpart and extracts Artist/Title.
|
||||
|
||||
Two passes:
|
||||
1. **Regex fast path** — handles the machine-friendly convention Vocal Star
|
||||
uses, e.g. ``S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3`` paired
|
||||
with ``S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3``.
|
||||
2. **LLM pass** (optional, injectable) — reasons about whatever the regex could
|
||||
not confidently pair (odd labels, missing pairs, future tenant conventions).
|
||||
Mirrors the ``match_judge`` Vertex-Gemini client pattern; injectable so unit
|
||||
tests stay deterministic without a live model call.
|
||||
|
||||
Pure analysis: no uploads, no state written, no audio read — filenames only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Audio extensions we treat as candidate track files. Anything else (images,
|
||||
# text, etc.) is surfaced under "ignored" rather than guessed at.
|
||||
AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".m4a", ".ogg", ".aac", ".opus", ".aiff", ".aif"}
|
||||
|
||||
# Labels that mark a file as the MIXED (has-vocals) version.
|
||||
_MIXED_LABELS = ("guide", "lead vocal", "lead", "vocals", "vocal", "with vocals")
|
||||
# Labels that mark a file as the INSTRUMENTAL (backing) version.
|
||||
_INSTRUMENTAL_LABELS = (
|
||||
"instrumental",
|
||||
"instru",
|
||||
"backing vocals",
|
||||
"backing",
|
||||
"karaoke",
|
||||
"bv",
|
||||
"off",
|
||||
)
|
||||
|
||||
# STRONG labels are unambiguous role markers: a bare trailing "Guide"/"Instru"
|
||||
# is a real label, so it OVERRIDES the -1/-2 slot (this is what flags the
|
||||
# S1102 "-2 … Guide" anomaly as a mixed-only file). WEAK labels double as
|
||||
# ordinary title words ("Turn It Off", "Take the Lead", "…Vocals") — a bare
|
||||
# trailing weak word is treated as part of the title, and role falls back to
|
||||
# the slot; a weak word is only trusted as a label when it is bracketed
|
||||
# ("(Karaoke)" / "[Backing]").
|
||||
_STRONG_LABELS = {"guide", "instrumental", "instru", "bv", "backing vocals"}
|
||||
|
||||
_ALL_LABELS = sorted(
|
||||
set(_MIXED_LABELS) | set(_INSTRUMENTAL_LABELS), key=len, reverse=True
|
||||
)
|
||||
_LABEL_ALTERNATION = "|".join(re.escape(lbl) for lbl in _ALL_LABELS)
|
||||
|
||||
# ``S1100-1 Eddy Grant - I Don't Wanna Dance Guide`` (extension already stripped).
|
||||
# group("code") -> "1100" group("slot") -> "1" group("rest") -> everything after
|
||||
_CODED_RE = re.compile(
|
||||
r"^S?(?P<code>\d+)\s*-\s*(?P<slot>[12])\s+(?P<rest>.+)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# A bracketed trailing label, e.g. ``Adele - Hello (Guide)`` / ``… [Instrumental]``.
|
||||
_BRACKETED_LABEL_RE = re.compile(
|
||||
rf"^(?P<body>.+?)\s*[\(\[]\s*(?P<label>{_LABEL_ALTERNATION})\s*[\)\]]\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# A bare trailing label word, e.g. ``… Straight Up Guide``.
|
||||
_BARE_LABEL_RE = re.compile(
|
||||
rf"^(?P<body>.+?)\s+(?P<label>{_LABEL_ALTERNATION})$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
MIXED = "mixed"
|
||||
INSTRUMENTAL = "instrumental"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProposedRow:
|
||||
"""A confident Mixed+Instrumental pair the operator can submit as one job."""
|
||||
|
||||
artist: str
|
||||
title: str
|
||||
mixed_filename: str
|
||||
instrumental_filename: str
|
||||
confidence: str = "high" # "high" | "medium" | "low"
|
||||
warning: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"artist": self.artist,
|
||||
"title": self.title,
|
||||
"mixed_filename": self.mixed_filename,
|
||||
"instrumental_filename": self.instrumental_filename,
|
||||
"confidence": self.confidence,
|
||||
"warning": self.warning,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class UnpairedFile:
|
||||
"""An audio file we could not confidently pair (surfaced as a warning)."""
|
||||
|
||||
filename: str
|
||||
reason: str # "no_instrumental" | "no_mixed" | "unparseable" | "duplicate"
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
role: Optional[str] = None # "mixed" | "instrumental" | None
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"filename": self.filename,
|
||||
"reason": self.reason,
|
||||
"artist": self.artist,
|
||||
"title": self.title,
|
||||
"role": self.role,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class IgnoredFile:
|
||||
"""A non-audio file that is not part of any job."""
|
||||
|
||||
filename: str
|
||||
reason: str = "non_audio"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"filename": self.filename, "reason": self.reason}
|
||||
|
||||
|
||||
@dataclass
|
||||
class BulkAnalysis:
|
||||
rows: list[ProposedRow] = field(default_factory=list)
|
||||
unpaired: list[UnpairedFile] = field(default_factory=list)
|
||||
ignored: list[IgnoredFile] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"rows": [r.to_dict() for r in self.rows],
|
||||
"unpaired": [u.to_dict() for u in self.unpaired],
|
||||
"ignored": [i.to_dict() for i in self.ignored],
|
||||
}
|
||||
|
||||
|
||||
# A parsed audio filename, before pairing.
|
||||
@dataclass
|
||||
class _Parsed:
|
||||
filename: str
|
||||
code: Optional[str]
|
||||
role: Optional[str] # MIXED | INSTRUMENTAL | None (unknown)
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
# generate(system_prompt, user_prompt) -> dict (parsed JSON matching RESPONSE_SCHEMA)
|
||||
Generate = Callable[[str, str], dict]
|
||||
|
||||
|
||||
def _role_of(label: str) -> Optional[str]:
|
||||
lbl = label.lower()
|
||||
if lbl in _MIXED_LABELS:
|
||||
return MIXED
|
||||
if lbl in _INSTRUMENTAL_LABELS:
|
||||
return INSTRUMENTAL
|
||||
return None
|
||||
|
||||
|
||||
def _slot_role(slot: Optional[str]) -> Optional[str]:
|
||||
if slot == "1":
|
||||
return MIXED
|
||||
if slot == "2":
|
||||
return INSTRUMENTAL
|
||||
return None
|
||||
|
||||
|
||||
def _peel_label(text: str, slot: Optional[str]) -> tuple[str, Optional[str]]:
|
||||
"""Split ``text`` into (body, role), trusting a trailing label only when safe.
|
||||
|
||||
- A **bracketed** label ("(Instrumental)", "[Guide]") is always trusted.
|
||||
- A bare **strong** label ("Guide", "Instru", "BV", …) is trusted and
|
||||
OVERRIDES the slot — this is what surfaces the S1102 "-2 … Guide" anomaly.
|
||||
- A bare **weak** label ("Off", "Lead", "Vocals", "Karaoke", …) doubles as a
|
||||
title word, so it is left in the title and the role falls back to the slot;
|
||||
e.g. ``S1100-1 Artist - Turn It Off`` stays a mixed file titled "Turn It Off".
|
||||
|
||||
When no label is trusted, role comes from the slot (may be None).
|
||||
"""
|
||||
m = _BRACKETED_LABEL_RE.match(text)
|
||||
if m:
|
||||
role = _role_of(m.group("label"))
|
||||
if role:
|
||||
return m.group("body").strip(), role
|
||||
|
||||
m = _BARE_LABEL_RE.match(text)
|
||||
if m and m.group("label").lower() in _STRONG_LABELS:
|
||||
role = _role_of(m.group("label"))
|
||||
if role:
|
||||
return m.group("body").strip(), role
|
||||
|
||||
return text.strip(), _slot_role(slot)
|
||||
|
||||
|
||||
def _split_artist_title(body: str) -> tuple[str, str]:
|
||||
"""Split ``Artist - Title`` on the first ` - `; whole string is the title if none."""
|
||||
body = body.strip()
|
||||
if " - " in body:
|
||||
artist, title = body.split(" - ", 1)
|
||||
return artist.strip(), title.strip()
|
||||
return "", body
|
||||
|
||||
|
||||
def _parse_one(filename: str) -> Optional[_Parsed]:
|
||||
stem = Path(filename).stem.strip()
|
||||
|
||||
m = _CODED_RE.match(stem)
|
||||
if m:
|
||||
body, role = _peel_label(m.group("rest"), m.group("slot"))
|
||||
artist, title = _split_artist_title(body)
|
||||
return _Parsed(filename, m.group("code"), role, artist, title)
|
||||
|
||||
# No S-code: only a strong/bracketed trailing label can classify it; a bare
|
||||
# weak trailing word can't be told apart from the title, so leave role unknown
|
||||
# (the file becomes a leftover for the LLM pass / warnings).
|
||||
body, role = _peel_label(stem, None)
|
||||
if role is None:
|
||||
return None
|
||||
artist, title = _split_artist_title(body)
|
||||
return _Parsed(filename, None, role, artist, title)
|
||||
|
||||
|
||||
def _pair_key(p: _Parsed) -> str:
|
||||
"""Group files that belong together. Prefer the S-code; else artist+title."""
|
||||
if p.code:
|
||||
return f"code:{p.code}"
|
||||
return f"song:{p.artist.lower()}|{p.title.lower()}"
|
||||
|
||||
|
||||
def _regex_analyze(audio_filenames: list[str]) -> tuple[list[ProposedRow], list[str]]:
|
||||
"""Regex fast path. Returns (confident rows, filenames left unpaired)."""
|
||||
parsed: list[_Parsed] = []
|
||||
unparseable: list[str] = []
|
||||
for fn in audio_filenames:
|
||||
p = _parse_one(fn)
|
||||
if p is None or p.role is None:
|
||||
unparseable.append(fn)
|
||||
else:
|
||||
parsed.append(p)
|
||||
|
||||
# Group and pair mixed<->instrumental within each group.
|
||||
groups: dict[str, list[_Parsed]] = {}
|
||||
for p in parsed:
|
||||
groups.setdefault(_pair_key(p), []).append(p)
|
||||
|
||||
rows: list[ProposedRow] = []
|
||||
leftover: list[str] = list(unparseable)
|
||||
for members in groups.values():
|
||||
mixed = [p for p in members if p.role == MIXED]
|
||||
instrumental = [p for p in members if p.role == INSTRUMENTAL]
|
||||
# Pair up as many as we can, one-to-one.
|
||||
for m, i in zip(mixed, instrumental):
|
||||
artist = m.artist or i.artist
|
||||
title = m.title or i.title
|
||||
rows.append(
|
||||
ProposedRow(
|
||||
artist=artist,
|
||||
title=title,
|
||||
mixed_filename=m.filename,
|
||||
instrumental_filename=i.filename,
|
||||
confidence="high",
|
||||
)
|
||||
)
|
||||
# Anything without a partner is left over for the LLM / warnings.
|
||||
leftover.extend(p.filename for p in mixed[len(instrumental):])
|
||||
leftover.extend(p.filename for p in instrumental[len(mixed):])
|
||||
|
||||
return rows, leftover
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM pass (optional)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You organise karaoke audio files for bulk import. You are given a list of "
|
||||
"audio filenames that a first-pass matcher could not confidently handle. "
|
||||
"Each song usually has TWO files: a MIXED version (the full song, contains "
|
||||
"lead vocals — often labelled Guide, Lead, Vocal) and an INSTRUMENTAL "
|
||||
"version (backing track, no lead vocals — often labelled Instrumental, "
|
||||
"Instru, BV, Backing, Karaoke). Pair the mixed and instrumental versions of "
|
||||
"the SAME song, and extract the artist and title from the filename.\n"
|
||||
"Return JSON with `rows` (confident mixed+instrumental pairs) and `unpaired` "
|
||||
"(files with no partner). Only use filenames exactly as given. Never invent "
|
||||
"files. A file may appear in at most one row. If unsure, put it in `unpaired`."
|
||||
)
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"rows": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
"mixed_filename": {"type": "string"},
|
||||
"instrumental_filename": {"type": "string"},
|
||||
"confidence": {"type": "string"},
|
||||
"warning": {"type": "string"},
|
||||
},
|
||||
"required": ["mixed_filename", "instrumental_filename"],
|
||||
},
|
||||
},
|
||||
"unpaired": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string"},
|
||||
"artist": {"type": "string"},
|
||||
"title": {"type": "string"},
|
||||
"reason": {"type": "string"},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": ["rows"],
|
||||
}
|
||||
|
||||
|
||||
def _llm_analyze(
|
||||
filenames: list[str], generate: Generate
|
||||
) -> tuple[list[ProposedRow], list[str]]:
|
||||
"""Run the LLM over leftover filenames. Returns (rows, still-unpaired)."""
|
||||
user_prompt = "Filenames:\n" + "\n".join(f"- {fn}" for fn in filenames)
|
||||
data = generate(_SYSTEM_PROMPT, user_prompt)
|
||||
if not isinstance(data, dict):
|
||||
return [], list(filenames)
|
||||
|
||||
available = set(filenames)
|
||||
used: set[str] = set()
|
||||
rows: list[ProposedRow] = []
|
||||
for raw in data.get("rows") or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
mixed = (raw.get("mixed_filename") or "").strip()
|
||||
instrumental = (raw.get("instrumental_filename") or "").strip()
|
||||
# Guard against hallucinated / duplicate filenames.
|
||||
if mixed not in available or instrumental not in available:
|
||||
continue
|
||||
if mixed == instrumental or mixed in used or instrumental in used:
|
||||
continue
|
||||
used.add(mixed)
|
||||
used.add(instrumental)
|
||||
confidence = str(raw.get("confidence") or "medium").lower()
|
||||
if confidence not in {"high", "medium", "low"}:
|
||||
confidence = "medium"
|
||||
rows.append(
|
||||
ProposedRow(
|
||||
artist=str(raw.get("artist") or "").strip(),
|
||||
title=str(raw.get("title") or "").strip(),
|
||||
mixed_filename=mixed,
|
||||
instrumental_filename=instrumental,
|
||||
confidence=confidence,
|
||||
warning=(str(raw["warning"]).strip() if raw.get("warning") else None),
|
||||
)
|
||||
)
|
||||
|
||||
still_unpaired = [fn for fn in filenames if fn not in used]
|
||||
return rows, still_unpaired
|
||||
|
||||
|
||||
def _describe_unpaired(filename: str) -> UnpairedFile:
|
||||
"""Best-effort artist/title + reason for a file with no partner."""
|
||||
p = _parse_one(filename)
|
||||
if p is None:
|
||||
return UnpairedFile(filename=filename, reason="unparseable")
|
||||
if p.role == MIXED:
|
||||
reason = "no_instrumental"
|
||||
elif p.role == INSTRUMENTAL:
|
||||
reason = "no_mixed"
|
||||
else:
|
||||
reason = "unparseable"
|
||||
return UnpairedFile(
|
||||
filename=filename,
|
||||
reason=reason,
|
||||
artist=p.artist or None,
|
||||
title=p.title or None,
|
||||
role=p.role,
|
||||
)
|
||||
|
||||
|
||||
def analyze_filenames(
|
||||
filenames: list[str],
|
||||
*,
|
||||
generate: Optional[Generate] = None,
|
||||
) -> BulkAnalysis:
|
||||
"""Analyse a flat list of filenames into proposed jobs.
|
||||
|
||||
Args:
|
||||
filenames: filenames from the operator's folder pick (no paths needed).
|
||||
generate: optional LLM callable (system_prompt, user_prompt) -> dict.
|
||||
When None, only the deterministic regex pass runs (used by tests and
|
||||
as the resilient fallback when the model is unavailable).
|
||||
"""
|
||||
seen: set[str] = set()
|
||||
audio: list[str] = []
|
||||
ignored: list[IgnoredFile] = []
|
||||
for fn in filenames:
|
||||
fn = (fn or "").strip()
|
||||
if not fn or fn in seen:
|
||||
continue
|
||||
seen.add(fn)
|
||||
ext = Path(fn).suffix.lower()
|
||||
if ext in AUDIO_EXTENSIONS:
|
||||
audio.append(fn)
|
||||
else:
|
||||
ignored.append(IgnoredFile(filename=fn))
|
||||
|
||||
rows, leftover = _regex_analyze(audio)
|
||||
|
||||
if leftover and generate is not None:
|
||||
try:
|
||||
llm_rows, leftover = _llm_analyze(leftover, generate)
|
||||
rows.extend(llm_rows)
|
||||
except Exception as e: # pragma: no cover - resilience guard
|
||||
logger.warning("Bulk-analyze LLM pass failed, using regex result: %s", e)
|
||||
|
||||
unpaired = [_describe_unpaired(fn) for fn in leftover]
|
||||
return BulkAnalysis(rows=rows, unpaired=unpaired, ignored=ignored)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Default Vertex-Gemini generate (mirrors backend.services.match_judge.ai)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _default_model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
|
||||
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return "gemini-3.5-flash"
|
||||
|
||||
|
||||
def default_generate(system_prompt: str, user_prompt: str) -> dict:
|
||||
"""Blocking Vertex-Gemini 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
|
||||
|
||||
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),
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=_default_model(),
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -15,20 +15,37 @@ Observability:
|
||||
- Propagates trace context through Cloud Tasks for distributed tracing
|
||||
- All worker invocations create spans linked to original request trace
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import json
|
||||
from typing import Optional
|
||||
import httpx
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
from google.protobuf import duration_pb2
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.config import get_settings, is_production
|
||||
from backend.services.tracing import inject_trace_context
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Transient control-plane errors from the Cloud Run Jobs Admin API (`JobsClient.run_job`)
|
||||
# that are safe to retry. run_job only *enqueues* an execution, so a one-off 5xx/429 from
|
||||
# the API control plane should be retried rather than hard-failing a real job's trigger.
|
||||
# (2026-08-24: a single 503 from lyrics-transcription-job's trigger failed a real job's
|
||||
# transcription with no retry — this is the guard.)
|
||||
_TRANSIENT_RUN_JOB_ERRORS = (
|
||||
gcp_exceptions.ServiceUnavailable, # 503
|
||||
gcp_exceptions.InternalServerError, # 500
|
||||
gcp_exceptions.GatewayTimeout, # 504
|
||||
gcp_exceptions.TooManyRequests, # 429
|
||||
)
|
||||
_RUN_JOB_MAX_ATTEMPTS = 3
|
||||
_RUN_JOB_BASE_DELAY_SECONDS = 1.0
|
||||
|
||||
|
||||
# Mapping of worker types to their Cloud Tasks queue names
|
||||
# These queues are created by Pulumi in infrastructure/__main__.py
|
||||
WORKER_QUEUES = {
|
||||
@@ -232,7 +249,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot enqueue Cloud Task")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region # Must match queue location
|
||||
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
@@ -387,6 +404,10 @@ class WorkerService:
|
||||
in AWAITING_AUDIO_SELECTION. Uses a Cloud Run Job (not BackgroundTasks) so
|
||||
the batch survives API instance scale-down and the user can close the tab.
|
||||
"""
|
||||
if not self._use_cloud_tasks and not is_production():
|
||||
return self._run_worker_module_locally(
|
||||
"bulk_search_worker", ["--batch-id", batch_id], log_prefix=f"[batch:{batch_id}]"
|
||||
)
|
||||
try:
|
||||
from google.cloud import run_v2
|
||||
|
||||
@@ -411,7 +432,9 @@ class WorkerService:
|
||||
]
|
||||
),
|
||||
)
|
||||
operation = client.run_job(request=request)
|
||||
operation = await self._run_job_with_retry(
|
||||
client, request, log_prefix=f"[batch:{batch_id}]"
|
||||
)
|
||||
logger.info(f"[batch:{batch_id}] Started Cloud Run Job bulk-search-job: {operation.metadata}")
|
||||
return True
|
||||
except Exception as e:
|
||||
@@ -538,6 +561,56 @@ class WorkerService:
|
||||
worker_module="video_worker",
|
||||
)
|
||||
|
||||
async def _run_job_with_retry(self, client, request, log_prefix: str):
|
||||
"""Invoke ``JobsClient.run_job`` with a small bounded retry on transient errors.
|
||||
|
||||
``run_job`` only enqueues an execution, so a one-off 5xx/429 from the Cloud Run
|
||||
Jobs Admin control plane is safe to retry rather than hard-failing the trigger.
|
||||
Non-transient errors (NotFound / PermissionDenied / InvalidArgument) are NOT
|
||||
caught here — they propagate immediately to the caller's error handling.
|
||||
Sleeps with ``asyncio.sleep`` so the event loop isn't blocked between attempts.
|
||||
"""
|
||||
last_exc: Optional[Exception] = None
|
||||
for attempt in range(1, _RUN_JOB_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return client.run_job(request=request)
|
||||
except _TRANSIENT_RUN_JOB_ERRORS as e:
|
||||
last_exc = e
|
||||
if attempt >= _RUN_JOB_MAX_ATTEMPTS:
|
||||
break
|
||||
delay = _RUN_JOB_BASE_DELAY_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
f"{log_prefix} transient error triggering Cloud Run Job "
|
||||
f"({type(e).__name__}, attempt {attempt}/{_RUN_JOB_MAX_ATTEMPTS}); "
|
||||
f"retrying in {delay:.0f}s"
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
# Exhausted transient retries — re-raise so the caller logs + returns False.
|
||||
raise last_exc
|
||||
|
||||
def _run_worker_module_locally(
|
||||
self, worker_module: str, args: list[str], log_prefix: str = ""
|
||||
) -> bool:
|
||||
"""
|
||||
Run a worker module as a detached local subprocess (development mode).
|
||||
|
||||
Mirrors what the corresponding Cloud Run Job would execute
|
||||
(``python -m backend.workers.<module> <args>``), so contributors can run
|
||||
the full pipeline locally against the emulators without GCP credentials.
|
||||
Worker output is streamed to the backend console.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
cmd = [sys.executable, "-m", f"backend.workers.{worker_module}", *args]
|
||||
try:
|
||||
subprocess.Popen(cmd, env=os.environ.copy())
|
||||
logger.info(f"{log_prefix} Started local worker subprocess: {' '.join(cmd)}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"{log_prefix} Failed to start local worker {worker_module}: {e}", exc_info=True)
|
||||
return False
|
||||
|
||||
async def _trigger_worker_cloud_run_job(
|
||||
self,
|
||||
job_id: str,
|
||||
@@ -561,6 +634,15 @@ class WorkerService:
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
"""
|
||||
# Local development (ENABLE_CLOUD_TASKS=false): run the worker module as a
|
||||
# local subprocess with the exact args the Cloud Run Job would receive.
|
||||
# The is_production() guard ensures a deployed environment that omits
|
||||
# ENABLE_CLOUD_TASKS still dispatches to Cloud Run Jobs, never Popen.
|
||||
if not self._use_cloud_tasks and not is_production():
|
||||
return self._run_worker_module_locally(
|
||||
worker_module, ["--job-id", job_id], log_prefix=f"[job:{job_id}]"
|
||||
)
|
||||
|
||||
try:
|
||||
from google.cloud import run_v2
|
||||
|
||||
@@ -590,8 +672,10 @@ class WorkerService:
|
||||
)
|
||||
)
|
||||
|
||||
# Run the job (async operation)
|
||||
operation = client.run_job(request=request)
|
||||
# Run the job (async operation), retrying transient control-plane errors.
|
||||
operation = await self._run_job_with_retry(
|
||||
client, request, log_prefix=f"[job:{job_id}]"
|
||||
)
|
||||
logger.info(
|
||||
f"[job:{job_id}] Started Cloud Run Job {cloud_run_job_name}: "
|
||||
f"{operation.metadata}"
|
||||
@@ -670,7 +754,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
@@ -759,7 +843,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Tests for POST /api/tenant/bulk/analyze (auth + feature gate + cap)."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _auth_override():
|
||||
async def override_auth():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="Valid",
|
||||
user_email="op@vocalstar.com",
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
app.dependency_overrides[require_auth] = override_auth
|
||||
yield
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def _tenant(bulk_upload=True):
|
||||
return SimpleNamespace(
|
||||
id="vocalstar", features=SimpleNamespace(bulk_upload=bulk_upload)
|
||||
)
|
||||
|
||||
|
||||
CLEAN = [
|
||||
"S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3",
|
||||
"S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3",
|
||||
"cover.png",
|
||||
]
|
||||
|
||||
|
||||
def test_403_when_not_a_tenant(client):
|
||||
with patch(
|
||||
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
|
||||
return_value=None,
|
||||
):
|
||||
r = client.post("/api/tenant/bulk/analyze", json={"filenames": CLEAN})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_403_when_feature_disabled(client):
|
||||
with patch(
|
||||
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
|
||||
return_value=_tenant(bulk_upload=False),
|
||||
):
|
||||
r = client.post("/api/tenant/bulk/analyze", json={"filenames": CLEAN})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_400_when_empty(client):
|
||||
with patch(
|
||||
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
|
||||
return_value=_tenant(),
|
||||
):
|
||||
r = client.post("/api/tenant/bulk/analyze", json={"filenames": []})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_400_when_over_cap(client):
|
||||
too_many = [f"S{i}-1 A - T Guide.mp3" for i in range(101)]
|
||||
with patch(
|
||||
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
|
||||
return_value=_tenant(),
|
||||
):
|
||||
r = client.post("/api/tenant/bulk/analyze", json={"filenames": too_many})
|
||||
assert r.status_code == 400
|
||||
assert "at most 100" in r.json()["detail"]
|
||||
|
||||
|
||||
def test_happy_path_returns_rows(client):
|
||||
# Clean batch has no leftovers, so the LLM generate is never invoked.
|
||||
with patch(
|
||||
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
|
||||
return_value=_tenant(),
|
||||
):
|
||||
r = client.post("/api/tenant/bulk/analyze", json={"filenames": CLEAN})
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert len(data["rows"]) == 1
|
||||
assert data["rows"][0]["artist"] == "Eddy Grant"
|
||||
assert {i["filename"] for i in data["ignored"]} == {"cover.png"}
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Tests for the opt-in resumable upload mode on create-with-upload-urls.
|
||||
|
||||
- upload_mode omitted / "signed_put" → signed PUT URLs (unchanged default path)
|
||||
- upload_mode "resumable" → GCS resumable session URIs created with the
|
||||
caller's Origin (so GCS answers CORS on the session itself), resumable=True
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from backend.api.routes.file_upload import (
|
||||
CreateJobWithUploadUrlsRequest,
|
||||
FileUploadRequest,
|
||||
create_job_with_upload_urls,
|
||||
)
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="OK",
|
||||
user_email="op@vocalstar.com",
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
|
||||
def _request(origin="https://vocalstar.nomadkaraoke.com"):
|
||||
req = Mock()
|
||||
req.headers = {"Origin": origin}
|
||||
req.state = Mock()
|
||||
return req
|
||||
|
||||
|
||||
def _body(**overrides):
|
||||
kwargs = dict(
|
||||
artist="Eddy Grant",
|
||||
title="I Don't Wanna Dance",
|
||||
files=[
|
||||
FileUploadRequest(filename="mixed.mp3", content_type="audio/mpeg", file_type="audio"),
|
||||
FileUploadRequest(filename="inst.mp3", content_type="audio/mpeg", file_type="existing_instrumental"),
|
||||
],
|
||||
is_private=True,
|
||||
existing_instrumental=True,
|
||||
)
|
||||
kwargs.update(overrides)
|
||||
return CreateJobWithUploadUrlsRequest(**kwargs)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def endpoint_mocks():
|
||||
"""Patch the endpoint's collaborators down to URL generation."""
|
||||
with patch("backend.api.routes.file_upload.get_tenant_config_from_request", return_value=None), \
|
||||
patch("backend.api.routes.file_upload.get_locale_from_request", return_value="en"), \
|
||||
patch("backend.api.routes.file_upload.get_full_locale_from_request", return_value="en"), \
|
||||
patch("backend.api.routes.file_upload.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.file_upload.get_theme_service") as theme_svc, \
|
||||
patch("backend.api.routes.file_upload.get_credential_manager") as cred_mgr, \
|
||||
patch("backend.api.routes.file_upload.get_effective_distribution_settings") as dist, \
|
||||
patch("backend.api.routes.file_upload.job_manager") as job_manager, \
|
||||
patch("backend.api.routes.file_upload.storage_service") as storage, \
|
||||
patch("backend.api.routes.file_upload.metrics"):
|
||||
theme_svc.return_value.get_default_theme_id.return_value = None
|
||||
# No distribution targets → no credential checks fire.
|
||||
dist.return_value = Mock(
|
||||
brand_prefix=None, dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None
|
||||
)
|
||||
cred_mgr.return_value = Mock()
|
||||
job_manager.create_job.return_value = Mock(job_id="job-123")
|
||||
storage.generate_signed_upload_url.return_value = "https://signed-put"
|
||||
storage.create_resumable_upload_session.return_value = "https://session-uri"
|
||||
yield {"storage": storage, "job_manager": job_manager}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_mode_returns_signed_put_urls(endpoint_mocks, auth):
|
||||
resp = await create_job_with_upload_urls(_request(), _body(), auth)
|
||||
assert resp.job_id == "job-123"
|
||||
assert [u.resumable for u in resp.upload_urls] == [False, False]
|
||||
assert all(u.upload_url == "https://signed-put" for u in resp.upload_urls)
|
||||
endpoint_mocks["storage"].create_resumable_upload_session.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resumable_mode_returns_session_uris_with_origin(endpoint_mocks, auth):
|
||||
resp = await create_job_with_upload_urls(
|
||||
_request(origin="https://vocalstar.nomadkaraoke.com"),
|
||||
_body(upload_mode="resumable", batch_id="batch-1"),
|
||||
auth,
|
||||
)
|
||||
assert [u.resumable for u in resp.upload_urls] == [True, True]
|
||||
assert all(u.upload_url == "https://session-uri" for u in resp.upload_urls)
|
||||
endpoint_mocks["storage"].generate_signed_upload_url.assert_not_called()
|
||||
# Sessions created with the caller's Origin so GCS handles session CORS.
|
||||
for call in endpoint_mocks["storage"].create_resumable_upload_session.call_args_list:
|
||||
assert call.kwargs["origin"] == "https://vocalstar.nomadkaraoke.com"
|
||||
# batch_id stamping still applies in resumable mode.
|
||||
endpoint_mocks["job_manager"].update_state_data.assert_any_call("job-123", "batch_id", "batch-1")
|
||||
|
||||
|
||||
def test_upload_mode_rejects_unknown_values():
|
||||
with pytest.raises(Exception):
|
||||
_body(upload_mode="carrier-pigeon")
|
||||
Whitespace-only changes.
@@ -0,0 +1,183 @@
|
||||
"""Tests for the server-side AI-suggestion apply engine.
|
||||
|
||||
This is a port of the review UI's auto-apply (autoCorrectApply.ts /
|
||||
autoCorrectConflicts.ts); these tests pin the port to the frontend's observable
|
||||
behaviour: op semantics, timing distribution, word flags, conflict resolution.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from backend.services.auto_approval.apply import (
|
||||
apply_all_suggestions,
|
||||
apply_suggestion,
|
||||
find_suspicious_duplicates,
|
||||
is_suggestion_stale,
|
||||
pick_accept_all_winners,
|
||||
)
|
||||
|
||||
|
||||
def _word(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end, "confidence": 0.9}
|
||||
|
||||
|
||||
def _segments() -> List[Dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": "s0",
|
||||
"text": "I am a fire",
|
||||
"words": [
|
||||
_word("w0", "I", 0.0, 0.3),
|
||||
_word("w1", "am", 0.3, 0.6),
|
||||
_word("w2", "a", 0.6, 0.9),
|
||||
_word("w3", "fire", 0.9, 1.5),
|
||||
],
|
||||
"start_time": 0.0,
|
||||
"end_time": 1.5,
|
||||
},
|
||||
{
|
||||
"id": "s1",
|
||||
"text": "gasoline",
|
||||
"words": [_word("w4", "gasoline", 2.0, 2.8)],
|
||||
"start_time": 2.0,
|
||||
"end_time": 2.8,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _sug(op: str, word_ids: List[str], new_text: str = "", **kw: Any) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": kw.pop("id", "sug1"),
|
||||
"op": op,
|
||||
"word_ids": word_ids,
|
||||
"segment_ids": ["s0"],
|
||||
"original_text": kw.pop("original_text", ""),
|
||||
"new_text": new_text,
|
||||
"confidence": kw.pop("confidence", 0.9),
|
||||
"consensus": kw.pop("consensus", 2),
|
||||
"total_models": kw.pop("total_models", 2),
|
||||
"conflict_group": kw.pop("conflict_group", None),
|
||||
}
|
||||
|
||||
|
||||
# --- replace ---
|
||||
|
||||
def test_replace_single_word_inherits_timing_and_flags() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("replace", ["w1"], "was", original_text="am"))
|
||||
assert result is not None
|
||||
words = result[0]["words"]
|
||||
assert [w["text"] for w in words] == ["I", "was", "a", "fire"]
|
||||
new = words[1]
|
||||
assert new["start_time"] == 0.3 and new["end_time"] == 0.6
|
||||
assert new["ai_corrected"] is True
|
||||
assert new["created_during_correction"] is True
|
||||
assert new["timing_estimated"] is False # single word inherits a real range
|
||||
assert new["original_text"] == "am"
|
||||
assert result[0]["text"] == "I was a fire"
|
||||
|
||||
|
||||
def test_replace_multi_word_splits_timing_and_marks_estimated() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("replace", ["w3"], "fire, you're"))
|
||||
assert result is not None
|
||||
words = result[0]["words"]
|
||||
assert [w["text"] for w in words] == ["I", "am", "a", "fire,", "you're"]
|
||||
a, b = words[3], words[4]
|
||||
assert a["start_time"] == 0.9 and abs(a["end_time"] - 1.2) < 1e-9
|
||||
assert abs(b["start_time"] - 1.2) < 1e-9 and b["end_time"] == 1.5
|
||||
assert a["timing_estimated"] is True and b["timing_estimated"] is True
|
||||
assert "original_text" in a and "original_text" not in b
|
||||
|
||||
|
||||
# --- insert_after ---
|
||||
|
||||
def test_insert_after_uses_gap_to_next_word() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("insert_after", ["w3"], "burning"))
|
||||
assert result is not None
|
||||
words = result[0]["words"]
|
||||
assert [w["text"] for w in words] == ["I", "am", "a", "fire", "burning"]
|
||||
new = words[4]
|
||||
assert new["start_time"] == 1.5 # anchor end
|
||||
assert new["timing_estimated"] is True
|
||||
|
||||
|
||||
# --- delete ---
|
||||
|
||||
def test_delete_word_updates_segment_text_and_timing() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w0"]))
|
||||
assert result is not None
|
||||
seg = result[0]
|
||||
assert seg["text"] == "am a fire"
|
||||
assert seg["start_time"] == 0.3
|
||||
|
||||
|
||||
def test_delete_last_word_removes_segment() -> None:
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w4"]))
|
||||
assert result is not None
|
||||
assert len(result) == 1
|
||||
assert result[0]["id"] == "s0"
|
||||
|
||||
|
||||
# --- staleness ---
|
||||
|
||||
def test_missing_word_is_stale() -> None:
|
||||
assert is_suggestion_stale(_segments(), _sug("replace", ["nope"], "x"))
|
||||
assert apply_suggestion(_segments(), _sug("replace", ["nope"], "x")) is None
|
||||
|
||||
|
||||
def test_non_contiguous_words_are_stale() -> None:
|
||||
assert is_suggestion_stale(_segments(), _sug("replace", ["w0", "w2"], "x"))
|
||||
|
||||
|
||||
def test_empty_word_ids_is_stale_not_crash() -> None:
|
||||
# all([]) is vacuously True — a cached suggestion with missing/empty
|
||||
# word_ids must be treated as stale, not crash min() on an empty list.
|
||||
assert is_suggestion_stale(_segments(), _sug("replace", [], "x"))
|
||||
assert apply_suggestion(_segments(), _sug("replace", [], "x")) is None
|
||||
|
||||
|
||||
# --- conflict groups / accept-all ---
|
||||
|
||||
def test_conflict_group_winner_by_consensus_then_confidence() -> None:
|
||||
s1 = _sug("replace", ["w1"], "was", id="a", conflict_group="g1", consensus=1, confidence=0.95)
|
||||
s2 = _sug("replace", ["w1"], "is", id="b", conflict_group="g1", consensus=2, confidence=0.7)
|
||||
s3 = _sug("replace", ["w0"], "You", id="c")
|
||||
assert pick_accept_all_winners([s1, s2, s3]) == ["b", "c"]
|
||||
|
||||
|
||||
def test_apply_all_resolves_conflicts_and_reports() -> None:
|
||||
s1 = _sug("replace", ["w1"], "was", id="a", conflict_group="g1", consensus=1)
|
||||
s2 = _sug("replace", ["w1"], "is", id="b", conflict_group="g1", consensus=2)
|
||||
out = apply_all_suggestions(_segments(), [s1, s2])
|
||||
assert out["applied_ids"] == ["b"]
|
||||
assert out["rejected_ids"] == ["a"]
|
||||
assert out["stale_ids"] == []
|
||||
assert [w["text"] for w in out["segments"][0]["words"]] == ["I", "is", "a", "fire"]
|
||||
|
||||
|
||||
def test_apply_all_flags_stale() -> None:
|
||||
out = apply_all_suggestions(_segments(), [_sug("replace", ["gone"], "x", id="a")])
|
||||
assert out["stale_ids"] == ["a"]
|
||||
assert out["applied_ids"] == []
|
||||
|
||||
|
||||
def test_p1_self_conflict_produces_detectable_duplicate() -> None:
|
||||
# Corpus f6439692: overlapping suggestions (conflict_group=null) both add
|
||||
# "you're" -> "fire, you're you're gasoline". The apply engine mirrors the
|
||||
# UI (both apply); find_suspicious_duplicates must catch the result.
|
||||
s1 = _sug("insert_after", ["w3"], "you're", id="a")
|
||||
s2 = _sug("replace", ["w3"], "fire, you're", id="b")
|
||||
out = apply_all_suggestions(_segments(), [s1, s2])
|
||||
dups = find_suspicious_duplicates(out["segments"], {})
|
||||
assert "you're" in dups
|
||||
|
||||
|
||||
def test_duplicates_supported_by_reference_are_ok() -> None:
|
||||
segments = [{
|
||||
"id": "s0", "text": "hey hey you",
|
||||
"words": [_word("w0", "hey", 0.0, 0.2), _word("w1", "hey", 0.2, 0.4),
|
||||
_word("w2", "you", 0.4, 0.6)],
|
||||
"start_time": 0.0, "end_time": 0.6,
|
||||
}]
|
||||
refs = {"genius": {"segments": [{"text": "Hey hey you"}]}}
|
||||
assert find_suspicious_duplicates(segments, refs) == []
|
||||
assert find_suspicious_duplicates(segments, {}) == ["hey"]
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Tests for the Phase-2B 3-stem backing decider (scorer branch + executor gating).
|
||||
|
||||
Comparison fixtures mirror the real corpus signal profiles (private
|
||||
validate_backing_decider.py table, 2026-08-28): the catastrophic
|
||||
backing-stem-is-the-lead job (1d45b286), the noise-floor grungegaze job
|
||||
(95d8e844), the quiet-genuine-harmonies job (d508adb6), and the high-corr
|
||||
genuine keep that must NOT trip the lead gate (33453fa0).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Dict, Optional
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_approval.models import BackingVerdict
|
||||
from backend.services.auto_approval.scorer import extract_backing_signals, score_backing
|
||||
|
||||
|
||||
def _analysis(
|
||||
audible_percentage: float = 25.0,
|
||||
loud: int = 2,
|
||||
comparison: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
segments = [
|
||||
{
|
||||
"start_seconds": 10.0 * i,
|
||||
"end_seconds": 10.0 * i + 5.0,
|
||||
"duration_seconds": 5.0,
|
||||
"avg_amplitude_db": -15.0 if i < loud else -35.0,
|
||||
"peak_amplitude_db": -10.0,
|
||||
}
|
||||
for i in range(4)
|
||||
]
|
||||
data: Dict[str, Any] = {
|
||||
"has_audible_content": True,
|
||||
"audible_percentage": audible_percentage,
|
||||
"audible_segments": segments,
|
||||
"recommended_selection": "with_backing",
|
||||
}
|
||||
if comparison is not None:
|
||||
data["stem_comparison"] = comparison
|
||||
return data
|
||||
|
||||
|
||||
def _comparison(**overrides: Any) -> Dict[str, Any]:
|
||||
base = {
|
||||
"window_ms": 100,
|
||||
"silence_threshold_db": -40.0,
|
||||
"duration_seconds": 200.0,
|
||||
"backing_audible_fraction": 0.30,
|
||||
"lead_audible_fraction": 0.65,
|
||||
"vocals_audible_fraction": 0.70,
|
||||
"coverage_ratio": 0.43,
|
||||
"corr_backing_vocals": 0.40,
|
||||
"corr_backing_lead": 0.20,
|
||||
"backing_median_db": -26.0,
|
||||
"lead_median_db": -18.0,
|
||||
"vocals_median_db": -17.0,
|
||||
"lead_overlap_fraction": 0.80,
|
||||
"backing_db_std": 4.5,
|
||||
"flat_fraction": 0.05,
|
||||
"error": None,
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def test_genuine_backing_is_confident_keep() -> None:
|
||||
result = score_backing(_analysis(comparison=_comparison()))
|
||||
assert result.verdict == BackingVerdict.WITH_BACKING
|
||||
assert result.non_subjective is True
|
||||
|
||||
|
||||
def test_no_comparison_stays_review() -> None:
|
||||
result = score_backing(_analysis())
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert result.non_subjective is False
|
||||
|
||||
|
||||
def test_errored_comparison_reads_as_absent() -> None:
|
||||
result = score_backing(
|
||||
_analysis(comparison=_comparison(error="boom"))
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert result.signals.comparison_present is False
|
||||
|
||||
|
||||
def test_backing_stem_is_lead_never_keeps() -> None:
|
||||
# 1d45b286 profile: covR 0.94, corr 0.95, backing 60% vs lead 18%.
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=60.0,
|
||||
comparison=_comparison(
|
||||
coverage_ratio=0.94,
|
||||
corr_backing_vocals=0.95,
|
||||
backing_audible_fraction=0.60,
|
||||
lead_audible_fraction=0.18,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert "BE the lead" in " ".join(result.reasons)
|
||||
|
||||
|
||||
def test_high_corr_keep_with_stronger_lead_does_not_trip_lead_gate() -> None:
|
||||
# 33453fa0 profile: covR 0.77 / corr 0.86 but backing (28%) < lead (34%).
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=28.0,
|
||||
comparison=_comparison(
|
||||
coverage_ratio=0.77,
|
||||
corr_backing_vocals=0.86,
|
||||
backing_audible_fraction=0.28,
|
||||
lead_audible_fraction=0.34,
|
||||
backing_median_db=-33.0,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.WITH_BACKING
|
||||
|
||||
|
||||
def test_noise_floor_signature_is_review() -> None:
|
||||
# 95d8e844 profile: median -38.6 dB over 30% of the track, corr -0.23.
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=30.0,
|
||||
comparison=_comparison(
|
||||
backing_median_db=-38.6,
|
||||
backing_audible_fraction=0.30,
|
||||
corr_backing_vocals=-0.23,
|
||||
coverage_ratio=0.42,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert "noise-floor" in " ".join(result.reasons)
|
||||
|
||||
|
||||
def test_quiet_sparse_harmonies_still_keep() -> None:
|
||||
# d508adb6 profile: 1% audible at -38 dB, overlap 0.89 — genuine harmonies.
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=1.0,
|
||||
loud=1,
|
||||
comparison=_comparison(
|
||||
backing_median_db=-38.1,
|
||||
backing_audible_fraction=0.01,
|
||||
corr_backing_vocals=0.19,
|
||||
coverage_ratio=0.01,
|
||||
lead_overlap_fraction=0.89,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.WITH_BACKING
|
||||
|
||||
|
||||
def test_sparse_full_lead_overlap_is_bleed_review() -> None:
|
||||
result = score_backing(
|
||||
_analysis(
|
||||
audible_percentage=2.0,
|
||||
comparison=_comparison(
|
||||
backing_audible_fraction=0.02,
|
||||
coverage_ratio=0.03,
|
||||
lead_overlap_fraction=0.99,
|
||||
),
|
||||
)
|
||||
)
|
||||
assert result.verdict == BackingVerdict.REVIEW
|
||||
assert "bleed" in " ".join(result.reasons)
|
||||
|
||||
|
||||
def test_near_silent_rule_still_wins_over_comparison() -> None:
|
||||
analysis = _analysis(audible_percentage=0.1, comparison=_comparison())
|
||||
analysis["audible_segments"] = []
|
||||
result = score_backing(analysis)
|
||||
assert result.verdict == BackingVerdict.CLEAN
|
||||
|
||||
|
||||
def test_comparison_signals_extracted() -> None:
|
||||
s = extract_backing_signals(_analysis(comparison=_comparison()))
|
||||
assert s.comparison_present is True
|
||||
assert s.coverage_ratio == 0.43
|
||||
assert s.corr_backing_vocals == 0.40
|
||||
assert s.lead_overlap_fraction == 0.80
|
||||
assert s.backing_median_db == -26.0
|
||||
assert s.flat_fraction == 0.05
|
||||
|
||||
|
||||
# ---- executor gating for WITH_BACKING enforcement ----
|
||||
|
||||
from backend.models.job import JobStatus # noqa: E402
|
||||
from backend.tests.services.auto_approval.test_executor import ( # noqa: E402
|
||||
_confident_corrections,
|
||||
_job,
|
||||
_run,
|
||||
)
|
||||
|
||||
|
||||
def _keep_backing_analysis() -> Dict[str, Any]:
|
||||
return _analysis(comparison=_comparison())
|
||||
|
||||
|
||||
def _keep_job(with_backing_stem: bool = True) -> SimpleNamespace:
|
||||
job = _job(backing=_keep_backing_analysis())
|
||||
if with_backing_stem:
|
||||
job.file_urls["stems"]["instrumental_with_backing"] = (
|
||||
"jobs/j1/stems/instrumental_with_backing.flac"
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
def _settings(keep_enabled: bool) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
auto_approval_enforce_enabled=True,
|
||||
auto_approval_backing_keep_enabled=keep_enabled,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_keep_blocked_while_flag_off() -> None:
|
||||
result, job_manager, *_ = await _run(_keep_job(), settings=_settings(False))
|
||||
assert result["outcome"] == "review"
|
||||
assert "backing_keep_disabled" in result["blockers"]
|
||||
payload = job_manager.update_processing_metadata.call_args[0][2]
|
||||
assert payload["backing"]["verdict"] == "with_backing"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_keep_enforced_when_flag_on() -> None:
|
||||
result, job_manager, _storage, worker = await _run(
|
||||
_keep_job(), settings=_settings(True)
|
||||
)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
job_manager.update_state_data.assert_any_call(
|
||||
"j1", "instrumental_selection", "with_backing"
|
||||
)
|
||||
worker.trigger_render_video_worker.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_keep_needs_with_backing_stem() -> None:
|
||||
result, *_ = await _run(
|
||||
_keep_job(with_backing_stem=False), settings=_settings(True)
|
||||
)
|
||||
assert result["outcome"] == "review"
|
||||
assert "no_with_backing_stem" in result["blockers"]
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Tests for the auto-approval executor.
|
||||
|
||||
The executor must (a) record a verdict on every scored job, (b) complete the
|
||||
review end-to-end ONLY when fully confident and eligible, and (c) fail safe —
|
||||
any anomaly or error leaves the job on the normal human-review path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Dict, List, Optional
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
|
||||
|
||||
def _confident_corrections() -> Dict[str, Any]:
|
||||
words = [
|
||||
{"id": f"w{i}", "text": f"word{i}", "start_time": i * 0.5, "end_time": i * 0.5 + 0.4}
|
||||
for i in range(20)
|
||||
]
|
||||
return {
|
||||
"corrected_segments": [{
|
||||
"id": "s0",
|
||||
"text": " ".join(w["text"] for w in words),
|
||||
"words": words,
|
||||
"start_time": 0.0,
|
||||
"end_time": 10.0,
|
||||
}],
|
||||
"corrections": [],
|
||||
"corrections_made": 0,
|
||||
"reference_lyrics": {"spotify": {"metadata": {"is_synced": True}, "segments": []}},
|
||||
"anchor_sequences": [{"id": "a0", "transcribed_word_ids": [w["id"] for w in words]}],
|
||||
"gap_sequences": [],
|
||||
"metadata": {"total_words": 20, "agentic_routing": "disabled", "correction_type": "none"},
|
||||
}
|
||||
|
||||
|
||||
def _clean_backing() -> Dict[str, Any]:
|
||||
return {
|
||||
"has_audible_content": False,
|
||||
"audible_percentage": 0.0,
|
||||
"audible_segments": [],
|
||||
"recommended_selection": "clean",
|
||||
}
|
||||
|
||||
|
||||
def _job(
|
||||
status: JobStatus = JobStatus.GENERATING_SCREENS,
|
||||
review_mode: str = "auto",
|
||||
made_for_you: bool = False,
|
||||
audio_complete: bool = True,
|
||||
backing: Optional[Dict[str, Any]] = None,
|
||||
existing_instrumental: Optional[str] = None,
|
||||
state_extra: Optional[Dict[str, Any]] = None,
|
||||
) -> SimpleNamespace:
|
||||
state: Dict[str, Any] = {"audio_complete": audio_complete}
|
||||
if backing is not None:
|
||||
state["backing_vocals_analysis"] = backing
|
||||
state.update(state_extra or {})
|
||||
return SimpleNamespace(
|
||||
status=status,
|
||||
state_data=state,
|
||||
review_mode=review_mode,
|
||||
made_for_you=made_for_you,
|
||||
existing_instrumental_gcs_path=existing_instrumental,
|
||||
file_urls={"stems": {"instrumental_clean": "jobs/j1/stems/clean.flac"}},
|
||||
)
|
||||
|
||||
|
||||
def _settings(enforce: bool = True) -> SimpleNamespace:
|
||||
return SimpleNamespace(auto_approval_enforce_enabled=enforce)
|
||||
|
||||
|
||||
async def _run(job, *, corrections=None, suggestions=None, settings=None):
|
||||
"""Drive maybe_auto_complete_review with everything mocked; returns
|
||||
(result, job_manager_mock, storage_mock, worker_service_mock)."""
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
storage = MagicMock()
|
||||
corrections = corrections if corrections is not None else _confident_corrections()
|
||||
storage.file_exists.return_value = True
|
||||
cache = {"suggestions": suggestions if suggestions is not None else []}
|
||||
storage.list_files.return_value = ["jobs/j1/lyrics/auto_correct_cache/x.json"]
|
||||
|
||||
def _download(path: str):
|
||||
if "auto_correct_cache" in path:
|
||||
return cache
|
||||
return corrections
|
||||
|
||||
storage.download_json.side_effect = _download
|
||||
|
||||
worker_service = MagicMock()
|
||||
worker_service.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.config.get_settings", return_value=settings or _settings()), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
return result, job_manager, storage, worker_service
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confident_job_is_auto_completed() -> None:
|
||||
result, jm, storage, ws = await _run(_job(backing=_clean_backing()))
|
||||
assert result["outcome"] == "auto_completed"
|
||||
|
||||
# corrections_updated.json saved with the auto-approval marker
|
||||
upload_path, uploaded = storage.upload_json.call_args.args
|
||||
assert upload_path == "jobs/j1/lyrics/corrections_updated.json"
|
||||
assert uploaded["metadata"]["auto_approval"]["auto_approved"] is True
|
||||
|
||||
# instrumental selection stored, progress keys cleared, transitioned, render triggered
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "clean")
|
||||
jm.delete_state_data_keys.assert_called_once()
|
||||
transition_kwargs = jm.transition_to_state.call_args.kwargs
|
||||
assert transition_kwargs["new_status"] == JobStatus.REVIEW_COMPLETE
|
||||
ws.trigger_render_video_worker.assert_awaited_once_with("j1")
|
||||
|
||||
# verdict recorded with outcome
|
||||
section, payload = jm.update_processing_metadata.call_args.args[1:3]
|
||||
assert section == "auto_approval"
|
||||
assert payload["outcome"] == "auto_completed"
|
||||
assert payload["mode"] == "enforce"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_suggestions_are_applied_in_saved_corrections() -> None:
|
||||
suggestions = [{
|
||||
"id": "sugA", "op": "replace", "word_ids": ["w3"], "segment_ids": ["s0"],
|
||||
"original_text": "word3", "new_text": "fixed", "confidence": 0.9,
|
||||
"consensus": 2, "total_models": 2, "conflict_group": None,
|
||||
}]
|
||||
result, jm, storage, _ = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
uploaded = storage.upload_json.call_args.args[1]
|
||||
texts = [w["text"] for w in uploaded["corrected_segments"][0]["words"]]
|
||||
assert "fixed" in texts and "word3" not in texts
|
||||
assert uploaded["metadata"]["auto_approval"]["applied_suggestion_ids"] == ["sugA"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unconfident_job_goes_to_review_with_verdict_recorded() -> None:
|
||||
audible = {"has_audible_content": True, "audible_percentage": 40.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -10.0}],
|
||||
"recommended_selection": "with_backing"}
|
||||
result, jm, storage, ws = await _run(_job(backing=audible))
|
||||
assert result["outcome"] == "review"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
ws.trigger_render_video_worker.assert_not_awaited()
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["outcome"] == "review"
|
||||
assert payload["mode"] == "shadow"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_always_review_mode_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(_job(review_mode="always_review", backing=_clean_backing()))
|
||||
assert result["outcome"] == "review"
|
||||
assert "review_mode:always_review" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_made_for_you_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(_job(made_for_you=True, backing=_clean_backing()))
|
||||
assert result["outcome"] == "review"
|
||||
assert "made_for_you" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flag_disabled_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=_clean_backing()), settings=_settings(enforce=False)
|
||||
)
|
||||
assert result["outcome"] == "review"
|
||||
assert "flag_disabled" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_incomplete_audio_blocks_enforcement() -> None:
|
||||
result, jm, _, _ = await _run(_job(audio_complete=False, backing=None))
|
||||
assert result["outcome"] == "review"
|
||||
assert "audio_incomplete" in result["blockers"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_instrumental_completes_with_custom_selection() -> None:
|
||||
# Tenant/bulk jobs with a user-supplied instrumental have NO instrumental
|
||||
# decision — confident lyrics alone auto-complete with selection="custom",
|
||||
# even with NO backing analysis at all (the backing verdict is moot).
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=None, existing_instrumental="jobs/j1/custom.flac")
|
||||
)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "custom")
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["enforcement_basis"] == "lyrics_only_custom_instrumental"
|
||||
assert payload["custom_instrumental"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_instrumental_stem_also_selects_custom() -> None:
|
||||
job = _job(backing=None)
|
||||
job.file_urls["stems"]["custom_instrumental"] = "jobs/j1/stems/custom.flac"
|
||||
# No separated instrumental required for custom jobs.
|
||||
del job.file_urls["stems"]["instrumental_clean"]
|
||||
result, jm, _, _ = await _run(job)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "custom")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_instrumental_still_requires_confident_lyrics() -> None:
|
||||
corrections = _confident_corrections()
|
||||
corrections["reference_lyrics"] = {} # no references -> lyrics review
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=None, existing_instrumental="jobs/j1/custom.flac"),
|
||||
corrections=corrections,
|
||||
)
|
||||
assert result["outcome"] == "review"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wrong_status_is_noop() -> None:
|
||||
result, jm, _, _ = await _run(_job(status=JobStatus.IN_REVIEW, backing=_clean_backing()))
|
||||
assert result["outcome"] == "wrong_status"
|
||||
jm.update_processing_metadata.assert_not_called()
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_selection_is_noop() -> None:
|
||||
result, jm, _, _ = await _run(
|
||||
_job(backing=_clean_backing(), state_extra={"instrumental_selection": "clean"})
|
||||
)
|
||||
assert result["outcome"] == "already_selected"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_suggestion_aborts_to_review() -> None:
|
||||
suggestions = [{
|
||||
"id": "sugA", "op": "replace", "word_ids": ["not-a-word"], "segment_ids": ["s0"],
|
||||
"original_text": "x", "new_text": "y", "confidence": 0.9,
|
||||
"consensus": 2, "total_models": 2, "conflict_group": None,
|
||||
}]
|
||||
result, jm, storage, ws = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
|
||||
assert result["outcome"] == "aborted"
|
||||
assert "stale_suggestions" in result["reason"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
ws.trigger_render_video_worker.assert_not_awaited()
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["outcome"] == "aborted"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duplicate_word_artifact_aborts_to_review() -> None:
|
||||
# P1 self-conflict: two overlapping suggestions both add the same token.
|
||||
suggestions = [
|
||||
{"id": "a", "op": "insert_after", "word_ids": ["w3"], "segment_ids": ["s0"],
|
||||
"original_text": "", "new_text": "extra", "confidence": 0.75,
|
||||
"consensus": 1, "total_models": 2, "conflict_group": None},
|
||||
{"id": "b", "op": "replace", "word_ids": ["w4"], "segment_ids": ["s0"],
|
||||
"original_text": "word4", "new_text": "extra word4", "confidence": 0.95,
|
||||
"consensus": 1, "total_models": 2, "conflict_group": None},
|
||||
]
|
||||
result, jm, storage, _ = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
|
||||
assert result["outcome"] == "aborted"
|
||||
assert "duplicate_words" in result["reason"]
|
||||
jm.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_change_during_enforce_aborts() -> None:
|
||||
# A human opening the editor between the snapshot read and the enforce
|
||||
# writes (AWAITING_REVIEW -> IN_REVIEW) must abort — IN_REVIEW ->
|
||||
# REVIEW_COMPLETE is a legal transition, so validation alone won't stop it.
|
||||
eligible = _job(backing=_clean_backing())
|
||||
editing = _job(status=JobStatus.IN_REVIEW, backing=_clean_backing())
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.side_effect = [eligible, editing]
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = True
|
||||
storage.list_files.return_value = []
|
||||
storage.download_json.return_value = _confident_corrections()
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.config.get_settings", return_value=_settings()):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
assert result["outcome"] == "aborted"
|
||||
assert result["reason"] == "state_changed_during_enforce"
|
||||
job_manager.transition_to_state.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_corrections_is_noop() -> None:
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = _job(backing=_clean_backing())
|
||||
storage = MagicMock()
|
||||
storage.file_exists.return_value = False
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.config.get_settings", return_value=_settings()):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
assert result["outcome"] == "no_corrections"
|
||||
job_manager.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_any_exception_is_nonfatal() -> None:
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.side_effect = Exception("firestore down")
|
||||
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.storage_service.StorageService", MagicMock()), \
|
||||
patch("backend.config.get_settings", return_value=_settings()):
|
||||
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
|
||||
assert result["outcome"] == "error"
|
||||
|
||||
|
||||
def _audible_backing() -> Dict[str, Any]:
|
||||
# Pink backing present, no 3-stem comparison -> scorer verdict REVIEW.
|
||||
return {
|
||||
"has_audible_content": True,
|
||||
"audible_percentage": 40.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -10.0}],
|
||||
"recommended_selection": "with_backing",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_backing_preference_clean_forces_clean_completion() -> None:
|
||||
# Backing is subjective (would normally gate), but the user chose "clean"
|
||||
# up-front -> auto-complete on lyrics alone with a clean instrumental.
|
||||
job = _job(backing=_audible_backing())
|
||||
job.backing_preference = "clean"
|
||||
result, jm, storage, ws = await _run(job)
|
||||
assert result["outcome"] == "auto_completed"
|
||||
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "clean")
|
||||
ws.trigger_render_video_worker.assert_awaited_once_with("j1")
|
||||
payload = jm.update_processing_metadata.call_args.args[2]
|
||||
assert payload["enforcement_basis"] == "lyrics_auto_backing_pref:clean"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_backing_preference_review_blocks_even_confident_clean() -> None:
|
||||
# User wants to always pick the instrumental -> never auto-skip the backing half.
|
||||
job = _job(backing=_clean_backing())
|
||||
job.backing_preference = "review"
|
||||
result, jm, _, ws = await _run(job)
|
||||
assert result["outcome"] == "review"
|
||||
jm.transition_to_state.assert_not_called()
|
||||
ws.trigger_render_video_worker.assert_not_awaited()
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Tests for the shared instrumental-decision helper (workstream C).
|
||||
|
||||
``backing_decision`` is the single source of truth used by the executor, the
|
||||
complete-review "auto" resolver, and the per-screen-skip UI summary — they must
|
||||
all agree, so the matrix is pinned here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.auto_approval.instrumental import (
|
||||
auto_approval_summary,
|
||||
backing_decision,
|
||||
has_custom_instrumental,
|
||||
resolve_auto_instrumental,
|
||||
)
|
||||
|
||||
|
||||
def _decide(**kw):
|
||||
base = dict(
|
||||
backing_verdict="clean",
|
||||
backing_non_subjective=True,
|
||||
backing_preference="auto",
|
||||
backing_keep_enabled=True,
|
||||
custom_instrumental=False,
|
||||
)
|
||||
base.update(kw)
|
||||
return backing_decision(**base)
|
||||
|
||||
|
||||
# ---- backing_decision matrix ------------------------------------------------
|
||||
|
||||
def test_custom_instrumental_always_custom():
|
||||
d = _decide(custom_instrumental=True, backing_verdict="review", backing_non_subjective=False)
|
||||
assert d == {"ok": True, "selection": "custom", "keep_backing": False}
|
||||
|
||||
|
||||
def test_clean_verdict_auto_resolves_clean():
|
||||
assert _decide(backing_verdict="clean")["selection"] == "clean"
|
||||
assert _decide(backing_verdict="clean")["ok"] is True
|
||||
|
||||
|
||||
def test_with_backing_verdict_keep_enabled_resolves_with_backing():
|
||||
d = _decide(backing_verdict="with_backing", backing_keep_enabled=True)
|
||||
assert d == {"ok": True, "selection": "with_backing", "keep_backing": True}
|
||||
|
||||
|
||||
def test_with_backing_verdict_keep_disabled_not_resolvable():
|
||||
d = _decide(backing_verdict="with_backing", backing_keep_enabled=False)
|
||||
assert d["ok"] is False and d["selection"] is None and d["keep_backing"] is True
|
||||
|
||||
|
||||
def test_review_verdict_not_resolvable():
|
||||
d = _decide(backing_verdict="review", backing_non_subjective=False)
|
||||
assert d["ok"] is False and d["selection"] is None
|
||||
|
||||
|
||||
def test_preference_clean_forces_clean_even_over_review_verdict():
|
||||
# User explicitly asked to strip backing vocals -> clean regardless of verdict.
|
||||
d = _decide(backing_verdict="review", backing_non_subjective=False, backing_preference="clean")
|
||||
assert d == {"ok": True, "selection": "clean", "keep_backing": False}
|
||||
|
||||
|
||||
def test_preference_clean_overrides_with_backing_verdict():
|
||||
d = _decide(backing_verdict="with_backing", backing_preference="clean")
|
||||
assert d["selection"] == "clean" and d["keep_backing"] is False
|
||||
|
||||
|
||||
def test_preference_review_suppresses_even_confident_clean():
|
||||
# User always wants to pick the instrumental themselves.
|
||||
d = _decide(backing_verdict="clean", backing_preference="review")
|
||||
assert d["ok"] is False and d["selection"] is None
|
||||
|
||||
|
||||
def test_unknown_preference_falls_back_to_auto():
|
||||
assert _decide(backing_verdict="clean", backing_preference="garbage")["selection"] == "clean"
|
||||
|
||||
|
||||
# ---- has_custom_instrumental ------------------------------------------------
|
||||
|
||||
def test_has_custom_instrumental_from_existing_path():
|
||||
job = SimpleNamespace(existing_instrumental_gcs_path="jobs/j/inst.flac", file_urls=None)
|
||||
assert has_custom_instrumental(job) is True
|
||||
|
||||
|
||||
def test_has_custom_instrumental_from_stem():
|
||||
job = SimpleNamespace(
|
||||
existing_instrumental_gcs_path=None,
|
||||
file_urls={"stems": {"custom_instrumental": "jobs/j/custom.flac"}},
|
||||
)
|
||||
assert has_custom_instrumental(job) is True
|
||||
|
||||
|
||||
def test_has_custom_instrumental_false():
|
||||
job = SimpleNamespace(
|
||||
existing_instrumental_gcs_path=None,
|
||||
file_urls={"stems": {"instrumental_clean": "jobs/j/clean.flac"}},
|
||||
)
|
||||
assert has_custom_instrumental(job) is False
|
||||
|
||||
|
||||
# ---- summary + resolver over stored verdict ---------------------------------
|
||||
|
||||
def _job_with_verdict(backing_verdict, non_subjective, lyrics_verdict="auto", pref="auto",
|
||||
custom=False, review_mode="auto", stems=None):
|
||||
if stems is None:
|
||||
stems = {
|
||||
"instrumental_clean": "jobs/j/clean.flac",
|
||||
"instrumental_with_backing": "jobs/j/backing.flac",
|
||||
}
|
||||
return SimpleNamespace(
|
||||
processing_metadata={
|
||||
"auto_approval": {
|
||||
"backing": {"verdict": backing_verdict, "non_subjective": non_subjective},
|
||||
"lyrics": {"verdict": lyrics_verdict},
|
||||
}
|
||||
},
|
||||
backing_preference=pref,
|
||||
review_mode=review_mode,
|
||||
existing_instrumental_gcs_path=("jobs/j/inst.flac" if custom else None),
|
||||
file_urls={"stems": stems},
|
||||
)
|
||||
|
||||
|
||||
def _settings(keep=True):
|
||||
return SimpleNamespace(auto_approval_backing_keep_enabled=keep)
|
||||
|
||||
|
||||
def test_summary_confident_clean():
|
||||
s = auto_approval_summary(_job_with_verdict("clean", True), _settings())
|
||||
assert s["backing"] == {"verdict": "clean", "confident": True, "resolved_selection": "clean"}
|
||||
assert s["lyrics"] == {"verdict": "auto", "confident": True}
|
||||
assert s["verdict_present"] is True
|
||||
|
||||
|
||||
def test_summary_backing_needs_review_not_confident():
|
||||
s = auto_approval_summary(_job_with_verdict("review", False), _settings())
|
||||
assert s["backing"]["confident"] is False
|
||||
assert s["backing"]["resolved_selection"] is None
|
||||
|
||||
|
||||
def test_summary_no_verdict_is_safe_default():
|
||||
job = SimpleNamespace(processing_metadata={}, backing_preference="auto",
|
||||
existing_instrumental_gcs_path=None, file_urls={"stems": {}})
|
||||
s = auto_approval_summary(job, _settings())
|
||||
assert s["verdict_present"] is False
|
||||
assert s["backing"]["confident"] is False
|
||||
assert s["lyrics"]["confident"] is False
|
||||
|
||||
|
||||
def test_resolve_auto_instrumental_with_backing_gated():
|
||||
# keep disabled -> not resolvable
|
||||
assert resolve_auto_instrumental(_job_with_verdict("with_backing", True), _settings(keep=False)) is None
|
||||
# keep enabled -> with_backing
|
||||
assert resolve_auto_instrumental(_job_with_verdict("with_backing", True), _settings(keep=True)) == "with_backing"
|
||||
|
||||
|
||||
def test_resolve_auto_instrumental_custom():
|
||||
assert resolve_auto_instrumental(_job_with_verdict("review", False, custom=True), _settings()) == "custom"
|
||||
|
||||
|
||||
def test_always_review_never_confident():
|
||||
# review_mode="always_review" -> the user wants every screen; nothing skips.
|
||||
s = auto_approval_summary(_job_with_verdict("clean", True, review_mode="always_review"), _settings())
|
||||
assert s["backing"]["confident"] is False
|
||||
assert s["backing"]["resolved_selection"] is None
|
||||
assert s["lyrics"]["confident"] is False
|
||||
assert resolve_auto_instrumental(
|
||||
_job_with_verdict("clean", True, review_mode="always_review"), _settings()) is None
|
||||
|
||||
|
||||
def test_resolve_returns_none_when_clean_stem_absent():
|
||||
# Confident clean verdict but the clean stem isn't present -> a human must pick.
|
||||
job = _job_with_verdict("clean", True, stems={"instrumental_with_backing": "x"})
|
||||
assert resolve_auto_instrumental(job, _settings()) is None
|
||||
assert auto_approval_summary(job, _settings())["backing"]["confident"] is False
|
||||
|
||||
|
||||
def test_resolve_returns_none_when_with_backing_stem_absent():
|
||||
job = _job_with_verdict("with_backing", True, stems={"instrumental_clean": "x"})
|
||||
assert resolve_auto_instrumental(job, _settings(keep=True)) is None
|
||||
|
||||
|
||||
# ---- JobCreate coercion (typo must never silently flip intent) ---------------
|
||||
|
||||
def test_jobcreate_coerces_out_of_set_preferences():
|
||||
from backend.models.job import JobCreate
|
||||
assert JobCreate(backing_preference="cleen").backing_preference == "auto"
|
||||
assert JobCreate(backing_preference="clean").backing_preference == "clean"
|
||||
# review_mode fails safe toward MORE review, never toward auto-skip.
|
||||
assert JobCreate(review_mode="typo").review_mode == "always_review"
|
||||
assert JobCreate(review_mode="auto").review_mode == "auto"
|
||||
assert JobCreate().backing_preference == "auto" and JobCreate().review_mode == "auto"
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Tests for the review-diff reconstruction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from backend.services.auto_approval.lyrics_diff import compute_lyrics_diff
|
||||
|
||||
|
||||
def _w(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end}
|
||||
|
||||
|
||||
def _seg(sid: str, words: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": sid,
|
||||
"text": " ".join(w["text"] for w in words),
|
||||
"words": words,
|
||||
"start_time": words[0]["start_time"] if words else 0.0,
|
||||
"end_time": words[-1]["end_time"] if words else 0.0,
|
||||
}
|
||||
|
||||
|
||||
def _doc(segments: List[Dict[str, Any]], corrections: List[Any] | None = None) -> Dict[str, Any]:
|
||||
return {"corrected_segments": segments, "corrections": corrections or []}
|
||||
|
||||
|
||||
def test_no_updated_data_means_no_changes() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "hello", 0.0, 0.5)])])
|
||||
diff = compute_lyrics_diff(orig, None)
|
||||
assert diff.has_changes is False
|
||||
assert diff.total_changes == 0
|
||||
assert diff.final_word_count == 1
|
||||
|
||||
|
||||
def test_text_edit_detected() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "helo", 0.0, 0.5), _w("w1", "wrld", 0.5, 1.0)])])
|
||||
final = _doc([_seg("s0", [_w("w0", "hello", 0.0, 0.5), _w("w1", "world", 0.5, 1.0)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert diff.total_changes == 2
|
||||
assert {e.final_text for e in diff.text_edits} == {"hello", "world"}
|
||||
assert not diff.timing_changes
|
||||
|
||||
|
||||
def test_replacement_paired_by_timing() -> None:
|
||||
# UI re-keys a corrected word but keeps its start/end/line -> should pair as replacement.
|
||||
orig = _doc([_seg("s0", [_w("wA", "Carl", 231.18, 231.80)])])
|
||||
final = _doc([_seg("s0", [_w("wB", "Karl", 231.18, 231.80)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert diff.total_changes == 1
|
||||
assert len(diff.replacements) == 1
|
||||
assert not diff.deletions and not diff.insertions
|
||||
r = diff.replacements[0]
|
||||
assert (r.original_text, r.final_text) == ("Carl", "Karl")
|
||||
assert r.original_word_id == "wA" and r.final_word_id == "wB"
|
||||
|
||||
|
||||
def test_replacement_not_paired_when_timing_differs() -> None:
|
||||
# Different timing -> genuine delete + insert, not a replacement.
|
||||
orig = _doc([_seg("s0", [_w("wA", "Carl", 231.18, 231.80)])])
|
||||
final = _doc([_seg("s0", [_w("wB", "Karl", 10.0, 10.5)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert not diff.replacements
|
||||
assert [d.text for d in diff.deletions] == ["Carl"]
|
||||
assert [i.text for i in diff.insertions] == ["Karl"]
|
||||
|
||||
|
||||
def test_timing_change_respects_epsilon() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "hey", 1.000, 1.500)])])
|
||||
# start moved 0.2s (significant), end moved 0.001s (noise, below epsilon)
|
||||
final = _doc([_seg("s0", [_w("w0", "hey", 1.200, 1.501)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert len(diff.timing_changes) == 1
|
||||
tc = diff.timing_changes[0]
|
||||
assert tc.start_delta == 0.2
|
||||
assert not diff.text_edits
|
||||
|
||||
|
||||
def test_deletion_and_insertion() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "one", 0.0, 0.5), _w("w1", "two", 0.5, 1.0)])])
|
||||
final = _doc([_seg("s0", [_w("w0", "one", 0.0, 0.5), _w("w2", "three", 1.0, 1.5)])])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert [d.text for d in diff.deletions] == ["two"]
|
||||
assert [i.text for i in diff.insertions] == ["three"]
|
||||
assert diff.total_changes == 2
|
||||
|
||||
|
||||
def test_split_detected_as_segmentation_change() -> None:
|
||||
orig = _doc([_seg("s0", [_w("w0", "a", 0.0, 0.5), _w("w1", "b", 0.5, 1.0)])])
|
||||
# Same words, now on two lines -> segment move for w1 + segment count change.
|
||||
final = _doc([
|
||||
_seg("s0", [_w("w0", "a", 0.0, 0.5)]),
|
||||
_seg("s1", [_w("w1", "b", 0.5, 1.0)]),
|
||||
])
|
||||
diff = compute_lyrics_diff(orig, final)
|
||||
assert diff.segmentation_changed is True
|
||||
assert len(diff.segment_moves) == 1
|
||||
assert diff.segment_moves[0].word_id == "w1"
|
||||
assert diff.original_segment_count == 1
|
||||
assert diff.final_segment_count == 2
|
||||
|
||||
|
||||
def test_clean_unedited_job_yields_empty_diff() -> None:
|
||||
seg = [_seg("s0", [_w("w0", "same", 0.0, 0.5)])]
|
||||
diff = compute_lyrics_diff(_doc(seg), _doc(seg))
|
||||
assert diff.has_changes is False
|
||||
assert diff.total_changes == 0
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Tests for the server-side pre-apply (workstream C, C2).
|
||||
|
||||
``ensure_and_pre_apply`` applies the cached AI suggestions BEFORE the review-ready
|
||||
notification and writes ``corrections_updated.json`` with a ``pre_applied`` marker.
|
||||
It is best-effort: any miss leaves corrections_updated absent so the review UI falls
|
||||
back to its client-side on-load auto-apply.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
|
||||
|
||||
|
||||
def _corrections() -> Dict[str, Any]:
|
||||
words = [
|
||||
{"id": f"w{i}", "text": t, "start_time": i * 0.5, "end_time": i * 0.5 + 0.4}
|
||||
for i, t in enumerate(["an", "amateur", "here"])
|
||||
]
|
||||
return {
|
||||
"corrected_segments": [{
|
||||
"id": "s0",
|
||||
"text": "an amateur here",
|
||||
"words": words,
|
||||
"start_time": 0.0,
|
||||
"end_time": 2.0,
|
||||
}],
|
||||
"reference_lyrics": {"spotify": {"segments": []}},
|
||||
"metadata": {"total_words": 3},
|
||||
}
|
||||
|
||||
|
||||
def _replace_suggestion() -> Dict[str, Any]:
|
||||
# Replace "an amateur" -> "not much" (op=replace on the first two words).
|
||||
return {
|
||||
"id": "sug1",
|
||||
"op": "replace",
|
||||
"segment_ids": ["s0"],
|
||||
"word_ids": ["w0", "w1"],
|
||||
"original_text": "an amateur",
|
||||
"new_text": "not much",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.95,
|
||||
"models": ["m1"],
|
||||
"consensus": 1,
|
||||
"total_models": 1,
|
||||
}
|
||||
|
||||
|
||||
class _FakeStorage:
|
||||
def __init__(self, files: Dict[str, Any]):
|
||||
self._files = dict(files)
|
||||
self.uploads: Dict[str, Any] = {}
|
||||
|
||||
def file_exists(self, path: str) -> bool:
|
||||
return path in self._files
|
||||
|
||||
def download_json(self, path: str):
|
||||
return self._files[path]
|
||||
|
||||
def list_files(self, prefix: str) -> List[str]:
|
||||
return [p for p in self._files if p.startswith(prefix)]
|
||||
|
||||
def upload_json(self, path: str, data: Any, if_generation_match=None):
|
||||
# Model create-only semantics: if_generation_match=0 fails when the object
|
||||
# already exists (mirrors GCS raising PreconditionFailed).
|
||||
if if_generation_match == 0 and path in self._files:
|
||||
from google.api_core.exceptions import PreconditionFailed
|
||||
raise PreconditionFailed("object exists")
|
||||
self.uploads[path] = data
|
||||
self._files[path] = data
|
||||
|
||||
|
||||
async def _run(storage, *, proactive=True, generate_on_miss=True):
|
||||
settings = MagicMock(auto_correct_proactive_enabled=proactive)
|
||||
jm = MagicMock()
|
||||
generated = {"called": False}
|
||||
|
||||
async def _fake_generate(job_id):
|
||||
generated["called"] = True
|
||||
return {"status": "generated"}
|
||||
|
||||
with patch("backend.config.get_settings", return_value=settings), \
|
||||
patch("backend.services.storage_service.StorageService", return_value=storage), \
|
||||
patch("backend.services.job_manager.JobManager", return_value=jm), \
|
||||
patch("backend.workers.auto_correct_worker.process_proactive_auto_correct", _fake_generate):
|
||||
result = await ensure_and_pre_apply("j1", generate_on_miss=generate_on_miss)
|
||||
return result, jm, generated
|
||||
|
||||
|
||||
CORR = "jobs/j1/lyrics/corrections.json"
|
||||
UPD = "jobs/j1/lyrics/corrections_updated.json"
|
||||
CACHE = "jobs/j1/lyrics/auto_correct_cache/x.json"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_writes_marker_and_applies():
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
})
|
||||
result, jm, _gen = await _run(storage)
|
||||
assert result["outcome"] == "pre_applied"
|
||||
assert result["applied"] == 1
|
||||
written = storage.uploads[UPD]
|
||||
aa = written["metadata"]["auto_approval"]
|
||||
assert aa["pre_applied"] is True
|
||||
assert aa["applied_suggestion_ids"] == ["sug1"]
|
||||
assert aa["suggestions"] # carried for the UI panel
|
||||
# The correction was actually applied to the segments.
|
||||
assert "not much" in written["corrected_segments"][0]["text"]
|
||||
jm.update_file_url.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_empty_suggestions_still_marks():
|
||||
# Known-empty cache: mark pre_applied so the UI doesn't run client-side.
|
||||
storage = _FakeStorage({CORR: _corrections(), CACHE: {"suggestions": []}})
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "pre_applied"
|
||||
assert result["applied"] == 0
|
||||
assert storage.uploads[UPD]["metadata"]["auto_approval"]["pre_applied"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_no_cache_and_proactive_disabled_is_noop():
|
||||
# No cache + proactive off -> unknown suggestion set -> do NOT mark (fall back).
|
||||
storage = _FakeStorage({CORR: _corrections()})
|
||||
result, _, _gen = await _run(storage, proactive=False)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "no_suggestions_cache"
|
||||
assert UPD not in storage.uploads
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_skips_when_already_applied():
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
UPD: {"metadata": {"auto_approval": {"auto_approved": True}}},
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
})
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "already_applied"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_no_corrections_is_noop():
|
||||
storage = _FakeStorage({})
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "no_corrections"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_path_applies_existing_cache_without_generating():
|
||||
# generate_on_miss=False (the /correction-data load path): an existing cache is
|
||||
# applied, but generation is never triggered (page must not block on an LLM call).
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
})
|
||||
result, jm, gen = await _run(storage, generate_on_miss=False)
|
||||
assert result["outcome"] == "pre_applied"
|
||||
assert gen["called"] is False
|
||||
assert storage.uploads[UPD]["metadata"]["auto_approval"]["pre_applied"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_path_cache_miss_does_not_generate_or_mark():
|
||||
# No cache + proactive ON but generate_on_miss=False -> no generation, no marker;
|
||||
# the UI falls back to its client-side apply (no page hang).
|
||||
storage = _FakeStorage({CORR: _corrections()})
|
||||
result, _, gen = await _run(storage, proactive=True, generate_on_miss=False)
|
||||
assert gen["called"] is False
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "no_suggestions_cache"
|
||||
assert UPD not in storage.uploads
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_screens_path_generates_on_cache_miss():
|
||||
# Default generate_on_miss=True (screens_worker path): generation IS triggered
|
||||
# on a cache miss.
|
||||
storage = _FakeStorage({CORR: _corrections()})
|
||||
result, _, gen = await _run(storage, proactive=True, generate_on_miss=True)
|
||||
assert gen["called"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pre_apply_raced_concurrent_write_does_not_clobber():
|
||||
# A concurrent writer created corrections_updated.json AFTER our existence check
|
||||
# (invisible to the check, present for the create-only upload) -> theirs wins.
|
||||
storage = _FakeStorage({
|
||||
CORR: _corrections(),
|
||||
CACHE: {"suggestions": [_replace_suggestion()]},
|
||||
UPD: {"metadata": {}, "corrected_segments": [{"id": "s0", "words": [{"id": "x"}]}]},
|
||||
})
|
||||
orig_exists = storage.file_exists
|
||||
storage.file_exists = lambda p: False if p == UPD else orig_exists(p)
|
||||
result, _, _gen = await _run(storage)
|
||||
assert result["outcome"] == "skipped"
|
||||
assert result["reason"] == "raced_concurrent_write"
|
||||
# The concurrent writer's content is untouched.
|
||||
assert storage._files[UPD]["metadata"] == {}
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Tests for the auto-approvability scorer.
|
||||
|
||||
These fixtures mirror the shape of a production ``corrections.json`` built by the
|
||||
uncorrected controller path (auto-correction disabled): ``corrections_made == 0``,
|
||||
``confidence == 1.0``, but anchors/gaps/reference_lyrics still populated.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from backend.services.auto_approval.models import BackingVerdict, LyricsVerdict
|
||||
from backend.services.auto_approval.scorer import (
|
||||
score_backing,
|
||||
score_job,
|
||||
score_lyrics,
|
||||
)
|
||||
|
||||
|
||||
def _word(wid: str, text: str) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": 0.0, "end_time": 0.5}
|
||||
|
||||
|
||||
def _segments(n_words: int) -> List[Dict[str, Any]]:
|
||||
words = [_word(f"w{i}", f"word{i}") for i in range(n_words)]
|
||||
return [{"id": "s0", "text": " ".join(w["text"] for w in words),
|
||||
"words": words, "start_time": 0.0, "end_time": 10.0}]
|
||||
|
||||
|
||||
def _corrections_json(
|
||||
n_words: int = 20,
|
||||
anchor_words: int = 20,
|
||||
gap_words: int = 0,
|
||||
synced: bool = True,
|
||||
sources: List[str] | None = None,
|
||||
) -> Dict[str, Any]:
|
||||
sources = sources if sources is not None else ["spotify", "genius"]
|
||||
anchor_seq = [{"id": "a0", "transcribed_word_ids": [f"w{i}" for i in range(anchor_words)]}]
|
||||
gap_seq = (
|
||||
[{"id": "g0", "transcribed_word_ids": [f"w{i}" for i in range(anchor_words, anchor_words + gap_words)]}]
|
||||
if gap_words
|
||||
else []
|
||||
)
|
||||
reference_lyrics = {
|
||||
src: {"metadata": {"is_synced": synced}, "segments": [], "source": src}
|
||||
for src in sources
|
||||
}
|
||||
return {
|
||||
"corrected_segments": _segments(n_words),
|
||||
"corrections": [],
|
||||
"corrections_made": 0,
|
||||
"confidence": 1.0, # the trap — must not drive AUTO
|
||||
"reference_lyrics": reference_lyrics,
|
||||
"anchor_sequences": anchor_seq,
|
||||
"gap_sequences": gap_seq,
|
||||
"metadata": {
|
||||
"correction_type": "none",
|
||||
"reason": "correction_disabled",
|
||||
"agentic_routing": "disabled",
|
||||
"total_words": n_words,
|
||||
"anchor_sequences_count": len(anchor_seq),
|
||||
"gap_sequences_count": len(gap_seq),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# --- Lyrics ---
|
||||
|
||||
def test_synced_perfect_is_auto() -> None:
|
||||
res = score_lyrics(_corrections_json(anchor_words=20, gap_words=0, synced=True))
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
assert res.tier == "synced-perfect"
|
||||
assert res.signals.anchor_word_fraction == 1.0
|
||||
assert res.signals.uncorrected_gap_fraction == 0.0
|
||||
|
||||
|
||||
def test_confidence_one_alone_does_not_trigger_auto() -> None:
|
||||
# No reference sources at all -> confidence 1.0 must NOT yield AUTO.
|
||||
data = _corrections_json(sources=[], anchor_words=0, gap_words=0)
|
||||
data["anchor_sequences"] = []
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "no-reference"
|
||||
|
||||
|
||||
def test_unsynced_reference_never_auto() -> None:
|
||||
res = score_lyrics(_corrections_json(anchor_words=20, gap_words=0, synced=False))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "near-miss"
|
||||
assert not res.signals.has_synced_reference
|
||||
|
||||
|
||||
def test_gaps_push_to_review() -> None:
|
||||
# 16 anchored / 4 gap of 20 -> 80% anchor, 20% gap -> needs-review.
|
||||
res = score_lyrics(_corrections_json(n_words=20, anchor_words=16, gap_words=4, synced=True))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "needs-review"
|
||||
|
||||
|
||||
def test_single_gap_word_blocks_auto() -> None:
|
||||
# Regression for job 79c4f60c "Clarity": 241/242 anchored (99.6%), one gap word that
|
||||
# was a real mis-transcription. A single unresolved gap must NOT be auto-approved.
|
||||
data = _corrections_json(n_words=242, anchor_words=241, gap_words=1, synced=True)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.signals.gap_word_count == 1
|
||||
|
||||
|
||||
def test_near_miss_band() -> None:
|
||||
# 19 anchored / 1 gap of 20 -> 95% anchor, 5% gap: within near-miss, below AUTO.
|
||||
res = score_lyrics(_corrections_json(n_words=20, anchor_words=19, gap_words=1, synced=True))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "near-miss"
|
||||
|
||||
|
||||
def test_too_few_words() -> None:
|
||||
res = score_lyrics(_corrections_json(n_words=5, anchor_words=5, gap_words=0))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "too-few-words"
|
||||
|
||||
|
||||
# --- AI-resolved tier (gap words covered by auto-applied suggestions) ---
|
||||
|
||||
def _suggestions_for_gaps(data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
gap_ids = [wid for seq in data["gap_sequences"] for wid in seq["transcribed_word_ids"]]
|
||||
return [
|
||||
{"id": f"sug{i}", "op": "replace", "word_ids": [wid], "segment_ids": ["s0"],
|
||||
"original_text": "x", "new_text": "y", "confidence": 0.9,
|
||||
"consensus": 2, "total_models": 2}
|
||||
for i, wid in enumerate(gap_ids)
|
||||
]
|
||||
|
||||
|
||||
def test_ai_covered_gaps_are_auto_resolved() -> None:
|
||||
# 95% anchored with 5 gap words, every gap covered by an auto-applied AI
|
||||
# suggestion -> the post-AI state is clean -> AUTO (ai-resolved tier).
|
||||
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
|
||||
res = score_lyrics(data, _suggestions_for_gaps(data))
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
assert res.tier == "ai-resolved"
|
||||
assert res.signals.gap_words_covered_by_ai == 5
|
||||
assert res.signals.uncovered_gap_word_count == 0
|
||||
assert res.signals.ai_full_consensus_count == 5
|
||||
|
||||
|
||||
def test_uncovered_gaps_beyond_threshold_stay_review() -> None:
|
||||
# 10 gaps, none covered -> 10% uncovered -> review.
|
||||
data = _corrections_json(n_words=100, anchor_words=90, gap_words=10, synced=True)
|
||||
res = score_lyrics(data, [])
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.signals.uncovered_gap_word_count == 10
|
||||
|
||||
|
||||
def test_no_suggestion_data_never_ai_resolved() -> None:
|
||||
# Without the suggestion cache we can't know what the AI will fix -> the
|
||||
# ai-resolved tier must not apply (only the strict zero-gap tier can).
|
||||
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
|
||||
res = score_lyrics(data, None)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert not res.signals.ai_suggestions_available
|
||||
|
||||
|
||||
def test_gates_override_ai_resolution() -> None:
|
||||
# Even with every gap covered, a vocalization section still gates to human.
|
||||
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
|
||||
voc = [_timed_word(f"v{i}", t, 10.0 + i * 0.4, 10.3 + i * 0.4)
|
||||
for i, t in enumerate(["Da-", "da-", "dun,", "da-", "da-", "dun"])]
|
||||
data = _with_extra_segment(data, voc, 10.0, 12.5)
|
||||
res = score_lyrics(data, _suggestions_for_gaps(data))
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "vocalization-gate"
|
||||
|
||||
|
||||
def test_low_anchor_never_ai_resolved() -> None:
|
||||
# Heavy correction of a messy transcription (corpus f247364e: 47.6% anchor,
|
||||
# nearly all gaps covered) still means likely uncaught errors -> review.
|
||||
data = _corrections_json(n_words=100, anchor_words=48, gap_words=52, synced=True)
|
||||
sugs = _suggestions_for_gaps(data)[:50] # 50 of 52 covered
|
||||
res = score_lyrics(data, sugs)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
|
||||
|
||||
# --- Never-auto gating classes (Pattern 3 vocalizations, Pattern 8 phantoms) ---
|
||||
|
||||
def _timed_word(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
|
||||
return {"id": wid, "text": text, "start_time": start, "end_time": end}
|
||||
|
||||
|
||||
def _with_extra_segment(data: Dict[str, Any], words: List[Dict[str, Any]],
|
||||
seg_start: float, seg_end: float,
|
||||
anchored: bool = True) -> Dict[str, Any]:
|
||||
"""Append a segment and (optionally) anchor its words so gates are the only blocker."""
|
||||
data["corrected_segments"].append({
|
||||
"id": f"s{len(data['corrected_segments'])}",
|
||||
"text": " ".join(w["text"] for w in words),
|
||||
"words": words,
|
||||
"start_time": seg_start,
|
||||
"end_time": seg_end,
|
||||
})
|
||||
if anchored:
|
||||
data["anchor_sequences"][0]["transcribed_word_ids"].extend(w["id"] for w in words)
|
||||
data["metadata"]["total_words"] += len(words)
|
||||
return data
|
||||
|
||||
|
||||
def test_vocalization_run_gates_even_when_otherwise_perfect() -> None:
|
||||
# b5a7b8aa "Two Birds": lines of "Da- da- dun, da- da- dun" — anchored or not,
|
||||
# the grouping/timing is a musical judgement -> never fully auto.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
voc = [_timed_word(f"v{i}", t, 10.0 + i * 0.4, 10.3 + i * 0.4)
|
||||
for i, t in enumerate(["Da-", "da-", "dun,", "da-", "da-", "dun"])]
|
||||
data = _with_extra_segment(data, voc, 10.0, 12.5)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "vocalization-gate"
|
||||
assert res.signals.has_vocalization_section
|
||||
assert res.signals.vocalization_max_run == 6
|
||||
|
||||
|
||||
def test_single_very_long_vocalization_gates() -> None:
|
||||
# 8f2305ee seg 35: a single "Ooh," spanning 10.1s = many vocalizations lumped into one.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(data, [_timed_word("v0", "Ooh,", 100.0, 110.1)], 100.0, 110.1)
|
||||
res = score_lyrics(data)
|
||||
assert res.tier == "vocalization-gate"
|
||||
assert res.signals.long_vocalization_word_count == 1
|
||||
|
||||
|
||||
def test_two_multi_second_vocalizations_gate() -> None:
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data,
|
||||
[_timed_word("v0", "Ooh,", 100.0, 104.0), _timed_word("v1", "ooh", 105.0, 109.1)],
|
||||
100.0, 109.1,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.tier == "vocalization-gate"
|
||||
|
||||
|
||||
def test_few_normal_vocalization_words_do_not_gate() -> None:
|
||||
# A couple of short "oh yeah"s in a normal song must not trip the gate.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data,
|
||||
[_timed_word("v0", "Oh,", 50.0, 50.4), _timed_word("v1", "yeah", 50.4, 50.9)],
|
||||
50.0, 50.9,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
assert not res.signals.has_vocalization_section
|
||||
|
||||
|
||||
def test_absurd_word_duration_is_phantom_gate() -> None:
|
||||
# 33453fa0 "Angel": phantom "(I'm sorry)" line with a 7.4s word.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data, [_timed_word("p0", "sorry", 0.0, 7.4)], 0.0, 7.4,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.REVIEW
|
||||
assert res.tier == "phantom-gate"
|
||||
assert res.signals.absurd_duration_word_count == 1
|
||||
assert res.signals.max_word_duration_s == 7.4
|
||||
|
||||
|
||||
def test_stretched_short_parenthetical_is_phantom_gate() -> None:
|
||||
# Short parenthetical line spanning several seconds, individual words normal-length.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data,
|
||||
[_timed_word("p0", "(I'm", 0.0, 0.4), _timed_word("p1", "sorry)", 4.4, 4.8)],
|
||||
0.0, 4.8,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.tier == "phantom-gate"
|
||||
assert res.signals.suspicious_parenthetical_count == 1
|
||||
|
||||
|
||||
def test_normal_parenthetical_backing_bit_does_not_gate() -> None:
|
||||
# Pattern 7 trailing "(Dreaming)" bits are left alone — a short parenthetical with
|
||||
# a normal duration must not be treated as a phantom.
|
||||
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
|
||||
data = _with_extra_segment(
|
||||
data, [_timed_word("p0", "(Dreaming)", 60.0, 61.2)], 60.0, 61.2,
|
||||
)
|
||||
res = score_lyrics(data)
|
||||
assert res.verdict == LyricsVerdict.AUTO
|
||||
|
||||
|
||||
def test_verdict_to_dict_is_json_safe() -> None:
|
||||
import json
|
||||
|
||||
v = score_job(
|
||||
_corrections_json(anchor_words=20, gap_words=0, synced=True),
|
||||
{"has_audible_content": False, "audible_percentage": 0.0, "audible_segments": []},
|
||||
)
|
||||
d = v.to_dict()
|
||||
json.dumps(d) # must not raise (enums converted to plain strings)
|
||||
assert d["lyrics"]["verdict"] == "auto"
|
||||
assert d["backing"]["verdict"] == "clean"
|
||||
|
||||
|
||||
# --- Backing ---
|
||||
|
||||
def test_no_audible_backing_is_non_subjective_clean() -> None:
|
||||
res = score_backing({"has_audible_content": False, "audible_percentage": 0.0,
|
||||
"audible_segments": [], "recommended_selection": "clean"})
|
||||
assert res.verdict == BackingVerdict.CLEAN
|
||||
assert res.non_subjective is True
|
||||
|
||||
|
||||
def test_near_silent_backing_is_clean() -> None:
|
||||
res = score_backing({"has_audible_content": True, "audible_percentage": 0.3,
|
||||
"audible_segments": [{"avg_amplitude_db": -35.0}],
|
||||
"recommended_selection": "clean"})
|
||||
assert res.verdict == BackingVerdict.CLEAN
|
||||
assert res.non_subjective is True
|
||||
|
||||
|
||||
def test_audible_backing_is_subjective_review() -> None:
|
||||
res = score_backing({"has_audible_content": True, "audible_percentage": 42.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -12.0, "peak_amplitude_db": -6.0}],
|
||||
"recommended_selection": "with_backing"})
|
||||
assert res.verdict == BackingVerdict.REVIEW
|
||||
assert res.non_subjective is False
|
||||
assert res.signals.loud_segment_count == 1
|
||||
|
||||
|
||||
def test_missing_backing_analysis_is_review() -> None:
|
||||
res = score_backing(None)
|
||||
assert res.verdict == BackingVerdict.REVIEW
|
||||
assert res.non_subjective is False
|
||||
|
||||
|
||||
def test_errored_backing_analysis_is_review_not_clean() -> None:
|
||||
# A failed analysis stores has_audible_content=None + analysis_error; it
|
||||
# must NOT read as "no audible content" (that would wrongly auto-pick clean).
|
||||
res = score_backing({
|
||||
"has_audible_content": None,
|
||||
"analysis_error": "download failed",
|
||||
"recommended_selection": "clean",
|
||||
})
|
||||
assert res.verdict == BackingVerdict.REVIEW
|
||||
assert res.non_subjective is False
|
||||
assert res.signals.analysis_present is False
|
||||
|
||||
|
||||
# --- Combined ---
|
||||
|
||||
def test_overall_auto_requires_both() -> None:
|
||||
v = score_job(
|
||||
_corrections_json(anchor_words=20, gap_words=0, synced=True),
|
||||
{"has_audible_content": False, "audible_percentage": 0.0, "audible_segments": []},
|
||||
)
|
||||
assert v.overall_auto is True
|
||||
|
||||
|
||||
def test_overall_not_auto_when_backing_subjective() -> None:
|
||||
v = score_job(
|
||||
_corrections_json(anchor_words=20, gap_words=0, synced=True),
|
||||
{"has_audible_content": True, "audible_percentage": 30.0,
|
||||
"audible_segments": [{"avg_amplitude_db": -10.0}]},
|
||||
)
|
||||
assert v.lyrics.verdict == LyricsVerdict.AUTO
|
||||
assert v.overall_auto is False
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Tests for the pure 3-stem comparison signal extraction.
|
||||
|
||||
Synthesizes tiny WAVs with pydub so the signal math is exercised on real
|
||||
audio decoding, not mocks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from pydub import AudioSegment
|
||||
from pydub.generators import Sine, WhiteNoise
|
||||
|
||||
from karaoke_gen.instrumental_review.stem_comparison import (
|
||||
StemComparison,
|
||||
compare_stems,
|
||||
)
|
||||
|
||||
|
||||
def _silence(ms: int = 4000) -> AudioSegment:
|
||||
return AudioSegment.silent(duration=ms, frame_rate=16000)
|
||||
|
||||
|
||||
def _tone_bursts(ms: int = 4000, *, burst_ms: int = 500, gain_db: float = -10.0) -> AudioSegment:
|
||||
"""Alternating 500ms tone / 500ms silence."""
|
||||
out = AudioSegment.silent(duration=0, frame_rate=16000)
|
||||
tone = Sine(440, sample_rate=16000).to_audio_segment(duration=burst_ms).apply_gain(gain_db)
|
||||
quiet = AudioSegment.silent(duration=burst_ms, frame_rate=16000)
|
||||
while len(out) < ms:
|
||||
out += tone + quiet
|
||||
return out[:ms]
|
||||
|
||||
|
||||
def _write(tmp_path, name: str, audio: AudioSegment) -> str:
|
||||
path = os.path.join(tmp_path, name)
|
||||
audio.export(path, format="wav")
|
||||
return path
|
||||
|
||||
|
||||
def test_silent_backing_has_zero_fractions(tmp_path) -> None:
|
||||
backing = _write(tmp_path, "b.wav", _silence())
|
||||
lead = _write(tmp_path, "l.wav", _tone_bursts())
|
||||
vocals = _write(tmp_path, "v.wav", _tone_bursts())
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.backing_audible_fraction == 0.0
|
||||
assert c.coverage_ratio == 0.0
|
||||
assert c.lead_overlap_fraction == 0.0
|
||||
assert c.lead_audible_fraction > 0.3
|
||||
|
||||
|
||||
def test_backing_identical_to_vocals_is_high_corr_full_coverage(tmp_path) -> None:
|
||||
# The backing-stem-is-the-lead shape: backing tracks the whole vocal line
|
||||
# while the lead stem is empty.
|
||||
bursts = _tone_bursts()
|
||||
backing = _write(tmp_path, "b.wav", bursts)
|
||||
lead = _write(tmp_path, "l.wav", _silence())
|
||||
vocals = _write(tmp_path, "v.wav", bursts)
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.coverage_ratio == 1.0
|
||||
assert c.corr_backing_vocals > 0.95
|
||||
assert c.backing_audible_fraction > c.lead_audible_fraction
|
||||
assert c.lead_overlap_fraction == 0.0
|
||||
|
||||
|
||||
def test_offset_backing_has_low_overlap_and_corr(tmp_path) -> None:
|
||||
# Backing sings only in the lead's gaps (genuine call-and-response shape).
|
||||
bursts = _tone_bursts()
|
||||
offset = _silence(500) + bursts
|
||||
backing = _write(tmp_path, "b.wav", offset[: len(bursts)])
|
||||
lead = _write(tmp_path, "l.wav", bursts)
|
||||
vocals = _write(tmp_path, "v.wav", bursts)
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.corr_backing_vocals < 0.0 # anti-phase with the vocal line
|
||||
assert c.lead_overlap_fraction < 0.2
|
||||
|
||||
|
||||
def test_continuous_noise_floor_is_flat(tmp_path) -> None:
|
||||
noise = WhiteNoise(sample_rate=16000).to_audio_segment(duration=8000).apply_gain(-25.0)
|
||||
backing = _write(tmp_path, "b.wav", noise)
|
||||
lead = _write(tmp_path, "l.wav", _tone_bursts(8000))
|
||||
vocals = _write(tmp_path, "v.wav", _tone_bursts(8000))
|
||||
c = compare_stems(backing, lead, vocals)
|
||||
assert c.error is None
|
||||
assert c.backing_audible_fraction == 1.0
|
||||
assert c.flat_fraction > 0.9 # sustained low-variance content
|
||||
assert c.backing_db_std < 2.5
|
||||
|
||||
|
||||
def test_missing_file_reports_error_not_raise(tmp_path) -> None:
|
||||
lead = _write(tmp_path, "l.wav", _silence(500))
|
||||
c = compare_stems(os.path.join(tmp_path, "nope.wav"), lead, lead)
|
||||
assert isinstance(c, StemComparison)
|
||||
assert c.error is not None
|
||||
|
||||
|
||||
def test_to_dict_round_trips_json_safe(tmp_path) -> None:
|
||||
import json
|
||||
|
||||
p = _write(tmp_path, "a.wav", _tone_bursts(1000))
|
||||
c = compare_stems(p, p, p)
|
||||
payload = c.to_dict()
|
||||
assert json.loads(json.dumps(payload)) == payload
|
||||
@@ -0,0 +1,481 @@
|
||||
"""Tests for the deterministic (no-LLM) suggestion generators + P1 conflict grouping.
|
||||
|
||||
Scenarios mirror the 2026-08 replay-review corpus jobs that motivated each
|
||||
pattern: P4 leading-connective over-insertion (8f2305ee "And they" -> "They"),
|
||||
P5 reference-majority resolution (6d0640fa "yo Mick," -> "Come here,"), and the
|
||||
P1 AI self-conflict (f6439692 insert+replace both adding "you're").
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.services.auto_correct.deterministic import (
|
||||
deterministic_suggestions,
|
||||
leading_connective_suggestions,
|
||||
reference_majority_suggestions,
|
||||
_ref_word_streams,
|
||||
)
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
Suggestion,
|
||||
_assign_conflict_groups,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
|
||||
def _ref_source(word_texts, prefix):
|
||||
"""A reference source with ids <prefix>0, <prefix>1, ..."""
|
||||
return {
|
||||
"segments": [
|
||||
{
|
||||
"text": " ".join(word_texts),
|
||||
"words": [
|
||||
{"id": f"{prefix}{i}", "text": t} for i, t in enumerate(word_texts)
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _seg(seg_id, words):
|
||||
return {
|
||||
"id": seg_id,
|
||||
"text": " ".join(t for _, t in words),
|
||||
"words": [{"id": wid, "text": t} for wid, t in words],
|
||||
}
|
||||
|
||||
|
||||
# ---- Pattern 4: leading connective ----
|
||||
|
||||
|
||||
def _p4_fixture(ref_line="They count everything", gap_ref_ids=None):
|
||||
"""Segment "And they count ..." where "And" is a gap word.
|
||||
|
||||
The single reference reads "They count everything" — no "And" — with the
|
||||
gap aligned to reference word r0 ("They") unless overridden.
|
||||
"""
|
||||
segments = [
|
||||
_seg("seg-0", [("w0", "And"), ("w1", "they"), ("w2", "count"), ("w3", "everything")])
|
||||
]
|
||||
refs = {"genius": _ref_source(ref_line.split(), "r")}
|
||||
correction_data = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w0"],
|
||||
"reference_word_ids": {"genius": gap_ref_ids if gap_ref_ids is not None else ["r0"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
return segments, refs, correction_data
|
||||
|
||||
|
||||
def test_p4_deletes_unsupported_leading_connective_and_recapitalizes() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert [s["op"] for s in out] == ["delete", "replace"]
|
||||
delete, recap = out
|
||||
assert delete["word_ids"] == ["w0"]
|
||||
assert delete["new_text"] == ""
|
||||
assert recap["word_ids"] == ["w1"]
|
||||
assert recap["new_text"] == "They"
|
||||
assert all(s["models"] == ["deterministic"] for s in out)
|
||||
|
||||
|
||||
def test_p4_skips_when_a_reference_supports_the_connective() -> None:
|
||||
segments, refs, cd = _p4_fixture(ref_line="And they count everything")
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert out == []
|
||||
|
||||
|
||||
def test_p4_skips_when_no_reference_evidence() -> None:
|
||||
# Gap aligned to nothing and no usable anchors -> no reading -> no delete.
|
||||
segments, refs, cd = _p4_fixture(gap_ref_ids=[])
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert out == []
|
||||
|
||||
|
||||
def test_p4_skips_anchored_leading_connective() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
cd["gap_sequences"] = [] # "And" is not a gap word
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p4_skips_vocalization_run() -> None:
|
||||
# "Oh- whoa whoa whoa" — grouping vocalizations is a musical judgement.
|
||||
segments = [
|
||||
_seg("seg-0", [("w0", "Oh-"), ("w1", "whoa,"), ("w2", "whoa,"), ("w3", "whoa")])
|
||||
]
|
||||
refs = {"genius": _ref_source(["Whoa,", "whoa,", "whoa"], "r")}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w0"],
|
||||
"reference_word_ids": {"genius": ["r0"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p4_skips_two_word_segment() -> None:
|
||||
segments = [_seg("seg-0", [("w0", "And"), ("w1", "run")])]
|
||||
refs = {"genius": _ref_source(["Run"], "r")}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{"id": "g", "transcribed_word_ids": ["w0"], "reference_word_ids": {"genius": ["r0"]}}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p4_already_capitalized_next_word_gets_no_recap_suggestion() -> None:
|
||||
segments = [
|
||||
_seg("seg-0", [("w0", "And"), ("w1", "Mary"), ("w2", "sings"), ("w3", "loud")])
|
||||
]
|
||||
refs = {"genius": _ref_source(["Mary", "sings", "loud"], "r")}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{"id": "g", "transcribed_word_ids": ["w0"], "reference_word_ids": {"genius": ["r0"]}}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert [s["op"] for s in out] == ["delete"]
|
||||
|
||||
|
||||
# ---- Pattern 5: reference majority ----
|
||||
|
||||
|
||||
def _p5_fixture():
|
||||
"""The 6d0640fa shape: transcription "yo Mick," where genius aligned
|
||||
"My man," on the gap, and lrclib/spotify (unaligned on the gap) read
|
||||
"Come here," after the preceding anchor."""
|
||||
segments = [
|
||||
_seg(
|
||||
"seg-0",
|
||||
[
|
||||
("w0", "Hit"),
|
||||
("w1", "the"),
|
||||
("w2", "button,"),
|
||||
("w3", "yo"),
|
||||
("w4", "Mick,"),
|
||||
("w5", "come"),
|
||||
("w6", "on"),
|
||||
],
|
||||
)
|
||||
]
|
||||
refs = {
|
||||
"lrclib": _ref_source(["Hit", "the", "button,", "Come", "here,", "come", "on"], "l"),
|
||||
"spotify": _ref_source(["Hit", "the", "button,", "Come", "here,", "come", "on"], "s"),
|
||||
"genius": _ref_source(["Hit", "the", "button,", "My", "man,", "come", "on"], "g"),
|
||||
}
|
||||
correction_data = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w3", "w4"],
|
||||
"preceding_anchor_id": "anchor-0",
|
||||
"following_anchor_id": None,
|
||||
"reference_word_ids": {"lrclib": [], "spotify": [], "genius": ["g3", "g4"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [
|
||||
{
|
||||
"id": "anchor-0",
|
||||
"transcribed_word_ids": ["w0", "w1", "w2"],
|
||||
"reference_word_ids": {
|
||||
"lrclib": ["l0", "l1", "l2"],
|
||||
"spotify": ["s0", "s1", "s2"],
|
||||
"genius": ["g0", "g1", "g2"],
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
return segments, refs, correction_data
|
||||
|
||||
|
||||
def test_p5_replaces_implausible_proper_noun_with_majority_reading() -> None:
|
||||
segments, refs, cd = _p5_fixture()
|
||||
out = deterministic_suggestions(segments, refs, cd)
|
||||
assert len(out) == 1
|
||||
s = out[0]
|
||||
assert s["op"] == "replace"
|
||||
assert s["word_ids"] == ["w3", "w4"]
|
||||
assert s["new_text"] == "Come here,"
|
||||
assert "Mick," in s["reason"]
|
||||
|
||||
|
||||
def test_p5_requires_the_red_flag_token() -> None:
|
||||
# Same majority disagreement but the transcription is plausible lowercase
|
||||
# ("though" vs 2/3 "dog") -> the human deliberately leaves these; so do we.
|
||||
segments, refs, cd = _p5_fixture()
|
||||
segments[0]["words"][3]["text"] = "yo"
|
||||
segments[0]["words"][4]["text"] = "mick,"
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_skips_spelling_variant_of_reference_token() -> None:
|
||||
# "Crick" ~ "Cricket": a truncation/spelling variant, the LLM's fix.
|
||||
segments, refs, cd = _p5_fixture()
|
||||
segments[0]["words"][4]["text"] = "Herre," # close to reference "here,"
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_requires_two_thirds_majority() -> None:
|
||||
segments, refs, cd = _p5_fixture()
|
||||
# Make spotify read something else -> no 2/3 agreement.
|
||||
for w, t in zip(refs["spotify"]["segments"][0]["words"][3:5], ["Over", "there,"]):
|
||||
w["text"] = t
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_ignores_segment_initial_capitalization() -> None:
|
||||
# A capitalized SEGMENT-FIRST word is sentence case, not a proper noun.
|
||||
segments = [_seg("seg-0", [("w0", "Mick,"), ("w1", "come"), ("w2", "on")])]
|
||||
refs = {
|
||||
"lrclib": _ref_source(["Quick,", "come", "on"], "l"),
|
||||
"spotify": _ref_source(["Quick,", "come", "on"], "s"),
|
||||
"genius": _ref_source(["Slick,", "come", "on"], "g"),
|
||||
}
|
||||
cd = {
|
||||
"gap_sequences": [
|
||||
{
|
||||
"id": "gap-0",
|
||||
"transcribed_word_ids": ["w0"],
|
||||
"reference_word_ids": {"lrclib": ["l0"], "spotify": ["s0"], "genius": ["g0"]},
|
||||
}
|
||||
],
|
||||
"anchor_sequences": [],
|
||||
}
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_p5_skips_stale_gap_word_ids() -> None:
|
||||
segments, refs, cd = _p5_fixture()
|
||||
cd["gap_sequences"][0]["transcribed_word_ids"] = ["w3", "gone"]
|
||||
assert deterministic_suggestions(segments, refs, cd) == []
|
||||
|
||||
|
||||
def test_generators_never_raise_on_garbage() -> None:
|
||||
assert deterministic_suggestions([], {}, None) == []
|
||||
assert deterministic_suggestions([{"weird": True}], {"x": {}}, {"gap_sequences": [{}]}) == []
|
||||
|
||||
|
||||
# ---- Pattern 1: insert/replace self-conflict grouping ----
|
||||
|
||||
|
||||
def _s(id_, op, word_ids, new_text, confidence=0.9, consensus=1):
|
||||
return Suggestion(
|
||||
id=id_,
|
||||
op=op,
|
||||
word_ids=word_ids,
|
||||
segment_ids=["seg-0"],
|
||||
original_text="fire" if op != "insert_after" else "",
|
||||
new_text=new_text,
|
||||
reason="r",
|
||||
category="mishearing",
|
||||
confidence=confidence,
|
||||
models=["m"],
|
||||
consensus=consensus,
|
||||
total_models=1,
|
||||
conflict_group=None,
|
||||
)
|
||||
|
||||
|
||||
def test_p1_insert_and_replace_adding_same_token_share_a_group() -> None:
|
||||
# f6439692: insert_after "fire" -> "you're" AND replace "fire" ->
|
||||
# "fire, you're" both applied -> "you're you're". Must become a conflict.
|
||||
insert = _s("i", "insert_after", ["w-fire"], "you're", confidence=0.75)
|
||||
replace = _s("r", "replace", ["w-fire"], "fire, you're", confidence=0.95)
|
||||
suggestions = [insert, replace]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert insert.conflict_group is not None
|
||||
assert insert.conflict_group == replace.conflict_group
|
||||
|
||||
|
||||
def test_p1_disjoint_tokens_stay_independent() -> None:
|
||||
# Replacing a word AND inserting different text after it is legitimate.
|
||||
insert = _s("i", "insert_after", ["w-fire"], "gasoline")
|
||||
replace = _s("r", "replace", ["w-fire"], "fire,")
|
||||
suggestions = [insert, replace]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert insert.conflict_group is None
|
||||
assert replace.conflict_group is None
|
||||
|
||||
|
||||
def test_p1_two_inserts_same_anchor_same_token_share_a_group() -> None:
|
||||
a = _s("a", "insert_after", ["w-fire"], "you're")
|
||||
b = _s("b", "insert_after", ["w-fire"], "you're baby")
|
||||
suggestions = [a, b]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert a.conflict_group is not None
|
||||
assert a.conflict_group == b.conflict_group
|
||||
|
||||
|
||||
def test_p1_insert_vs_delete_not_grouped() -> None:
|
||||
insert = _s("i", "insert_after", ["w-fire"], "you're")
|
||||
delete = _s("d", "delete", ["w-fire"], "")
|
||||
suggestions = [insert, delete]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert insert.conflict_group is None
|
||||
|
||||
|
||||
def test_assign_conflict_groups_is_idempotent_and_resets() -> None:
|
||||
a = _s("a", "replace", ["w1"], "x")
|
||||
b = _s("b", "replace", ["w2"], "y")
|
||||
a.conflict_group = b.conflict_group = "stale-group"
|
||||
suggestions = [a, b]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert a.conflict_group is None
|
||||
assert b.conflict_group is None
|
||||
|
||||
|
||||
def test_word_overlap_grouping_still_works() -> None:
|
||||
a = _s("a", "replace", ["w1", "w2"], "x")
|
||||
b = _s("b", "delete", ["w2"], "")
|
||||
suggestions = [a, b]
|
||||
_assign_conflict_groups(suggestions)
|
||||
assert a.conflict_group is not None
|
||||
assert a.conflict_group == b.conflict_group
|
||||
|
||||
|
||||
# ---- pipeline integration: suggest() folds deterministic suggestions in ----
|
||||
|
||||
|
||||
def _run_single_model(llm_suggestions, segments, refs, correction_data):
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
return {"suggestions": llm_suggestions}, None
|
||||
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
return service.suggest(
|
||||
job_id="job-1",
|
||||
segments=segments,
|
||||
reference_lyrics=refs,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
correction_data=correction_data,
|
||||
)
|
||||
|
||||
|
||||
def test_suggest_appends_deterministic_suggestions() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
result = _run_single_model([], segments, refs, cd)
|
||||
assert [s.op for s in result.suggestions] == ["delete", "replace"]
|
||||
assert all(s.models == ["deterministic"] for s in result.suggestions)
|
||||
|
||||
|
||||
def test_suggest_dedupes_identical_llm_and_deterministic() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
llm = [
|
||||
{
|
||||
"op": "delete",
|
||||
"start_idx": 0,
|
||||
"end_idx": 0,
|
||||
"new_text": "",
|
||||
"reason": "spurious leading word",
|
||||
"category": "mishearing",
|
||||
"confidence": 0.8,
|
||||
}
|
||||
]
|
||||
result = _run_single_model(llm, segments, refs, cd)
|
||||
deletes = [s for s in result.suggestions if s.op == "delete"]
|
||||
assert len(deletes) == 1
|
||||
assert "deterministic" in deletes[0].models
|
||||
assert deletes[0].confidence == 0.9 # bumped to the deterministic confidence
|
||||
# The deterministic generator counts as an agreeing source.
|
||||
assert deletes[0].consensus == 2
|
||||
assert deletes[0].total_models == 2
|
||||
assert deletes[0].consensus == len(deletes[0].models)
|
||||
|
||||
|
||||
def test_suggest_groups_conflicting_llm_and_deterministic() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
llm = [
|
||||
{
|
||||
"op": "replace",
|
||||
"start_idx": 0,
|
||||
"end_idx": 0,
|
||||
"new_text": "And,",
|
||||
"reason": "punctuation",
|
||||
"category": "formatting",
|
||||
"confidence": 0.7,
|
||||
}
|
||||
]
|
||||
result = _run_single_model(llm, segments, refs, cd)
|
||||
on_w0 = [s for s in result.suggestions if s.word_ids == ["w0"]]
|
||||
assert len(on_w0) == 2
|
||||
assert on_w0[0].conflict_group is not None
|
||||
assert on_w0[0].conflict_group == on_w0[1].conflict_group
|
||||
|
||||
|
||||
def test_suggest_without_correction_data_still_works() -> None:
|
||||
segments, refs, _ = _p4_fixture()
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
return {"suggestions": []}, None
|
||||
|
||||
with patch.object(service, "_cache_get", return_value=None), \
|
||||
patch.object(service, "_cache_put"), \
|
||||
patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
|
||||
patch.object(service, "_call_model", side_effect=fake_call):
|
||||
result = service.suggest(
|
||||
job_id="job-1",
|
||||
segments=segments,
|
||||
reference_lyrics=refs,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(),
|
||||
)
|
||||
assert result.suggestions == []
|
||||
|
||||
|
||||
def test_deterministic_respects_min_confidence_setting() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
service = AutoCorrectService()
|
||||
|
||||
def fake_call(model, system_prompt, user_prompt, *, job_id):
|
||||
return {"suggestions": []}, None
|
||||
|
||||
with 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="job-1",
|
||||
segments=segments,
|
||||
reference_lyrics=refs,
|
||||
artist="A",
|
||||
title="T",
|
||||
settings=AutoCorrectSettings(min_confidence=0.95),
|
||||
correction_data=cd,
|
||||
)
|
||||
assert result.suggestions == []
|
||||
|
||||
|
||||
# ---- module-level helpers ----
|
||||
|
||||
|
||||
def test_ref_word_streams_indexes_ids() -> None:
|
||||
streams = _ref_word_streams({"genius": _ref_source(["a", "b"], "g")})
|
||||
texts, index = streams["genius"]
|
||||
assert texts == ["a", "b"]
|
||||
assert index == {"g0": 0, "g1": 1}
|
||||
|
||||
|
||||
def test_direct_generator_calls_share_stream_shape() -> None:
|
||||
segments, refs, cd = _p4_fixture()
|
||||
streams = _ref_word_streams(refs)
|
||||
assert leading_connective_suggestions(segments, cd, streams)
|
||||
segments5, refs5, cd5 = _p5_fixture()
|
||||
streams5 = _ref_word_streams(refs5)
|
||||
assert reference_majority_suggestions(segments5, cd5, streams5)
|
||||
Whitespace-only changes.
@@ -0,0 +1,202 @@
|
||||
"""Tests for tenant bulk-upload filename analysis.
|
||||
|
||||
The regex fast path is deterministic and covers the real Vocal Star convention,
|
||||
so most assertions run with ``generate=None`` (no LLM). A couple of tests inject
|
||||
a fake ``generate`` to exercise the LLM merge + hallucination guards.
|
||||
"""
|
||||
from backend.services.tenant_bulk import analyze_filenames
|
||||
|
||||
# The real "Bulk-Batch-1-Inputs" folder listing (see BACKLOG.md INBOX spec).
|
||||
BULK_BATCH_1 = [
|
||||
"S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3",
|
||||
"S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3",
|
||||
"S1101-1 Smokey Joes Cafe - Some Cats Know Guide.mp3",
|
||||
"S1101-2 Smokey Joes Cafe - Some Cats Know Instru.mp3",
|
||||
"S1102-2 The Brian Setzer Orchestra - Straight Up Guide.mp3", # anomaly: -2 but Guide, no pair
|
||||
"S1103-1 Cyndi Lauper - Girls Just Want to Have Fun Guide.mp3",
|
||||
"S1103-2 Cyndi Lauper - Girls Just Want to Have Fun BV.mp3",
|
||||
"S1104-1 Herman's Hermits - There's a Kind of Hush Guide.mp3",
|
||||
"S1104-2 Herman's Hermits - There's a Kind of Hush BV.mp3",
|
||||
"S1105-1 Nat King Cole - Smile Guide.mp3",
|
||||
"S1105-2 Nat King Cole - Smile Instru.mp3",
|
||||
]
|
||||
|
||||
|
||||
class TestRegexFastPath:
|
||||
def test_pairs_clean_batch(self):
|
||||
result = analyze_filenames(BULK_BATCH_1).to_dict()
|
||||
rows = result["rows"]
|
||||
# 5 complete pairs (1100, 1101, 1103, 1104, 1105); 1102 is unpaired.
|
||||
assert len(rows) == 5
|
||||
by_mixed = {r["mixed_filename"]: r for r in rows}
|
||||
|
||||
eddy = by_mixed["S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3"]
|
||||
assert eddy["artist"] == "Eddy Grant"
|
||||
assert eddy["title"] == "I Don't Wanna Dance"
|
||||
assert eddy["instrumental_filename"] == "S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3"
|
||||
assert eddy["confidence"] == "high"
|
||||
|
||||
# "Instru" label is recognised as instrumental, not just "-2".
|
||||
smokey = by_mixed["S1101-1 Smokey Joes Cafe - Some Cats Know Guide.mp3"]
|
||||
assert smokey["instrumental_filename"] == "S1101-2 Smokey Joes Cafe - Some Cats Know Instru.mp3"
|
||||
|
||||
# Apostrophes / punctuation preserved in title extraction.
|
||||
herman = by_mixed["S1104-1 Herman's Hermits - There's a Kind of Hush Guide.mp3"]
|
||||
assert herman["artist"] == "Herman's Hermits"
|
||||
assert herman["title"] == "There's a Kind of Hush"
|
||||
|
||||
def test_s1102_anomaly_flagged_unpaired_not_mispaired(self):
|
||||
result = analyze_filenames(BULK_BATCH_1).to_dict()
|
||||
unpaired = result["unpaired"]
|
||||
assert len(unpaired) == 1
|
||||
u = unpaired[0]
|
||||
assert u["filename"] == "S1102-2 The Brian Setzer Orchestra - Straight Up Guide.mp3"
|
||||
# Guide label -> treated as MIXED with no instrumental partner.
|
||||
assert u["role"] == "mixed"
|
||||
assert u["reason"] == "no_instrumental"
|
||||
assert u["artist"] == "The Brian Setzer Orchestra"
|
||||
assert u["title"] == "Straight Up"
|
||||
|
||||
def test_non_audio_files_ignored(self):
|
||||
files = BULK_BATCH_1 + [
|
||||
"ALWAYS REMEMBER US THIS WAY CDG.fw.png",
|
||||
"prepped", # a subfolder entry, no extension
|
||||
"notes.txt",
|
||||
]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
ignored = {i["filename"] for i in result["ignored"]}
|
||||
assert "ALWAYS REMEMBER US THIS WAY CDG.fw.png" in ignored
|
||||
assert "notes.txt" in ignored
|
||||
assert "prepped" in ignored
|
||||
# Audio pairing unaffected by the extra junk.
|
||||
assert len(result["rows"]) == 5
|
||||
|
||||
def test_duplicate_filenames_deduped(self):
|
||||
files = BULK_BATCH_1 + [BULK_BATCH_1[0], BULK_BATCH_1[1]]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
assert len(result["rows"]) == 5
|
||||
|
||||
def test_no_scode_prefix_pairs_by_artist_title(self):
|
||||
files = [
|
||||
"Adele - Hello (Guide).mp3",
|
||||
"Adele - Hello (Instrumental).mp3",
|
||||
]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
assert len(result["rows"]) == 1
|
||||
row = result["rows"][0]
|
||||
assert row["artist"] == "Adele"
|
||||
assert row["title"] == "Hello"
|
||||
|
||||
def test_empty_input(self):
|
||||
result = analyze_filenames([]).to_dict()
|
||||
assert result == {"rows": [], "unpaired": [], "ignored": []}
|
||||
|
||||
def test_title_ending_in_weak_label_word_is_not_mis_roled(self):
|
||||
# "Off" is a title word here, not an instrumental label; the -1/-2 slots
|
||||
# must still pair these correctly and keep the full title.
|
||||
files = [
|
||||
"S2000-1 The Artist - Turn It Off Guide.mp3", # mixed (Guide strong)
|
||||
"S2000-2 The Artist - Turn It Off Instru.mp3", # instrumental
|
||||
]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
assert len(result["rows"]) == 1
|
||||
row = result["rows"][0]
|
||||
assert row["title"] == "Turn It Off"
|
||||
assert row["mixed_filename"] == "S2000-1 The Artist - Turn It Off Guide.mp3"
|
||||
|
||||
def test_bare_weak_label_falls_back_to_slot(self):
|
||||
# No strong label / brackets: "Off" and "Lead" stay in the title and the
|
||||
# slot decides the role, so the pair is preserved.
|
||||
files = [
|
||||
"S2001-1 Band - Show Off.mp3", # slot 1 -> mixed, title keeps "Off"
|
||||
"S2001-2 Band - Show Off.mp3", # slot 2 -> instrumental
|
||||
]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
assert len(result["rows"]) == 1
|
||||
assert result["rows"][0]["title"] == "Show Off"
|
||||
|
||||
def test_bracketed_weak_label_is_trusted(self):
|
||||
files = [
|
||||
"Adele - Hello (Vocals).mp3",
|
||||
"Adele - Hello (Karaoke).mp3",
|
||||
]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
assert len(result["rows"]) == 1
|
||||
row = result["rows"][0]
|
||||
assert row["title"] == "Hello"
|
||||
assert row["mixed_filename"] == "Adele - Hello (Vocals).mp3"
|
||||
|
||||
def test_scode_file_with_subfolder_path_still_parses(self):
|
||||
# Frontend may send a webkitRelativePath; Path().stem uses the basename.
|
||||
files = [
|
||||
"batch/S3000-1 A - Song Guide.mp3",
|
||||
"batch/S3000-2 A - Song Instru.mp3",
|
||||
]
|
||||
result = analyze_filenames(files).to_dict()
|
||||
assert len(result["rows"]) == 1
|
||||
assert result["rows"][0]["instrumental_filename"] == "batch/S3000-2 A - Song Instru.mp3"
|
||||
|
||||
|
||||
class TestLLMPass:
|
||||
def test_llm_pairs_leftovers_regex_missed(self):
|
||||
# Two files the regex can't confidently pair (no label, no S-code).
|
||||
files = [
|
||||
"eddygrant_dance_vox.mp3",
|
||||
"eddygrant_dance_backing.mp3",
|
||||
]
|
||||
|
||||
def fake_generate(system_prompt, user_prompt):
|
||||
assert "eddygrant_dance_vox.mp3" in user_prompt
|
||||
return {
|
||||
"rows": [
|
||||
{
|
||||
"artist": "Eddy Grant",
|
||||
"title": "I Don't Wanna Dance",
|
||||
"mixed_filename": "eddygrant_dance_vox.mp3",
|
||||
"instrumental_filename": "eddygrant_dance_backing.mp3",
|
||||
"confidence": "medium",
|
||||
}
|
||||
],
|
||||
"unpaired": [],
|
||||
}
|
||||
|
||||
result = analyze_filenames(files, generate=fake_generate).to_dict()
|
||||
assert len(result["rows"]) == 1
|
||||
row = result["rows"][0]
|
||||
assert row["mixed_filename"] == "eddygrant_dance_vox.mp3"
|
||||
assert row["confidence"] == "medium"
|
||||
assert result["unpaired"] == []
|
||||
|
||||
def test_llm_hallucinated_filenames_rejected(self):
|
||||
files = ["mystery_track.mp3"]
|
||||
|
||||
def fake_generate(system_prompt, user_prompt):
|
||||
return {
|
||||
"rows": [
|
||||
{
|
||||
"artist": "Made",
|
||||
"title": "Up",
|
||||
"mixed_filename": "mystery_track.mp3",
|
||||
"instrumental_filename": "does_not_exist.mp3", # hallucinated
|
||||
}
|
||||
],
|
||||
"unpaired": [],
|
||||
}
|
||||
|
||||
result = analyze_filenames(files, generate=fake_generate).to_dict()
|
||||
# Row rejected because the instrumental isn't a real input file.
|
||||
assert result["rows"] == []
|
||||
assert len(result["unpaired"]) == 1
|
||||
assert result["unpaired"][0]["filename"] == "mystery_track.mp3"
|
||||
|
||||
def test_llm_error_falls_back_to_regex(self):
|
||||
def boom(system_prompt, user_prompt):
|
||||
raise RuntimeError("model unavailable")
|
||||
|
||||
# Regex handles the clean batch; LLM only runs on leftovers (none here),
|
||||
# but even a raising generate must never break analysis.
|
||||
files = BULK_BATCH_1 + ["weird_unparseable_name.mp3"]
|
||||
result = analyze_filenames(files, generate=boom).to_dict()
|
||||
assert len(result["rows"]) == 5
|
||||
leftover = {u["filename"] for u in result["unpaired"]}
|
||||
assert "weird_unparseable_name.mp3" in leftover
|
||||
@@ -231,7 +231,7 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
|
||||
sent = {}
|
||||
|
||||
class _CapturingProvider:
|
||||
def send_email(self, to_email, subject, html_content, text_content):
|
||||
def send_email(self, to_email, subject, html_content, text_content=None, **kwargs):
|
||||
sent['subject'] = subject
|
||||
sent['text'] = text_content
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Unit tests for the admin create-user endpoint.
|
||||
|
||||
Tests POST /api/users/admin/users, which lets admins create a user account
|
||||
directly (e.g. to grant credits, submit jobs on behalf of, or impersonate
|
||||
someone who has never logged in).
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
|
||||
from backend.api.routes.users import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.models.user import User
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=-1,
|
||||
message="Admin session valid",
|
||||
user_email="admin@nomadkaraoke.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_service():
|
||||
service = Mock()
|
||||
service.get_user.return_value = None # default: user doesn't exist
|
||||
new_user = Mock(spec=User)
|
||||
new_user.email = "new@example.com"
|
||||
new_user.credits = 0
|
||||
service.get_or_create_user.return_value = new_user
|
||||
service.add_credits.return_value = (True, 3, "Added 3 credits")
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_user_service):
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestAdminCreateUser:
|
||||
"""Tests for POST /api/users/admin/users."""
|
||||
|
||||
def test_create_user_minimal(self, client, mock_user_service):
|
||||
"""Creating with just an email creates the account with zero credits."""
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "new@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["email"] == "new@example.com"
|
||||
assert data["credits"] == 0
|
||||
mock_user_service.get_or_create_user.assert_called_once_with("new@example.com")
|
||||
mock_user_service.add_credits.assert_not_called()
|
||||
mock_user_service.update_user.assert_not_called()
|
||||
|
||||
def test_create_user_with_credits_and_display_name(self, client, mock_user_service):
|
||||
"""Initial credits are granted and the welcome-credit flag is set."""
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={
|
||||
"email": "new@example.com",
|
||||
"display_name": "Jane Singer",
|
||||
"initial_credits": 3,
|
||||
"credit_reason": "made-for-you order",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["credits"] == 3
|
||||
assert "3 credit(s)" in data["message"]
|
||||
|
||||
mock_user_service.add_credits.assert_called_once_with(
|
||||
email="new@example.com",
|
||||
amount=3,
|
||||
reason="made-for-you order",
|
||||
admin_email="admin@nomadkaraoke.com",
|
||||
)
|
||||
# display_name saved + welcome credit suppressed (admin credits replace it)
|
||||
update_kwargs = mock_user_service.update_user.call_args.kwargs
|
||||
assert update_kwargs["display_name"] == "Jane Singer"
|
||||
assert update_kwargs["welcome_credits_granted"] is True
|
||||
|
||||
def test_create_without_credits_leaves_welcome_credit_eligible(self, client, mock_user_service):
|
||||
"""No initial credits → welcome_credits_granted is left untouched."""
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "new@example.com", "display_name": "Somebody"},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
update_kwargs = mock_user_service.update_user.call_args.kwargs
|
||||
assert "welcome_credits_granted" not in update_kwargs
|
||||
|
||||
def test_email_normalized_to_lowercase(self, client, mock_user_service):
|
||||
"""Mixed-case emails are lowercased before lookup and creation."""
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "Mixed.Case@Example.COM"},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert response.json()["email"] == "mixed.case@example.com"
|
||||
mock_user_service.get_user.assert_called_once_with("mixed.case@example.com")
|
||||
mock_user_service.get_or_create_user.assert_called_once_with("mixed.case@example.com")
|
||||
|
||||
def test_duplicate_user_returns_409(self, client, mock_user_service):
|
||||
"""Creating a user that already exists returns 409."""
|
||||
mock_user_service.get_user.return_value = Mock(spec=User)
|
||||
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "existing@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 409
|
||||
assert "already exists" in response.json()["detail"]
|
||||
mock_user_service.get_or_create_user.assert_not_called()
|
||||
|
||||
def test_invalid_email_rejected(self, client, mock_user_service):
|
||||
"""A malformed email fails validation with 422."""
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "not-an-email"},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
mock_user_service.get_or_create_user.assert_not_called()
|
||||
|
||||
def test_credits_out_of_range_rejected(self, client, mock_user_service):
|
||||
"""initial_credits outside 0-1000 is rejected."""
|
||||
for bad_amount in (-1, 1001):
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "new@example.com", "initial_credits": bad_amount},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
mock_user_service.get_or_create_user.assert_not_called()
|
||||
|
||||
def test_add_credits_failure_returns_500(self, client, mock_user_service):
|
||||
"""If granting credits fails after creation, the endpoint reports it."""
|
||||
mock_user_service.add_credits.return_value = (False, 0, "Firestore unavailable")
|
||||
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "new@example.com", "initial_credits": 2},
|
||||
)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert "adding credits failed" in response.json()["detail"]
|
||||
|
||||
def test_requires_admin(self, mock_user_service):
|
||||
"""Non-admin requests are rejected."""
|
||||
def deny_admin():
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
app.dependency_overrides[require_admin] = deny_admin
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
try:
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/users/admin/users",
|
||||
json={"email": "new@example.com"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -127,11 +127,13 @@ class TestUpdateJob:
|
||||
|
||||
def test_update_user_email(self, client, mock_job):
|
||||
"""Test updating user_email field."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
mock_get_us.return_value.get_user.return_value = Mock() # user exists
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
@@ -324,3 +326,116 @@ class TestUpdateJobAuthorization:
|
||||
app.dependency_overrides[require_admin] = original_override
|
||||
else:
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
class TestUpdateJobUserEmailAutoCreate:
|
||||
"""Tests for auto-creating a user account when user_email is reassigned."""
|
||||
|
||||
def _patch(self, mock_job, existing_user):
|
||||
"""Return patched JobManager + user_service context managers."""
|
||||
jm_patch = patch('backend.api.routes.admin.JobManager')
|
||||
us_patch = patch('backend.api.routes.admin.get_user_service')
|
||||
return jm_patch, us_patch
|
||||
|
||||
def test_creates_user_when_email_unknown(self, client, mock_job):
|
||||
"""Reassigning to an email with no account auto-creates the account."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_us = Mock()
|
||||
mock_us.get_user.return_value = None # no account exists
|
||||
mock_get_us.return_value = mock_us
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"user_email": "brandnew@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_us.get_or_create_user.assert_called_once_with("brandnew@example.com")
|
||||
assert "Created new user account for brandnew@example.com" in response.json()["message"]
|
||||
|
||||
def test_does_not_create_when_user_exists(self, client, mock_job):
|
||||
"""Reassigning to an existing user's email does not create anything."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_us = Mock()
|
||||
mock_us.get_user.return_value = Mock() # account exists
|
||||
mock_get_us.return_value = mock_us
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"user_email": "existing@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_us.get_or_create_user.assert_not_called()
|
||||
assert "Created new user account" not in response.json()["message"]
|
||||
|
||||
def test_email_is_normalized_to_lowercase(self, client, mock_job):
|
||||
"""Mixed-case emails are lowercased before saving to the job."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_us = Mock()
|
||||
mock_us.get_user.return_value = None
|
||||
mock_get_us.return_value = mock_us
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"user_email": " Mixed.Case@Example.COM "},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][1]["user_email"] == "mixed.case@example.com"
|
||||
mock_us.get_user.assert_called_once_with("mixed.case@example.com")
|
||||
mock_us.get_or_create_user.assert_called_once_with("mixed.case@example.com")
|
||||
|
||||
def test_other_field_updates_skip_user_lookup(self, client, mock_job):
|
||||
"""Updating non-email fields never touches the user service."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"artist": "Someone Else"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_get_us.assert_not_called()
|
||||
|
||||
def test_blank_user_email_rejected(self, client, mock_job):
|
||||
"""Whitespace-only or non-email values for user_email return 400."""
|
||||
for bad_value in (" ", "not-an-email"):
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_get_us:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"user_email": bad_value},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "valid email" in response.json()["detail"]
|
||||
mock_jm.update_job.assert_not_called()
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
Tests for POST /api/admin/orphaned-outputs/cleanup.
|
||||
|
||||
This endpoint deletes distributed outputs whose owning job doc no longer exists
|
||||
(a job deleted while its outputs were still published). Targets are explicit —
|
||||
YouTube video ID, Dropbox folder path, GDrive file IDs, kjbox mirror filename
|
||||
prefix — because there is no job doc left to resolve them from.
|
||||
|
||||
Origin: NOMAD-1583 duplicate incident (2026-08-29) — a job was deleted with its
|
||||
outputs still live, the brand code was recycled and reused, and the orphaned files
|
||||
had to be removed without any job record.
|
||||
"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
URL = "/api/admin/orphaned-outputs/cleanup"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupValidation:
|
||||
def test_no_targets_returns_400(self, client):
|
||||
response = client.post(URL, json={})
|
||||
assert response.status_code == 400
|
||||
assert "No cleanup targets" in response.json()["detail"]
|
||||
|
||||
@pytest.mark.parametrize("prefix", ["NOMAD-1583", "NOMAD-1583 - ", "Mazzy Star"])
|
||||
def test_unsafe_mirror_prefix_returns_400_before_any_cleanup(self, client, prefix):
|
||||
"""An unsafe mirror prefix fails the whole request up front — even the other
|
||||
(valid) targets must not run, so a bad call can be corrected and retried
|
||||
atomically."""
|
||||
with patch("backend.services.youtube_service.get_youtube_service") as mock_get_yt:
|
||||
response = client.post(URL, json={
|
||||
"youtube_video_id": "vid",
|
||||
"mirror_filename_prefix": prefix,
|
||||
})
|
||||
assert response.status_code == 400
|
||||
assert "mirror_filename_prefix" in response.json()["detail"]
|
||||
mock_get_yt.assert_not_called()
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupYouTube:
|
||||
def test_deletes_youtube_video_by_id(self, client):
|
||||
mock_finalise = MagicMock()
|
||||
mock_finalise.delete_youtube_video.return_value = True
|
||||
mock_yt = MagicMock()
|
||||
mock_yt.is_configured = True
|
||||
mock_yt.get_credentials_dict.return_value = {"token": "x"}
|
||||
|
||||
with patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", return_value=mock_finalise), \
|
||||
patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt):
|
||||
response = client.post(URL, json={"youtube_video_id": "R3QZm8yXqvw"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["youtube"] == {"status": "success", "video_id": "R3QZm8yXqvw"}
|
||||
mock_finalise.delete_youtube_video.assert_called_once_with("R3QZm8yXqvw")
|
||||
|
||||
def test_youtube_not_configured_reports_failed(self, client):
|
||||
mock_yt = MagicMock()
|
||||
mock_yt.is_configured = False
|
||||
with patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt):
|
||||
response = client.post(URL, json={"youtube_video_id": "abc123"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["youtube"]["status"] == "failed"
|
||||
|
||||
def test_youtube_error_is_captured_not_raised(self, client):
|
||||
with patch("backend.services.youtube_service.get_youtube_service", side_effect=RuntimeError("boom")):
|
||||
response = client.post(URL, json={"youtube_video_id": "abc123"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["youtube"]["status"] == "error"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupDropbox:
|
||||
def test_deletes_dropbox_folder(self, client):
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
path = "/MediaUnsynced/Karaoke/Tracks-Organized/NOMAD-1583 - Mazzy Star - Fade Into You"
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox):
|
||||
response = client.post(URL, json={"dropbox_folder_path": path})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["dropbox"] == {"status": "success", "path": path}
|
||||
mock_dropbox.delete_folder.assert_called_once_with(path)
|
||||
|
||||
def test_dropbox_delete_failure_reported(self, client):
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = False
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox):
|
||||
response = client.post(URL, json={"dropbox_folder_path": "/x/y"})
|
||||
assert response.json()["results"]["dropbox"]["status"] == "failed"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupGDrive:
|
||||
def test_deletes_gdrive_files_by_id(self, client):
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"id1": True, "id2": True}
|
||||
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive):
|
||||
response = client.post(URL, json={"gdrive_file_ids": ["id1", "id2"]})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["gdrive"]["status"] == "success"
|
||||
mock_gdrive.delete_files.assert_called_once_with(["id1", "id2"])
|
||||
|
||||
def test_partial_gdrive_failure_reported(self, client):
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"id1": True, "id2": False}
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive):
|
||||
response = client.post(URL, json={"gdrive_file_ids": ["id1", "id2"]})
|
||||
assert response.json()["results"]["gdrive"]["status"] == "partial"
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupMirror:
|
||||
def test_deletes_mirror_objects_by_track_prefix(self, client):
|
||||
mock_mirror = MagicMock()
|
||||
mock_mirror.delete_track_objects_by_filename_prefix.return_value = {
|
||||
"masters_deleted": 1, "vocals_guides_deleted": 1,
|
||||
}
|
||||
with patch("backend.services.nomad_master_mirror.NomadMasterMirror", return_value=mock_mirror):
|
||||
response = client.post(URL, json={"mirror_filename_prefix": "NOMAD-1583 - Mazzy Star"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["results"]["mirror"] == {
|
||||
"status": "success", "masters_deleted": 1, "vocals_guides_deleted": 1,
|
||||
}
|
||||
mock_mirror.delete_track_objects_by_filename_prefix.assert_called_once_with("NOMAD-1583 - Mazzy Star")
|
||||
|
||||
|
||||
class TestOrphanedOutputsCleanupCombined:
|
||||
def test_all_targets_cleaned_in_one_call(self, client):
|
||||
mock_finalise = MagicMock()
|
||||
mock_finalise.delete_youtube_video.return_value = True
|
||||
mock_yt = MagicMock(is_configured=True)
|
||||
mock_yt.get_credentials_dict.return_value = {}
|
||||
mock_dropbox = MagicMock(is_configured=True)
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
mock_gdrive = MagicMock(is_configured=True)
|
||||
mock_gdrive.delete_files.return_value = {"id1": True}
|
||||
mock_mirror = MagicMock()
|
||||
mock_mirror.delete_track_objects_by_filename_prefix.return_value = {
|
||||
"masters_deleted": 1, "vocals_guides_deleted": 0,
|
||||
}
|
||||
|
||||
with patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", return_value=mock_finalise), \
|
||||
patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt), \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.nomad_master_mirror.NomadMasterMirror", return_value=mock_mirror):
|
||||
response = client.post(URL, json={
|
||||
"youtube_video_id": "vid",
|
||||
"dropbox_folder_path": "/a/b",
|
||||
"gdrive_file_ids": ["id1"],
|
||||
"mirror_filename_prefix": "NOMAD-1583 - Mazzy Star",
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
results = response.json()["results"]
|
||||
assert {results[k]["status"] for k in ("youtube", "dropbox", "gdrive", "mirror")} == {"success"}
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Unit tests for the admin stats overview endpoint.
|
||||
|
||||
Covers the exclude_test=True path (the admin dashboard default), which streams
|
||||
users and jobs with Firestore field masks. The field masks are load-bearing:
|
||||
without them the endpoint streams full job documents (~100MB collection-wide)
|
||||
and takes 15-20s, blocking the event loop for every other request.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.admin import (
|
||||
router,
|
||||
_compute_admin_stats_overview,
|
||||
_OVERVIEW_USER_FIELDS,
|
||||
_OVERVIEW_JOB_FIELDS,
|
||||
)
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.user_service import get_user_service, USERS_COLLECTION
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
def make_docs(dicts):
|
||||
docs = []
|
||||
for d in dicts:
|
||||
m = Mock()
|
||||
m.to_dict.return_value = d
|
||||
docs.append(m)
|
||||
return docs
|
||||
|
||||
|
||||
def make_db(user_dicts, job_dicts):
|
||||
"""Fake Firestore db supporting .collection(...).select(...).limit(...).stream()."""
|
||||
users_coll = Mock()
|
||||
users_coll.select.return_value.limit.return_value.stream.return_value = make_docs(user_dicts)
|
||||
jobs_coll = Mock()
|
||||
jobs_coll.select.return_value.limit.return_value.stream.return_value = make_docs(job_dicts)
|
||||
|
||||
db = Mock()
|
||||
db.collection.side_effect = lambda name: users_coll if name == USERS_COLLECTION else jobs_coll
|
||||
return db, users_coll, jobs_coll
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def now():
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_data(now):
|
||||
users = [
|
||||
{"email": "real1@example.com", "last_login_at": now - timedelta(days=1),
|
||||
"credit_transactions": [{"amount": 5, "created_at": now - timedelta(days=2)}]},
|
||||
{"email": "real2@example.com", "last_login_at": now - timedelta(days=20),
|
||||
"credit_transactions": [{"amount": -1, "created_at": now - timedelta(days=2)},
|
||||
{"amount": 3, "created_at": now - timedelta(days=45)}]},
|
||||
# Test user — must be excluded from all counts
|
||||
{"email": "abc@inbox.testmail.app", "last_login_at": now - timedelta(days=1),
|
||||
"credit_transactions": [{"amount": 100, "created_at": now - timedelta(days=1)}]},
|
||||
]
|
||||
jobs = [
|
||||
{"user_email": "real1@example.com", "created_at": now - timedelta(days=1), "status": "complete"},
|
||||
{"user_email": "real1@example.com", "created_at": now - timedelta(days=10), "status": "failed"},
|
||||
{"user_email": "real2@example.com", "created_at": now - timedelta(days=40), "status": "transcribing"},
|
||||
{"user_email": "real2@example.com", "created_at": now - timedelta(days=1), "status": "awaiting_review"},
|
||||
# Test-user job — must be excluded
|
||||
{"user_email": "abc@inbox.testmail.app", "created_at": now - timedelta(days=1), "status": "complete"},
|
||||
]
|
||||
return users, jobs
|
||||
|
||||
|
||||
def test_compute_overview_counts_and_filters_test_data(sample_data):
|
||||
users, jobs = sample_data
|
||||
db, _, _ = make_db(users, jobs)
|
||||
|
||||
result = _compute_admin_stats_overview(db, exclude_test=True)
|
||||
|
||||
assert result.total_users == 2
|
||||
assert result.active_users_7d == 1
|
||||
assert result.active_users_30d == 2
|
||||
assert result.total_jobs == 4
|
||||
assert result.jobs_last_7d == 2
|
||||
assert result.jobs_last_30d == 3
|
||||
assert result.jobs_by_status.complete == 1
|
||||
assert result.jobs_by_status.failed == 1
|
||||
assert result.jobs_by_status.processing == 1 # transcribing
|
||||
assert result.jobs_by_status.awaiting_review == 1
|
||||
# 5 (recent) — excludes the 3 older than 30d, the negative txn, and the test user's 100
|
||||
assert result.total_credits_issued_30d == 5
|
||||
|
||||
|
||||
def test_compute_overview_uses_field_masks(sample_data):
|
||||
"""The .select() field masks are a performance guarantee — full job docs are huge."""
|
||||
users, jobs = sample_data
|
||||
db, users_coll, jobs_coll = make_db(users, jobs)
|
||||
|
||||
_compute_admin_stats_overview(db, exclude_test=True)
|
||||
|
||||
users_coll.select.assert_called_once_with(_OVERVIEW_USER_FIELDS)
|
||||
jobs_coll.select.assert_called_once_with(_OVERVIEW_JOB_FIELDS)
|
||||
|
||||
|
||||
def test_overview_endpoint_returns_stats(sample_data):
|
||||
users, jobs = sample_data
|
||||
db, _, _ = make_db(users, jobs)
|
||||
mock_service = Mock()
|
||||
mock_service.db = db
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_service
|
||||
try:
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/admin/stats/overview?exclude_test=true")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["total_users"] == 2
|
||||
assert body["total_jobs"] == 4
|
||||
assert body["jobs_by_status"]["failed"] == 1
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_user_service, None)
|
||||
|
||||
|
||||
def test_overview_handles_empty_collections():
|
||||
db, _, _ = make_db([], [])
|
||||
result = _compute_admin_stats_overview(db, exclude_test=True)
|
||||
assert result.total_users == 0
|
||||
assert result.total_jobs == 0
|
||||
assert result.total_credits_issued_30d == 0
|
||||
@@ -177,11 +177,12 @@ class TestAnalyzeAndGenerateWaveform:
|
||||
service = AudioAnalysisService()
|
||||
|
||||
# Call method
|
||||
result, waveform_path = service.analyze_and_generate_waveform(
|
||||
result, waveform_path, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="uploads/job123/backing.flac",
|
||||
job_id="job123",
|
||||
gcs_waveform_destination="uploads/job123/waveform.png",
|
||||
)
|
||||
assert comparison is None # no lead/vocals stems passed
|
||||
|
||||
# Verify analysis was performed
|
||||
mock_analyzer.analyze.assert_called_once()
|
||||
|
||||
@@ -145,17 +145,78 @@ class TestAudioAnalysisService:
|
||||
mock_storage_service.upload_file.return_value = "jobs/test/analysis/waveform.png"
|
||||
|
||||
service = AudioAnalysisService(storage_service=mock_storage_service)
|
||||
result, waveform_path = service.analyze_and_generate_waveform(
|
||||
result, waveform_path, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="jobs/test/stems/backing_vocals.flac",
|
||||
job_id="test-job",
|
||||
gcs_waveform_destination="jobs/test/analysis/waveform.png",
|
||||
)
|
||||
|
||||
|
||||
# Verify upload was called
|
||||
mock_storage_service.upload_file.assert_called_once()
|
||||
|
||||
|
||||
# Verify waveform path is returned
|
||||
assert waveform_path == "jobs/test/analysis/waveform.png"
|
||||
# No lead/vocals stems passed -> no 3-stem comparison
|
||||
assert comparison is None
|
||||
|
||||
def test_analyze_with_extra_stems_returns_comparison(
|
||||
self, mock_storage_service, temp_audio_file
|
||||
):
|
||||
"""Passing lead + vocals stem paths yields a stem_comparison dict."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
def mock_download(gcs_path, local_path):
|
||||
import shutil
|
||||
shutil.copy(temp_audio_file, local_path)
|
||||
return local_path
|
||||
|
||||
mock_storage_service.download_file.side_effect = mock_download
|
||||
mock_storage_service.upload_file.return_value = "jobs/test/analysis/waveform.png"
|
||||
|
||||
service = AudioAnalysisService(storage_service=mock_storage_service)
|
||||
_result, _waveform, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="jobs/test/stems/backing_vocals.flac",
|
||||
job_id="test-job",
|
||||
gcs_waveform_destination="jobs/test/analysis/waveform.png",
|
||||
gcs_lead_vocals_path="jobs/test/stems/lead_vocals.flac",
|
||||
gcs_vocals_path="jobs/test/stems/vocals_clean.flac",
|
||||
)
|
||||
|
||||
assert comparison is not None
|
||||
assert comparison["error"] is None
|
||||
# All three "stems" are the same file here -> full coverage + corr 1.
|
||||
assert comparison["coverage_ratio"] == 1.0
|
||||
|
||||
def test_comparison_download_failure_is_non_fatal(
|
||||
self, mock_storage_service, temp_audio_file
|
||||
):
|
||||
"""A failure fetching the extra stems yields comparison=None, no raise."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
def mock_download(gcs_path, local_path):
|
||||
import shutil
|
||||
calls["n"] += 1
|
||||
if calls["n"] > 1: # backing succeeds, extra stems fail
|
||||
raise RuntimeError("gcs down")
|
||||
shutil.copy(temp_audio_file, local_path)
|
||||
return local_path
|
||||
|
||||
mock_storage_service.download_file.side_effect = mock_download
|
||||
mock_storage_service.upload_file.return_value = "jobs/test/analysis/waveform.png"
|
||||
|
||||
service = AudioAnalysisService(storage_service=mock_storage_service)
|
||||
_result, waveform_path, comparison = service.analyze_and_generate_waveform(
|
||||
gcs_audio_path="jobs/test/stems/backing_vocals.flac",
|
||||
job_id="test-job",
|
||||
gcs_waveform_destination="jobs/test/analysis/waveform.png",
|
||||
gcs_lead_vocals_path="jobs/test/stems/lead_vocals.flac",
|
||||
gcs_vocals_path="jobs/test/stems/vocals_clean.flac",
|
||||
)
|
||||
|
||||
assert waveform_path == "jobs/test/analysis/waveform.png"
|
||||
assert comparison is None
|
||||
|
||||
def test_get_waveform_data_returns_amplitudes(
|
||||
self, mock_storage_service, temp_audio_file
|
||||
|
||||
@@ -394,3 +394,52 @@ class TestGetReviewAudioUrlAsync:
|
||||
result = await service.get_review_audio_url_async("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed/url"
|
||||
|
||||
|
||||
class TestGetReviewAudioBytes:
|
||||
"""get_review_audio_bytes() proxies the audio through the API (CORS-safe)."""
|
||||
|
||||
def test_returns_ogg_bytes_on_success(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True # cache hit
|
||||
mock_storage.download_bytes.return_value = b"OggS-transcoded-bytes"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
data, content_type = service.get_review_audio_bytes("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
assert data == b"OggS-transcoded-bytes"
|
||||
assert content_type == "audio/ogg"
|
||||
mock_storage.download_bytes.assert_called_once_with("jobs/abc/review-audio/vocals_clean.ogg")
|
||||
|
||||
def test_falls_back_to_source_bytes_on_transcode_error(self):
|
||||
"""A transient transcode failure serves the original source, not a 500."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False # cache miss → transcode path
|
||||
mock_storage.download_file.side_effect = Exception("ffmpeg input download failed")
|
||||
mock_storage.download_bytes.return_value = b"fLaC-source-bytes"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
data, content_type = service.get_review_audio_bytes("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
assert data == b"fLaC-source-bytes"
|
||||
assert content_type == "audio/flac"
|
||||
# Fell back to proxying the original source object.
|
||||
mock_storage.download_bytes.assert_called_once_with("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_wrapper_delegates(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.download_bytes.return_value = b"OggS"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
data, content_type = await service.get_review_audio_bytes_async("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
assert data == b"OggS"
|
||||
assert content_type == "audio/ogg"
|
||||
+101
-50
@@ -215,61 +215,30 @@ class TestDeleteJob:
|
||||
|
||||
|
||||
class TestDeleteJobBrandCodeRecycling:
|
||||
"""Tests for brand code recycling in DELETE /api/jobs/{job_id}."""
|
||||
"""Tests for published-output cleanup + brand code recycling in DELETE /api/jobs/{job_id}.
|
||||
|
||||
def test_brand_code_recycled_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that brand code is recycled before the job is deleted."""
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-123",
|
||||
Recycling must ONLY happen via the distribution cleanup (which gates it on
|
||||
Dropbox + GDrive success). Blind-recycling on delete hands the same NOMAD-####
|
||||
to a future job while the old files are still in the public share (duplicate
|
||||
brand code incident, NOMAD-1583, 2026-08-29).
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _job_with_brand(job_id, outputs_deleted_at=None):
|
||||
return Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0042"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
outputs_deleted_at=outputs_deleted_at,
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', return_value=("NOMAD", 42)) as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_svc = MagicMock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-123", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_parse.assert_called_once_with("NOMAD-0042")
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
|
||||
def test_recycling_failure_does_not_prevent_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that job deletion proceeds even if brand code recycling fails."""
|
||||
def _delete(self, job, auth_headers, mock_worker_service, mock_theme_service, cleanup_patch):
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-456",
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0099"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
@@ -281,14 +250,96 @@ class TestDeleteJobBrandCodeRecycling:
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', side_effect=ValueError("Bad format")):
|
||||
patch('backend.api.routes.jobs._run_distribution_cleanup', cleanup_patch) as mock_cleanup:
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-456", headers=auth_headers)
|
||||
response = client.delete(f"/api/jobs/{job.job_id}", headers=auth_headers)
|
||||
return response, mock_job_manager, mock_cleanup
|
||||
|
||||
assert response.status_code == 200
|
||||
# Job should still be deleted despite recycling failure
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
def test_published_outputs_cleaned_up_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""A job with a brand code and outputs never cleaned up gets full distribution
|
||||
cleanup (which owns the gated recycle) before the record is deleted."""
|
||||
job = self._job_with_brand("test-bc-123", outputs_deleted_at=None)
|
||||
cleanup = MagicMock(return_value={"youtube": {"status": "success"}})
|
||||
|
||||
response, mock_job_manager, mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_cleanup.assert_called_once_with("test-bc-123", job)
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
assert response.json()["distribution_cleanup"] == {"youtube": {"status": "success"}}
|
||||
|
||||
def test_outputs_already_deleted_skips_cleanup_and_recycle(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""A job whose outputs were already deleted (admin delete-outputs recycled the
|
||||
code then) must NOT be cleaned up or recycled again — re-recycling a code that
|
||||
a new job may have since claimed would create duplicates."""
|
||||
job = self._job_with_brand("test-bc-456", outputs_deleted_at=datetime.now(UTC))
|
||||
cleanup = MagicMock()
|
||||
|
||||
response, mock_job_manager, mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_cleanup.assert_not_called()
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
assert "distribution_cleanup" not in response.json()
|
||||
|
||||
def test_delete_files_false_rejected_for_published_job(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Published outputs can't be preserved when their job record is deleted —
|
||||
the record holds the only file IDs/paths needed to ever clean them up."""
|
||||
job = self._job_with_brand("test-bc-df", outputs_deleted_at=None)
|
||||
cleanup = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.api.routes.jobs._run_distribution_cleanup', cleanup):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-df?delete_files=false", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 400
|
||||
cleanup.assert_not_called()
|
||||
mock_job_manager.delete_job.assert_not_called()
|
||||
|
||||
def test_incomplete_cleanup_aborts_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""If any provider cleanup reports failed/partial/error, the job record must
|
||||
be kept so the cleanup can be retried with its IDs intact."""
|
||||
job = self._job_with_brand("test-bc-incomplete", outputs_deleted_at=None)
|
||||
cleanup = MagicMock(return_value={
|
||||
"youtube": {"status": "success"},
|
||||
"dropbox": {"status": "failed", "path": "/x"},
|
||||
"gdrive": {"status": "success"},
|
||||
})
|
||||
|
||||
response, mock_job_manager, _mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 502
|
||||
assert "dropbox" in response.json()["detail"]
|
||||
mock_job_manager.delete_job.assert_not_called()
|
||||
|
||||
def test_unexpected_cleanup_error_aborts_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""If cleanup crashes outright (per-service failures are handled internally),
|
||||
the job record must be preserved — deleting it would orphan the outputs with
|
||||
no way to resolve their IDs later."""
|
||||
job = self._job_with_brand("test-bc-789", outputs_deleted_at=None)
|
||||
cleanup = MagicMock(side_effect=RuntimeError("boom"))
|
||||
|
||||
response, mock_job_manager, _mock_cleanup = self._delete(
|
||||
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
|
||||
|
||||
assert response.status_code == 500
|
||||
mock_job_manager.delete_job.assert_not_called()
|
||||
|
||||
def test_no_brand_code_skips_recycling(self, client, mock_job_manager, auth_headers):
|
||||
"""Test that deletion without brand code doesn't attempt recycling."""
|
||||
|
||||
@@ -206,3 +206,92 @@ def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
|
||||
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
|
||||
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
|
||||
assert mod.cleanup_nomad_masters(brand) == 0
|
||||
|
||||
|
||||
# --- delete_track_objects_by_filename_prefix (single-track orphan cleanup) ---
|
||||
|
||||
def _blob(name):
|
||||
b = MagicMock()
|
||||
b.name = name
|
||||
return b
|
||||
|
||||
|
||||
def _mirror_with_blobs_per_prefix(blobs_by_prefix):
|
||||
"""Mirror whose bucket.list_blobs returns blobs matching the requested prefix,
|
||||
like real GCS (the shared-list shortcut breaks delimiter-bound tests)."""
|
||||
bucket = MagicMock()
|
||||
|
||||
def list_blobs(prefix):
|
||||
return [b for b in blobs_by_prefix if b.name.startswith(prefix)]
|
||||
|
||||
bucket.list_blobs.side_effect = list_blobs
|
||||
client = MagicMock()
|
||||
client.bucket.return_value = bucket
|
||||
return NomadMasterMirror(client=client), bucket
|
||||
|
||||
|
||||
def test_delete_track_objects_by_filename_prefix_deletes_from_both_prefixes():
|
||||
# One master + one vocals guide for the orphaned track; both must go.
|
||||
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
|
||||
guide = _blob("files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star - Fade Into You.flac")
|
||||
mirror, bucket = _mirror_with_blobs_per_prefix([master, guide])
|
||||
|
||||
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
|
||||
|
||||
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 1}
|
||||
prefixes = [c.kwargs.get("prefix") or c.args[0] for c in bucket.list_blobs.call_args_list]
|
||||
assert prefixes == [
|
||||
"files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star",
|
||||
"files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star",
|
||||
]
|
||||
master.delete.assert_called_once()
|
||||
guide.delete.assert_called_once()
|
||||
|
||||
|
||||
def test_delete_track_objects_by_filename_prefix_is_delimiter_bounded():
|
||||
# "NOMAD-1583 - Mazzy Star" must NOT match a different track by a longer-named
|
||||
# artist that happens to share the recycled brand code and the string prefix.
|
||||
orphan = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
|
||||
other = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Starlight - Other Song.mp4")
|
||||
mirror, _bucket = _mirror_with_blobs_per_prefix([orphan, other])
|
||||
|
||||
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
|
||||
|
||||
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
|
||||
orphan.delete.assert_called_once()
|
||||
other.delete.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_track_objects_full_stem_matches_extension_boundary():
|
||||
# A full "brand - artist - title" stem must still match its own files (".mp4").
|
||||
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
|
||||
mirror, _bucket = _mirror_with_blobs_per_prefix([master])
|
||||
|
||||
counts = mirror.delete_track_objects_by_filename_prefix(
|
||||
"NOMAD-1583 - Mazzy Star - Fade Into You"
|
||||
)
|
||||
|
||||
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
|
||||
master.delete.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", [
|
||||
"NOMAD-1583", # bare brand code — would match BOTH tracks sharing it
|
||||
"NOMAD-1583 - ", # brand code + separator but no artist text
|
||||
"NOMADNP-0001 - X", # private prefix
|
||||
"Mazzy Star", # no brand code
|
||||
"",
|
||||
None,
|
||||
])
|
||||
def test_delete_track_objects_by_filename_prefix_refuses_unsafe_prefixes(prefix):
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
with pytest.raises(ValueError):
|
||||
mirror.delete_track_objects_by_filename_prefix(prefix)
|
||||
bucket.list_blobs.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_track_objects_by_filename_prefix_non_fatal_on_list_error():
|
||||
mirror, bucket, _blobs = _mirror_with_blobs([])
|
||||
bucket.list_blobs.side_effect = RuntimeError("gcs down")
|
||||
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
|
||||
assert counts == {"masters_deleted": 0, "vocals_guides_deleted": 0}
|
||||
@@ -55,16 +55,19 @@ def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=No
|
||||
)
|
||||
|
||||
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 3 status queries.
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 4 status queries.
|
||||
|
||||
downloading/rendering use .where().stream(); pending uses .where().limit().stream().
|
||||
`jobs` maps job_id -> Job returned by get_job().
|
||||
downloading/rendering/review_complete use .where().stream(); pending uses
|
||||
.where().limit().stream(). `jobs` maps job_id -> Job returned by get_job().
|
||||
"""
|
||||
mock_jm = MagicMock()
|
||||
where = mock_jm.firestore.db.collection.return_value.where.return_value
|
||||
# Two non-limited .stream() calls in order: downloading_audio, rendering_video
|
||||
where.stream.side_effect = [iter(downloading or []), iter(rendering or [])]
|
||||
# Non-limited .stream() calls in order: downloading_audio, rendering_video,
|
||||
# review_complete (lost-render-trigger sweep)
|
||||
where.stream.side_effect = [
|
||||
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
|
||||
]
|
||||
# One .limit().stream() call: download_pending_retry
|
||||
where.limit.return_value.stream.return_value = iter(pending or [])
|
||||
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
|
||||
@@ -175,3 +178,38 @@ def test_fresh_render_not_reparked(client):
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["reparked_render_count"] == 0
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
def test_stalled_review_complete_render_is_retriggered(client):
|
||||
"""REVIEW_COMPLETE >10 min with no render_progress = lost render trigger
|
||||
(e.g. Cloud Tasks enqueue failed from the GPU worker) -> re-trigger."""
|
||||
job = _job("rc1", JobStatus.REVIEW_COMPLETE, minutes_stale=30)
|
||||
mock_jm = _mock_jm(
|
||||
review_complete=[_doc("rc1", JobStatus.REVIEW_COMPLETE)],
|
||||
jobs={"rc1": job},
|
||||
)
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
mock_ws.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
resp = client.post("/api/internal/recover-stuck-jobs")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["render_retriggered_jobs"] == ["rc1"]
|
||||
mock_ws.trigger_render_video_worker.assert_awaited_once_with("rc1")
|
||||
|
||||
|
||||
def test_fresh_review_complete_is_left_alone(client):
|
||||
job = _job("rc2", JobStatus.REVIEW_COMPLETE, minutes_stale=1)
|
||||
mock_jm = _mock_jm(
|
||||
review_complete=[_doc("rc2", JobStatus.REVIEW_COMPLETE)],
|
||||
jobs={"rc2": job},
|
||||
)
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
resp = client.post("/api/internal/recover-stuck-jobs")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["render_retriggered_jobs"] == []
|
||||
mock_ws.trigger_render_video_worker.assert_not_awaited()
|
||||
@@ -76,6 +76,13 @@ class TestSummaryFieldPathsIncludesRetryPending:
|
||||
from backend.api.routes.jobs import _SUMMARY_STATE_DATA_KEYS
|
||||
assert 'cloud_run_retry_pending' in _SUMMARY_STATE_DATA_KEYS
|
||||
|
||||
def test_firestore_projection_includes_existing_instrumental_path(self):
|
||||
# Top-level field (not state_data), so only SUMMARY_FIELD_PATHS is needed —
|
||||
# the frontend job list uses it to relabel the "downloading" step as
|
||||
# "Preparing your audio" for tenant / upload-based jobs.
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
assert 'existing_instrumental_gcs_path' in FirestoreService.SUMMARY_FIELD_PATHS
|
||||
|
||||
|
||||
class TestSummaryFieldPathsIncludesDurationPricing:
|
||||
"""Regression: duration-pricing fields must be in both SUMMARY_FIELD_PATHS
|
||||
|
||||
@@ -209,10 +209,10 @@ class TestAddLyricsEndpoint:
|
||||
def test_add_lyrics_uses_correction_operations(self):
|
||||
"""Verify CorrectionOperations.add_lyrics_source is available."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
|
||||
# The method should exist
|
||||
assert hasattr(CorrectionOperations, 'add_lyrics_source')
|
||||
|
||||
|
||||
# It should be a static method
|
||||
import inspect
|
||||
# Get the method and check it's callable
|
||||
@@ -220,6 +220,99 @@ class TestAddLyricsEndpoint:
|
||||
assert callable(method)
|
||||
|
||||
|
||||
class TestAddLyricsRejectionHandling:
|
||||
"""Endpoint tests for the relevance-filter rejection flow of add-lyrics.
|
||||
|
||||
The relevance filter can silently drop a pasted lyrics source during the
|
||||
correction rerun. The endpoint must report that as status="rejected" (with
|
||||
the relevance details) instead of a misleading generic success, and must
|
||||
not persist the no-op rerun to GCS.
|
||||
"""
|
||||
|
||||
REJECTION = {"relevance": 0.013, "matched_words": 3, "total_words": 230}
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def auth_overrides(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
def _make_updated_result(self, source_kept: bool, source: str = "manual"):
|
||||
result = MagicMock()
|
||||
if source_kept:
|
||||
result.reference_lyrics = {source: MagicMock()}
|
||||
result.metadata = {}
|
||||
else:
|
||||
result.reference_lyrics = {}
|
||||
result.metadata = {"rejected_sources": {source: dict(self.REJECTION)}}
|
||||
result.to_dict.return_value = {"reference_lyrics": {}, "metadata": result.metadata}
|
||||
return result
|
||||
|
||||
def _post_add_lyrics(self, test_client, updated_result, payload):
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.status = JobStatus.IN_REVIEW
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
|
||||
def fake_download(gcs_path, local_path):
|
||||
with open(local_path, "w") as f:
|
||||
json.dump({}, f)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.review.CorrectionResult") as mock_cr, \
|
||||
patch("backend.api.routes.review.CorrectionOperations") as mock_ops, \
|
||||
patch("backend.api.routes.review._get_audio_hash", return_value="hash123"):
|
||||
mock_jm.return_value.get_job.return_value = mock_job
|
||||
mock_storage = mock_storage_cls.return_value
|
||||
mock_storage.download_file.side_effect = fake_download
|
||||
mock_cr.from_dict.return_value = MagicMock()
|
||||
mock_ops.add_lyrics_source.return_value = updated_result
|
||||
|
||||
response = test_client.post("/api/review/job1/add-lyrics", json=payload)
|
||||
return response, mock_ops, mock_storage
|
||||
|
||||
def test_kept_source_returns_success_and_uploads(self, test_client):
|
||||
updated = self._make_updated_result(source_kept=True)
|
||||
response, _, mock_storage = self._post_add_lyrics(
|
||||
test_client, updated, {"source": "manual", "lyrics": "la la la"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["status"] == "success"
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
|
||||
def test_rejected_source_returns_rejected_without_upload(self, test_client):
|
||||
updated = self._make_updated_result(source_kept=False)
|
||||
response, _, mock_storage = self._post_add_lyrics(
|
||||
test_client, updated, {"source": "manual", "lyrics": "wrong song lyrics"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["status"] == "rejected"
|
||||
assert body["rejection"] == self.REJECTION
|
||||
# The no-op rerun must not overwrite corrections.json
|
||||
mock_storage.upload_json.assert_not_called()
|
||||
|
||||
def test_force_flag_is_passed_through(self, test_client):
|
||||
updated = self._make_updated_result(source_kept=True)
|
||||
_, mock_ops, _ = self._post_add_lyrics(
|
||||
test_client, updated, {"source": "manual", "lyrics": "la la la", "force": "true"}
|
||||
)
|
||||
|
||||
assert mock_ops.add_lyrics_source.call_args.kwargs["force"] is True
|
||||
|
||||
|
||||
class TestReviewResubmissionClearsWorkerProgress:
|
||||
"""Tests for ensuring review submission clears worker progress keys.
|
||||
|
||||
@@ -1132,3 +1225,409 @@ class TestGetPreviewVideoRedirect:
|
||||
self._call(mock_storage)
|
||||
assert exc_info.value.status_code == 404
|
||||
mock_storage.generate_signed_url.assert_not_called()
|
||||
|
||||
|
||||
class TestGetVocalsAudio:
|
||||
"""The vocals waveform endpoint proxies the full vocal stem for the timeline.
|
||||
|
||||
Two behaviours: (1) select the fullest vocal mix (vocals_clean) — real jobs
|
||||
never store a plain 'vocals' key, they store vocals_clean / lead_vocals /
|
||||
backing_vocals. (2) Return the bytes directly (not a 302 to GCS): the
|
||||
waveform fetch()es + decodeAudioData()s the audio, and a cross-origin
|
||||
redirect makes the browser send `Origin: null` which the bucket CORS rejects,
|
||||
so the waveform never loads.
|
||||
"""
|
||||
|
||||
def _call(self, stems, audio_complete=True):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _stream_audio
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
job.file_urls = {"stems": stems}
|
||||
job.state_data = {"audio_complete": audio_complete}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
transcoding = MagicMock()
|
||||
transcoding.get_review_audio_bytes_async = AsyncMock(
|
||||
return_value=(b"OggS-fake-vocals-bytes", "audio/ogg")
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=transcoding,
|
||||
):
|
||||
resp = asyncio.run(
|
||||
_stream_audio(job_id="j", stem="vocals")
|
||||
)
|
||||
return resp, transcoding
|
||||
|
||||
def test_proxies_bytes_not_redirect(self):
|
||||
from starlette.responses import RedirectResponse, Response
|
||||
|
||||
resp, _ = self._call({"vocals_clean": "jobs/j/stems/vocals_clean.flac"})
|
||||
|
||||
# Must serve the bytes from the API (CORS-friendly), never 302 to GCS.
|
||||
assert not isinstance(resp, RedirectResponse)
|
||||
assert isinstance(resp, Response)
|
||||
assert resp.status_code == 200
|
||||
assert resp.media_type == "audio/ogg"
|
||||
assert resp.body == b"OggS-fake-vocals-bytes"
|
||||
|
||||
def test_selects_vocals_clean_when_no_plain_vocals_key(self):
|
||||
# The shape produced by real cloud jobs (no plain "vocals").
|
||||
_, transcoding = self._call(
|
||||
{
|
||||
"instrumental_clean": "jobs/j/stems/instrumental_clean.flac",
|
||||
"vocals_clean": "jobs/j/stems/vocals_clean.flac",
|
||||
"lead_vocals": "jobs/j/stems/lead_vocals.flac",
|
||||
"backing_vocals": "jobs/j/stems/backing_vocals.flac",
|
||||
}
|
||||
)
|
||||
# Must pick the full vocal mix (vocals_clean), not lead_vocals or KeyError.
|
||||
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/vocals_clean.flac"
|
||||
|
||||
def test_prefers_plain_vocals_then_falls_back_to_lead(self):
|
||||
# 2-stem split exposes a plain "vocals" — preferred.
|
||||
_, transcoding = self._call({"vocals": "jobs/j/stems/vocals.flac"})
|
||||
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/vocals.flac"
|
||||
|
||||
# Only lead_vocals available — last-resort fallback.
|
||||
_, transcoding = self._call({"lead_vocals": "jobs/j/stems/lead_vocals.flac"})
|
||||
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/lead_vocals.flac"
|
||||
|
||||
def test_404_when_no_vocal_stem_present(self):
|
||||
"""audio_complete=True + no vocal stem = the stem will never exist -> 404."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._call({"instrumental_clean": "jobs/j/stems/instrumental_clean.flac"})
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_202_when_separation_still_in_progress(self):
|
||||
"""Users can open lyrics review before audio separation finishes (it's
|
||||
decoupled from the critical path), so a missing vocal stem while
|
||||
audio_complete=False means "not yet" — return 202 so the frontend polls
|
||||
instead of permanently hiding the waveform on a terminal 404."""
|
||||
resp, transcoding = self._call({}, audio_complete=False)
|
||||
|
||||
assert resp.status_code == 202
|
||||
assert resp.headers.get("Retry-After") == "15"
|
||||
transcoding.get_review_audio_bytes_async.assert_not_called()
|
||||
|
||||
def test_404_when_separation_skipped_and_no_vocal_stem(self):
|
||||
"""Existing-instrumental jobs set audio_complete=True without ever
|
||||
producing vocal stems — must 404 (terminal), not 202 (retry forever)."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._call({}, audio_complete=True)
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
|
||||
class TestReplayCorrectionData:
|
||||
"""Replay mode for correction-data: re-open a COMPLETED job read-only.
|
||||
|
||||
Verifies the status gate is bypassed with ?replay=true (full auth only), the
|
||||
AWAITING_REVIEW->IN_REVIEW transition is skipped, and the edit_log is attached.
|
||||
"""
|
||||
|
||||
def _client_with_auth(self, auth_type: str = "full"):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
async def _mock_auth(job_id: str = "job1"):
|
||||
return (job_id, auth_type)
|
||||
|
||||
app.dependency_overrides[require_review_auth] = _mock_auth
|
||||
return TestClient(app)
|
||||
|
||||
def _teardown(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
def _completed_job(self):
|
||||
from backend.models.job import JobStatus
|
||||
job = MagicMock()
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.job_id = "job1"
|
||||
job.artist = "A"
|
||||
job.title = "T"
|
||||
job.input_media_gcs_path = "jobs/job1/input/audio.flac"
|
||||
job.file_urls = {"lyrics": {"corrections_updated": "jobs/job1/lyrics/corrections_updated.json"},
|
||||
"stems": {}, "analysis": {}}
|
||||
job.state_data = {"instrumental_selection": "with_backing",
|
||||
"last_edit_log_path": "jobs/job1/lyrics/edit_log_x.json"}
|
||||
return job
|
||||
|
||||
def test_replay_bypasses_status_gate_and_attaches_edit_log(self):
|
||||
client = self._client_with_auth("full")
|
||||
try:
|
||||
with patch("backend.api.routes.review.JobManager") as jm, \
|
||||
patch("backend.api.routes.review.StorageService") as storage_cls, \
|
||||
patch("backend.api.routes.review._get_audio_hash", return_value="h1"):
|
||||
jm.return_value.get_job.return_value = self._completed_job()
|
||||
storage = storage_cls.return_value
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.side_effect = lambda p: (
|
||||
{"entries": [{"operation": "ai_suggestion_accept"}]}
|
||||
if p.endswith("edit_log_x.json")
|
||||
else {"corrected_segments": [], "metadata": {}}
|
||||
)
|
||||
resp = client.get("/api/review/job1/correction-data?replay=true")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["replay"]["is_replay"] is True
|
||||
assert body["replay"]["instrumental_selection"] == "with_backing"
|
||||
assert body["replay"]["job_status"] # some status string
|
||||
assert len(body["replay"]["edit_log"]["entries"]) == 1
|
||||
# Read-only: must NOT transition state.
|
||||
jm.return_value.transition_to_state.assert_not_called()
|
||||
finally:
|
||||
self._teardown()
|
||||
|
||||
def test_non_replay_completed_job_is_rejected(self):
|
||||
client = self._client_with_auth("full")
|
||||
try:
|
||||
with patch("backend.api.routes.review.JobManager") as jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
jm.return_value.get_job.return_value = self._completed_job()
|
||||
resp = client.get("/api/review/job1/correction-data")
|
||||
assert resp.status_code == 400
|
||||
finally:
|
||||
self._teardown()
|
||||
|
||||
def test_replay_requires_full_auth(self):
|
||||
client = self._client_with_auth("review_token")
|
||||
try:
|
||||
with patch("backend.api.routes.review.JobManager") as jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
jm.return_value.get_job.return_value = self._completed_job()
|
||||
resp = client.get("/api/review/job1/correction-data?replay=true")
|
||||
assert resp.status_code == 403
|
||||
finally:
|
||||
self._teardown()
|
||||
|
||||
|
||||
class TestDevAudioProxy:
|
||||
"""The dev-only audio byte-proxy is inert unless REVIEW_AUDIO_PROXY is set."""
|
||||
|
||||
def test_dev_audio_404_when_flag_disabled(self, monkeypatch):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.delenv("REVIEW_AUDIO_PROXY", raising=False)
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/review/job1/dev-audio?path=jobs/job1/stems/x.flac")
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_dev_audio_rejects_out_of_scope_path(self, monkeypatch):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.setenv("REVIEW_AUDIO_PROXY", "1")
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/review/job1/dev-audio?path=jobs/other/stems/x.flac")
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_dev_audio_rejects_prefix_bypass_shapes(self, monkeypatch):
|
||||
# The path must be anchored at jobs/{job_id}/ — a job_id that merely
|
||||
# appears somewhere in the path (e.g. job_id="jobs") must not pass.
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
monkeypatch.setenv("REVIEW_AUDIO_PROXY", "1")
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/review/jobs/dev-audio?path=jobs/other/stems/x.flac")
|
||||
assert resp.status_code == 400
|
||||
resp = client.get("/api/review/job1/dev-audio?path=jobs/job1/../other/x.flac")
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
class TestPreviewVideoAsyncFlow:
|
||||
"""Tests for the async (non-blocking) GCE preview flow.
|
||||
|
||||
POST /preview-video must NOT wait for GCE encoding — cold-starting a
|
||||
fallback encoder VM can take 2-3 minutes, longer than Cloudflare's ~100s
|
||||
edge timeout (incident 2026-08-29, job 326e1aef: preview encoded fine but
|
||||
the browser connection was cut and the UI spun forever). Instead the
|
||||
endpoint returns {"status": "generating"} immediately and the browser
|
||||
polls the /status endpoint until the mp4 exists in GCS.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job(self):
|
||||
from backend.models.job import Job, JobStatus
|
||||
job = MagicMock(spec=Job)
|
||||
job.job_id = "job-preview-async"
|
||||
job.status = JobStatus.AWAITING_REVIEW
|
||||
job.input_media_gcs_path = "jobs/job-preview-async/audio/input.flac"
|
||||
job.style_params_gcs_path = None
|
||||
job.style_assets = {}
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Song"
|
||||
return job
|
||||
|
||||
def _run_gce_preview(self, mock_job, *, mp4_exists, background_mock):
|
||||
"""Run generate_preview_video with GCE enabled and heavy deps mocked."""
|
||||
import asyncio
|
||||
from backend.api.routes.review import generate_preview_video
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.return_value = mp4_exists
|
||||
|
||||
mock_encoding_service = MagicMock()
|
||||
mock_encoding_service.is_preview_enabled = True
|
||||
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
|
||||
async def _run():
|
||||
result = await generate_preview_video(
|
||||
job_id=mock_job.job_id,
|
||||
updated_data={},
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
)
|
||||
# Let any create_task'd background coroutine start
|
||||
await asyncio.sleep(0)
|
||||
return result
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=mock_job_manager), \
|
||||
patch("backend.api.routes.review.StorageService", return_value=mock_storage), \
|
||||
patch("backend.api.routes.review.get_encoding_service", return_value=mock_encoding_service), \
|
||||
patch("backend.api.routes.review.get_settings", return_value=mock_settings), \
|
||||
patch("backend.api.routes.review._prepare_preview_inputs",
|
||||
return_value=(MagicMock(), "/tmp/audio.flac", MagicMock())), \
|
||||
patch("backend.api.routes.review._encode_preview_in_background", background_mock), \
|
||||
patch("backend.api.routes.review.CorrectionOperations") as mock_co, \
|
||||
patch("tempfile.TemporaryDirectory") as mock_tmpdir:
|
||||
mock_tmpdir.return_value.__enter__ = MagicMock(return_value="/tmp/preview_test")
|
||||
mock_tmpdir.return_value.__exit__ = MagicMock(return_value=False)
|
||||
mock_co.generate_preview_video.return_value = {
|
||||
"preview_hash": "hash123",
|
||||
"ass_path": "/tmp/preview.ass",
|
||||
}
|
||||
result = asyncio.run(_run())
|
||||
return result, mock_storage, mock_co
|
||||
|
||||
def test_cache_hit_returns_success_without_encoding(self, mock_job):
|
||||
"""Same edits → same hash: if the mp4 already exists (e.g. user retried
|
||||
after a dropped connection), return success immediately."""
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, mock_co = self._run_gce_preview(
|
||||
mock_job, mp4_exists=True, background_mock=background_mock)
|
||||
assert result == {"status": "success", "preview_hash": "hash123"}
|
||||
background_mock.assert_not_called()
|
||||
# ASS is generated with ass_only=True (no local video render)
|
||||
assert mock_co.generate_preview_video.call_args.kwargs["ass_only"] is True
|
||||
|
||||
def test_cache_miss_returns_generating_and_spawns_background_encode(self, mock_job):
|
||||
"""When the mp4 doesn't exist, the endpoint must return immediately
|
||||
with status=generating and hand encoding to a background task."""
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, _ = self._run_gce_preview(
|
||||
mock_job, mp4_exists=False, background_mock=background_mock)
|
||||
assert result == {"status": "generating", "preview_hash": "hash123"}
|
||||
background_mock.assert_called_once()
|
||||
kwargs = background_mock.call_args.kwargs
|
||||
assert kwargs["preview_hash"] == "hash123"
|
||||
assert kwargs["encode_kwargs"]["job_id"] == "preview_job-preview-async_hash123"
|
||||
assert kwargs["encode_kwargs"]["output_gcs_path"] == \
|
||||
"gs://test-bucket/jobs/job-preview-async/previews/hash123.mp4"
|
||||
# Stale error marker from a previous failed attempt must be cleared
|
||||
mock_storage.delete_file.assert_called_once_with(
|
||||
"jobs/job-preview-async/previews/hash123.error.json", ignore_missing=True)
|
||||
|
||||
|
||||
class TestPreviewVideoStatusEndpoint:
|
||||
"""GET /{job_id}/preview-video/{hash}/status — poll target for async encodes."""
|
||||
|
||||
def _call(self, mock_storage, job_id="job-x", preview_hash="abc123"):
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_preview_video_status
|
||||
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
|
||||
return asyncio.run(get_preview_video_status(
|
||||
job_id=job_id,
|
||||
preview_hash=preview_hash,
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
))
|
||||
|
||||
def test_ready_when_mp4_exists(self):
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.side_effect = lambda p: p.endswith(".mp4")
|
||||
result = self._call(mock_storage)
|
||||
assert result == {"status": "ready", "preview_hash": "abc123"}
|
||||
|
||||
def test_error_when_marker_exists(self):
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.side_effect = lambda p: p.endswith(".error.json")
|
||||
mock_storage.download_json.return_value = {"error": "encoder exploded"}
|
||||
result = self._call(mock_storage)
|
||||
assert result["status"] == "error"
|
||||
assert result["message"] == "encoder exploded"
|
||||
|
||||
def test_generating_when_neither_exists(self):
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
result = self._call(mock_storage)
|
||||
assert result == {"status": "generating", "preview_hash": "abc123"}
|
||||
|
||||
|
||||
class TestEncodePreviewInBackground:
|
||||
"""The background encode task: GCE first, local fallback, error marker last."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job(self):
|
||||
from backend.models.job import Job
|
||||
job = MagicMock(spec=Job)
|
||||
job.job_id = "job-bg"
|
||||
return job
|
||||
|
||||
def _run(self, mock_job, encoding_service, storage, local_render):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _encode_preview_in_background
|
||||
with patch("backend.api.routes.review.get_encoding_service", return_value=encoding_service), \
|
||||
patch("backend.api.routes.review.StorageService", return_value=storage), \
|
||||
patch("backend.api.routes.review._render_preview_locally", local_render):
|
||||
asyncio.run(_encode_preview_in_background(
|
||||
job=mock_job,
|
||||
preview_hash="h1",
|
||||
encode_kwargs={"job_id": "preview_job-bg_h1"},
|
||||
updated_data={},
|
||||
is_duet=False,
|
||||
))
|
||||
|
||||
def test_gce_success_skips_local_fallback(self, mock_job):
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(return_value={"status": "complete"})
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock()
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
local_render.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
def test_gce_failure_falls_back_to_local(self, mock_job):
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(return_value="h1")
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
local_render.assert_called_once()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
def test_both_failures_write_error_marker(self, mock_job):
|
||||
"""If GCE and the local fallback both fail, an error marker must land in
|
||||
GCS so the status poll surfaces the failure instead of timing out."""
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(side_effect=RuntimeError("ffmpeg died"))
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
storage.upload_json.assert_called_once_with(
|
||||
"jobs/job-bg/previews/h1.error.json",
|
||||
{"error": "ffmpeg died"},
|
||||
)
|
||||
@@ -168,7 +168,7 @@ class TestWorkerService:
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
@@ -211,7 +211,7 @@ class TestWorkerService:
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
@@ -244,7 +244,184 @@ class TestWorkerService:
|
||||
call_args = mock_run_v2.RunJobRequest.call_args
|
||||
assert call_args is not None
|
||||
assert "lyrics-transcription-job" in str(call_args)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_audio_worker_local_subprocess_in_dev_mode(self):
|
||||
"""With ENABLE_CLOUD_TASKS=false, CRJ-based workers run as local subprocesses."""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
with patch('subprocess.Popen') as mock_popen:
|
||||
service = WorkerService()
|
||||
result = await service.trigger_audio_worker("test123")
|
||||
|
||||
assert result is True
|
||||
mock_popen.assert_called_once()
|
||||
cmd = mock_popen.call_args[0][0]
|
||||
assert cmd[1:] == ["-m", "backend.workers.audio_worker", "--job-id", "test123"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_local_subprocess_in_production_even_without_cloud_tasks(self):
|
||||
"""A prod deploy that omits ENABLE_CLOUD_TASKS must still use Cloud Run Jobs."""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings, \
|
||||
patch('backend.services.worker_service.is_production', return_value=True):
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
mock_operation = MagicMock()
|
||||
mock_operation.metadata = "test-metadata"
|
||||
mock_run_v2, mock_jobs_client = self._mock_run_v2([mock_operation])
|
||||
|
||||
import google.cloud
|
||||
with patch('subprocess.Popen') as mock_popen, \
|
||||
patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_audio_worker("test123")
|
||||
|
||||
assert result is True
|
||||
mock_popen.assert_not_called()
|
||||
mock_jobs_client.run_job.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_bulk_search_worker_local_subprocess_in_dev_mode(self):
|
||||
"""Bulk search worker also falls back to a local subprocess in dev mode."""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
with patch('subprocess.Popen') as mock_popen:
|
||||
service = WorkerService()
|
||||
result = await service.trigger_bulk_search_worker("batch-1")
|
||||
|
||||
assert result is True
|
||||
cmd = mock_popen.call_args[0][0]
|
||||
assert cmd[1:] == ["-m", "backend.workers.bulk_search_worker", "--batch-id", "batch-1"]
|
||||
|
||||
def _mock_run_v2(self, run_job_side_effect):
|
||||
"""Build a mocked run_v2 module whose JobsClient.run_job uses side_effect."""
|
||||
mock_jobs_client = MagicMock()
|
||||
mock_jobs_client.run_job.side_effect = run_job_side_effect
|
||||
mock_run_v2 = MagicMock()
|
||||
mock_run_v2.JobsClient.return_value = mock_jobs_client
|
||||
mock_run_v2.RunJobRequest = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
|
||||
return mock_run_v2, mock_jobs_client
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_worker_retries_transient_503_then_succeeds(self):
|
||||
"""A one-off transient 503 from the Jobs Admin API is retried, not fatal."""
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
from backend.services.worker_service import (
|
||||
WorkerService, reset_worker_service, _RUN_JOB_MAX_ATTEMPTS,
|
||||
)
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings, \
|
||||
patch('backend.services.worker_service.asyncio.sleep', new=AsyncMock()) as mock_sleep:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
mock_operation = MagicMock()
|
||||
mock_operation.metadata = "test-metadata"
|
||||
# Fail once with a transient 503, then succeed on retry.
|
||||
mock_run_v2, mock_jobs_client = self._mock_run_v2(
|
||||
[gcp_exceptions.ServiceUnavailable("503 unavailable"), mock_operation]
|
||||
)
|
||||
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_lyrics_worker("test123")
|
||||
|
||||
assert result is True
|
||||
assert mock_jobs_client.run_job.call_count == 2 # first fails, retry succeeds
|
||||
assert mock_sleep.await_count == 1 # backed off once between attempts
|
||||
assert _RUN_JOB_MAX_ATTEMPTS >= 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_worker_gives_up_after_max_attempts(self):
|
||||
"""Persistent transient errors exhaust retries and return False (not a raise)."""
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
from backend.services.worker_service import (
|
||||
WorkerService, reset_worker_service, _RUN_JOB_MAX_ATTEMPTS,
|
||||
)
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings, \
|
||||
patch('backend.services.worker_service.asyncio.sleep', new=AsyncMock()):
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
mock_run_v2, mock_jobs_client = self._mock_run_v2(
|
||||
gcp_exceptions.ServiceUnavailable("503 unavailable")
|
||||
)
|
||||
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_lyrics_worker("test123")
|
||||
|
||||
assert result is False
|
||||
assert mock_jobs_client.run_job.call_count == _RUN_JOB_MAX_ATTEMPTS
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_worker_does_not_retry_permanent_error(self):
|
||||
"""Non-transient errors (e.g. PermissionDenied) fail fast without retry."""
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings, \
|
||||
patch('backend.services.worker_service.asyncio.sleep', new=AsyncMock()) as mock_sleep:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_video = False
|
||||
|
||||
mock_run_v2, mock_jobs_client = self._mock_run_v2(
|
||||
gcp_exceptions.PermissionDenied("permission denied")
|
||||
)
|
||||
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_lyrics_worker("test123")
|
||||
|
||||
assert result is False
|
||||
assert mock_jobs_client.run_job.call_count == 1 # no retry on permanent error
|
||||
assert mock_sleep.await_count == 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_screens_worker(self):
|
||||
"""Test triggering screens worker via internal HTTP."""
|
||||
|
||||
@@ -448,7 +448,14 @@ class TestStorageServiceFileOperations:
|
||||
|
||||
class TestStorageServiceSignedUrls:
|
||||
"""Test signed URL generation."""
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_emulator_env(self, monkeypatch):
|
||||
# Other test modules (e.g. test_emulator_integration) export
|
||||
# STORAGE_EMULATOR_HOST at import time, which would divert these tests
|
||||
# into the emulator URL fallback instead of real signing.
|
||||
monkeypatch.delenv("STORAGE_EMULATOR_HOST", raising=False)
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_generate_signed_url(self, mock_settings, mock_client_class):
|
||||
@@ -541,3 +548,42 @@ class TestStorageServiceSignedUrls:
|
||||
assert call_kwargs["service_account_email"] == "sa@project.iam.gserviceaccount.com"
|
||||
assert call_kwargs["access_token"] == "access-token-123"
|
||||
|
||||
|
||||
|
||||
class TestStorageServiceEmulatorUrls:
|
||||
"""Test emulator URL fallback when STORAGE_EMULATOR_HOST is set (local dev)."""
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_get_url_uses_emulator_download_path(self, mock_settings, mock_client_class, monkeypatch):
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.name = "test-bucket"
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
monkeypatch.setenv("STORAGE_EMULATOR_HOST", "http://127.0.0.1:4443")
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
url = StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
|
||||
assert url == (
|
||||
"http://127.0.0.1:4443/download/storage/v1/b/test-bucket/o/"
|
||||
"jobs%2Fabc%2Freview-audio%2Fsong.ogg?alt=media"
|
||||
)
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_put_url_uses_emulator_signed_style_path(self, mock_settings, mock_client_class, monkeypatch):
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.name = "test-bucket"
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
monkeypatch.setenv("STORAGE_EMULATOR_HOST", "http://127.0.0.1:4443")
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
url = StorageService().generate_signed_upload_url("uploads/x/file.bin")
|
||||
|
||||
# fake-gcs-server accepts PUTs with (unvalidated) X-Goog signature params
|
||||
assert url.startswith("http://127.0.0.1:4443/test-bucket/uploads/x/file.bin?")
|
||||
assert "X-Goog-Signature=" in url
|
||||
@@ -11,6 +11,28 @@ from backend.models.user import VerifyMagicLinkResponse, UserPublic
|
||||
from backend.services.auth_service import AuthResult, AuthService, UserType
|
||||
|
||||
|
||||
def _sent_fields(call_args):
|
||||
"""Extract the sent email's fields regardless of positional/keyword call style.
|
||||
|
||||
Sends now flow through EmailService._log_and_send, which invokes the provider
|
||||
with keyword args; older direct calls used positionals. Read both.
|
||||
"""
|
||||
args, kwargs = call_args.args, call_args.kwargs
|
||||
|
||||
def pick(name, idx):
|
||||
if name in kwargs:
|
||||
return kwargs[name]
|
||||
return args[idx] if len(args) > idx else None
|
||||
|
||||
return {
|
||||
"to_email": pick("to_email", 0),
|
||||
"subject": pick("subject", 1),
|
||||
"html_content": pick("html_content", 2),
|
||||
"text_content": pick("text_content", 3),
|
||||
"from_email_override": kwargs.get("from_email_override"),
|
||||
}
|
||||
|
||||
|
||||
class TestTenantConfigGetFrontendUrl:
|
||||
"""Tests for TenantConfig.get_frontend_url()."""
|
||||
|
||||
@@ -47,10 +69,10 @@ class TestSendMagicLinkTenantParams:
|
||||
"""Without tenant params, email uses default Nomad Karaoke branding."""
|
||||
email_service.send_magic_link("user@test.com", "abc123")
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
subject = f["subject"]
|
||||
html_content = f["html_content"]
|
||||
text_content = f["text_content"]
|
||||
|
||||
assert subject == "Sign in to Nomad Karaoke"
|
||||
assert "Nomad Karaoke" in html_content
|
||||
@@ -66,9 +88,9 @@ class TestSendMagicLinkTenantParams:
|
||||
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
|
||||
)
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
html_content = f["html_content"]
|
||||
text_content = f["text_content"]
|
||||
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in html_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in text_content
|
||||
@@ -83,10 +105,10 @@ class TestSendMagicLinkTenantParams:
|
||||
tenant_name="Vocal Star",
|
||||
)
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
subject = f["subject"]
|
||||
html_content = f["html_content"]
|
||||
text_content = f["text_content"]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "Vocal Star" in html_content
|
||||
@@ -100,8 +122,7 @@ class TestSendMagicLinkTenantParams:
|
||||
tenant_name='<script>alert("xss")</script>',
|
||||
)
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
html_content = call_args[0][2]
|
||||
html_content = _sent_fields(email_service.provider.send_email.call_args)["html_content"]
|
||||
|
||||
# Should be escaped in HTML
|
||||
assert "<script>" not in html_content
|
||||
@@ -119,14 +140,14 @@ class TestSendMagicLinkTenantParams:
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
subject = f["subject"]
|
||||
html_content = f["html_content"]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=token123" in html_content
|
||||
# Check sender email override was passed through
|
||||
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
|
||||
assert f["from_email_override"] == "vocalstar@nomadkaraoke.com"
|
||||
|
||||
|
||||
class TestVerifyMagicLinkResponseTenantSubdomain:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Cloud Tasks queue paths must use cloud_tasks_region, not gcp_region.
|
||||
|
||||
The GPU audio-separation-job runs with GCP_REGION set to its GPU region, but
|
||||
every Cloud Tasks queue lives in us-central1 — building queue paths from
|
||||
gcp_region 404s ("Queue does not exist") from that worker, which silently
|
||||
dropped the auto-approval render trigger (job b8bda9c2, 2026-08-27).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enqueue_uses_cloud_tasks_region_not_gcp_region(monkeypatch) -> None:
|
||||
monkeypatch.setenv("ENABLE_CLOUD_TASKS", "true")
|
||||
monkeypatch.setenv("GCP_REGION", "us-east4") # simulate the GPU job env
|
||||
monkeypatch.delenv("CLOUD_TASKS_REGION", raising=False)
|
||||
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "test-project")
|
||||
|
||||
from backend.config import Settings
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
with patch("backend.services.worker_service.get_settings", return_value=Settings()):
|
||||
service = WorkerService()
|
||||
tasks_client = MagicMock()
|
||||
tasks_client.queue_path.side_effect = (
|
||||
lambda project, location, queue: f"projects/{project}/locations/{location}/queues/{queue}"
|
||||
)
|
||||
service._tasks_client = tasks_client
|
||||
|
||||
await service._enqueue_cloud_task("render-video", "job1")
|
||||
|
||||
args = tasks_client.queue_path.call_args.args
|
||||
assert args[1] == "us-central1", f"queue location must be us-central1, got {args[1]}"
|
||||
|
||||
|
||||
def test_settings_cloud_tasks_region_default(monkeypatch) -> None:
|
||||
monkeypatch.delenv("CLOUD_TASKS_REGION", raising=False)
|
||||
from backend.config import Settings
|
||||
assert Settings().cloud_tasks_region == "us-central1"
|
||||
|
||||
|
||||
# --- REVIEW_COMPLETE stall detection (lost render trigger) ---
|
||||
|
||||
def _job(minutes_old: float, render_progress: bool = False) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
state_data={"render_progress": {"stage": "encoding"}} if render_progress else {},
|
||||
updated_at=datetime.now(timezone.utc) - timedelta(minutes=minutes_old),
|
||||
)
|
||||
|
||||
|
||||
def test_review_complete_stalled_after_ten_minutes() -> None:
|
||||
from backend.api.routes.internal import _review_complete_stalled
|
||||
assert _review_complete_stalled(_job(minutes_old=15)) is True
|
||||
|
||||
|
||||
def test_review_complete_fresh_is_not_stalled() -> None:
|
||||
from backend.api.routes.internal import _review_complete_stalled
|
||||
assert _review_complete_stalled(_job(minutes_old=2)) is False
|
||||
|
||||
|
||||
def test_review_complete_with_render_underway_is_not_stalled() -> None:
|
||||
from backend.api.routes.internal import _review_complete_stalled
|
||||
assert _review_complete_stalled(_job(minutes_old=30, render_progress=True)) is False
|
||||
@@ -48,7 +48,8 @@
|
||||
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selected. Video generation started.",
|
||||
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error getting download URLs: {error}"
|
||||
"downloadUrlsError": "Error getting download URLs: {error}",
|
||||
"deletePublishedRequiresFiles": "This track's published files must be removed when the job is deleted. Retry the delete without delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
|
||||
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
|
||||
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}",
|
||||
"fileNoLongerAvailable": "الملف لم يعد متاحاً"
|
||||
"fileNoLongerAvailable": "الملف لم يعد متاحاً",
|
||||
"deletePublishedRequiresFiles": "يجب إزالة الملفات المنشورة لهذا المسار عند حذف المهمة. يُرجى إعادة محاولة الحذف بدون delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "المهمة غير موجودة",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
|
||||
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
|
||||
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}",
|
||||
"fileNoLongerAvailable": "El fitxer ja no està disponible"
|
||||
"fileNoLongerAvailable": "El fitxer ja no està disponible",
|
||||
"deletePublishedRequiresFiles": "Els fitxers publicats d'aquesta pista s'han d'eliminar quan s'elimini la tasca. Torna a intentar l'eliminació sense delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tasca no trobada",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
|
||||
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}",
|
||||
"fileNoLongerAvailable": "Soubor již není dostupný"
|
||||
"fileNoLongerAvailable": "Soubor již není dostupný",
|
||||
"deletePublishedRequiresFiles": "Při mazání úlohy je nutné odstranit i publikované soubory této skladby. Zkus to smazat znovu bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha nebyla nalezena",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
|
||||
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig"
|
||||
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig",
|
||||
"deletePublishedRequiresFiles": "Dette spors udgivne filer skal fjernes, når jobbet slettes. Prøv at slette igen uden delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet blev ikke fundet",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
|
||||
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}",
|
||||
"fileNoLongerAvailable": "Datei nicht mehr verfügbar"
|
||||
"fileNoLongerAvailable": "Datei nicht mehr verfügbar",
|
||||
"deletePublishedRequiresFiles": "Die veröffentlichten Dateien dieses Tracks müssen entfernt werden, wenn der Auftrag gelöscht wird. Versuche den Löschvorgang ohne delete_files=false erneut."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
|
||||
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
|
||||
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}",
|
||||
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο"
|
||||
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο",
|
||||
"deletePublishedRequiresFiles": "Τα δημοσιευμένα αρχεία αυτού του κομματιού πρέπει να αφαιρεθούν όταν διαγράφεται η εργασία. Δοκίμασε ξανά τη διαγραφή χωρίς το delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Η εργασία δεν βρέθηκε",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selected. Video generation started.",
|
||||
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error getting download URLs: {error}"
|
||||
"downloadUrlsError": "Error getting download URLs: {error}",
|
||||
"deletePublishedRequiresFiles": "This track's published files must be removed when the job is deleted. Retry the delete without delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
|
||||
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}",
|
||||
"fileNoLongerAvailable": "El archivo ya no está disponible"
|
||||
"fileNoLongerAvailable": "El archivo ya no está disponible",
|
||||
"deletePublishedRequiresFiles": "Los archivos publicados de esta pista deben eliminarse cuando se elimine el trabajo. Vuelve a intentar la eliminación sin delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
|
||||
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
|
||||
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}",
|
||||
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla"
|
||||
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla",
|
||||
"deletePublishedRequiresFiles": "Tämän kappaleen julkaistut tiedostot täytyy poistaa työn poistamisen yhteydessä. Yritä poistoa uudelleen ilman delete_files=false -määritystä."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Työtä ei löytynyt",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
|
||||
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
|
||||
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}",
|
||||
"fileNoLongerAvailable": "Le fichier n'est plus disponible"
|
||||
"fileNoLongerAvailable": "Le fichier n'est plus disponible",
|
||||
"deletePublishedRequiresFiles": "Les fichiers publiés de cette piste doivent être supprimés en même temps que la tâche. Réessaie la suppression sans delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tâche introuvable",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
|
||||
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
|
||||
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}",
|
||||
"fileNoLongerAvailable": "הקובץ אינו זמין יותר"
|
||||
"fileNoLongerAvailable": "הקובץ אינו זמין יותר",
|
||||
"deletePublishedRequiresFiles": "יש להסיר את הקבצים שפורסמו עבור רצועה זו בעת מחיקת המשימה. נסה שוב את המחיקה ללא delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "המשימה לא נמצאה",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
|
||||
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
|
||||
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}",
|
||||
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है"
|
||||
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है",
|
||||
"deletePublishedRequiresFiles": "जॉब डिलीट करते समय इस ट्रैक की पब्लिश की गई फ़ाइलों को हटाना ज़रूरी है। delete_files=false के बिना डिलीट करने की दोबारा कोशिश करो।"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "जॉब नहीं मिली",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
|
||||
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
|
||||
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}",
|
||||
"fileNoLongerAvailable": "Datoteka više nije dostupna"
|
||||
"fileNoLongerAvailable": "Datoteka više nije dostupna",
|
||||
"deletePublishedRequiresFiles": "Objavljene datoteke ove pjesme moraju se ukloniti kada se zadatak izbriše. Pokušaj ponovno obrisati bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Zadatak nije pronađen",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
|
||||
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
|
||||
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}",
|
||||
"fileNoLongerAvailable": "A fájl már nem elérhető"
|
||||
"fileNoLongerAvailable": "A fájl már nem elérhető",
|
||||
"deletePublishedRequiresFiles": "Ennek a számnak a közzétett fájljait el kell távolítani a feladat törlésekor. Próbáld újra a törlést a delete_files=false nélkül."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "A feladat nem található",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
|
||||
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
|
||||
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}",
|
||||
"fileNoLongerAvailable": "File sudah tidak tersedia"
|
||||
"fileNoLongerAvailable": "File sudah tidak tersedia",
|
||||
"deletePublishedRequiresFiles": "File yang telah dipublikasikan dari trek ini harus ikut dihapus saat tugas dihapus. Silakan ulangi penghapusan tanpa delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugas tidak ditemukan",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
|
||||
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
|
||||
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}",
|
||||
"fileNoLongerAvailable": "File non più disponibile"
|
||||
"fileNoLongerAvailable": "File non più disponibile",
|
||||
"deletePublishedRequiresFiles": "I file pubblicati di questa traccia devono essere rimossi quando il lavoro viene eliminato. Riprova l'eliminazione senza delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Lavoro non trovato",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
|
||||
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
|
||||
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}",
|
||||
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました"
|
||||
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました",
|
||||
"deletePublishedRequiresFiles": "ジョブを削除する際は、このトラックの公開済みファイルも削除する必要があります。delete_files=false を指定せずに、削除を再試行してください。"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ジョブが見つかりません",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
|
||||
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
|
||||
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}",
|
||||
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다"
|
||||
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다",
|
||||
"deletePublishedRequiresFiles": "작업을 삭제할 때 이 트랙에 게시된 파일도 함께 삭제해야 합니다. delete_files=false 없이 삭제를 다시 시도해 주세요."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "작업을 찾을 수 없습니다",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
|
||||
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
|
||||
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}",
|
||||
"fileNoLongerAvailable": "Fail tidak lagi tersedia"
|
||||
"fileNoLongerAvailable": "Fail tidak lagi tersedia",
|
||||
"deletePublishedRequiresFiles": "Fail terbitan trek ini mesti dipadamkan apabila tugas dipadamkan. Sila cuba padam semula tanpa delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugasan tidak dijumpai",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering startet.",
|
||||
"instrumentalSelectionError": "Feil ved valg av instrumental for jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig"
|
||||
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig",
|
||||
"deletePublishedRequiresFiles": "De publiserte filene for dette sporet må fjernes når jobben slettes. Prøv å slette på nytt uten delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobben ble ikke funnet",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental geselecteerd. Videogeneratie is gestart.",
|
||||
"instrumentalSelectionError": "Fout bij het selecteren van instrumental voor taak {job_id}: {error}",
|
||||
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}",
|
||||
"fileNoLongerAvailable": "Bestand niet meer beschikbaar"
|
||||
"fileNoLongerAvailable": "Bestand niet meer beschikbaar",
|
||||
"deletePublishedRequiresFiles": "De gepubliceerde bestanden van deze track moeten worden verwijderd als de taak wordt verwijderd. Probeer het verwijderen opnieuw zonder delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Taak niet gevonden",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Wybrano podkład. Rozpoczęto generowanie wideo.",
|
||||
"instrumentalSelectionError": "Błąd podczas wybierania podkładu dla zadania {job_id}: {error}",
|
||||
"downloadUrlsError": "Błąd podczas pobierania linków: {error}",
|
||||
"fileNoLongerAvailable": "Plik nie jest już dostępny"
|
||||
"fileNoLongerAvailable": "Plik nie jest już dostępny",
|
||||
"deletePublishedRequiresFiles": "Opublikowane pliki tego utworu muszą zostać usunięte podczas usuwania zadania. Spróbuj usunąć ponownie bez delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Nie znaleziono zadania",
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"instrumentalSelected": "Instrumental selecionado. Geração de vídeo iniciada.",
|
||||
"instrumentalSelectionError": "Erro ao selecionar instrumental para o job {job_id}: {error}",
|
||||
"downloadUrlsError": "Erro ao obter URLs de download: {error}",
|
||||
"fileNoLongerAvailable": "O arquivo não está mais disponível"
|
||||
"fileNoLongerAvailable": "O arquivo não está mais disponível",
|
||||
"deletePublishedRequiresFiles": "Os arquivos publicados desta faixa devem ser removidos quando a tarefa for excluída. Tente excluir novamente sem delete_files=false."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job não encontrado",
|
||||
|
||||
Loaded 100 of 3828 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user