mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-06 09:57:39 +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
|
||||
|
||||
@@ -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"]
|
||||
|
||||
|
||||
@@ -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.
|
||||
+109
-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,8 @@ 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
|
||||
|
||||
# Editable boolean fields
|
||||
enable_cdg: Optional[bool] = None
|
||||
@@ -127,6 +131,7 @@ EDITABLE_JOB_FIELDS = {
|
||||
"non_interactive",
|
||||
"prep_only",
|
||||
"is_private",
|
||||
"review_mode",
|
||||
}
|
||||
|
||||
|
||||
@@ -153,10 +158,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 +198,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 +251,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 +335,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 +970,35 @@ 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"',
|
||||
)
|
||||
|
||||
# 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 +1048,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)."
|
||||
|
||||
@@ -2977,6 +3030,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__)
|
||||
|
||||
@@ -806,6 +806,7 @@ async def search_audio(
|
||||
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__)
|
||||
@@ -348,6 +349,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__)
|
||||
|
||||
@@ -248,13 +249,25 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
# 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):
|
||||
@@ -685,6 +698,8 @@ async def upload_and_create_job(
|
||||
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 +814,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
|
||||
@@ -1269,6 +1286,8 @@ async def create_job_with_upload_urls(
|
||||
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 +1300,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 +1322,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,
|
||||
@@ -1897,6 +1944,8 @@ async def create_job_from_url(
|
||||
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 +2251,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/
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -2541,6 +2542,7 @@ async def create_job_from_search(
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
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
|
||||
|
||||
+369
-37
@@ -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
|
||||
@@ -237,9 +237,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 +402,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,7 +419,12 @@ 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)
|
||||
@@ -314,18 +478,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({
|
||||
@@ -352,19 +523,43 @@ async def get_correction_data(
|
||||
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 +567,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 +596,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 +611,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 +671,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,
|
||||
@@ -851,16 +1162,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:
|
||||
@@ -1345,6 +1669,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 +1699,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
|
||||
+256
-60
@@ -9,6 +9,7 @@ Handles:
|
||||
- Admin user management
|
||||
"""
|
||||
import hashlib
|
||||
import html
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
@@ -35,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,
|
||||
@@ -47,6 +49,8 @@ from backend.models.user import (
|
||||
ResendFromTokenResponse,
|
||||
AddCreditsRequest,
|
||||
AddCreditsResponse,
|
||||
AdminCreateUserRequest,
|
||||
AdminCreateUserResponse,
|
||||
UserListResponse,
|
||||
UserFeedback,
|
||||
UserFeedbackRequest,
|
||||
@@ -271,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,
|
||||
@@ -437,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
|
||||
|
||||
@@ -800,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),
|
||||
):
|
||||
"""
|
||||
@@ -824,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:
|
||||
@@ -844,6 +864,72 @@ async def create_made_for_you_checkout(
|
||||
ADMIN_EMAIL = "madeforyou@nomadkaraoke.com"
|
||||
|
||||
|
||||
def _send_mfy_failure_alert(
|
||||
email_service: EmailService,
|
||||
*,
|
||||
customer_email: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
job_id: Optional[str],
|
||||
error: Exception,
|
||||
) -> None:
|
||||
"""Best-effort admin alert when a made-for-you order can't be fully processed.
|
||||
|
||||
This never raises: a failure to send the alert must not mask the original
|
||||
error, nor interfere with the customer-facing order-confirmation email
|
||||
(which is sent independently, before audio acquisition is attempted).
|
||||
"""
|
||||
safe_customer = html.escape(customer_email or "")
|
||||
safe_artist = html.escape(artist or "")
|
||||
safe_title = html.escape(title or "")
|
||||
safe_error = html.escape(str(error))
|
||||
job_line_html = f"<li><strong>Job ID:</strong> {html.escape(job_id)}</li>" if job_id else ""
|
||||
job_line_text = f"Job ID: {job_id}\n" if job_id else ""
|
||||
remediation = (
|
||||
"The customer's order-confirmation email is sent separately and up-front, so it "
|
||||
"is unaffected by failures during processing. Please review this order and take "
|
||||
"any needed manual action — e.g. provide/repair the audio source, or resend the "
|
||||
"customer confirmation."
|
||||
)
|
||||
try:
|
||||
sent = email_service.send_email(
|
||||
to_email=ADMIN_EMAIL,
|
||||
subject=f"[FAILED] Made For You Order: {artist} - {title}",
|
||||
html_content=f"""
|
||||
<h2>Made-For-You Order — Action Needed</h2>
|
||||
<p>A problem occurred while processing this order:</p>
|
||||
<ul>
|
||||
<li><strong>Customer:</strong> {safe_customer}</li>
|
||||
<li><strong>Artist:</strong> {safe_artist}</li>
|
||||
<li><strong>Title:</strong> {safe_title}</li>
|
||||
{job_line_html}
|
||||
<li><strong>Error:</strong> {safe_error}</li>
|
||||
</ul>
|
||||
<p>{remediation}</p>
|
||||
""",
|
||||
text_content=(
|
||||
"Made-For-You Order — Action Needed\n\n"
|
||||
f"Customer: {customer_email}\n"
|
||||
f"Artist: {artist}\n"
|
||||
f"Title: {title}\n"
|
||||
f"{job_line_text}"
|
||||
f"Error: {error}\n\n"
|
||||
f"{remediation}"
|
||||
),
|
||||
)
|
||||
if sent:
|
||||
logger.info(f"Sent made-for-you failure alert to admin for job {job_id}")
|
||||
else:
|
||||
logger.error(
|
||||
f"Made-for-you failure alert to admin was rejected by the email provider (job {job_id})"
|
||||
)
|
||||
except Exception as email_error:
|
||||
logger.error(
|
||||
f"Failed to send made-for-you failure alert (job {job_id}): {email_error}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
async def _handle_made_for_you_order(
|
||||
session_id: str,
|
||||
metadata: dict,
|
||||
@@ -892,6 +978,10 @@ async def _handle_made_for_you_order(
|
||||
f"(session: {session_id}, source_type: {source_type})"
|
||||
)
|
||||
|
||||
# Defined up-front so the outer failure handler can reference it even if job
|
||||
# creation is what failed (job_id stays None until the job actually exists).
|
||||
job_id = None
|
||||
|
||||
try:
|
||||
job_manager = JobManager()
|
||||
storage_service = StorageService()
|
||||
@@ -937,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)
|
||||
@@ -977,6 +1069,48 @@ async def _handle_made_for_you_order(
|
||||
# Initialize search_results for later use in email notification
|
||||
search_results = None
|
||||
|
||||
# Send the customer's order-confirmation email NOW, before attempting audio
|
||||
# acquisition. The order is paid and confirmed regardless of whether the
|
||||
# (fallible) YouTube download / audio search succeeds, so a failure there must
|
||||
# never rob the customer of their confirmation email. Resilient: a delivery
|
||||
# failure is logged but does not abort order processing.
|
||||
confirmation_ok = False
|
||||
try:
|
||||
# Providers return False (not an exception) when the send is rejected, so
|
||||
# check the result rather than assuming success.
|
||||
confirmation_ok = bool(email_service.send_made_for_you_order_confirmation(
|
||||
to_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
notes=notes,
|
||||
))
|
||||
if confirmation_ok:
|
||||
logger.info(f"Sent made-for-you customer confirmation for job {job_id}")
|
||||
else:
|
||||
logger.error(
|
||||
f"Job {job_id}: customer order-confirmation email was rejected by the email provider"
|
||||
)
|
||||
except Exception as confirm_error:
|
||||
logger.error(
|
||||
f"Job {job_id}: Failed to send customer order-confirmation email: {confirm_error}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
if not confirmation_ok:
|
||||
# A paid customer must never silently miss their confirmation. Escalate to
|
||||
# the admin so it can be resent manually. Order processing still continues.
|
||||
_send_mfy_failure_alert(
|
||||
email_service,
|
||||
customer_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
error=RuntimeError(
|
||||
"Customer order-confirmation email failed to send — please resend it manually"
|
||||
),
|
||||
)
|
||||
|
||||
# Handle based on whether we have a YouTube URL or need to search
|
||||
if youtube_url:
|
||||
# URL provided - download audio first, then trigger workers
|
||||
@@ -1099,66 +1233,59 @@ async def _handle_made_for_you_order(
|
||||
# (search_results may be set from the search flow above, or None for YouTube URL orders)
|
||||
audio_source_count = len(search_results) if search_results else 0
|
||||
|
||||
# Generate admin login token for one-click email access (24hr expiry)
|
||||
admin_login = user_service.create_admin_login_token(
|
||||
email=ADMIN_EMAIL,
|
||||
expiry_hours=24,
|
||||
)
|
||||
# Send notification email to admin using professional template.
|
||||
# Resilient: an email delivery error here must not turn a successfully-created
|
||||
# order into a "[FAILED]" alert — it's logged and swallowed instead.
|
||||
try:
|
||||
# Generate admin login token for one-click email access (24hr expiry)
|
||||
admin_login = user_service.create_admin_login_token(
|
||||
email=ADMIN_EMAIL,
|
||||
expiry_hours=24,
|
||||
)
|
||||
admin_notified = bool(email_service.send_made_for_you_admin_notification(
|
||||
to_email=ADMIN_EMAIL,
|
||||
customer_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
admin_login_token=admin_login.token,
|
||||
notes=notes,
|
||||
audio_source_count=audio_source_count,
|
||||
))
|
||||
if admin_notified:
|
||||
logger.info(f"Sent made-for-you admin notification for job {job_id}")
|
||||
else:
|
||||
logger.error(
|
||||
f"Job {job_id}: admin order notification was rejected by the email provider"
|
||||
)
|
||||
except Exception as admin_email_error:
|
||||
logger.error(
|
||||
f"Job {job_id}: Failed to send admin order notification: {admin_email_error}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
# Send confirmation email to customer using professional template
|
||||
email_service.send_made_for_you_order_confirmation(
|
||||
to_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
notes=notes,
|
||||
)
|
||||
|
||||
# Send notification email to admin using professional template
|
||||
email_service.send_made_for_you_admin_notification(
|
||||
to_email=ADMIN_EMAIL,
|
||||
except Exception as e:
|
||||
# A hard failure in order processing (e.g. job creation, or audio acquisition
|
||||
# raising after transitioning the job to FAILED). The customer confirmation is
|
||||
# sent earlier and independently, so it is unaffected by failures here. Alert
|
||||
# the admin so they can intervene manually.
|
||||
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
|
||||
_send_mfy_failure_alert(
|
||||
email_service,
|
||||
customer_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
admin_login_token=admin_login.token,
|
||||
notes=notes,
|
||||
audio_source_count=audio_source_count,
|
||||
error=e,
|
||||
)
|
||||
|
||||
logger.info(f"Sent made-for-you order notifications for job {job_id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
|
||||
# Still try to notify Andrew of the failure
|
||||
try:
|
||||
email_service.send_email(
|
||||
to_email=ADMIN_EMAIL,
|
||||
subject=f"[FAILED] Made For You Order: {artist} - {title}",
|
||||
html_content=f"""
|
||||
<h2>Made-For-You Order Failed</h2>
|
||||
<p>An error occurred processing this order:</p>
|
||||
<ul>
|
||||
<li><strong>Customer:</strong> {customer_email}</li>
|
||||
<li><strong>Artist:</strong> {artist}</li>
|
||||
<li><strong>Title:</strong> {title}</li>
|
||||
<li><strong>Error:</strong> {str(e)}</li>
|
||||
</ul>
|
||||
<p>Please manually create this job and notify the customer.</p>
|
||||
""",
|
||||
text_content=f"""
|
||||
Made-For-You Order Failed
|
||||
|
||||
Customer: {customer_email}
|
||||
Artist: {artist}
|
||||
Title: {title}
|
||||
Error: {str(e)}
|
||||
|
||||
Please manually create this job and notify the customer.
|
||||
""".strip(),
|
||||
)
|
||||
except Exception as email_error:
|
||||
logger.error(f"Failed to send error notification: {email_error}")
|
||||
# If we failed before the job was even created, no job exists and the Stripe
|
||||
# session was never marked processed — re-raise so the webhook returns non-2xx
|
||||
# and Stripe retries the (likely transient) failure rather than silently
|
||||
# dropping a paid order. Post-creation failures keep job_id set: those return
|
||||
# normally (job exists, session marked processed, admin already alerted), so a
|
||||
# retry would be a no-op / risk a duplicate job.
|
||||
if job_id is None:
|
||||
raise
|
||||
|
||||
|
||||
@router.post("/webhooks/stripe")
|
||||
@@ -1652,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
|
||||
@@ -1816,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
|
||||
@@ -1852,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,
|
||||
@@ -1872,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,
|
||||
|
||||
+84
-5
@@ -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__)
|
||||
|
||||
@@ -107,15 +112,36 @@ class Settings(BaseSettings):
|
||||
# Models used by the multi-model "compare" mode (semicolon-separated —
|
||||
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
|
||||
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
|
||||
# Proactively generate (and cache) auto-correct suggestions in the lyrics
|
||||
# worker once transcription + references are ready, so the review UI has
|
||||
# them instantly. Best-effort: failures never block or fail the job. Only
|
||||
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
|
||||
# (the lyrics-transcription-job, via ci.yml). Default off.
|
||||
# Proactively generate (and cache) auto-correct suggestions once
|
||||
# transcription + references are ready, so the review UI has them instantly.
|
||||
# This flag gates whether the lyrics worker fires the trigger; the actual
|
||||
# multi-model LLM call + caching runs on the API service (auto_correct_worker),
|
||||
# which holds the model credentials — the lyrics-transcription-job itself does
|
||||
# NOT need ANTHROPIC_API_KEY / AUTO_CORRECT_COMPARE_MODELS. Best-effort:
|
||||
# failures never block or fail the job. Default off.
|
||||
auto_correct_proactive_enabled: bool = os.getenv(
|
||||
"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-FIRST: default off — the verdict is scored and
|
||||
# recorded on every job regardless, so prod shadow data accumulates
|
||||
# alongside human picks; flip on after reviewing it. While off, confident
|
||||
# WITH_BACKING jobs simply go to normal human review (status quo).
|
||||
auto_approval_backing_keep_enabled: bool = os.getenv(
|
||||
"AUTO_APPROVAL_BACKING_KEEP_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Match judge — artist/title formatting + match-acceptance for the job
|
||||
# submission flow. Deterministic + catalog layers always run; the light AI
|
||||
# layer (Vertex Gemini Flash) fires only when those aren't confident.
|
||||
@@ -147,6 +173,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
|
||||
@@ -307,3 +338,51 @@ def get_settings() -> Settings:
|
||||
"""Get the global settings instance."""
|
||||
return settings
|
||||
|
||||
|
||||
def is_production() -> bool:
|
||||
"""True when running in a deployed/production environment.
|
||||
|
||||
Cloud Run automatically sets ``K_SERVICE``, so we treat its presence as
|
||||
production even if ``ENVIRONMENT`` were somehow unset — a production-safe
|
||||
default. Local dev/test have no ``K_SERVICE`` and a non-"production"
|
||||
``ENVIRONMENT``. (Fallback audit 2026-06-09, Theme 7.)
|
||||
"""
|
||||
env = (os.environ.get("ENVIRONMENT") or os.environ.get("ENV") or "").lower()
|
||||
if env == "production":
|
||||
return True
|
||||
return bool(os.environ.get("K_SERVICE"))
|
||||
|
||||
|
||||
# Env vars that MUST be explicitly set in production. A missing one used to
|
||||
# silently fall back to a dev default and produce wrong behaviour with only a
|
||||
# warning (wrong GCP project for secret lookups, wrong GCS bucket, localhost
|
||||
# worker URL). We only require vars that infra confirms are set on every service
|
||||
# (GCS temp/output buckets are intentionally excluded — their defaults are
|
||||
# load-bearing and not set via env). (Fallback audit 2026-06-09, Theme 7.)
|
||||
_REQUIRED_PRODUCTION_ENV_VARS = (
|
||||
"GOOGLE_CLOUD_PROJECT",
|
||||
"GCS_BUCKET_NAME",
|
||||
"CLOUD_RUN_SERVICE_URL",
|
||||
)
|
||||
|
||||
|
||||
def validate_production_config() -> None:
|
||||
"""Fail fast at startup if required production env vars are missing.
|
||||
|
||||
In production each var in ``_REQUIRED_PRODUCTION_ENV_VARS`` must be explicitly
|
||||
set; otherwise the service would silently run with a dev default (wrong GCP
|
||||
project / wrong GCS bucket / localhost worker URL) and appear to work while
|
||||
doing the wrong thing. Raises RuntimeError listing every missing var. No-op
|
||||
outside production. (Fallback audit 2026-06-09, Theme 7.)
|
||||
"""
|
||||
if not is_production():
|
||||
return
|
||||
missing = [v for v in _REQUIRED_PRODUCTION_ENV_VARS if not (os.environ.get(v) or "").strip()]
|
||||
if missing:
|
||||
raise RuntimeError(
|
||||
"Production misconfiguration: required environment variable(s) not set: "
|
||||
+ ", ".join(missing)
|
||||
+ ". Refusing to start with silent dev defaults (wrong GCP project / "
|
||||
"GCS bucket / localhost worker URL)."
|
||||
)
|
||||
|
||||
@@ -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:
|
||||
|
||||
+8
-2
@@ -9,8 +9,8 @@ from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
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, 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
|
||||
@@ -77,6 +77,11 @@ async def lifespan(app: FastAPI):
|
||||
logger.info(f"GCS Bucket: {settings.gcs_bucket_name}")
|
||||
logger.info(f"Tracing enabled: {tracing_enabled}")
|
||||
|
||||
# Fail fast if required production config is missing, rather than silently
|
||||
# running on dev defaults (wrong GCP project / GCS bucket / localhost worker
|
||||
# URL). No-op outside production. (Fallback audit 2026-06-09, Theme 7.)
|
||||
validate_production_config()
|
||||
|
||||
# Preload NLP models and resources to avoid cold start delays
|
||||
# See docs/archive/2026-01-08-performance-investigation.md for background
|
||||
|
||||
@@ -198,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
|
||||
|
||||
@@ -26,9 +26,14 @@ from backend.models.tenant import TenantConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Only allow query param tenant override in non-production environments
|
||||
# Only allow the `?tenant=` query-param override in non-production environments —
|
||||
# in production it is a tenant-spoofing vector. Production-safe by default: Cloud
|
||||
# Run always sets K_SERVICE, so we treat its presence as production even if
|
||||
# ENVIRONMENT were somehow unset (which would otherwise re-enable the override).
|
||||
# (Fallback audit 2026-06-09, Theme 7.)
|
||||
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
|
||||
os.environ.get("ENVIRONMENT", "").lower() == "production"
|
||||
os.environ.get("ENVIRONMENT", "").lower() == "production" or \
|
||||
bool(os.environ.get("K_SERVICE"))
|
||||
|
||||
|
||||
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
|
||||
|
||||
+25
-2
@@ -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,22 @@ 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"
|
||||
|
||||
# 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,6 +567,9 @@ 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"
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
@@ -631,6 +650,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."""
|
||||
|
||||
@@ -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,261 @@
|
||||
"""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 _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,352 @@
|
||||
"""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.models import BackingVerdict, 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
|
||||
|
||||
|
||||
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"`` — so the
|
||||
auto class is lyrics-only and the backing verdict is moot.
|
||||
"""
|
||||
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")
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
keep_backing = (
|
||||
not custom_instrumental
|
||||
and verdict.backing.verdict == BackingVerdict.WITH_BACKING
|
||||
)
|
||||
if not audio_complete:
|
||||
blockers.append("audio_incomplete")
|
||||
elif custom_instrumental:
|
||||
# User-supplied instrumental -> selection is "custom" by
|
||||
# definition; no separated-stem requirements. The video worker
|
||||
# validates the custom source itself.
|
||||
pass
|
||||
elif keep_backing:
|
||||
# Confident-keep (3-stem decider) selects the with-backing
|
||||
# instrumental — gated shadow-first behind its own flag.
|
||||
if not settings.auto_approval_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"):
|
||||
blockers.append("no_clean_stem")
|
||||
|
||||
# Eligibility: with a user-supplied instrumental the backing decision
|
||||
# is moot, so confident lyrics alone qualify; otherwise the narrow
|
||||
# intersection (confident lyrics AND non-subjective backing) applies.
|
||||
if custom_instrumental:
|
||||
eligible = verdict.lyrics.verdict == LyricsVerdict.AUTO
|
||||
enforcement_basis = "lyrics_only_custom_instrumental"
|
||||
else:
|
||||
eligible = verdict.overall_auto
|
||||
enforcement_basis = "overall_auto"
|
||||
|
||||
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,
|
||||
"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: user-supplied instrumental -> "custom"
|
||||
# (mirrors the human tenant complete-review flow); otherwise the
|
||||
# non-subjective backing verdict picks the separated stem — CLEAN
|
||||
# ("no audible backing") -> clean, WITH_BACKING (confident 3-stem
|
||||
# decider keep, flag-gated above) -> with-backing.
|
||||
if custom_instrumental:
|
||||
selection = "custom"
|
||||
else:
|
||||
selection = "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": [...]}``.
|
||||
"""
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if not segments:
|
||||
return {"aborted": "no_segments"}
|
||||
|
||||
from backend.services.auto_approval.apply import (
|
||||
apply_all_suggestions,
|
||||
find_suspicious_duplicates,
|
||||
)
|
||||
|
||||
result = apply_all_suggestions(segments, ai_suggestions)
|
||||
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])}"}
|
||||
|
||||
updated = dict(corrections)
|
||||
updated["corrected_segments"] = new_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,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,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(
|
||||
|
||||
@@ -30,8 +30,13 @@ class DropboxService:
|
||||
"""Load OAuth credentials from Secret Manager."""
|
||||
try:
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
# Try to get the project ID from environment or use default
|
||||
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "karaoke-gen")
|
||||
# Use the configured GCP project. The old default "karaoke-gen" was a
|
||||
# WRONG literal (the real project is "nomadkaraoke"); an unset var
|
||||
# would silently target a non-existent project and disable Dropbox.
|
||||
# Prod always sets GOOGLE_CLOUD_PROJECT (startup validation requires
|
||||
# it), so use an empty default rather than a misleading wrong one.
|
||||
# (Fallback audit 2026-06-09, Theme 7.)
|
||||
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
|
||||
name = f"projects/{project_id}/secrets/dropbox-oauth-credentials/versions/latest"
|
||||
response = client.access_secret_version(request={"name": name})
|
||||
return json.loads(response.payload.data.decode("UTF-8"))
|
||||
|
||||
@@ -138,7 +138,24 @@ async def reconcile_and_maybe_pause(job_id: str) -> bool:
|
||||
user_service = get_user_service()
|
||||
storage = StorageService()
|
||||
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
|
||||
email_service = get_email_service()
|
||||
#
|
||||
# Email is only actually sent on the rare over-limit *cancel* branch. Building
|
||||
# the service must never crash an otherwise-successful download: EmailService()
|
||||
# raises in production when POSTMARK_SERVER_TOKEN is unset (the "fail loudly"
|
||||
# guard from the 2026-06-09 fallback audit), and this worker runs as the
|
||||
# audio-download-job Cloud Run Job. If the provider can't be built, reconcile
|
||||
# still proceeds (reconcile_duration tolerates email_service=None); we log
|
||||
# loudly so a config regression is visible rather than silently dropping a
|
||||
# customer notification. (Job a453d1d5: token missing on the job crashed the
|
||||
# download entirely.)
|
||||
try:
|
||||
email_service = get_email_service()
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"Job %s: could not construct email service for duration reconcile "
|
||||
"(%s); proceeding without customer email notifications", job_id, e,
|
||||
)
|
||||
email_service = None
|
||||
|
||||
result = await asyncio.get_running_loop().run_in_executor(
|
||||
None,
|
||||
|
||||
@@ -10,14 +10,16 @@ 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
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.config import get_settings, is_production
|
||||
from backend.i18n import t, get_locale_prefix
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
@@ -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]:
|
||||
@@ -231,7 +316,7 @@ class EmailService:
|
||||
"""Get the configured email provider.
|
||||
|
||||
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
|
||||
back to console logging (dev/test).
|
||||
back to console logging (dev/test only).
|
||||
"""
|
||||
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
|
||||
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
@@ -241,13 +326,159 @@ class EmailService:
|
||||
logger.info("Using Postmark email provider")
|
||||
return PostmarkEmailProvider(postmark_token, from_email, from_name)
|
||||
|
||||
logger.warning("No email provider configured, using console logging")
|
||||
# In production a missing Postmark token used to silently fall back to
|
||||
# console logging — every send "succeeded" while magic-link/completion/
|
||||
# receipt emails vanished (users can't log in or get downloads). Fail
|
||||
# loudly instead. (Fallback audit 2026-06-09, Theme 7.)
|
||||
if is_production():
|
||||
raise RuntimeError(
|
||||
"POSTMARK_SERVER_TOKEN is not set in production. Refusing to "
|
||||
"silently drop emails via the console provider — set the Postmark "
|
||||
"token secret."
|
||||
)
|
||||
|
||||
logger.warning("No email provider configured, using console logging (dev/test)")
|
||||
return ConsoleEmailProvider()
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
"""Check if a real email provider is configured (not just console logging)."""
|
||||
return isinstance(self.provider, PostmarkEmailProvider)
|
||||
|
||||
def send_email(
|
||||
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,
|
||||
) -> bool:
|
||||
"""Send a raw email via the configured provider.
|
||||
|
||||
Thin passthrough for callers that need to send an ad-hoc/plain email
|
||||
(e.g. internal failure alerts) without a dedicated template method.
|
||||
Prefer a dedicated ``send_*`` template method for customer-facing mail.
|
||||
"""
|
||||
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,
|
||||
text_content=text_content,
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
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,
|
||||
@@ -341,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
|
||||
)
|
||||
|
||||
@@ -414,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:
|
||||
"""
|
||||
@@ -556,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."""
|
||||
@@ -936,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,
|
||||
@@ -1013,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,
|
||||
@@ -1113,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,
|
||||
@@ -1255,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,
|
||||
@@ -1348,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,
|
||||
@@ -1490,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,
|
||||
@@ -1540,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,
|
||||
@@ -1633,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,
|
||||
@@ -1743,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,
|
||||
@@ -1875,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,
|
||||
@@ -1990,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,
|
||||
@@ -2045,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,8 @@ 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,
|
||||
# Distribution settings
|
||||
brand_prefix=job_create.brand_prefix,
|
||||
discord_webhook_url=job_create.discord_webhook_url,
|
||||
@@ -119,6 +121,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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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")
|
||||
@@ -502,8 +502,12 @@ class TestMadeForYouYouTubeErrorHandling:
|
||||
youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that exceptions during processing send failure notification to admin.
|
||||
Test that a job-creation failure sends a failure notification to admin AND
|
||||
re-raises so the Stripe webhook returns non-2xx and Stripe retries the (likely
|
||||
transient) failure — a paid order must not be silently dropped when no job was
|
||||
ever created.
|
||||
"""
|
||||
import pytest
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
# Make job creation fail
|
||||
@@ -516,15 +520,16 @@ class TestMadeForYouYouTubeErrorHandling:
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)):
|
||||
|
||||
# Should not raise - error is handled internally
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_error",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
# Re-raises (job never created) so the webhook returns non-2xx -> Stripe retries
|
||||
with pytest.raises(Exception, match="Database error"):
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_error",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify failure email was sent to admin
|
||||
# Verify failure email was sent to admin before re-raising
|
||||
mock_email_service.send_email.assert_called()
|
||||
call_args = mock_email_service.send_email.call_args
|
||||
assert call_args.kwargs['to_email'] == ADMIN_EMAIL
|
||||
|
||||
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,329 @@
|
||||
"""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"
|
||||
@@ -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,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
|
||||
@@ -258,3 +258,58 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
|
||||
assert "48" not in sent['subject'] and "not confirmed" not in sent['subject'], (
|
||||
f"over_limit email should not say '48 hours'. subject={sent.get('subject')!r}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Regression (job a453d1d5): a failing email-service construction must NOT
|
||||
# crash an otherwise-successful audio download. reconcile_and_maybe_pause runs
|
||||
# in the audio-download-job Cloud Run Job; EmailService() raises in production
|
||||
# when POSTMARK_SERVER_TOKEN is unset. Reconcile must degrade to no-email.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds):
|
||||
"""Patch the function-scoped imports reconcile_and_maybe_pause pulls in.
|
||||
|
||||
These are imported inside the function (to avoid circular imports), so they
|
||||
must be patched at their source modules, not on duration_reconciliation.
|
||||
"""
|
||||
from backend.services import duration_reconciliation as dr
|
||||
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
|
||||
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: us)
|
||||
monkeypatch.setattr("backend.services.storage_service.StorageService", lambda: MagicMock())
|
||||
monkeypatch.setattr(
|
||||
"backend.services.email_service.get_email_service",
|
||||
MagicMock(side_effect=RuntimeError("POSTMARK_SERVER_TOKEN is not set in production")),
|
||||
)
|
||||
monkeypatch.setattr(dr, "_ffprobe_seconds", lambda job, storage: actual_seconds)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_and_maybe_pause_survives_email_service_failure(monkeypatch):
|
||||
from backend.services import duration_reconciliation as dr
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _job(credits_charged=2)
|
||||
# Duration matches estimate → proceed, no email needed anyway.
|
||||
_patch_reconcile_singletons(monkeypatch, jm, MagicMock(), actual_seconds=900.0) # 15min -> 2 credits
|
||||
|
||||
# Must not raise despite email service construction failing.
|
||||
blocked = await dr.reconcile_and_maybe_pause("job1")
|
||||
assert blocked is False # proceeds normally
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_and_maybe_pause_over_limit_still_cancels_without_email(monkeypatch):
|
||||
"""Over-limit cancel must still refund+cancel even if email can't be built."""
|
||||
from backend.services import duration_reconciliation as dr
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _job(credits_charged=2)
|
||||
us = MagicMock()
|
||||
us.add_credits.return_value = (True, 99, "ok")
|
||||
_patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds=4000.0) # >60min
|
||||
|
||||
blocked = await dr.reconcile_and_maybe_pause("job1")
|
||||
assert blocked is True # cancelled
|
||||
jm.cancel_job.assert_called_once()
|
||||
us.add_credits.assert_called_once() # full refund still happens
|
||||
@@ -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,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"
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
Fallback audit (Theme 7): production must fail loudly on missing required config
|
||||
rather than silently running on dev defaults (wrong GCP project / GCS bucket /
|
||||
localhost worker URL / console-only email), and the tenant query-param override
|
||||
must be production-safe by default.
|
||||
"""
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.config import is_production, validate_production_config
|
||||
from backend.services.email_service import EmailService
|
||||
|
||||
|
||||
# ---- is_production() ----
|
||||
|
||||
def test_is_production_via_environment(monkeypatch):
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
assert is_production() is True
|
||||
|
||||
|
||||
def test_is_production_via_k_service(monkeypatch):
|
||||
"""Cloud Run sets K_SERVICE automatically — production-safe even if ENVIRONMENT is unset."""
|
||||
monkeypatch.delenv("ENVIRONMENT", raising=False)
|
||||
monkeypatch.delenv("ENV", raising=False)
|
||||
monkeypatch.setenv("K_SERVICE", "karaoke-api")
|
||||
assert is_production() is True
|
||||
|
||||
|
||||
def test_is_production_false_in_dev(monkeypatch):
|
||||
monkeypatch.delenv("ENVIRONMENT", raising=False)
|
||||
monkeypatch.delenv("ENV", raising=False)
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
assert is_production() is False
|
||||
|
||||
|
||||
# ---- validate_production_config() ----
|
||||
|
||||
def test_validate_raises_when_required_var_missing_in_prod(monkeypatch):
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
|
||||
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
|
||||
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False) # missing!
|
||||
|
||||
with pytest.raises(RuntimeError, match="CLOUD_RUN_SERVICE_URL"):
|
||||
validate_production_config()
|
||||
|
||||
|
||||
def test_validate_passes_when_all_required_set_in_prod(monkeypatch):
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
|
||||
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
|
||||
monkeypatch.setenv("CLOUD_RUN_SERVICE_URL", "https://api.nomadkaraoke.com")
|
||||
|
||||
validate_production_config() # must not raise
|
||||
|
||||
|
||||
def test_validate_noop_in_dev(monkeypatch):
|
||||
monkeypatch.delenv("ENVIRONMENT", raising=False)
|
||||
monkeypatch.delenv("ENV", raising=False)
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False)
|
||||
validate_production_config() # no-op, must not raise
|
||||
|
||||
|
||||
# ---- email provider (7.5) ----
|
||||
|
||||
def test_email_provider_raises_in_prod_without_postmark(monkeypatch):
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
|
||||
with pytest.raises(RuntimeError, match="POSTMARK_SERVER_TOKEN"):
|
||||
EmailService()
|
||||
|
||||
|
||||
def test_email_provider_console_in_dev_without_postmark(monkeypatch):
|
||||
monkeypatch.delenv("ENVIRONMENT", raising=False)
|
||||
monkeypatch.delenv("ENV", raising=False)
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
|
||||
svc = EmailService() # must not raise — console fallback is fine in dev
|
||||
assert svc.is_configured() is False
|
||||
|
||||
|
||||
# ---- tenant gate (7.4) ----
|
||||
|
||||
def test_tenant_gate_production_safe_with_k_service(monkeypatch):
|
||||
"""K_SERVICE present (Cloud Run) → IS_PRODUCTION True → query-param override disabled."""
|
||||
monkeypatch.delenv("ENVIRONMENT", raising=False)
|
||||
monkeypatch.delenv("ENV", raising=False)
|
||||
monkeypatch.setenv("K_SERVICE", "karaoke-api")
|
||||
import backend.middleware.tenant as tenant_mod
|
||||
try:
|
||||
importlib.reload(tenant_mod)
|
||||
assert tenant_mod.IS_PRODUCTION is True
|
||||
finally:
|
||||
# Restore module to a clean (dev) state so other tests aren't affected.
|
||||
monkeypatch.delenv("K_SERVICE", raising=False)
|
||||
importlib.reload(tenant_mod)
|
||||
@@ -266,6 +266,37 @@ class TestMadeForYouOrderConfirmationEmail:
|
||||
assert call_kwargs.get('cc_emails') is None
|
||||
|
||||
|
||||
class TestEmailServiceSendEmailPassthrough:
|
||||
"""Tests for the generic EmailService.send_email passthrough.
|
||||
|
||||
Regression (2026-08-22): the made-for-you failure handler called
|
||||
``email_service.send_email(...)`` but EmailService had no such method (only the
|
||||
provider did), so the failure alert itself crashed with
|
||||
``'EmailService' object has no attribute 'send_email'`` — masking the original
|
||||
error and losing the admin alert entirely.
|
||||
"""
|
||||
|
||||
def test_send_email_delegates_to_provider(self):
|
||||
service = EmailService()
|
||||
service.provider = Mock()
|
||||
service.provider.send_email.return_value = True
|
||||
|
||||
result = service.send_email(
|
||||
to_email="admin@example.com",
|
||||
subject="[FAILED] Test",
|
||||
html_content="<p>oops</p>",
|
||||
text_content="oops",
|
||||
)
|
||||
|
||||
assert result is True
|
||||
service.provider.send_email.assert_called_once()
|
||||
call_kwargs = service.provider.send_email.call_args.kwargs
|
||||
assert call_kwargs["to_email"] == "admin@example.com"
|
||||
assert call_kwargs["subject"] == "[FAILED] Test"
|
||||
assert call_kwargs["html_content"] == "<p>oops</p>"
|
||||
assert call_kwargs["text_content"] == "oops"
|
||||
|
||||
|
||||
class TestMadeForYouAdminNotificationEmail:
|
||||
"""Tests for send_made_for_you_admin_notification method."""
|
||||
|
||||
@@ -1757,6 +1788,179 @@ class TestMadeForYouYouTubeDownloadContract:
|
||||
assert "[FAILED]" in email_call.kwargs.get('subject', ''), \
|
||||
"Error notification email should have [FAILED] in subject"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_download_failure_still_sends_customer_confirmation(
|
||||
self, mock_job_manager, mock_email_service, mock_user_service,
|
||||
mock_theme_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Regression: a YouTube download failure must NOT prevent the paid customer
|
||||
from receiving their order-confirmation email, nor prevent the admin from
|
||||
being alerted.
|
||||
|
||||
Bug context (2026-08-22): Job 17dc6f48 failed on a YouTube bot-check
|
||||
download error. Because the confirmation + admin emails were only sent
|
||||
*after* audio acquisition, the download failure skipped both — Andrew never
|
||||
received the "New Made-For-You Order Received!" notification and there was no
|
||||
guarantee the customer got their confirmation. The confirmation email is now
|
||||
sent up-front, independently of the (fallible) audio acquisition step.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
from backend.services.youtube_download_service import YouTubeDownloadError
|
||||
|
||||
mock_youtube_service = MagicMock()
|
||||
mock_youtube_service.download = AsyncMock(
|
||||
side_effect=YouTubeDownloadError(
|
||||
"Sign in to confirm you're not a bot"
|
||||
)
|
||||
)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
|
||||
# Must not raise - order intake is resilient to audio-acquisition failures
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_123",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# CRITICAL: customer still receives their order confirmation despite the failure
|
||||
mock_email_service.send_made_for_you_order_confirmation.assert_called_once()
|
||||
confirm_kwargs = mock_email_service.send_made_for_you_order_confirmation.call_args.kwargs
|
||||
assert confirm_kwargs['to_email'] == youtube_order_metadata['customer_email']
|
||||
assert confirm_kwargs['job_id'] == "test-job-123"
|
||||
|
||||
# CRITICAL: admin is alerted to the failure so they can intervene manually
|
||||
mock_email_service.send_email.assert_called_once()
|
||||
failure_kwargs = mock_email_service.send_email.call_args.kwargs
|
||||
assert failure_kwargs['to_email'] == ADMIN_EMAIL
|
||||
assert "[FAILED]" in failure_kwargs['subject']
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_customer_confirmation_email_failure_does_not_abort_order(
|
||||
self, mock_job_manager, mock_email_service, mock_user_service,
|
||||
mock_theme_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Resilience: if the customer confirmation email itself fails to send, order
|
||||
processing (audio acquisition + admin notification) must still proceed, and the
|
||||
failed confirmation must be escalated to the admin (never silently lost). An
|
||||
email-provider hiccup should never block the actual work.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
# Confirmation email raises, but the order must still be processed
|
||||
mock_email_service.send_made_for_you_order_confirmation.side_effect = \
|
||||
RuntimeError("Postmark timeout")
|
||||
|
||||
# start_job_processing is async - mock it so the success path completes
|
||||
mock_job_manager.start_job_processing = AsyncMock()
|
||||
|
||||
mock_youtube_service = MagicMock()
|
||||
mock_youtube_service.download = AsyncMock(
|
||||
return_value="uploads/test-job-123/audio/test.webm"
|
||||
)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
|
||||
# Must not raise despite the confirmation email failure
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_123",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Download still happened and admin notification still sent
|
||||
mock_youtube_service.download.assert_called_once()
|
||||
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
|
||||
# The failed customer confirmation is escalated to the admin so it can be
|
||||
# resent manually — a paid confirmation must never be silently lost.
|
||||
mock_email_service.send_email.assert_called_once()
|
||||
alert_kwargs = mock_email_service.send_email.call_args.kwargs
|
||||
assert alert_kwargs['to_email'] == ADMIN_EMAIL
|
||||
assert "[FAILED]" in alert_kwargs['subject']
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_confirmation_provider_rejection_is_escalated(
|
||||
self, mock_job_manager, mock_email_service, mock_user_service,
|
||||
mock_theme_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Providers return False (not an exception) when a send is rejected. A rejected
|
||||
customer confirmation must be escalated to the admin, not silently logged as
|
||||
sent. Regression guard for the "log success even on False" bug.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
# Provider rejects the confirmation (returns False, does not raise)
|
||||
mock_email_service.send_made_for_you_order_confirmation.return_value = False
|
||||
mock_job_manager.start_job_processing = AsyncMock()
|
||||
|
||||
mock_youtube_service = MagicMock()
|
||||
mock_youtube_service.download = AsyncMock(
|
||||
return_value="uploads/test-job-123/audio/test.webm"
|
||||
)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_123",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Rejected confirmation escalated to admin; order still processed
|
||||
mock_email_service.send_email.assert_called_once()
|
||||
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
|
||||
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_creation_failure_reraises_for_stripe_retry(
|
||||
self, mock_email_service, mock_user_service, mock_theme_service,
|
||||
youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
If job creation fails (no job_id, session never marked processed), the handler
|
||||
must re-raise so the Stripe webhook returns non-2xx and Stripe retries — a paid
|
||||
order must not be silently dropped. The admin is still alerted first.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.create_job.side_effect = RuntimeError("Firestore unavailable")
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service):
|
||||
|
||||
with pytest.raises(RuntimeError, match="Firestore unavailable"):
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_123",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Admin alerted before the re-raise; no confirmation (job never created)
|
||||
mock_email_service.send_email.assert_called_once()
|
||||
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
|
||||
mock_email_service.send_made_for_you_order_confirmation.assert_not_called()
|
||||
|
||||
|
||||
class TestMadeForYouYouTubeImports:
|
||||
"""
|
||||
|
||||
@@ -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,221 @@ 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
|
||||
@@ -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
|
||||
@@ -360,6 +360,19 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
# This will check if lyrics are also complete and transition to next stage if so
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
|
||||
# Auto-approval second chance: when lyrics/screens finished BEFORE
|
||||
# audio, the job is already parked in AWAITING_REVIEW and the
|
||||
# screens-worker scoring ran without backing analysis. Now that
|
||||
# stems + analysis exist, re-score and auto-complete the review if
|
||||
# fully confident. No-op (fail-safe) in every other state.
|
||||
try:
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
auto_result = await maybe_auto_complete_review(job_id, trigger="audio_worker")
|
||||
if auto_result.get("outcome") == "auto_completed":
|
||||
job_log.info("Auto-approved after audio completion: review skipped")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] auto-approval attempt failed (non-fatal): {e}")
|
||||
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
|
||||
return True
|
||||
|
||||
@@ -70,6 +70,9 @@ async def process_proactive_auto_correct(job_id: str) -> dict:
|
||||
# Must match what the review UI sends (default settings,
|
||||
# multi-model) or the cache key won't line up.
|
||||
settings=AutoCorrectSettings(compare_models=True),
|
||||
# Already loaded — saves the service re-fetching it for the
|
||||
# deterministic (P4/P5) generators.
|
||||
correction_data=data,
|
||||
),
|
||||
timeout=180,
|
||||
)
|
||||
|
||||
@@ -209,14 +209,28 @@ async def generate_screens(job_id: str) -> bool:
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
else:
|
||||
# Normal flow: transition to combined review
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message="Ready for review. Please review lyrics and select your instrumental."
|
||||
)
|
||||
# Auto-approval: score the job (verdict always recorded in
|
||||
# processing_metadata.auto_approval) and, when fully confident
|
||||
# and eligible, complete the review here — skipping the
|
||||
# AWAITING_REVIEW state (and its notifications) entirely.
|
||||
# Fail-safe: anything short of confident falls through to
|
||||
# normal human review.
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
with job_span("auto-approval", job_id):
|
||||
auto_result = await maybe_auto_complete_review(job_id, trigger="screens_worker")
|
||||
|
||||
if auto_result.get("outcome") == "auto_completed":
|
||||
job_log.info("Auto-approved: review screens skipped, render triggered")
|
||||
logger.info(f"[job:{job_id}] Auto-approved — review skipped")
|
||||
else:
|
||||
# Normal flow: transition to combined review
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message="Ready for review. Please review lyrics and select your instrumental."
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
# Store worker-level timing
|
||||
@@ -561,7 +575,8 @@ async def _analyze_backing_vocals(
|
||||
return
|
||||
|
||||
# Get backing vocals path
|
||||
backing_vocals_path = job.file_urls.get('stems', {}).get('backing_vocals')
|
||||
stems = job.file_urls.get('stems', {})
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
if not backing_vocals_path:
|
||||
job_log.warning("No backing vocals file found - skipping analysis")
|
||||
return
|
||||
@@ -574,11 +589,16 @@ async def _analyze_backing_vocals(
|
||||
# Define output path for waveform
|
||||
waveform_gcs_path = f"jobs/{job_id}/analysis/backing_vocals_waveform.png"
|
||||
|
||||
# Run analysis and generate waveform
|
||||
result, waveform_path = analysis_service.analyze_and_generate_waveform(
|
||||
# Run analysis and generate waveform. Passing the lead + full-vocals
|
||||
# stems as well enables the 3-stem comparison the backing-vocals
|
||||
# decider uses to tell genuine harmonies from lead bleed / a
|
||||
# misclassified lead / flat noise (best-effort — None when missing).
|
||||
result, waveform_path, stem_comparison = analysis_service.analyze_and_generate_waveform(
|
||||
gcs_audio_path=backing_vocals_path,
|
||||
job_id=job_id,
|
||||
gcs_waveform_destination=waveform_gcs_path,
|
||||
gcs_lead_vocals_path=stems.get('lead_vocals'),
|
||||
gcs_vocals_path=stems.get('vocals_clean'),
|
||||
)
|
||||
|
||||
# Store analysis results in job state_data
|
||||
@@ -600,6 +620,8 @@ async def _analyze_backing_vocals(
|
||||
'audible_percentage': result.audible_percentage,
|
||||
'silence_threshold_db': result.silence_threshold_db,
|
||||
}
|
||||
if stem_comparison is not None:
|
||||
analysis_data['stem_comparison'] = stem_comparison
|
||||
|
||||
job_manager.update_state_data(job_id, 'backing_vocals_analysis', analysis_data)
|
||||
|
||||
|
||||
+136
-4
@@ -213,6 +213,17 @@ Content-Type: application/json
|
||||
|
||||
Triggers async processing.
|
||||
|
||||
**Optional fields:**
|
||||
- `upload_mode`: `"signed_put"` (default) or `"resumable"`. With `"resumable"`, each
|
||||
`upload_urls` entry has `resumable: true` and `upload_url` is a **GCS resumable session
|
||||
URI** — upload in 256KiB-aligned chunks with `Content-Range` headers, query the persisted
|
||||
offset after an interruption (`PUT` with `Content-Range: bytes */<total>` → `308` +
|
||||
`Range` header), and resume mid-file. Sessions are created with the caller's `Origin` so
|
||||
GCS answers session CORS itself. Used by the tenant bulk-upload flow
|
||||
(`frontend/lib/resumable-upload.ts`).
|
||||
- `batch_id`: groups jobs created together in one bulk batch — stamped into
|
||||
`state_data.batch_id` with `created_from: "tenant-bulk"`.
|
||||
|
||||
#### Get Job Status
|
||||
|
||||
```http
|
||||
@@ -285,6 +296,15 @@ Response:
|
||||
|
||||
The combined review flow allows users to review lyrics AND select instrumental track in a single session.
|
||||
|
||||
**Auto-approval:** jobs default to `review_mode="auto"` — when the auto-approval scorer is fully
|
||||
confident (lyrics verified against a synced reference with every gap covered by the auto-applied
|
||||
AI suggestions, AND no audible backing vocals), the review screens are skipped entirely: the AI
|
||||
suggestions are applied server-side, the clean instrumental is selected, and the job goes
|
||||
straight to render. All other jobs stop at review as before. The verdict for every job is
|
||||
recorded in `processing_metadata.auto_approval` (fields: `mode`, `outcome`, per-axis verdicts +
|
||||
signals). Set `review_mode="always_review"` (admin job PATCH) to force the review screens;
|
||||
global kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false`.
|
||||
|
||||
#### Get Correction Data
|
||||
|
||||
```http
|
||||
@@ -544,13 +564,25 @@ Content-Type: application/json
|
||||
{
|
||||
"source": "manual",
|
||||
"lyrics": "Full lyrics text...",
|
||||
"force": false
|
||||
"force": "false"
|
||||
}
|
||||
```
|
||||
|
||||
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
|
||||
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`, sent as a string because the body is typed `Dict[str, str]`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
|
||||
|
||||
Returns `{ "status": "success", "data": <CorrectionData> }`.
|
||||
Returns `{ "status": "success", "data": <CorrectionData> }` when the source is kept.
|
||||
|
||||
If the relevance filter drops the source (below the 30% anchor-match threshold), the corrections are **not** persisted and the response is instead:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "rejected",
|
||||
"rejection": { "relevance": 0.013, "matched_words": 3, "total_words": 230 },
|
||||
"data": { "...": "CorrectionData from the discarded rerun" }
|
||||
}
|
||||
```
|
||||
|
||||
The frontend paste tab shows the match % and offers "Add Anyway", which retries with `force: "true"`.
|
||||
|
||||
#### AI Auto-Correct Suggestions
|
||||
|
||||
@@ -1132,6 +1164,41 @@ Serves tenant assets (logos, etc.) from GCS. No authentication required. Returns
|
||||
|
||||
Used by the frontend `TenantLogo` component to load tenant logos. Tenant configs store logo paths as `https://api.nomadkaraoke.com/api/tenant/asset/{tenant_id}/logo.png` (the frontend also converts legacy `gs://` paths to this format as a fallback).
|
||||
|
||||
#### Tenant Bulk Upload — Filename Analysis
|
||||
|
||||
```http
|
||||
POST /api/tenant/bulk/analyze
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer <tenant session token>
|
||||
|
||||
{"filenames": ["S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3", "S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3", "cover.png"]}
|
||||
```
|
||||
|
||||
Analyses a flat list of filenames (from a browser folder pick) into proposed karaoke jobs:
|
||||
pairs each **Mixed** (with-vocals) file with its **Instrumental** counterpart and extracts
|
||||
Artist/Title. Pure analysis — filenames only, no uploads, no state written.
|
||||
|
||||
- **Auth:** tenant session required; gated on the tenant's `features.bulk_upload` flag (403 otherwise).
|
||||
- **Limits:** max 100 audio files per request (non-audio files don't count toward the cap; 2000-filename payload guard).
|
||||
- **Two passes:** deterministic regex for the `S<code>-<1|2> Artist - Title <Guide|BV|Instru>`
|
||||
convention, then a Vertex-Gemini pass (`backend/services/tenant_bulk/analyze.py`) for
|
||||
whatever the regex couldn't confidently pair. Falls back to regex-only if the model errors.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"rows": [{"artist": "Eddy Grant", "title": "I Don't Wanna Dance",
|
||||
"mixed_filename": "…Guide.mp3", "instrumental_filename": "…BV.mp3",
|
||||
"confidence": "high", "warning": null}],
|
||||
"unpaired": [{"filename": "…", "reason": "no_instrumental", "artist": "…", "title": "…", "role": "mixed"}],
|
||||
"ignored": [{"filename": "cover.png", "reason": "non_audio"}]
|
||||
}
|
||||
```
|
||||
|
||||
The tenant portal's Bulk mode (`TenantBulkFlow.tsx`) renders these rows as an editable review
|
||||
table, then submits each confirmed row through the standard signed-URL upload flow
|
||||
(`upload_mode: "resumable"`, `batch_id` grouping).
|
||||
|
||||
### Internal (Admin Only)
|
||||
|
||||
These endpoints are used by workers and require admin tokens.
|
||||
@@ -1504,10 +1571,70 @@ Authorization: Bearer ADMIN_TOKEN
|
||||
|
||||
Returns full user profile including:
|
||||
- User info and stats
|
||||
- `locale` (email locale: en/es/de) and `ui_locale` (full UI language, any of 33)
|
||||
- Recent credit transactions (last 20)
|
||||
- Recent jobs (last 10)
|
||||
- Recent jobs (last 10, each with its `locale`)
|
||||
- Active sessions count
|
||||
|
||||
### Email History (Admin)
|
||||
|
||||
List every email ever sent to a user, then fetch one for full-fidelity preview.
|
||||
Merges the Postmark Messages API (last ~45 days, with delivery metadata) with a
|
||||
persisted Firestore `email_log` (permanent), de-duplicated by message id.
|
||||
|
||||
```http
|
||||
GET /api/admin/users/{email}/emails
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Response: `{ email, count, postmark_available, emails: [{ message_id, source,
|
||||
subject, to, from_email, sent_at, status, email_type, has_stored_html }] }`.
|
||||
|
||||
```http
|
||||
GET /api/admin/emails/{message_id}?source=postmark
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
`source` is `postmark` (default; falls back to the stored log on 404/expiry) or
|
||||
`log` (read the persisted copy directly). Returns the full rendered `html_body`,
|
||||
`text_body`, addressing, `status`, `delivered_at`, `open_count`, `click_count`,
|
||||
`bounce`, and the raw `events`.
|
||||
|
||||
### Create User (Admin)
|
||||
|
||||
Create a user account directly — e.g. to grant credits, submit jobs on behalf of,
|
||||
or impersonate someone who has never logged in. The user can later log in normally
|
||||
via magic link with the same email.
|
||||
|
||||
```http
|
||||
POST /api/users/admin/users
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "user@example.com",
|
||||
"display_name": "Optional Name",
|
||||
"initial_credits": 3,
|
||||
"credit_reason": "made-for-you order"
|
||||
}
|
||||
```
|
||||
|
||||
Response (201):
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"email": "user@example.com",
|
||||
"credits": 3,
|
||||
"message": "Created user user@example.com with 3 credit(s)"
|
||||
}
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `display_name`, `initial_credits` (0-1000), and `credit_reason` are optional
|
||||
- If `initial_credits` > 0, `welcome_credits_granted` is set so the user does NOT
|
||||
also receive the automatic welcome credit on first login
|
||||
- Returns 409 if the user already exists
|
||||
|
||||
### Add Credits (Admin)
|
||||
|
||||
```http
|
||||
@@ -1783,6 +1910,11 @@ Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `t
|
||||
|
||||
**Note:** Setting `is_private=true` on a completed job with existing outputs triggers automatic output deletion.
|
||||
|
||||
**Note:** `user_email` is trimmed and lowercased before saving. If no account exists
|
||||
for that email, one is auto-created (so the recipient can log in and see the job,
|
||||
and the admin can impersonate them immediately). The response message notes when
|
||||
an account was created.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
|
||||
+15
-3
@@ -1,5 +1,10 @@
|
||||
# Development Guide
|
||||
|
||||
> **External contributor?** See [CONTRIBUTING.md](../CONTRIBUTING.md) at the repo
|
||||
> root — the backend runs fully locally against emulators with **no GCP
|
||||
> credentials or paid API keys**. This file covers the full setup including
|
||||
> production/deployment concerns.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
@@ -24,9 +29,9 @@ source venv/bin/activate
|
||||
# Install dependencies
|
||||
poetry install
|
||||
|
||||
# Copy environment template
|
||||
# Optional: copy environment template for API keys / overrides
|
||||
# (nothing in it is required to run locally with emulators)
|
||||
cp .env.example .env
|
||||
# Edit .env with required API keys
|
||||
```
|
||||
|
||||
### Frontend Setup
|
||||
@@ -43,13 +48,20 @@ cp .env.example .env.local
|
||||
### Backend with Emulators
|
||||
|
||||
```bash
|
||||
# Start emulators and backend
|
||||
# Start emulators, create the bucket, seed a default theme, run the backend
|
||||
./scripts/run-backend-local.sh --with-emulators
|
||||
|
||||
# Backend runs at http://localhost:8000
|
||||
# API docs at http://localhost:8000/docs
|
||||
```
|
||||
|
||||
In emulator mode no GCP credentials are needed: workers run as local
|
||||
subprocesses, signed URLs are rewritten to emulator URLs, and magic-link
|
||||
login emails are printed to the console. Jobs must be created via **file
|
||||
upload** (URL jobs require the flacfetch cloud service). Set `MODEL_DIR` to
|
||||
enable local audio separation. See [CONTRIBUTING.md](../CONTRIBUTING.md) for
|
||||
the full walkthrough.
|
||||
|
||||
### Frontend
|
||||
|
||||
```bash
|
||||
|
||||
+110
-2
@@ -14,6 +14,7 @@
|
||||
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
|
||||
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
|
||||
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
|
||||
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 24h |
|
||||
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
|
||||
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
|
||||
| AWS credentials (offline) | KeepassXC — "Nomad Karaoke — DR backup AWS access" | Manual lookup | On-change |
|
||||
@@ -24,6 +25,7 @@
|
||||
- [ ] KeepassXC contains "Nomad Karaoke — DR backup AWS access" (access key, secret key, region, S3 bucket name)
|
||||
- [ ] KeepassXC contains "Nomad Karaoke — DR backup decryption key" (Curve25519 private key, 64 hex chars)
|
||||
- [ ] GitHub repo `nomadkaraoke/karaoke-gen` has the secrets `AWS_BACKUP_READONLY_ACCESS_KEY_ID`, `AWS_BACKUP_READONLY_SECRET_ACCESS_KEY`, `DR_MONITOR_DISCORD_WEBHOOK` configured (powers the freshness monitor)
|
||||
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the nightly job can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
|
||||
- [ ] You can decrypt yesterday's secrets backup locally (run the drill in § "Quarterly restore drill")
|
||||
- [ ] Your KeepassXC database itself is backed up off-machine (cloud sync, second device, or printed paper recovery)
|
||||
|
||||
@@ -301,6 +303,112 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
|
||||
- Discord webhook URLs (re-issue if old GCP exposure could have leaked them)
|
||||
- Cloudflare API tokens (rotate)
|
||||
|
||||
## Scenario 3: Loss of GitHub access (account ban / repo takedown)
|
||||
|
||||
If the GitHub account is suspended (e.g. an automated copyright false-positive)
|
||||
or repos are taken down, **the code and its full history are still in S3**. The
|
||||
nightly backup bundles every repo under `github.com/nomadkaraoke` and
|
||||
`github.com/beveradb` into a single `git bundle` per repo — a self-contained
|
||||
file you can clone from directly, no GitHub required. GCP is unaffected, so
|
||||
production keeps running; this is purely about recovering the source of truth to
|
||||
a new home.
|
||||
|
||||
### What's backed up
|
||||
|
||||
- `s3://nomadkaraoke-backup/git-repos/{owner}/{repo}.bundle` — one bundle per
|
||||
repo, containing **all branches and tags** (entire reachable history).
|
||||
- `s3://nomadkaraoke-backup/git-repos/manifest.json` — inventory of every repo
|
||||
at backup time: visibility, default branch, description, size, fork/archived
|
||||
flags, and per-repo backup status. Use it to know exactly what existed and to
|
||||
recreate repo settings on the new host.
|
||||
|
||||
Forks are excluded by default (recoverable from upstream). Repos are only as
|
||||
fresh as the last nightly run (24h RPO).
|
||||
|
||||
### Restore
|
||||
|
||||
```bash
|
||||
# 1. Set AWS creds (see § "Setting AWS creds locally") and pull the bundles.
|
||||
aws s3 sync s3://nomadkaraoke-backup/git-repos/ /tmp/git-repos/
|
||||
|
||||
# 2. Review the inventory — what existed, and did every repo back up cleanly?
|
||||
jq '{total, bundled, errors, skipped, repos: [.repos[] | {full_name, status, default_branch, private}]}' \
|
||||
/tmp/git-repos/manifest.json
|
||||
|
||||
# 3. Reconstruct the repo from any bundle. Use --mirror so EVERY branch and tag
|
||||
# is restored as a real ref — a plain `git clone` keeps non-default branches
|
||||
# only as remote-tracking refs, and `git push --all` would then omit them.
|
||||
cd /tmp/git-repos/nomadkaraoke
|
||||
git clone --mirror karaoke-gen.bundle karaoke-gen.git
|
||||
cd karaoke-gen.git
|
||||
git show-ref # every branch + tag is present as a real ref
|
||||
|
||||
# 4. Point it at a new remote and push everything (--mirror pushes all refs).
|
||||
# New home options: a fresh GitHub org/account, GitLab, Codeberg, or a
|
||||
# self-hosted Gitea. Create the empty repo there first, then:
|
||||
git remote set-url origin <NEW_REMOTE_URL> # bare mirror already has 'origin'
|
||||
git push --mirror origin
|
||||
# (For a normal working clone afterwards: `git clone <NEW_REMOTE_URL>`.)
|
||||
```
|
||||
|
||||
To restore *all* repos in one pass:
|
||||
|
||||
```bash
|
||||
cd /tmp/git-repos
|
||||
for owner in */; do
|
||||
for bundle in "$owner"*.bundle; do
|
||||
name=$(basename "$bundle" .bundle)
|
||||
# --mirror preserves all branches/tags; `git clone` creates leading dirs.
|
||||
git clone --mirror "$bundle" "restored/${owner}${name}.git"
|
||||
# then: cd in, `git remote set-url origin <NEW_URL>`, `git push --mirror origin`
|
||||
done
|
||||
done
|
||||
```
|
||||
|
||||
**Verify a bundle without cloning:** `git bundle verify /tmp/git-repos/nomadkaraoke/karaoke-gen.bundle`.
|
||||
|
||||
### After restore — repoint tooling
|
||||
|
||||
The DR runbook, CI, `poetry`/`pip` VCS deps, and cross-repo scripts reference
|
||||
`github.com/nomadkaraoke/...` URLs. Once repos live at a new host, update:
|
||||
|
||||
- Git remotes in every local clone / worktree
|
||||
- CI/CD config that clones sibling repos (e.g. `flacfetch` in `karaoke-gen`)
|
||||
- Any `poetry`/`pip` dependency pinned to a GitHub URL
|
||||
- Webhooks / deploy keys / Actions secrets on the new host
|
||||
- `GIT_BACKUP_OWNERS` + the `github-backup-token` PAT so the nightly backup keeps
|
||||
bundling from the new location
|
||||
|
||||
## Git repo backup setup
|
||||
|
||||
One-time setup so the nightly job can bundle private repos:
|
||||
|
||||
1. Create a GitHub PAT owned by **beveradb** (a member of the `nomadkaraoke` org):
|
||||
- **Classic PAT:** scopes `repo` (full, to read private repos) + `read:org`
|
||||
(to enumerate org repos). Simplest.
|
||||
- **Fine-grained PAT:** resource owner = beveradb *and* a second token for the
|
||||
nomadkaraoke org (fine-grained tokens are single-owner); grant
|
||||
`Contents: Read-only` + `Metadata: Read-only`. Classic is easier here.
|
||||
2. Store it in Secret Manager (value added manually — Pulumi only creates the
|
||||
empty secret resource):
|
||||
```bash
|
||||
printf %s '<PAT>' | gcloud secrets versions add github-backup-token \
|
||||
--data-file=- --project=nomadkaraoke
|
||||
```
|
||||
Also keep a copy in KeepassXC as "Nomad Karaoke — DR GitHub backup PAT".
|
||||
3. The owners backed up are set by the `GIT_BACKUP_OWNERS` env var on the
|
||||
`backup-to-aws` function (default `nomadkaraoke,beveradb`), wired in
|
||||
`infrastructure/modules/backup.py`.
|
||||
4. Trigger a run and confirm bundles appear:
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
|
||||
https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws
|
||||
aws s3 ls s3://nomadkaraoke-backup/git-repos/ --recursive | head
|
||||
```
|
||||
|
||||
If the PAT is missing/expired the git-repo step logs a warning and skips; the
|
||||
freshness monitor then flags `git-repos/` as stale within ~36h.
|
||||
|
||||
## Decrypting the secrets backup
|
||||
|
||||
```bash
|
||||
@@ -341,13 +449,13 @@ export AWS_DEFAULT_REGION=us-east-1
|
||||
|
||||
## Backup freshness monitor
|
||||
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, and `bigquery/daily-refresh/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
|
||||
|
||||
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
|
||||
|
||||
| Prefix | S3 upload cadence | Monitor limit |
|
||||
|--------|-------------------|---------------|
|
||||
| `gcs/job-files/`, `secrets/` | nightly | 36h |
|
||||
| `gcs/job-files/`, `secrets/`, `git-repos/` | nightly | 36h |
|
||||
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
|
||||
|
||||
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
|
||||
|
||||
@@ -1025,6 +1025,41 @@ All status transitions after workers complete fail silently because they're inva
|
||||
- `test_youtube_url_calls_start_job_processing_after_download` - verifies proper sequence
|
||||
- `TestInvalidStateTransitionError`, `TestValidateStateTransitionRaisesBehavior`, `TestStartJobProcessing` in `test_job_manager.py`
|
||||
|
||||
### Made-For-You Order Emails Must Be Isolated From Audio Acquisition (Aug 2026)
|
||||
|
||||
**Problem**: Job 17dc6f48 (made_for_you order) failed on a YouTube "confirm you're
|
||||
not a bot" download error, and the admin never received the "New Made-For-You Order
|
||||
Received!" email. The error-fallback then crashed with
|
||||
`'EmailService' object has no attribute 'send_email'`, so even the failure alert was lost.
|
||||
|
||||
**Root cause**: In `_handle_made_for_you_order`, both the customer order-confirmation
|
||||
and the admin notification were sent *after* the fallible audio-acquisition step
|
||||
(YouTube download / audio search). When acquisition raised, execution jumped straight
|
||||
to the outer `except`, skipping BOTH emails. Separately, the fallback called
|
||||
`email_service.send_email(...)` — a method that only existed on the *provider*
|
||||
(`self.provider.send_email`), never on `EmailService` itself.
|
||||
|
||||
**Fix**:
|
||||
1. Send the customer order-confirmation email **up-front**, right after job creation and
|
||||
*before* audio acquisition — the order is paid/confirmed regardless of whether the
|
||||
download or search succeeds. Wrapped so an email error is logged, not fatal.
|
||||
2. Wrap the admin notification so an email hiccup on a successful order can't fake a
|
||||
`[FAILED]` alert.
|
||||
3. Route the outer failure handler through `_send_mfy_failure_alert()` (never raises,
|
||||
HTML-escapes user input, tolerates `job_id=None`): success → normal admin
|
||||
notification; acquisition failure → `[FAILED]` admin alert while the customer is
|
||||
still confirmed.
|
||||
4. Add a thin `EmailService.send_email()` passthrough to the provider so ad-hoc/plain
|
||||
emails (like the failure alert) work.
|
||||
|
||||
**Why tests didn't catch it**: `email_service` was a `MagicMock` in the handler tests,
|
||||
so `mock.send_email(...)` auto-created the attribute and never surfaced the real
|
||||
`AttributeError`. **Pattern**: for critical fallbacks, add at least one test that
|
||||
exercises the real `EmailService` (only mocking `.provider`), and assert that a failure
|
||||
in a *later* step (audio) does not suppress *earlier* side effects (the confirmation
|
||||
email). Idempotency note: mark the Stripe session processed *before* sending the
|
||||
confirmation so a webhook retry can't double-send.
|
||||
|
||||
### Use data-testid for E2E
|
||||
Prefer `data-testid` over label/text selectors. They're immune to label changes and won't break when similar fields are added.
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
| Auto-correction (agentic + heuristic) | Disabled (raw transcription goes to human review) |
|
||||
| **AI auto-correct suggestions (opt-in)** | Working ("AI Suggest" button in lyrics review — whole-song LLM call, per-suggestion accept/reject) |
|
||||
| Combined review (lyrics + instrumental) | Working |
|
||||
| **Auto-approval (fully-auto review)** | Live (default `review_mode="auto"`): when the scorer is fully confident (synced-reference lyrics with all gaps AI-covered + no audible backing vocals), the review screens are skipped and the job renders straight through; every other job falls back to human review. Verdict on every job in `processing_metadata.auto_approval`. Kill switch `AUTO_APPROVAL_ENFORCE_ENABLED=false`; per-job `review_mode="always_review"` (admin-editable). See `docs/archive/2026-08-25-full-auto-review-design.md` |
|
||||
| **Review replay tool (admin)** | Working (`?replay=1` read-only replay of completed jobs — see `docs/REPLAY.md`) |
|
||||
| Preview video generation | Working |
|
||||
| Multi-format encoding | Working |
|
||||
| Token-based auth | Working |
|
||||
@@ -55,6 +57,10 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Admin Dashboard Stats 18s → ~1s** (2026-08-23): `GET /api/admin/stats/overview?exclude_test=true` streamed every user and job document **in full** to filter test data in Python — ~110 MB across 658 jobs (job docs carry `state_data`/timeline payloads), ~18s per dashboard load. Worse, the sync streaming ran inside an async route, blocking the event loop so every other request on the instance (`/me`, `/config`, payments summary) stalled behind it. **Fix**: Firestore `.select()` field masks on all three streams (jobs need only `user_email`/`created_at`/`status`; measured 15.0s → 1.1s for the jobs stream) and the whole computation now runs via `asyncio.to_thread()` so it can't stall other requests. Unit tests assert the field masks stay in place. Same sync-over-async trap as the Feb 2026 audio-search fix — see [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
|
||||
|
||||
- **Admin UI/UX Overhaul** (2026-08-22): Made the admin pages usable on mobile and fixed the long-standing overflow problems on the job detail page (v0.197.0). Long status timelines (retried/edited jobs) now collapse to the last 6 stages behind a "+N earlier (M failed)" expander; the Source field no longer bleeds across the info grid (CSS grid `min-w-0`); the Audio Source Details modal got wrap-safe stacked rows plus an "Open in YouTube/Spotify" link built from provider + source ID; Configuration fields are click-to-edit with always-visible pencils. The jobs list search box jumps straight to a job when given a job ID, and the status filter is URL-synced (`/admin/jobs?status=failed`), which the dashboard's now-clickable stat cards and status-breakdown rows link into. Also fixed a real crash: the "Trigger Now" button in the reset-result dialog referenced a deleted handler. Users list/detail, breadcrumbs, and the admin header are all responsive down to phone widths. 4 new e2e tests.
|
||||
|
||||
- **Portrait (9:16) Karaoke Video Output** (2026-07-13): When enabled (`PORTRAIT_RENDER_ENABLED`, default on), every finalised job also gets a portrait 1080×1920 karaoke video for phone viewing / social sharing, distributed to **GCS + the Dropbox brand-code folder only** (never Drive/YouTube). It is a genuine **re-render** at portrait resolution with re-wrapped lyrics — not a transform of the finished landscape video (letterbox = tiny lyrics, crop = cuts the ends off every line; proven in the design experiments). The new `karaoke_gen/portrait/` module reuses the same `SubtitlesGenerator` engine + corrected-lyrics data, so word-by-word timing is identical; it adds an orphan-merging wrapper, a branded portrait background (wordmark/header + song/artist + footer), and title/end cards. Rendered on the GCE encoder inside `run_encoding` (best-effort + `PORTRAIT_RENDER_ENABLED` flag; a failure never fails the job) and carried to Dropbox via the existing `finals/` upload path. ~15–30s + ~10 MB per job. See [archive/2026-06-14-portrait-video-design.md](archive/2026-06-14-portrait-video-design.md) and [archive/2026-07-13-portrait-video-plan.md](archive/2026-07-13-portrait-video-plan.md).
|
||||
|
||||
- **Cloudflare Edge Security for the Backend API** (2026-07-20): `api.nomadkaraoke.com` is now proxied through Cloudflare (WAF + rate limiting + origin lock), after a vuln-scanner hammered the previously directly-exposed Cloud Run origin. WAF blocks exploit/secret-exposure paths (`contains` operator — regex needs a Business plan); per-IP rate limiting excludes `/api/internal/*`; a Transform Rule injects a secret `X-Edge-Auth` header that the backend's `EdgeAuthMiddleware` (`EDGE_AUTH_MODE=enforce`) requires, blocking direct-to-`*.run.app` bypass (health/root exempt). Key finding: the Cloud Run managed cert can't provision behind Cloudflare, but zone SSL mode "full" (not strict) doesn't validate the origin cert, so it works and is renewal-safe — **never switch the zone to "full (strict)".** Managed as IaC in `infrastructure/modules/edge_security.py`. Also retuned the "High Error Rate" alert to 5xx-only (scanner 404s no longer page). See [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare), [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloudflare-edge-in-front-of-cloud-run--the-ssl-dragon-jul-2026), and [archive/2026-07-20-edge-security-cutover-runbook.md](archive/2026-07-20-edge-security-cutover-runbook.md).
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Review Replay (read-only re-open of completed jobs)
|
||||
|
||||
Re-open the **real** lyrics-review and instrumental-selection UIs for a job that's
|
||||
already **completed**, with full audio playback + backing-vocals previews (streamed
|
||||
from GCS), plus a side panel showing your ordered actions (AI-accept / AI-reject /
|
||||
manual / timing) from the stored edit log.
|
||||
|
||||
Built for the fully-automated-review recording program — see
|
||||
`docs/archive/2026-08-25-full-auto-review-design.md`.
|
||||
|
||||
## What it is
|
||||
|
||||
- Backend `GET /api/review/{job_id}/correction-data?replay=true` (admin/owner only):
|
||||
serves the same payload for a job in **any** status — skips the
|
||||
AWAITING_REVIEW/IN_REVIEW gate and the status-transition side-effect, and attaches
|
||||
the reviewer's `edit_log`. Purely read-only.
|
||||
- Frontend `?replay=1` on the review/instrumental route: bypasses the state gate
|
||||
(admins), renders the existing UI with `isReadOnly` (no submit / no mutations),
|
||||
and shows the **Replay action log** panel.
|
||||
- `REVIEW_AUDIO_PROXY=1` (local dev only): the backend streams review audio **bytes**
|
||||
instead of GCS signed URLs, because local user ADC can't sign. Inert in prod.
|
||||
|
||||
## Run it locally (against real prod data, read-only)
|
||||
|
||||
```bash
|
||||
# Terminal 1 — backend (needs `gcloud auth application-default login` with read
|
||||
# access to Firestore `jobs` + the GCS bucket; makes NO writes):
|
||||
./scripts/run-replay-local.sh
|
||||
|
||||
# Terminal 2 — frontend:
|
||||
cd frontend && npm run dev # http://localhost:3000
|
||||
```
|
||||
|
||||
Then in the browser:
|
||||
|
||||
1. Open http://localhost:3000, open DevTools console, and sign in as admin:
|
||||
```js
|
||||
localStorage.setItem('karaoke_access_token', 'replay-local-token') // matches ADMIN_TOKENS
|
||||
```
|
||||
Reload — you're now `admin@nomadkaraoke.com`.
|
||||
2. Open a job in replay:
|
||||
- Lyrics review:
|
||||
`http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1#/<JOB_ID>/review`
|
||||
- Instrumental screen:
|
||||
`http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1#/<JOB_ID>/instrumental`
|
||||
|
||||
Audio, vocals waveform, and backing-vocals previews all play (proxied through the
|
||||
local backend). The submit/mutation controls are hidden; nothing can be changed.
|
||||
|
||||
## Using it for the recording sessions
|
||||
|
||||
Work through the job list in the private corpus
|
||||
(`~/Projects/nomadkaraoke/docs/automation-corpus/`). For each job, with the replay
|
||||
UI open, narrate the two things we're capturing (the agent writes them into the
|
||||
corpus record):
|
||||
|
||||
1. **Lyrics — what I corrected and why** (per manual edit / AI rejection: why the AI
|
||||
was wrong, how you knew the right answer, whether a deterministic check could catch it).
|
||||
**Timings too**: which timing adjustments you make, and what signal (e.g. the
|
||||
separated vocal audio) could detect them automatically.
|
||||
2. **Backing vocals — what I heard and how I decided** (clean vs. with-backing, why;
|
||||
what would make it a clear yes/no vs. a judgement call).
|
||||
|
||||
The action-log panel groups your edits as **AI ✓ / AI ✗ / manual / timing** so it's
|
||||
easy to talk through what the AI got right, what you overrode, and what's left.
|
||||
|
||||
## Notes / limitations
|
||||
|
||||
- Fidelity is "final state + ordered action log", not a per-keystroke visual replay
|
||||
(no intermediate full-state snapshots are stored). The final lyrics are shown with
|
||||
AI-corrected words tagged (`ai_corrected`, `original_text`, `timing_estimated`).
|
||||
- If a job had its outputs deleted (admin "delete outputs"), stems may be gone and
|
||||
audio won't load — the lyrics/action-log still work.
|
||||
@@ -54,6 +54,18 @@ instead of every screen throwing a generic error.
|
||||
outstanding** (`beginRequest`/`endRequest`): `reconnecting` at
|
||||
`STALL_RECONNECTING_MS` (10s), `unavailable` at `STALL_UNAVAILABLE_MS` (20s),
|
||||
back to `online` the instant the stalled read settles.
|
||||
|
||||
**Addendum (2026-08-23, v0.198.3): stall + health-probe confirmation.** A stall
|
||||
alone turned out not to be proof of an outage either — first-time
|
||||
instrumental-analysis / lyrics-review loads transcode audio server-side and can
|
||||
legitimately run 20–60s, false-firing the banner. Now, once a stall crosses the
|
||||
threshold, the store confirms with a cheap `GET /api/health` probe (registered by
|
||||
`lib/api.ts` via `configureHealthProbe`; 4s timeout, `Promise.race`d so a hung
|
||||
origin can't wedge it). While the probe answers OK — or has no verdict yet — the
|
||||
banner stays hidden; only a failed/timed-out probe (as during a real recycle,
|
||||
when the origin hangs) lets it surface (~4s later than before). The probe
|
||||
re-fires every `PROBE_FRESH_MS` (10s) while the stall persists, so recovery
|
||||
clears the banner even if the original read is still hung.
|
||||
- **`lib/api.ts` — `apiFetch`** wraps every backend call (drop-in for `fetch`;
|
||||
internals use `globalThis.fetch`). Design decisions:
|
||||
- **The banner keys on a genuine STALL, not slowness.** A read that completes —
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
# Admin: Locale/Language/Country Visibility + Email History
|
||||
|
||||
**Branch:** `feat/sess-20260822-2340-admin-locale-emails`
|
||||
**Date:** 2026-08-23
|
||||
|
||||
Two independent admin-facing features so support/intervention work can (a) know what
|
||||
language/country a user is using the product in, and (b) see the exact emails ever sent
|
||||
to a user, rendered as they appeared in the inbox with full delivery metadata.
|
||||
|
||||
Decisions (confirmed with user):
|
||||
- **Email history:** Postmark live query (rich metadata, ~45d retention) **+** persist every
|
||||
future send to Firestore for permanent history beyond 45 days. Merge both sources.
|
||||
- **Locale:** Full capture — add a real per-job `locale` (any of 33 langs from the actual
|
||||
`Accept-Language` header), surface the user's UI language, and derive country from IP.
|
||||
|
||||
---
|
||||
|
||||
## Feature A — Locale / language / country
|
||||
|
||||
### Backend
|
||||
|
||||
1. **New helper** `get_full_locale_from_request(request)` in `backend/i18n.py`
|
||||
- Returns the first language tag from `Accept-Language` **without** narrowing to en/es/de
|
||||
(e.g. `pt`, `ja`, `zh`). Keep the existing `get_locale_from_request` untouched (emails
|
||||
still need en/es/de).
|
||||
|
||||
2. **Job model** `backend/models/job.py`
|
||||
- Add `locale: Optional[str] = None` to `Job` (~L239-531) and `JobCreate` (~L534-655).
|
||||
|
||||
3. **Capture on job creation** (populate `locale` from `get_full_locale_from_request`):
|
||||
- URL jobs: `backend/api/routes/jobs.py` (~L79-197)
|
||||
- File upload: `backend/api/routes/file_upload.py`
|
||||
- Audio search: `backend/api/routes/audio_search.py`
|
||||
- Made-for-you: capture at checkout (`backend/api/routes/users.py` create_made_for_you_checkout,
|
||||
~L801) → put `locale` in Stripe session metadata → read in the `checkout.session.completed`
|
||||
webhook (~L1313) when the job is created.
|
||||
|
||||
4. **Dashboard summary projection**: add `'locale'` to `SUMMARY_FIELD_PATHS`
|
||||
(`backend/services/firestore_service.py` ~L200-220) so it appears in `list_jobs_summary`.
|
||||
(Top-level field → only this constant, not `_SUMMARY_STATE_DATA_KEYS`.)
|
||||
|
||||
5. **User UI locale (full value)** `backend/models/user.py`
|
||||
- Add `ui_locale: Optional[str] = None` (keep existing `locale` en/es/de for email rendering).
|
||||
- Populate in `verify_magic_link` (`users.py` ~L441-446) from the full Accept-Language, and
|
||||
update it opportunistically on job creation (cheap `update_user` when it changes).
|
||||
|
||||
6. **Surface in admin responses**
|
||||
- `UserDetailResponse` (`users.py` ~L1753-1780): add `locale`, `ui_locale`.
|
||||
- `get_user_detail` return (~L1954): include them; add `locale` to each `recent_jobs` entry (~L1919-1925).
|
||||
|
||||
### Frontend
|
||||
|
||||
7. **`LocaleBadge` component** `frontend/components/admin/locale-badge.tsx`
|
||||
- Input: a locale string. Renders a small pill: flag emoji + human language name.
|
||||
- Language name via `Intl.DisplayNames(['en'], { type: 'language' })`; flag via a
|
||||
locale→region map (reuse `countryCodeToFlag` from `frontend/lib/ip-geolocation.ts:78`).
|
||||
- Graceful fallback for unknown/empty locale (`🌐 —`).
|
||||
|
||||
8. **Types**: add `locale` to `Job` (`frontend/lib/api.ts` ~L105-152) and `locale`/`ui_locale`
|
||||
to `AdminUserDetail` (~L2256-2301) + the recent-jobs entry type.
|
||||
|
||||
9. **Placements**
|
||||
- Jobs table (`frontend/app/admin/jobs/page.tsx` ~L2142-2211): `LocaleBadge` in the row
|
||||
(language only — cheap, no IP lookup per row).
|
||||
- Job detail info grid (`jobs/page.tsx` ~L1113-1179): Language cell (`LocaleBadge`) +
|
||||
Country via existing `<IpInfo ip={creation_ip} />`.
|
||||
- User detail (`frontend/app/admin/users/detail/page.tsx`): `LocaleBadge` in the header
|
||||
(~L342-348) / Account Info card. Country already shown via `<IpInfo>`.
|
||||
|
||||
Note: keep IP→country lookups to the single-record detail views (cached in the
|
||||
`ip_geolocation` Firestore collection). The jobs *list* shows language only, to avoid N
|
||||
geolocation calls per page.
|
||||
|
||||
---
|
||||
|
||||
## Feature B — Email history ("emails sent to this user")
|
||||
|
||||
### Backend
|
||||
|
||||
10. **Persist every send** — single chokepoint in `EmailService`
|
||||
(`backend/services/email_service.py`). Route all sends through one private
|
||||
`_log_and_send(...)` that calls `self.provider.send_email(...)`, captures the Postmark
|
||||
`MessageID` from the response, then best-effort writes a Firestore `email_log` doc:
|
||||
`{ recipient, cc, bcc, from, subject, html_content, text_content, email_type,
|
||||
message_stream, postmark_message_id, created_at }`.
|
||||
- Mechanical: replace the ~15 `self.provider.send_email(` call sites with `self._log_and_send(`.
|
||||
- Add optional `email_type` kwarg to each `send_*` for categorization (default inferred/None).
|
||||
- Wrap the Firestore write in try/except — **logging must never break a send**.
|
||||
- Capture `MessageID`: `PostmarkEmailProvider.send_email` must return it (change return to
|
||||
include message id, or add an out-param) — currently it discards the response body.
|
||||
|
||||
11. **`PostmarkAdminService`** `backend/services/postmark_admin_service.py`
|
||||
(model on `stripe_admin_service.py`):
|
||||
- `get_user_email_history(email)` → `GET https://api.postmarkapp.com/messages/outbound?recipient=<email>&count=...`
|
||||
using `X-Postmark-Server-Token` (env `POSTMARK_SERVER_TOKEN`). Merge with Firestore
|
||||
`email_log` docs for that recipient; dedupe by `postmark_message_id`; sort by sent-at desc.
|
||||
- `get_email_detail(message_id)` → `GET /messages/outbound/{id}/details` (full `HtmlBody`,
|
||||
subject, status, opens/clicks, bounce). Fallback to the Firestore `email_log` doc for
|
||||
messages older than Postmark's 45-day retention.
|
||||
|
||||
12. **Admin endpoints** `backend/api/routes/admin.py` (pattern: `get_user_payments` ~L2969,
|
||||
guarded by `Depends(require_admin)`):
|
||||
- `GET /admin/users/{email}/emails` → summary list.
|
||||
- `GET /admin/emails/{message_id}` → full detail (HTML + metadata); `?source=log` for
|
||||
Firestore-only records.
|
||||
|
||||
### Frontend
|
||||
|
||||
13. **API client** `frontend/lib/api.ts`: `adminApi.getUserEmails(email)` +
|
||||
`adminApi.getEmailDetail(id, source?)`, plus `UserEmailSummary` / `EmailDetail` interfaces.
|
||||
|
||||
14. **User detail page**: new **"Emails sent to this user"** `<Card>` (rows: subject,
|
||||
type badge, sent-at, delivery-status badge). Row click → **`EmailPreviewDialog`**:
|
||||
- Left/main: `<iframe srcDoc={html} sandbox>` so the email renders exactly as in the inbox
|
||||
(isolated styles), inside `<DialogContent>` + `<ScrollArea>`.
|
||||
- Side panel: To / From / CC / BCC / Subject / sent-at / status / open & click counts /
|
||||
bounce reason.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
- **Backend unit**: `get_full_locale_from_request` parsing; job `locale` persisted on each
|
||||
creation path; `_log_and_send` writes an `email_log` doc (Postmark mocked) and never raises
|
||||
when Firestore fails; `PostmarkAdminService` list/detail with `requests` mocked incl. the
|
||||
45-day fallback; admin endpoints with the service mocked + `require_admin` auth.
|
||||
- **Frontend unit (jest)**: `LocaleBadge` rendering (known/unknown locale); email list + modal
|
||||
render; iframe `srcDoc` wiring.
|
||||
- **Prod E2E (Playwright)**: optional — user-detail page shows the emails card + opens a
|
||||
preview for a known recipient.
|
||||
|
||||
## Infra / ops
|
||||
|
||||
- No new secrets (`postmark-server-token` already wired into the API service).
|
||||
- New Firestore collection `email_log`. Add a composite index (recipient asc, created_at desc)
|
||||
if the merge query needs it — note in PR; Firestore will surface the index hint on first query.
|
||||
- Bump `tool.poetry.version` in `pyproject.toml`.
|
||||
|
||||
## Risks / notes
|
||||
|
||||
- Postmark `MessageID` isn't captured today — must thread it through the provider return.
|
||||
- Not all `send_*` funnel through `send_email` today (e.g. `send_magic_link` calls
|
||||
`self.provider.send_email` directly), which is exactly why the `_log_and_send` chokepoint
|
||||
replaces the provider call sites rather than wrapping `send_email`.
|
||||
- `User.locale` stays en/es/de (emails depend on it); the true UI language lives in the new
|
||||
`ui_locale`.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Admin Create Users + Auto-Create on Job Reassignment (2026-08-24)
|
||||
|
||||
## Task (Andrew's prompt, verbatim)
|
||||
|
||||
> I'd like to be able to create users from the gen admin users page, so I can submit jobs
|
||||
> on their behalf (while logged in as admin, after impersonating the new user account) and
|
||||
> assign free credits to users who have never logged in before. I've actually just edited
|
||||
> an admin-created job to change the user email address to this:
|
||||
> "[customer email redacted — public repo]" but that user didn't exist yet, so i'm not sure
|
||||
> what happens in this case. Ideally in this scenario that user account would get created
|
||||
> on the fly and the job would be assigned to the new user account
|
||||
|
||||
## What happened with the reassigned job (investigation)
|
||||
|
||||
The reassigned job had `user_email` set to the customer's email, but
|
||||
`PATCH /api/admin/jobs/{id}` only wrote the string to
|
||||
the job doc — no `gen_users` account was created. Consequences: notification emails still
|
||||
send (notifier uses the raw email, falls back to `en` locale), and the job would appear in
|
||||
the user's list if they ever logged in (jobs are associated purely by the `user_email`
|
||||
string; magic-link login lazily creates the account). But until then: no account, no
|
||||
credits, impersonation 404s.
|
||||
|
||||
## Changes (v0.199.0)
|
||||
|
||||
1. **`POST /api/users/admin/users`** (`backend/api/routes/users.py`) — admin creates a
|
||||
user account directly: `email` (required), `display_name`, `initial_credits` (0-1000),
|
||||
`credit_reason`. 409 if exists. If initial credits are granted,
|
||||
`welcome_credits_granted` is set so the user doesn't also get the automatic welcome
|
||||
credit on first login. Models in `backend/models/user.py`
|
||||
(`AdminCreateUserRequest/Response`).
|
||||
|
||||
2. **Auto-create on job reassignment** (`backend/api/routes/admin.py` `update_job`) —
|
||||
when an admin PATCHes `user_email`, the email is trimmed + lowercased before saving,
|
||||
and if no `gen_users` account exists one is created via `get_or_create_user`. The
|
||||
response message notes the creation, and the admin jobs page toast surfaces it.
|
||||
|
||||
3. **Admin users page** (`frontend/app/admin/users/page.tsx`) — "Create User" button +
|
||||
dialog (email, optional display name, optional initial credits). On success the list
|
||||
is filtered to the new user, so the existing Impersonate / Add Credits buttons work
|
||||
immediately (impersonation only requires the account doc to exist).
|
||||
|
||||
4. `adminApi.createUser` in `frontend/lib/api.ts`; docs in `docs/API.md`.
|
||||
|
||||
## Tests
|
||||
|
||||
- New `backend/tests/test_admin_create_user.py` (9 tests: minimal create, credits +
|
||||
display name + welcome-flag suppression, lowercase normalization, 409 duplicate,
|
||||
422 invalid email, 400 out-of-range credits, 500 add-credits failure, 403 non-admin).
|
||||
- `backend/tests/test_admin_job_update.py`: new `TestUpdateJobUserEmailAutoCreate` class
|
||||
(creates when unknown, skips when existing, lowercases, non-email edits never touch
|
||||
user service).
|
||||
- Full backend suite: 3917 passed. Frontend: 1151 Jest tests passed; eslint + tsc clean
|
||||
on touched files.
|
||||
|
||||
## Post-deploy TODO
|
||||
|
||||
- Backfill the account for the customer whose job was reassigned before this shipped
|
||||
(details in agent memory, kept out of this public repo): either re-save the
|
||||
`user_email` field on the job in the admin UI (now auto-creates), or call the new
|
||||
create endpoint — then grant credits/impersonate as desired.
|
||||
|
||||
## Design decisions
|
||||
|
||||
- Admin-granted initial credits suppress the automatic welcome credit (set
|
||||
`welcome_credits_granted=True`) to avoid double-granting.
|
||||
- `email_verified` stays false on admin-created accounts — verification still happens on
|
||||
first magic-link login.
|
||||
- Job reassignment now lowercases the email; job→user association is a string match on
|
||||
`user_email`, and all account doc IDs are lowercased emails, so mixed-case entry would
|
||||
otherwise silently orphan the job.
|
||||
@@ -0,0 +1,431 @@
|
||||
# Toward Fully-Automated Review (skip lyrics review + instrumental selection when confident)
|
||||
|
||||
**Status:** Design / research program. Started 2026-08-25.
|
||||
**Author:** Andrew (spec) + agent (design).
|
||||
**Worktree:** `karaoke-gen-full-auto-review`
|
||||
|
||||
---
|
||||
|
||||
## The goal (Andrew's words, verbatim spec)
|
||||
|
||||
> Ideally I'd like to make the karaoke-gen system even more automated, potentially _fully_
|
||||
> automated (skipping the lyrics review and instrumental selection processes entirely) for songs
|
||||
> where for both decisions, we have enough heuristics in place to be pretty confident there are no
|
||||
> potential issues warranting human input.
|
||||
>
|
||||
> However, to actually reach that confidence bar is non-trivial without risking sloppy releases
|
||||
> (which was originally the whole point of the lyrics review UI still being a manual human step).
|
||||
>
|
||||
> Please help me reach that level of automation, starting out with the easy cases where both synced
|
||||
> lyrics are perfect and there's no subjectivity in the backing vocals decision. Then once we have a
|
||||
> couple of working fully auto examples, we can start reviewing every job I complete the
|
||||
> review+select process for, and for each record:
|
||||
> - exactly what did I correct manually in the lyrics review process, and why
|
||||
> - what did I hear when I previewed the backing vocals, how did i make the decision about backing
|
||||
> vocals vs. clean instrumental.
|
||||
>
|
||||
> once we've recorded the output of me making at least 10 tracks, recording my answers for both of
|
||||
> those diligently, in detail, via interactive claude session where I can both describe and share
|
||||
> screenshots... then we can start brainstorming what types of automated checks and (post-AI
|
||||
> correction) heuristic fixes we might be able to apply to fully "solve" (fully automate with
|
||||
> confidence) more whole classes of tracks in the lyrics review. and brainstorm how we could fully
|
||||
> automate the backing vocals decision, turn it into a simple "retain backing vocals where possible?"
|
||||
> (yes/no/review) toggle option made up-front during job submission (defaulting to on).
|
||||
|
||||
Context: Andrew is currently submitting Vocal Star **tenant** test jobs. This applies to **both**
|
||||
public and tenant sides of the product.
|
||||
|
||||
---
|
||||
|
||||
## Guiding principle: shadow-first, never sloppy
|
||||
|
||||
The review UI exists precisely to prevent sloppy releases. So we do **not** flip a switch and hope.
|
||||
The rollout is:
|
||||
|
||||
1. **Shadow** — compute an "auto-approvability" verdict on *every* job at the review gate, record it,
|
||||
but keep sending the job to human review as normal. No behaviour change, zero release risk.
|
||||
2. **Record** — for every job Andrew reviews, capture (a) exactly what he changed in the lyrics and
|
||||
why, (b) what he heard in the backing-vocals preview and how he decided. Store alongside the shadow
|
||||
verdict + all signals that existed at gate time.
|
||||
3. **Validate** — over ≥10 tracks, check the core hypothesis: **does a "would auto-approve" verdict
|
||||
reliably coincide with "Andrew changed nothing / made a non-subjective clean call"?** Tune
|
||||
thresholds against this real ground truth.
|
||||
4. **Enforce (narrow)** — only once validated, let the gate actually skip review for the provably-easy
|
||||
intersection, starting maximally conservative and widening class-by-class as the corpus grows.
|
||||
|
||||
This gives Andrew the "couple of working fully-auto examples" he asked to start with (the narrow safe
|
||||
intersection can be enforced early), while the recording program de-risks widening it.
|
||||
|
||||
---
|
||||
|
||||
## What the system already gives us (investigation results)
|
||||
|
||||
### Lyrics confidence signals (all already in `jobs/{id}/lyrics/corrections.json`)
|
||||
|
||||
`CorrectionResult` (`karaoke_gen/lyrics_transcriber/types.py:609`) serialized per job. Auto-correction
|
||||
is **disabled** in prod, so `corrected_segments` ≈ raw AudioShake transcription and `corrections_made`
|
||||
≈ 0. Useful fields:
|
||||
|
||||
- `original_segments` — raw transcription (words + timings + ids).
|
||||
- `anchor_sequences[]` — runs of transcribed words that matched reference lyrics, each with its own
|
||||
`confidence` and `reference_positions` (which sources agreed).
|
||||
- `gap_sequences[]` — the **uncertain regions** between anchors (transcribed words with no confident
|
||||
reference match). Few/short gaps ⇒ high confidence.
|
||||
- `metadata.rejected_sources` — per reference source: `relevance`, `matched_words`, `total_words`.
|
||||
Strong multi-source agreement is the best proxy for "these lyrics are truly right."
|
||||
- `metadata.anchor_sequences_count`, `gap_sequences_count`, `total_words`.
|
||||
- Per-word `confidence` — **only present for Whisper**, absent for AudioShake (prod). Treat as optional.
|
||||
|
||||
**Derived gate signals** (mirroring `frontend/components/lyrics-review/CorrectionMetrics.tsx:92-99`):
|
||||
- `anchor_word_fraction` = anchored words / total words → want ≈ 1.0
|
||||
- `uncorrected_gap_fraction` = gap words not corrected / total → want ≈ 0.0
|
||||
- `reference_agreement` = ≥N sources with high `matched_words/total_words`
|
||||
|
||||
⚠️ **Trap:** the top-level `CorrectionResult.confidence` is `1.0` whenever correction is *disabled*
|
||||
(`controller.py:593-594`), not because lyrics are perfect. Never gate on it.
|
||||
|
||||
**Strongest "easy case" of all:** a user/tenant-supplied **synced** reference (LRC) that the
|
||||
transcription matches at ~100% anchor coverage with zero gaps. Vocal Star jobs frequently ship their
|
||||
own instrumental + known-good lyrics — a prime full-auto candidate class.
|
||||
|
||||
### Backing-vocals signals (already in `state_data.backing_vocals_analysis`)
|
||||
|
||||
`AudioAnalyzer` (`karaoke_gen/instrumental_review/analyzer.py`) analyses the isolated
|
||||
`backing_vocals.flac` stem: `has_audible_content`, `audible_percentage`, per-segment
|
||||
`avg/peak_amplitude_db`, and a `recommended_selection` (CLEAN / WITH_BACKING; **never** REVIEW_NEEDED).
|
||||
|
||||
- **Non-subjective case:** `has_audible_content == False` ⇒ there are no backing vocals to retain ⇒
|
||||
clean is unambiguously correct. Safe to auto-decide today.
|
||||
- **Subjective case:** audible backing content exists → clean-vs-with is a taste/quality call
|
||||
("does it sound good / help singers / is it just vocal bleed?"). This is what the recording program
|
||||
must characterise before we can automate it. The current energy heuristic cannot: it has no measure
|
||||
of backing-vocal *quality* or of the delta between the two mixes.
|
||||
|
||||
### Where review happens / the insertion point
|
||||
|
||||
- `screens_worker.py:214` unconditionally transitions every job → `AWAITING_REVIEW`. **This is where an
|
||||
auto-skip gate goes.** The `AWAITING_REVIEW → REVIEW_COMPLETE` transition is already legal
|
||||
(`job.py:152`).
|
||||
- `POST /api/review/{id}/complete` (`review.py:472`) is what a human submit does: writes
|
||||
`corrections_updated.json` (only if there are edits), sets `state_data.instrumental_selection`,
|
||||
transitions to `REVIEW_COMPLETE`, triggers render. An auto-path must replicate this — including
|
||||
supplying a default `instrumental_selection` (the selection requirement is enforced only in the HTTP
|
||||
endpoint, not the state machine).
|
||||
- Render consumes `state_data.instrumental_selection` (`clean`|`with_backing`|`custom`); default when
|
||||
absent is already `clean` (`video_worker.py:108`).
|
||||
|
||||
### Existing "what changed" records (insufficient for our purpose)
|
||||
|
||||
- `review_sessions` `changed_words[]` (`review_session.py:14`) — per-word diff, **no why**.
|
||||
- `annotations.json` `CorrectionAnnotation` (`review.py:1345`) — has `agentic_agreed`, **no free-text
|
||||
why, nothing about backing vocals.**
|
||||
|
||||
Neither captures *reasoning*, and nothing captures the backing-vocals listening decision. **That gap is
|
||||
the core of the recording program.**
|
||||
|
||||
---
|
||||
|
||||
## Plan
|
||||
|
||||
### Phase 0 — Recording + shadow-scoring harness (foundation, zero release risk)
|
||||
|
||||
A **plain-files + script** tool (honouring "meta-tooling = plain files + slash commands, never a new
|
||||
UI"). No frontend, no production code-path change.
|
||||
|
||||
**0a. `AutoApprovabilityScorer` (pure function, shared module).** Input: `corrections.json` +
|
||||
`backing_vocals_analysis`. Output: structured verdict per axis —
|
||||
`lyrics: {verdict: auto|review, signals:{anchor_word_fraction, uncorrected_gap_fraction,
|
||||
reference_agreement, total_words, has_synced_reference, ...}, reasons:[...]}` and
|
||||
`backing: {verdict: clean|with|review, signals:{has_audible_content, audible_percentage, loud_segments,
|
||||
...}, reasons:[...]}`. Starts with deliberately conservative thresholds. Fully unit-tested against
|
||||
fixtures. This same module later powers the real gate — build it once, use it in shadow first.
|
||||
|
||||
**0b. `scripts/review_capture.py` (the recording tool).** Given a completed/ reviewed job id:
|
||||
- Pulls `corrections.json` + `corrections_updated.json` + `backing_vocals_analysis` (+ chosen
|
||||
`instrumental_selection`) from GCS/Firestore (read-only; works under `claude-readonly` ADC).
|
||||
- Computes the **structured lyrics diff** (word-text edits, timing nudges, splits/merges, insertions,
|
||||
deletions) = exactly what Andrew changed.
|
||||
- Runs the shadow scorer and prints the verdict + signals next to what Andrew *actually* did.
|
||||
- Emits a per-job record and appends to a corpus.
|
||||
|
||||
**0c. The corpus** (`docs/automation-corpus/` or similar, in-repo, plain files):
|
||||
- `jobs/{job_id}.md` — human-readable: song, signals, shadow verdict, the diff, and Andrew's dictated
|
||||
**why** (lyrics) + **backing-vocals reasoning** (what he heard, how he decided). Screenshots welcome.
|
||||
- `corpus.jsonl` — one machine-readable row per job for later threshold calibration.
|
||||
- `README.md` — running tally toward the ≥10-track target + emerging patterns.
|
||||
|
||||
**0d. Interactive flow** (this is the "via interactive claude session" Andrew described): after Andrew
|
||||
finishes a review, we run the tool, look at the diff + signals together, and he dictates the reasoning;
|
||||
the agent writes it into the corpus. Screenshots pasted into the session get referenced.
|
||||
|
||||
**0e. (optional, tiny) shadow logging in prod** — write the scorer's verdict into
|
||||
`processing_metadata.auto_approvability` at the `screens_worker` gate, without changing behaviour, so
|
||||
we accumulate verdicts on jobs even when we don't run the capture tool. Deferred until 0a-0d prove out.
|
||||
|
||||
### Phase 1 — Narrow, conservative enforcement (the "couple of fully-auto examples")
|
||||
|
||||
Once a handful of jobs in the corpus show the safe intersection firing correctly, enable **actual**
|
||||
auto-skip in `screens_worker` for that intersection **only**:
|
||||
- Lyrics: synced reference present AND anchor_word_fraction ≥ (high) AND uncorrected_gap_fraction ≈ 0.
|
||||
- Backing: `has_audible_content == False` → auto-select `clean`.
|
||||
- Everything else → human review, unchanged.
|
||||
- Guardrails: feature-flagged (env), tenant-scoped opt-in first (Vocal Star), full audit trail in
|
||||
`processing_metadata`, and a kill switch. Auto-approved jobs still get every downstream QC that exists.
|
||||
|
||||
### Phase 2 — Widen by class (after ≥10 recorded tracks)
|
||||
|
||||
Brainstorm + build **post-AI-correction heuristic fixes** and **checks** that let whole classes pass
|
||||
without human input, driven by patterns in the corpus (e.g. common mechanical corrections Andrew makes
|
||||
that we can auto-apply and then re-verify; classes of gap that are reliably safe to accept).
|
||||
|
||||
### Phase 3 — Backing-vocals up-front toggle
|
||||
|
||||
Add `retain_backing_vocals: yes|no|review` (default `yes`) to submission (`URLSubmissionRequest` /
|
||||
`UploadSubmissionRequest` → `JobCreate` → `state_data`). Semantics:
|
||||
- `no` → force `clean`, skip instrumental step.
|
||||
- `yes` → retain backing **where the (improved) analysis says it's safe**, else fall back per policy.
|
||||
- `review` → today's human behaviour.
|
||||
Requires a better backing-vocal quality signal than the current energy threshold — the corpus reasoning
|
||||
is what tells us what "sounds good enough to retain" actually means.
|
||||
|
||||
---
|
||||
|
||||
## Day-1 validation (scorer + capture harness, 2026-08-25)
|
||||
|
||||
Built the shared scorer (`backend/services/auto_approval/`), the review-diff, and
|
||||
`scripts/review_capture.py`, then shadow-scanned 30 recent completed jobs (read-only):
|
||||
|
||||
- **1/30 would fully auto-approve today** — `56411c70` Nat King Cole "Never Let Me Go":
|
||||
100% anchor, 0 gaps, **0 lyric edits**, no audible backing → clean. Independently the
|
||||
scorer said AUTO. That's the first genuine fully-auto example, with no false positives in
|
||||
the batch.
|
||||
- **The predictive hypothesis broadly holds:** high anchor / low gap ⇒ few edits; low anchor
|
||||
⇒ many edits (e.g. 61.6% anchor → heavy correction). But it is *not* perfectly monotonic —
|
||||
some ~95-98% jobs needed only a handful of edits, one 94% job needed 269. This is exactly
|
||||
why the reasoning corpus is needed: to learn *which* edits the high-coverage jobs still need.
|
||||
- **Key threshold finding → applied:** job `79c4f60c` "Clarity" scored 99.6% anchor with a
|
||||
**single gap word**, which turned out to be a real mis-transcription the reviewer fixed
|
||||
(`I` → `High`). A gap word is by definition a word with no confident reference match — where
|
||||
errors hide. So the AUTO tier was tightened from "≤1% gap" to **zero unresolved gaps**
|
||||
(`AUTO_MAX_GAP_FRACTION = 0.0`). This demotes Clarity to `near-miss`/review while keeping
|
||||
Nat King Cole as AUTO. Regression test: `test_single_gap_word_blocks_auto`.
|
||||
- **Diff quality:** the review UI re-keys a word's id when its text is replaced but preserves
|
||||
its timing/line, so text corrections first appeared as delete+insert. The diff now pairs
|
||||
them into clean **replacements** (`Carl → Karl`, `they're → their`, `you've → you`).
|
||||
|
||||
Deliverables this session (all tested, 21 unit tests):
|
||||
`backend/services/auto_approval/{models,scorer,lyrics_diff}.py`,
|
||||
`scripts/review_capture.py`, corpus scaffold at workspace-root `docs/automation-corpus/`.
|
||||
|
||||
## Session 2 update (2026-08-25) — replay tool + corrected baseline
|
||||
|
||||
Andrew refined the plan: instead of capturing via offline markdown diffs, **replay the
|
||||
real review UIs** for past completed jobs (full audio/backing previews from GCS) and
|
||||
narrate the decisions, then walk the **20 most-recent `admin@nomadkaraoke.com` jobs**.
|
||||
|
||||
**Critical correction to the lyrics baseline.** AI auto-correct is doing the heavy
|
||||
lifting (proactive suggestions, accepted in the review UI). The **authoritative record
|
||||
of what happened is the `edit_log_*.json`** (ordered, typed ops: `ai_suggestion_accept`
|
||||
/ `ai_suggestion_reject` / manual `word_*` / `timing_change`), plus `ai_corrected` /
|
||||
`original_text` / `timing_estimated` provenance baked into saved words. My earlier raw
|
||||
`corrections.json → corrections_updated.json` id-diff was misleading (word-id
|
||||
regeneration inflated del/ins). **Right baseline = post-AI; the interesting signal =
|
||||
residual manual edits + AI rejections (⚠️ superseded: session-3 established these are the auto-apply's own conflict resolution, NOT human decisions — see session-4 update) + timing.**
|
||||
|
||||
Findings from the 20 admin jobs (edit_log counts): AI solves lyrics outright on several
|
||||
(0 manual, 0 reject: d508adb6, 69ca7c1e, 507513ba, b5a7b8aa, 35ed9697, f986dfe5); AI
|
||||
rejections cluster the failure modes (f247364e=15, 44622ffa=5, 8e465dc7=4); residual
|
||||
manual concentrates in a few (a4dcaa21=17, 95d8e844=12). **⚠️ Zero `timing_change` ops
|
||||
logged across all 20** despite timing being a stated axis — open question for the sessions.
|
||||
|
||||
**Built + verified end-to-end against real prod data (read-only):**
|
||||
- Backend replay: `GET /correction-data?replay=true` (full-auth only) skips the status
|
||||
gate + transition and attaches the `edit_log`. `review.py`.
|
||||
- Dev audio proxy: `REVIEW_AUDIO_PROXY=1` streams review audio **bytes** (local user ADC
|
||||
can't sign GCS URLs; impersonating the backend SA is denied and granting it is a GCP
|
||||
write we won't make). New `GET /{job}/dev-audio` (prod-inert). Wired into
|
||||
correction-data, instrumental-analysis, `_stream_audio`, waveform.
|
||||
- Frontend replay: `?replay=1` bypasses the state gate (admin), passes `isReadOnly` to
|
||||
the already-wired `LyricsAnalyzer` + new `isReadOnly` on `InstrumentalSelector`, and
|
||||
renders a **ReplayActionLog** panel (AI✓/AI✗/manual/timing). `client.tsx`.
|
||||
- Run locally: `./scripts/run-replay-local.sh` + `cd frontend && npm run dev`. See
|
||||
`docs/REPLAY.md`. Job queue: private corpus `docs/automation-corpus/REVIEW-QUEUE.md`.
|
||||
- Tests: 5 new backend (replay gate/auth + dev-audio inert), 61 review-suite pass; 21
|
||||
scorer/diff tests pass; frontend changed files typecheck clean.
|
||||
|
||||
**Remaining (post-sessions):** refine AI-vs-manual attribution into the corpus
|
||||
(edit_log-driven), design timing-adjustment detection (incl. vocal-audio signal for
|
||||
cut-off sustained words), and the backing-vocals decider + up-front toggle
|
||||
(retain-where-possible / clean / review).
|
||||
|
||||
## Open questions / decisions
|
||||
|
||||
- **Corpus location & format** — `docs/automation-corpus/` in this repo vs workspace-level. (Leaning
|
||||
in-repo so it travels with the code that consumes it.)
|
||||
- **How much to enforce early** — stay in pure shadow until ≥N corpus jobs, or enable the ultra-narrow
|
||||
intersection as soon as it's proven on 2-3 jobs (Andrew's "couple of working examples").
|
||||
- **Public vs tenant first** — tenant (Vocal Star, own instrumental + known lyrics) is the safest place
|
||||
to enable narrow enforcement first.
|
||||
|
||||
---
|
||||
|
||||
## Key file/line index (for implementers)
|
||||
|
||||
| Concern | Location |
|
||||
|---|---|
|
||||
| Correction data model | `karaoke_gen/lyrics_transcriber/types.py:609` (`CorrectionResult`) |
|
||||
| Confidence/metadata computation | `karaoke_gen/lyrics_transcriber/correction/corrector.py:203-256` |
|
||||
| `confidence=1.0`-when-disabled trap | `karaoke_gen/lyrics_transcriber/core/controller.py:593-669` |
|
||||
| Review gate (insertion point) | `backend/workers/screens_worker.py:214` |
|
||||
| Human review-complete behaviour to mirror | `backend/api/routes/review.py:472-604` |
|
||||
| Legal auto transition | `backend/models/job.py:152` (`AWAITING_REVIEW→REVIEW_COMPLETE`) |
|
||||
| BV energy analysis + recommendation | `karaoke_gen/instrumental_review/analyzer.py:80-165, 380-409` |
|
||||
| BV analysis invocation + storage | `backend/workers/screens_worker.py:533-637`, `state_data.backing_vocals_analysis` |
|
||||
| Instrumental selection → stem mapping | `backend/workers/video_worker.py:1341-1380,1438-1464` |
|
||||
| Submission-time options | `backend/models/requests.py:8-40`, `backend/models/job.py:540-609` (`JobCreate`) |
|
||||
| Existing "what changed" records | `backend/models/review_session.py:14`, `backend/api/routes/review.py:1345` |
|
||||
|
||||
---
|
||||
|
||||
## Session 4 update (2026-08-27) — shadow gate WIRED + scorer v0.2.0
|
||||
|
||||
The shadow scorer is now wired into the pipeline (`screens_worker._record_auto_approval_shadow`,
|
||||
called just before the AWAITING_REVIEW transition; non-fatal; writes
|
||||
`processing_metadata.auto_approval_shadow`). Scorer v0.2.0 adds, from the 20-job corpus findings:
|
||||
|
||||
- **P3 vocalization gate** (runs of ≥5 vocalization tokens / multi-second "Ooh"s) and
|
||||
**P8 phantom gate** (words >5s; stretched short parenthetical lines) — never-auto classes that
|
||||
override everything.
|
||||
- **AI-suggestion awareness**: the proactive auto-correct cache
|
||||
(`jobs/{id}/lyrics/auto_correct_cache/`) is loaded at scoring time; gap words *covered* by a
|
||||
suggestion are auto-fixed on review load, so confidence keys off the **uncovered** remainder.
|
||||
New AUTO tier `ai-resolved`: synced ref + anchor ≥90% + uncovered ≤2% and ≤6 words + no gates.
|
||||
|
||||
Calibration vs the 20-job corpus (full table in the private corpus,
|
||||
`docs/automation-corpus/scorer-calibration-2026-08-27.md`): **safety 100%** (all truly-human jobs
|
||||
gated), lyrics auto 3/20, overall auto 1/20. Raw gap counts demonstrably do NOT separate AI-solved
|
||||
from human-needed jobs; suggestion coverage does.
|
||||
|
||||
Next per SYNTHESIS build order: collect shadow verdicts on live traffic; build the Pattern 4
|
||||
leading-connective auto-fixer (+P1 dedupe, P5 reference-majority); then revisit thresholds and
|
||||
begin enforcement (tenant jobs first).
|
||||
|
||||
---
|
||||
|
||||
## Session 4b update (2026-08-27, same session) — ENFORCEMENT SHIPPED
|
||||
|
||||
Andrew's directive: *"keep driving towards eventually shipping fully auto processing, on by
|
||||
default, for all gen users, only showing the lyrics and/or instrumental review screens when one
|
||||
or the other is unsolved / definitely needs human review"* → shipped the framework + the
|
||||
narrow fully-confident class:
|
||||
|
||||
- **`Job.review_mode`** (`"auto"` default | `"always_review"`, admin-PATCH-editable) — the
|
||||
autonomy/review-level setting. Legacy `non_interactive` is untouched (CLI packaging semantics;
|
||||
never gated the cloud review).
|
||||
- **`backend/services/auto_approval/apply.py`** — faithful server-side port of the review UI's
|
||||
on-load auto-apply (`autoCorrectApply.ts` + `autoCorrectConflicts.ts` + `acceptAll`):
|
||||
replace/insert_after/delete ops, timing distribution, word provenance flags, conflict-group
|
||||
winners by consensus→confidence. Plus `find_suspicious_duplicates` (the P1 self-conflict
|
||||
duplicate-word signature, reference-aware).
|
||||
- **`backend/services/auto_approval/executor.py`** — `maybe_auto_complete_review(job_id, trigger)`
|
||||
called from `screens_worker` (pre-AWAITING_REVIEW) and `audio_worker` (post-analysis, for
|
||||
audio-lags-lyrics ordering). Scores + records `processing_metadata.auto_approval` on EVERY job;
|
||||
enforces only when: flag on + review_mode=auto + not made-for-you + no existing/custom
|
||||
instrumental + `overall_auto` + audio complete + clean stem present. Enforce = apply cached AI
|
||||
suggestions server-side → sanity checks (stale/duplicates/empty ⇒ abort to review) →
|
||||
`corrections_updated.json` → instrumental=clean → clear progress keys →
|
||||
GENERATING_SCREENS→REVIEW_COMPLETE (new legal edge; skips the review notification entirely) →
|
||||
trigger render worker. FAIL-SAFE: every anomaly/exception falls back to normal human review.
|
||||
- **Backing-analysis-error trap fixed**: a failed analysis stores `has_audible_content=None`,
|
||||
which previously read as `False` ("no audible content") in the scorer — would have wrongly
|
||||
auto-picked clean. Now treated as analysis-absent → review.
|
||||
- Kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false` (scoring/recording continues).
|
||||
|
||||
Expected initial auto rate ~5% of jobs (1/20 in the calibration corpus): lyrics must be
|
||||
synced-perfect or ai-resolved AND backing must be non-subjectively clean. Widening comes from
|
||||
build-order #2-#4 (P4 fixer, vocalization detector already gating, backing decider).
|
||||
|
||||
## Session 5 update (2026-08-28) — Phase 2A: deterministic P4/P1/P5 fixers (v0.203.0)
|
||||
|
||||
Build-order item #2 shipped: the three mechanical residual-edit classes from the corpus are now
|
||||
**deterministic suggestion generators inside the auto-correct pipeline** (not executor hacks), so
|
||||
one mechanism feeds the review UI's on-load auto-apply, the executor's server-side apply, the
|
||||
scorer's gap-coverage signal, and the proactive cache.
|
||||
|
||||
- **`backend/services/auto_correct/deterministic.py`** (new) — pure generators keyed off
|
||||
`corrections.json` gap/anchor alignment:
|
||||
- **P4 leading-connective delete**: segment starts with And/But/So/Oh/A, the word is a gap
|
||||
word, and no reference source's reading of that gap contains it → emit `delete` (+ a
|
||||
`replace` re-capitalizing the next word when lowercase). Guard: skipped when the next word is
|
||||
a vocalization token (an "Oh- whoa," run is musical judgement, corpus 5c80991d).
|
||||
- **P5 reference-majority replace**: a gap whose transcription contains an implausible proper
|
||||
noun (capitalized mid-line token absent from every reference) and where ≥2/3 of reference
|
||||
sources agree on the same reading → replace with the majority reading. The red flag is
|
||||
REQUIRED — plain 2/3 majority over-fires on gaps the human deliberately left (6d0640fa
|
||||
"though"→"dog", explicit-lyrics rewrite). Spelling-variant guard: a red-flag token
|
||||
string-similar (≥0.75) to a reference token is a transliteration/truncation ("Crick"~
|
||||
"Cricket", "Projectorinsky"~"Projektorinski") whose gap alignment is often junk → skip
|
||||
(that's the LLM's fix).
|
||||
- Per-source gap readings come from the gap's own `reference_word_ids`, else are derived by
|
||||
walking the reference stream past the surrounding anchors (the 6d0640fa "Come here," case —
|
||||
the aligner had empty alignments for 2 of 3 sources).
|
||||
- **P1 self-conflict grouping at source** — `service._assign_conflict_groups` (extracted, reused
|
||||
post-integration) now also unions an `insert_after` with any suggestion targeting/anchored on
|
||||
the same word whose new_text shares a token: the f6439692 "insert you're + replace fire→fire,
|
||||
you're → 'you're you're'" signature becomes a pick-one conflict group (winner by consensus→
|
||||
confidence picks the 0.95 replace — correct). Executor's `find_suspicious_duplicates` abort
|
||||
stays as belt-and-braces.
|
||||
- Pipeline: `suggest(..., correction_data=None)` — proactive worker passes corrections.json in;
|
||||
the review route lets the service fetch it (best-effort). Deterministic suggestions identical
|
||||
to an LLM one just tag it (`models += ["deterministic"]`); new ones append; conflict groups are
|
||||
recomputed over the combined set. Suggestion-cache key bumped to v2 (old cached results predate
|
||||
the fixers).
|
||||
- **Corpus validation** (private validate_scorer.py, extended with FIXER assertions): safety
|
||||
still 100% (all MUST_NOT_AUTO stay review; gates unchanged). P4 fires on all six corpus
|
||||
examples; P5 reproduces Andrew's one ref-majority edit ("yo Mick,"→"Come here,") and fires
|
||||
nowhere it must not. **6d0640fa (Miguel) now scores lyrics=auto + clean backing → would fully
|
||||
auto-ship WITH the human's exact edit applied**; ae0cd7e8 (Samson corpus job) now has its P4
|
||||
edits actually applied when auto-shipping. `ai-resolved` caps deliberately NOT loosened
|
||||
(69ca7c1e still 14 uncovered words — needs more coverage, not looser caps).
|
||||
|
||||
## Session 6 update (2026-08-28) — Phase 2B: 3-stem backing decider (v0.204.0)
|
||||
|
||||
Build-order item #4 shipped (decider + signals; enforcement shadow-first):
|
||||
|
||||
- **`karaoke_gen/instrumental_review/stem_comparison.py`** (new, pure pydub) — compares the
|
||||
backing / lead / full-vocals stems: audible coverage per stem + coverage ratio, envelope
|
||||
Pearson correlations (backing↔vocals, backing↔lead), median audible levels, lead-overlap
|
||||
fraction, within-run flatness. Wired into `_analyze_backing_vocals` (screens_worker →
|
||||
AudioAnalysisService) → stored as `backing_vocals_analysis.stem_comparison` on every new job.
|
||||
- **Scorer v0.3.0** — `score_backing` decides the pink-present branch (previously always
|
||||
review): confident **WITH_BACKING** (non-subjective keep) unless one of the corpus-validated
|
||||
"pink but don't keep" modes fires: backing-stem-IS-the-lead (covR ≥0.80 + corr ≥0.80 +
|
||||
backing more present than lead — the decisive discriminator; the dB-margin idea nearly
|
||||
misfired on a genuine keep), noise-floor signature (median ≤ −35 dB over ≥15% of track,
|
||||
corr ≤0.05 — REVIEW, marginal per corpus), narrow bleed rule (≤3% audible, lead overlap
|
||||
≥0.95 — d508adb6's genuine 0.89-overlap harmonies must stay keepable).
|
||||
- **Corpus validation (validate_backing_decider.py, private; ~2.4 GB stems cached locally):
|
||||
13/14 true keeps → confident WITH_BACKING — including BOTH jobs the human under-kept
|
||||
(44622ffa, 35ed9697): the decider beats the human's quick review. 95d8e844 (marginal
|
||||
grungegaze) → review. All clean-correct jobs → clean. 1d45b286 (catastrophic
|
||||
backing-is-lead) → review. Zero unsafe outcomes.**
|
||||
- **Executor**: WITH_BACKING verdict enforces `instrumental_selection="with_backing"` ONLY
|
||||
behind `AUTO_APPROVAL_BACKING_KEEP_ENABLED` (default **false** — shadow-first per plan);
|
||||
while off, such jobs record blocker `backing_keep_disabled` + full verdict/signals in
|
||||
`processing_metadata.auto_approval` for prod shadow calibration alongside human picks.
|
||||
Requires the `instrumental_with_backing` stem (blocker `no_with_backing_stem`).
|
||||
- Flip-on procedure: review shadow verdicts vs human picks for a while, then set
|
||||
`AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` on the backend service. The Cher-class jobs
|
||||
(lyrics solved, gated only by audible backing — 46201da4) then become fully auto.
|
||||
|
||||
## Session 7 update (2026-08-28 evening) — Phase 2D: user-supplied-instrumental jobs auto-complete (v0.205.0)
|
||||
|
||||
Tenant/bulk jobs (and any job with `existing_instrumental_gcs_path` or a `custom_instrumental`
|
||||
stem) previously carried the `custom_instrumental` enforcement blocker. But these jobs have NO
|
||||
instrumental decision — the human flow completes them with `instrumental_selection="custom"`
|
||||
(validated in review.py complete; video worker prefers the user-provided source). Executor now:
|
||||
confident lyrics alone ⇒ auto-complete with selection="custom"
|
||||
(`enforcement_basis="lyrics_only_custom_instrumental"` recorded in the payload; backing verdict
|
||||
moot). Non-custom jobs unchanged (`overall_auto`). Per-job opt-out stays `review_mode=
|
||||
"always_review"`; per-tenant default config is future work (workstream C/D follow-up).
|
||||
This makes tenant bulk uploads the highest-auto-rate population (B2B throughput).
|
||||
@@ -0,0 +1,147 @@
|
||||
# Full-Auto Review — Session Handoff (2026-08-27)
|
||||
|
||||
Comprehensive handoff for a fresh Claude session picking up the "fully-automated review" initiative.
|
||||
Read this + the two design docs + the private corpus, then continue from **§8 Next steps**.
|
||||
|
||||
- **Initiative goal (Andrew's spec):** make karaoke-gen able to SKIP the manual lyrics-review +
|
||||
instrumental-selection steps for tracks where we're confident it's safe — without sloppy releases.
|
||||
Start with easy cases, record real review decisions, then build heuristics + gating.
|
||||
- **Worktree:** `<workspace>/karaoke-gen-full-auto-review`
|
||||
**Branch:** `feat/sess-20260825-0000-full-auto-review` (all work UNCOMMITTED).
|
||||
- **Design docs:** `docs/archive/2026-08-25-full-auto-review-design.md` (original plan + session-2 update),
|
||||
this handoff, `docs/REPLAY.md` (how to run the replay tool).
|
||||
- **Corpus (PRIVATE, workspace root — NOT in the public repo):**
|
||||
`<workspace>/docs/automation-corpus/ (private, outside this repo)` →
|
||||
`SYNTHESIS.md` (★ read first), `lyrics-manual-edit-patterns.md`, `backing-vocals-decision-logic.md`,
|
||||
`REVIEW-QUEUE.md`, `jobs/*.md` (20 per-job records), `snapshots/`.
|
||||
|
||||
---
|
||||
|
||||
## 1. TL;DR of what happened across 3 sessions
|
||||
|
||||
- **Session 1:** built the offline `AutoApprovabilityScorer` + review-diff + a capture script + corpus
|
||||
scaffold; validated against 30 real jobs.
|
||||
- **Session 2:** built the **replay tool** — reopen the real lyrics/instrumental review UIs read-only for
|
||||
COMPLETED jobs, with audio, running LOCALLY against prod data (read-only).
|
||||
- **Session 3 (this one):** walked all **20** most-recent `the admin account` jobs in the replay UI
|
||||
with Andrew, recording his reasoning → produced the full **pattern catalogue + SYNTHESIS.md**. Also
|
||||
hardened the replay tool (nav bar, Post-AI toggle, audio seeking) and fixed several reconstruction bugs.
|
||||
|
||||
## 2. ★ The key conceptual reframe (read this or you'll misread everything)
|
||||
|
||||
**AI lyric suggestions AUTO-APPLY on load** (`frontend/hooks/useAutoCorrect.ts` `autoApplyOnLoad` →
|
||||
`acceptAll(true)`). Andrew never manually reviews them. Therefore in a job's `edit_log`:
|
||||
- `ai_suggestion_accept` / `ai_suggestion_reject` = the **auto-apply's own conflict resolution**, NOT
|
||||
human decisions. **Ignore AI✗ counts as a human signal.** (Jobs I first flagged as "15-rejection
|
||||
goldmines" are actually near-pure-AI wins.)
|
||||
- **Only the non-`ai_suggestion` ops are Andrew's** (`word_change/word_delete/word_add/segment_*/
|
||||
timing_change/find_replace`). Those are the real residual work.
|
||||
|
||||
So the goal is NOT "skip a manual step" — it's **"per track, is the auto-applied result safe to ship, or
|
||||
does it need a human glance?"** 8/20 jobs had zero human edits.
|
||||
|
||||
## 3. The findings (see SYNTHESIS.md for full detail)
|
||||
|
||||
**Lyrics — 3-tier strategy:**
|
||||
- **★ MASTER GATE = post-AI confidence score** (anchor coverage + gap fraction/count + #corrections +
|
||||
phantom/absurd-duration flags). Low → human; high → auto-ship. This is *exactly* what
|
||||
`backend/services/auto_approval/scorer.py` already computes — Andrew reinvented it independently.
|
||||
- **Auto-fix classes:** **P4** leading connective/interjection over-insertion (`And`/`Oh`/`A`, seen 6× —
|
||||
biggest win); **P5** reference-majority (≥2/3) resolution; **P1** dedupe AI self-conflicting suggestions.
|
||||
- **Gate→human (never auto):** **P3** vocalization sections (da-da-dun/woo-woo — dominates heavy-manual
|
||||
jobs); **P6** missed line; **P8** phantom/hallucinated lines (absurd durations).
|
||||
- **Defer:** **P7** trailing parenthetical backing bits → delete + extend last word (= the real timing
|
||||
axis; detect via lead-vocal audio energy after the transcribed end-time).
|
||||
|
||||
**Backing:** no-pink → clean (always right in data); pink → **KEEP** (human UNDER-keeps — 2/8 clean picks
|
||||
were wrong). Bias to keep. "Pink but don't keep" needs **3-stem analysis** (mixed/lead/backing): lead
|
||||
bleed (ae0cd7e8), backing-stem-IS-lead when lead quiet/reverby (1d45b286, catastrophic if kept),
|
||||
flat-noise pink (95d8e844). Maps to the up-front toggle `retain-where-possible(default)/clean/review`.
|
||||
|
||||
## 4. Code built (all in the worktree, UNCOMMITTED)
|
||||
|
||||
New:
|
||||
- `backend/services/auto_approval/{__init__,models,scorer,lyrics_diff}.py` — the shadow scorer +
|
||||
review-diff. Pure, tested. Will power the real gate at `screens_worker.py:214` later.
|
||||
- `backend/tests/services/auto_approval/{test_scorer,test_lyrics_diff}.py` (21 tests).
|
||||
- `scripts/review_capture.py` — offline per-job corpus record generator (superseded in practice by the
|
||||
replay UI, but still works).
|
||||
- `scripts/run-replay-local.sh` — one-command local replay backend.
|
||||
- `docs/REPLAY.md`, `docs/archive/2026-08-25-full-auto-review-design.md`.
|
||||
|
||||
Modified (the replay tool):
|
||||
- `backend/api/routes/review.py` — `GET /correction-data?replay=true` (admin/owner only): serves review
|
||||
data for ANY status (skips the status gate + the AWAITING→IN_REVIEW transition), attaches the parsed
|
||||
`edit_log` + a reconstructed `post_ai_segments` ("post-AI, pre-human" state). Plus a **dev-only audio
|
||||
byte-proxy** (`GET /{job}/dev-audio`, gated by env `REVIEW_AUDIO_PROXY`, supports HTTP Range) so review
|
||||
audio plays locally without GCS URL-signing. Helpers: `_reconstruct_post_ai_segments`, `_load_edit_log`,
|
||||
`_dev_audio_url`, `_ranged_response`, `_dev_audio_proxy_enabled`. Prod behaviour unchanged (flag off).
|
||||
- `backend/tests/test_routes_review.py` — +5 tests (replay gate/auth, dev-audio inert). 61 pass.
|
||||
- Frontend: `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx` (replay mode via `?replay=1`:
|
||||
bypass state gate for admin, `isReadOnly`, `ReplayNavBar` Prev/Next+Lyrics/Instrumental via `queue`
|
||||
URL param, `ReplayActionLog` panel, Post-AI/Final toggle), `components/instrumental-review/
|
||||
InstrumentalSelector.tsx` (+`isReadOnly` prop), `lib/api.ts` (+`replay` opt), `lib/lyrics-review/
|
||||
types.ts` (+`replay` fields). Changed files typecheck clean.
|
||||
|
||||
**Tests:** `python -m pytest backend/tests/services/auto_approval/ backend/tests/test_routes_review.py`
|
||||
→ 82 pass. Full `make test` NOT yet run. No version bump yet. Not PR'd.
|
||||
|
||||
## 5. How to resume the local replay environment
|
||||
|
||||
Backend + frontend may still be running from this session (check `curl localhost:8000/api/health` and
|
||||
`localhost:3000`). To (re)start:
|
||||
```bash
|
||||
cd <workspace>/karaoke-gen-full-auto-review
|
||||
./scripts/run-replay-local.sh # backend :8000, REAL prod data (read-only), REVIEW_AUDIO_PROXY on
|
||||
# in another terminal:
|
||||
cd frontend && npm run dev # :3000
|
||||
```
|
||||
Then in the browser: `localStorage.setItem('karaoke_access_token','replay-local-token')`, reload, and open:
|
||||
```
|
||||
http://localhost:3000/en/app/jobs?baseApiUrl=http://127.0.0.1:8000&replay=1&queue=<comma-ids>#/<jobId>/review
|
||||
```
|
||||
The 20-job `queue=` string is in `REVIEW-QUEUE.md` / the session transcript. Requires `gcloud auth
|
||||
application-default login` with READ access to Firestore `jobs` + GCS `karaoke-gen-storage-nomadkaraoke`.
|
||||
**Driving it in Playwright:** the Playwright browser is shared with Andrew (he can interact with the same
|
||||
window). You can extract his live in-browser edits via a React fiber full-tree walk (see transcript for the
|
||||
snippet) — needed because read-only blocks *save*, not in-UI editing.
|
||||
|
||||
## 6. Gotchas / caveats (IMPORTANT)
|
||||
|
||||
- **Don't trust the Post-AI reconstruction blindly.** It had 3 bugs this session (multi-word-replace
|
||||
"cram", dropped words, split-word identical timing) that briefly misled Andrew into thinking the AI had
|
||||
bugs it didn't. All fixed, but: **treat `corrections_updated.json` (final) as ground truth**; use the
|
||||
reconstruction/edit_log for *what changed*, not exact values.
|
||||
- **edit_log is not always complete** — it can miss segment-level deletions (e.g. 33453fa0's phantom-line
|
||||
deletes aren't in its log though the final has them removed). Use raw→final diff for completeness.
|
||||
- **Same-job reload doesn't re-fetch** after a backend change (SPA); do a hard reload (Cmd+Shift+R).
|
||||
- **Prod bucket = `karaoke-gen-storage-nomadkaraoke`** (config default `karaoke-gen-storage` is overridden
|
||||
by env in prod). Prod Firestore collection = `jobs`.
|
||||
- **GCP is read-only for this workspace** (claude-readonly ADC / here it was admin@ ADC but no
|
||||
Token-Creator). Can't sign GCS URLs locally (hence the dev-audio byte-proxy) and can't impersonate the
|
||||
backend SA. Don't attempt IAM/Pulumi writes.
|
||||
- **Public repo:** never commit customer emails / the private corpus into `karaoke-gen`. Corpus lives at
|
||||
workspace root on purpose.
|
||||
|
||||
## 7. What's PR-ready vs not
|
||||
|
||||
The scorer/diff/tests and the replay tool are self-contained and green. Before PR: run full `make test`,
|
||||
bump `pyproject.toml` version, `/docs-review`, `/coderabbit`. The dev-audio proxy + replay param are
|
||||
prod-inert (env/flag gated) so shipping them is low-risk, but confirm the `?replay=true` admin-gating and
|
||||
that `REVIEW_AUDIO_PROXY` is unset in prod. (Frontend `?replay=1` is admin-only via the existing gate.)
|
||||
|
||||
## 8. ★ Next steps (build order, from SYNTHESIS.md §4)
|
||||
|
||||
1. **Confidence gate (shadow → enforce).** Wire `auto_approval/scorer.py` into `screens_worker.py:214` in
|
||||
SHADOW mode (record verdict in `processing_metadata`, no behaviour change); validate its verdict
|
||||
against the 20-job corpus; then enforce (auto-ship high-confidence, route rest to human). Add the new
|
||||
signals: phantom/absurd-duration (P8), vocalization detector (P3).
|
||||
2. **Pattern 4 auto-fixer** (leading connective/interjection) — validate against the 6 examples in the
|
||||
corpus. Then **P1 dedupe** + **P5 reference-majority** in the AI-correct step.
|
||||
3. **Vocalization detector (P3)** → force human review (also feeds the gate).
|
||||
4. **Backing decider + 3-stem analysis** (bias-to-keep; reject bleed / lead-misclassification /
|
||||
flat-noise) → ship the up-front `retain backing vocals?` toggle (default retain-where-possible).
|
||||
5. **Timing: trailing-word extension via lead-vocal audio** (P7 + end-time-too-early) — later.
|
||||
|
||||
No new transcription model needed for 1–4; hard problems are *gated*, not solved. Start with #1 (validates
|
||||
the whole thesis cheaply) unless Andrew redirects.
|
||||
@@ -6,9 +6,10 @@
|
||||
* and backend calls are addressed with relative "/api/..." URLs.
|
||||
*/
|
||||
|
||||
import { apiFetch, BackendUnavailableError } from '@/lib/api'
|
||||
import { apiFetch, BackendUnavailableError, __backendHealthProbe } from '@/lib/api'
|
||||
import {
|
||||
getBackendStatus,
|
||||
configureHealthProbe,
|
||||
STALL_RECONNECTING_MS,
|
||||
STALL_UNAVAILABLE_MS,
|
||||
} from '@/lib/backend-status'
|
||||
@@ -42,6 +43,8 @@ describe('apiFetch', () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
;(globalThis as unknown as { fetch: unknown }).fetch = fetchMock
|
||||
// Re-register the real probe so its cached verdict resets between tests.
|
||||
configureHealthProbe(__backendHealthProbe)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -108,21 +111,57 @@ describe('apiFetch', () => {
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('surfaces the banner only once a GET has STALLED past the thresholds, then clears', async () => {
|
||||
it('surfaces the banner for a stalled GET once the health probe confirms the outage, then clears', async () => {
|
||||
jest.useFakeTimers()
|
||||
const d = deferredFetch()
|
||||
fetchMock.mockImplementation(d.fn)
|
||||
// Everything hangs — the backend is genuinely unreachable (recycle-style: the
|
||||
// origin holds requests open, so the probe only fails via its own timeout).
|
||||
let settleGet!: (r: Response) => void
|
||||
fetchMock.mockImplementation((url: unknown) => {
|
||||
if (String(url).includes('/api/health')) return new Promise<Response>(() => {})
|
||||
return new Promise<Response>((res) => {
|
||||
settleGet = res
|
||||
})
|
||||
})
|
||||
|
||||
const p = apiFetch('/api/jobs/abc')
|
||||
p.catch(() => {}) // avoid unhandled rejection if it ever fails
|
||||
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
// Stall threshold crossed → probe fires, but until it has a verdict the banner
|
||||
// stays hidden (a slow endpoint must not alarm the user without evidence).
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
// Probe times out (~4s) → outage confirmed → the hint appears.
|
||||
await jest.advanceTimersByTimeAsync(5_000)
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS - 5_000)
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
|
||||
d.settle(mockResponse(200, { ok: true }))
|
||||
settleGet(mockResponse(200, { ok: true }))
|
||||
await p
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
it('never surfaces the banner for a slow GET while the backend is reachable (health probe OK)', async () => {
|
||||
jest.useFakeTimers()
|
||||
// The read is legitimately slow (e.g. first-time instrumental-analysis
|
||||
// transcoding) but /api/health answers instantly — no banner, ever.
|
||||
let settleGet!: (r: Response) => void
|
||||
fetchMock.mockImplementation((url: unknown) => {
|
||||
if (String(url).includes('/api/health')) return Promise.resolve(mockResponse(200))
|
||||
return new Promise<Response>((res) => {
|
||||
settleGet = res
|
||||
})
|
||||
})
|
||||
|
||||
const p = apiFetch('/api/jobs/abc')
|
||||
p.catch(() => {})
|
||||
|
||||
// Well past both stall thresholds (but under the 45s hard timeout).
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 15_000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
|
||||
settleGet(mockResponse(200, { ok: true }))
|
||||
await p
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
|
||||
@@ -10,8 +10,10 @@ import {
|
||||
getBackendStatus,
|
||||
beginRequest,
|
||||
endRequest,
|
||||
configureHealthProbe,
|
||||
STALL_RECONNECTING_MS,
|
||||
STALL_UNAVAILABLE_MS,
|
||||
PROBE_FRESH_MS,
|
||||
} from '@/lib/backend-status'
|
||||
|
||||
describe('backend-status store (stall-based)', () => {
|
||||
@@ -88,3 +90,72 @@ describe('backend-status store (stall-based)', () => {
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
})
|
||||
})
|
||||
|
||||
describe('backend-status store (health-probe confirmation)', () => {
|
||||
let open: number[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
open = []
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
open.forEach((id) => endRequest(id))
|
||||
// Restore pure stall-based behavior so other suites are unaffected.
|
||||
configureHealthProbe(null)
|
||||
jest.clearAllTimers()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('suppresses the banner while the probe reports the backend reachable', async () => {
|
||||
const probe = jest.fn(() => Promise.resolve(true))
|
||||
configureHealthProbe(probe)
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
expect(probe).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the banner once the probe confirms the backend is unreachable', async () => {
|
||||
configureHealthProbe(() => Promise.resolve(false))
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
})
|
||||
|
||||
it('re-probes as the verdict goes stale, and clears the banner if the backend recovers', async () => {
|
||||
let reachable = false
|
||||
const probe = jest.fn(() => Promise.resolve(reachable))
|
||||
configureHealthProbe(probe)
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
|
||||
// Backend comes back (even though the old read is still hung) — the next
|
||||
// re-probe succeeds and the banner clears.
|
||||
reachable = true
|
||||
await jest.advanceTimersByTimeAsync(PROBE_FRESH_MS + 2000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
expect(probe.mock.calls.length).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('holds the banner back while the probe has no verdict yet', async () => {
|
||||
// A probe that takes 3s to fail (e.g. its own timeout racing a hung origin).
|
||||
configureHealthProbe(
|
||||
() => new Promise((res) => setTimeout(() => res(false), 3000)),
|
||||
)
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
|
||||
expect(getBackendStatus()).toBe('online') // stalled, but not yet confirmed
|
||||
|
||||
await jest.advanceTimersByTimeAsync(3000) // verdict lands
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
})
|
||||
})
|
||||
@@ -139,6 +139,69 @@ describe('getJobStep', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Upload-based (tenant / existing-instrumental) jobs', () => {
|
||||
const withInstrumental = (status: string, stateData?: Record<string, any>): Job => ({
|
||||
...createJob(status, stateData),
|
||||
existing_instrumental_gcs_path: 'uploads/test-job-123/audio/existing_instrumental.mp3',
|
||||
});
|
||||
|
||||
it('shows "preparingAudio" instead of "downloading" while staging uploads', () => {
|
||||
const result = getJobStep(withInstrumental('downloading'));
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('preparingAudio');
|
||||
});
|
||||
|
||||
it('also relabels the downloading_audio stage for uploaded audio', () => {
|
||||
const result = getJobStep(withInstrumental('downloading_audio'));
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('preparingAudio');
|
||||
});
|
||||
|
||||
it('advances to step 4 (transcribing) once the lyrics worker starts', () => {
|
||||
const result = getJobStep(withInstrumental('downloading', {
|
||||
lyrics_progress: { stage: 'transcribing', progress: 10 },
|
||||
}));
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('transcribing');
|
||||
});
|
||||
|
||||
it('does not relabel a normal download job (no uploaded instrumental)', () => {
|
||||
const result = getJobStep(createJob('downloading'));
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('downloading');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Status labels are always valid i18n keys (no raw "jobStatus.X")', () => {
|
||||
// Regression: the "downloading + workers" path used to pass the literal
|
||||
// "Processing" (not a jobStatus key), which rendered as "jobStatus.Processing".
|
||||
it('returns a valid key (transcribing) for lyrics-only progress, not "Processing"', () => {
|
||||
const result = getJobStep(createJob('downloading', {
|
||||
lyrics_progress: { stage: 'transcribing', progress: 5 },
|
||||
}));
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('transcribing');
|
||||
expect(result.label).not.toBe('Processing');
|
||||
});
|
||||
|
||||
it('every label getJobStep can emit exists in en.json jobStatus', () => {
|
||||
const en = require('../messages/en.json');
|
||||
const jobStatusKeys = new Set(Object.keys(en.jobStatus));
|
||||
// Static labels from STATUS_CONFIG plus keys emitted by the parallel/upload helpers.
|
||||
const dynamicKeys = [
|
||||
'processing', 'preparingAudio', 'processingComplete',
|
||||
'audio1of2', 'audio2of2', 'audioDone', 'audio',
|
||||
'transcribing', 'correcting', 'lyricsDone', 'lyrics',
|
||||
];
|
||||
for (const cfg of Object.values(STATUS_CONFIG)) {
|
||||
expect(jobStatusKeys.has((cfg as any).label)).toBe(true);
|
||||
}
|
||||
for (const k of dynamicKeys) {
|
||||
expect(jobStatusKeys.has(k)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Step 4: Parallel Processing', () => {
|
||||
it('returns step 4 for separating_stage1', () => {
|
||||
const job = createJob('separating_stage1');
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Tests for LocaleBadge — the admin-only flag + language pill showing what UI
|
||||
* language a user/job was using.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { LocaleBadge, localeDisplayName } from '@/components/admin/locale-badge'
|
||||
|
||||
describe('LocaleBadge', () => {
|
||||
it('renders the locale code with a flag for a known language', () => {
|
||||
render(<LocaleBadge locale="pt" />)
|
||||
// Shows the code by default
|
||||
expect(screen.getByText(/pt/)).toBeInTheDocument()
|
||||
// Language name is in the tooltip
|
||||
expect(screen.getByTitle(/Portuguese/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the full language name when showName is set', () => {
|
||||
render(<LocaleBadge locale="ja" showName />)
|
||||
expect(screen.getByText(/Japanese/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('normalizes a region-qualified locale to its primary subtag', () => {
|
||||
render(<LocaleBadge locale="pt-BR" />)
|
||||
expect(screen.getByTitle(/Portuguese \(pt\)/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders nothing for an empty locale by default', () => {
|
||||
const { container } = render(<LocaleBadge locale={null} />)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders a placeholder for an empty locale when showEmpty is set', () => {
|
||||
render(<LocaleBadge locale={undefined} showEmpty />)
|
||||
expect(screen.getByText(/—/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('localeDisplayName returns a readable name or null', () => {
|
||||
expect(localeDisplayName('de')).toMatch(/German/i)
|
||||
expect(localeDisplayName(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Tests for the GCS resumable upload engine.
|
||||
*
|
||||
* XHR is replaced with a scripted mock so we can assert the exact
|
||||
* Content-Range choreography: offset query → chunked PUTs → resume-from-offset
|
||||
* after failures, with no persisted byte ever re-sent.
|
||||
*/
|
||||
import {
|
||||
uploadResumable,
|
||||
queryUploadOffset,
|
||||
CHUNK_ALIGNMENT,
|
||||
ResumableUploadError,
|
||||
} from '@/lib/resumable-upload'
|
||||
|
||||
interface Scripted {
|
||||
status?: number
|
||||
range?: string
|
||||
progress?: number[]
|
||||
networkError?: boolean
|
||||
timeout?: boolean
|
||||
}
|
||||
|
||||
interface RecordedRequest {
|
||||
method: string
|
||||
url: string
|
||||
headers: Record<string, string>
|
||||
bodySize: number
|
||||
}
|
||||
|
||||
class MockXHR {
|
||||
static queue: Scripted[] = []
|
||||
static requests: RecordedRequest[] = []
|
||||
|
||||
method = ''
|
||||
url = ''
|
||||
status = 0
|
||||
timeout = 0
|
||||
upload: { onprogress: ((e: { lengthComputable: boolean; loaded: number }) => void) | null } = { onprogress: null }
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
onabort: (() => void) | null = null
|
||||
ontimeout: (() => void) | null = null
|
||||
private headers: Record<string, string> = {}
|
||||
private responseHeaders: Record<string, string> = {}
|
||||
private aborted = false
|
||||
|
||||
open(method: string, url: string) {
|
||||
this.method = method
|
||||
this.url = url
|
||||
}
|
||||
setRequestHeader(k: string, v: string) {
|
||||
this.headers[k] = v
|
||||
}
|
||||
getResponseHeader(k: string): string | null {
|
||||
return this.responseHeaders[k] ?? null
|
||||
}
|
||||
abort() {
|
||||
this.aborted = true
|
||||
setTimeout(() => this.onabort?.(), 0)
|
||||
}
|
||||
send(body?: Blob) {
|
||||
MockXHR.requests.push({
|
||||
method: this.method,
|
||||
url: this.url,
|
||||
headers: { ...this.headers },
|
||||
bodySize: body ? (body as Blob).size : 0,
|
||||
})
|
||||
const script = MockXHR.queue.shift() ?? { status: 200 }
|
||||
setTimeout(() => {
|
||||
if (this.aborted) return
|
||||
for (const loaded of script.progress ?? []) {
|
||||
this.upload.onprogress?.({ lengthComputable: true, loaded })
|
||||
}
|
||||
if (script.networkError) {
|
||||
this.onerror?.()
|
||||
return
|
||||
}
|
||||
if (script.timeout) {
|
||||
this.ontimeout?.()
|
||||
return
|
||||
}
|
||||
this.status = script.status ?? 200
|
||||
if (script.range) this.responseHeaders['Range'] = script.range
|
||||
this.onload?.()
|
||||
}, 0)
|
||||
}
|
||||
}
|
||||
|
||||
const realXHR = global.XMLHttpRequest
|
||||
|
||||
beforeEach(() => {
|
||||
MockXHR.queue = []
|
||||
MockXHR.requests = []
|
||||
;(global as any).XMLHttpRequest = MockXHR
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
;(global as any).XMLHttpRequest = realXHR
|
||||
})
|
||||
|
||||
function makeFile(size: number): File {
|
||||
return new File([new ArrayBuffer(size)], 'track.mp3')
|
||||
}
|
||||
|
||||
const SESSION = 'https://storage.googleapis.com/upload/session-abc'
|
||||
// Fast options for tests: minimal chunk, near-instant backoff.
|
||||
const OPTS = { chunkSize: CHUNK_ALIGNMENT, baseRetryDelayMs: 1 }
|
||||
|
||||
describe('uploadResumable — chunk choreography', () => {
|
||||
it('queries offset then uploads aligned chunks with correct Content-Range', async () => {
|
||||
const size = CHUNK_ALIGNMENT + 5000 // one full chunk + a final partial
|
||||
MockXHR.queue = [
|
||||
{ status: 308 }, // offset query: fresh session, nothing persisted
|
||||
{ status: 308, range: `bytes=0-${CHUNK_ALIGNMENT - 1}` }, // chunk 1 ack
|
||||
{ status: 200 }, // final chunk → complete
|
||||
]
|
||||
|
||||
await uploadResumable(SESSION, makeFile(size), OPTS)
|
||||
|
||||
const [query, chunk1, chunk2] = MockXHR.requests
|
||||
expect(query.headers['Content-Range']).toBe(`bytes */${size}`)
|
||||
expect(query.bodySize).toBe(0)
|
||||
expect(chunk1.headers['Content-Range']).toBe(`bytes 0-${CHUNK_ALIGNMENT - 1}/${size}`)
|
||||
expect(chunk1.bodySize).toBe(CHUNK_ALIGNMENT)
|
||||
expect(chunk2.headers['Content-Range']).toBe(`bytes ${CHUNK_ALIGNMENT}-${size - 1}/${size}`)
|
||||
expect(chunk2.bodySize).toBe(5000)
|
||||
})
|
||||
|
||||
it('resumes from the offset the session reports (no persisted bytes re-sent)', async () => {
|
||||
const size = 3 * CHUNK_ALIGNMENT
|
||||
const persisted = 2 * CHUNK_ALIGNMENT
|
||||
MockXHR.queue = [
|
||||
{ status: 308, range: `bytes=0-${persisted - 1}` }, // session already has 2 chunks
|
||||
{ status: 200 }, // remaining chunk completes the object
|
||||
]
|
||||
|
||||
await uploadResumable(SESSION, makeFile(size), OPTS)
|
||||
|
||||
expect(MockXHR.requests).toHaveLength(2)
|
||||
const chunk = MockXHR.requests[1]
|
||||
expect(chunk.headers['Content-Range']).toBe(`bytes ${persisted}-${size - 1}/${size}`)
|
||||
expect(chunk.bodySize).toBe(size - persisted)
|
||||
})
|
||||
|
||||
it('resolves without uploading when the session reports complete', async () => {
|
||||
MockXHR.queue = [{ status: 200 }] // offset query says done
|
||||
await uploadResumable(SESSION, makeFile(1000), OPTS)
|
||||
expect(MockXHR.requests).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('uploadResumable — failure recovery', () => {
|
||||
it('recovers the true offset after a network failure and resumes there', async () => {
|
||||
const size = 2 * CHUNK_ALIGNMENT
|
||||
MockXHR.queue = [
|
||||
{ status: 308 }, // initial offset query: 0
|
||||
{ networkError: true }, // chunk 1 dies mid-flight
|
||||
{ status: 308, range: `bytes=0-${CHUNK_ALIGNMENT - 1}` }, // recovery query: GCS kept chunk 1!
|
||||
{ status: 200 }, // only the remainder is sent
|
||||
]
|
||||
|
||||
await uploadResumable(SESSION, makeFile(size), OPTS)
|
||||
|
||||
expect(MockXHR.requests).toHaveLength(4)
|
||||
const retried = MockXHR.requests[3]
|
||||
// Resumes at the recovered offset — the persisted chunk is never re-sent.
|
||||
expect(retried.headers['Content-Range']).toBe(`bytes ${CHUNK_ALIGNMENT}-${size - 1}/${size}`)
|
||||
expect(retried.bodySize).toBe(CHUNK_ALIGNMENT)
|
||||
})
|
||||
|
||||
it('discovers completion during failure recovery', async () => {
|
||||
const size = CHUNK_ALIGNMENT
|
||||
MockXHR.queue = [
|
||||
{ status: 308 },
|
||||
{ networkError: true }, // chunk dies... but GCS actually persisted it all
|
||||
{ status: 200 }, // recovery query: complete
|
||||
]
|
||||
await uploadResumable(SESSION, makeFile(size), OPTS)
|
||||
expect(MockXHR.requests).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('throws immediately on a permanent error (session expired)', async () => {
|
||||
MockXHR.queue = [
|
||||
{ status: 308 },
|
||||
{ status: 410 }, // session gone — retrying is pointless
|
||||
]
|
||||
await expect(uploadResumable(SESSION, makeFile(1000), OPTS)).rejects.toMatchObject({
|
||||
name: 'ResumableUploadError',
|
||||
status: 410,
|
||||
permanent: true,
|
||||
})
|
||||
expect(MockXHR.requests).toHaveLength(2) // no retries
|
||||
})
|
||||
|
||||
it('treats a non-advancing 308 as a transient failure (no infinite loop)', async () => {
|
||||
// GCS acknowledges the chunk but reports the SAME offset every time —
|
||||
// without the guard this would re-send the identical chunk forever.
|
||||
MockXHR.queue = [{ status: 308 }] // initial offset query: 0
|
||||
for (let i = 0; i < 20; i++) {
|
||||
MockXHR.queue.push({ status: 308, range: 'bytes=0-0' }) // never advances (offset stays ~0)
|
||||
MockXHR.queue.push({ status: 308, range: 'bytes=0-0' }) // recovery query, same story
|
||||
}
|
||||
|
||||
await expect(
|
||||
uploadResumable(SESSION, makeFile(2 * CHUNK_ALIGNMENT), { ...OPTS, maxConsecutiveFailures: 3 }),
|
||||
).rejects.toMatchObject({ name: 'ResumableUploadError', permanent: false })
|
||||
// Bounded attempts, not an endless loop.
|
||||
expect(MockXHR.requests.length).toBeLessThan(15)
|
||||
})
|
||||
|
||||
it('offset-query timeout is surfaced as a transient error', async () => {
|
||||
MockXHR.queue = [{ timeout: true }]
|
||||
await expect(queryUploadOffset(SESSION, 1000)).rejects.toMatchObject({
|
||||
name: 'ResumableUploadError',
|
||||
permanent: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('gives up after maxConsecutiveFailures transient failures', async () => {
|
||||
// Every chunk attempt and every recovery query fails.
|
||||
MockXHR.queue = [{ status: 308 }]
|
||||
for (let i = 0; i < 20; i++) MockXHR.queue.push({ networkError: true })
|
||||
|
||||
await expect(
|
||||
uploadResumable(SESSION, makeFile(CHUNK_ALIGNMENT), { ...OPTS, maxConsecutiveFailures: 2 }),
|
||||
).rejects.toMatchObject({ name: 'ResumableUploadError', permanent: false })
|
||||
})
|
||||
|
||||
it('reports progress with loaded bytes and state transitions', async () => {
|
||||
const size = CHUNK_ALIGNMENT
|
||||
MockXHR.queue = [
|
||||
{ status: 308 },
|
||||
{ status: 200, progress: [100_000, size] },
|
||||
]
|
||||
const states: string[] = []
|
||||
let lastLoaded = 0
|
||||
await uploadResumable(SESSION, makeFile(size), {
|
||||
...OPTS,
|
||||
onProgress: (p) => {
|
||||
states.push(p.state)
|
||||
expect(p.loaded).toBeGreaterThanOrEqual(lastLoaded)
|
||||
lastLoaded = p.loaded
|
||||
expect(p.total).toBe(size)
|
||||
},
|
||||
})
|
||||
expect(lastLoaded).toBe(size)
|
||||
expect(states).toContain('uploading')
|
||||
})
|
||||
})
|
||||
|
||||
describe('queryUploadOffset', () => {
|
||||
it('parses the Range header into the next offset', async () => {
|
||||
MockXHR.queue = [{ status: 308, range: 'bytes=0-1048575' }]
|
||||
await expect(queryUploadOffset(SESSION, 5_000_000)).resolves.toBe(1_048_576)
|
||||
})
|
||||
|
||||
it('returns 0 for a fresh session with no Range header', async () => {
|
||||
MockXHR.queue = [{ status: 308 }]
|
||||
await expect(queryUploadOffset(SESSION, 5_000_000)).resolves.toBe(0)
|
||||
})
|
||||
|
||||
it('returns "complete" when the object is finished', async () => {
|
||||
MockXHR.queue = [{ status: 201 }]
|
||||
await expect(queryUploadOffset(SESSION, 5_000_000)).resolves.toBe('complete')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,338 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Tests for TenantBulkFlow — the tenant portal bulk folder-upload review table.
|
||||
*
|
||||
* Verifies the review-table interactions the plan calls out:
|
||||
* - analyze populates an editable row per proposed pair
|
||||
* - an operator can edit a cell (artist)
|
||||
* - an operator can remove a row
|
||||
* - submit runs the create → upload(x2) → complete sequence once per remaining
|
||||
* valid row, all sharing one batch_id
|
||||
* - unpaired (mixed-only) files are surfaced as warnings, never auto-submitted
|
||||
*
|
||||
* next-intl is globally mocked in jest.setup.js (real en strings).
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'
|
||||
import { api } from '@/lib/api'
|
||||
import { TenantBulkFlow } from '@/components/job/TenantBulkFlow'
|
||||
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
analyzeBulk: jest.fn(),
|
||||
createJobWithUploadUrls: jest.fn(),
|
||||
uploadToSignedUrl: jest.fn(),
|
||||
completeJobUpload: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
status: number
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
// The resumable engine is unit-tested separately; here we assert the component
|
||||
// routes resumable entries through it (and legacy entries through signed PUT).
|
||||
jest.mock('@/lib/resumable-upload', () => ({
|
||||
uploadResumable: jest.fn().mockResolvedValue(undefined),
|
||||
ResumableUploadError: class ResumableUploadError extends Error {
|
||||
status: number
|
||||
permanent: boolean
|
||||
constructor(message: string, status: number, permanent: boolean) {
|
||||
super(message)
|
||||
this.name = 'ResumableUploadError'
|
||||
this.status = status
|
||||
this.permanent = permanent
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
// IndexedDB isn't available in jsdom; mock persistence but keep the real
|
||||
// matchRepickedFile so the recovery flow exercises genuine matching logic.
|
||||
jest.mock('@/lib/upload-recovery', () => {
|
||||
const actual = jest.requireActual('@/lib/upload-recovery')
|
||||
return {
|
||||
...actual,
|
||||
saveRowSessions: jest.fn().mockResolvedValue(undefined),
|
||||
markRowDone: jest.fn().mockResolvedValue(undefined),
|
||||
clearBatch: jest.fn().mockResolvedValue(undefined),
|
||||
loadPendingBatch: jest.fn().mockResolvedValue(null),
|
||||
}
|
||||
})
|
||||
|
||||
import { uploadResumable } from '@/lib/resumable-upload'
|
||||
import { saveRowSessions, markRowDone, loadPendingBatch } from '@/lib/upload-recovery'
|
||||
|
||||
const mockApi = api as jest.Mocked<typeof api>
|
||||
const mockUploadResumable = uploadResumable as jest.MockedFunction<typeof uploadResumable>
|
||||
const mockLoadPendingBatch = loadPendingBatch as jest.MockedFunction<typeof loadPendingBatch>
|
||||
|
||||
const MIXED_1 = 'S1100-1 Eddy Grant - I Dont Wanna Dance Guide.mp3'
|
||||
const INST_1 = 'S1100-2 Eddy Grant - I Dont Wanna Dance BV.mp3'
|
||||
const MIXED_2 = 'S1101-1 Smokey - Some Cats Know Guide.mp3'
|
||||
const INST_2 = 'S1101-2 Smokey - Some Cats Know Instru.mp3'
|
||||
const ORPHAN = 'S1102-2 Setzer - Straight Up Guide.mp3'
|
||||
|
||||
function makeFiles(): File[] {
|
||||
return [MIXED_1, INST_1, MIXED_2, INST_2, ORPHAN, 'cover.png'].map(
|
||||
name => new File(['x'], name, { type: name.endsWith('.png') ? 'image/png' : 'audio/mpeg' }),
|
||||
)
|
||||
}
|
||||
|
||||
function analysisResponse() {
|
||||
return {
|
||||
rows: [
|
||||
{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'high', warning: null },
|
||||
{ artist: 'Smokey', title: 'Some Cats Know', mixed_filename: MIXED_2, instrumental_filename: INST_2, confidence: 'high', warning: null },
|
||||
],
|
||||
unpaired: [
|
||||
{ filename: ORPHAN, reason: 'no_instrumental', artist: 'Setzer', title: 'Straight Up', role: 'mixed' },
|
||||
],
|
||||
ignored: [{ filename: 'cover.png', reason: 'non_audio' }],
|
||||
}
|
||||
}
|
||||
|
||||
function selectFiles() {
|
||||
const input = screen.getByTestId('bulk-files-input')
|
||||
fireEvent.change(input, { target: { files: makeFiles() } })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockLoadPendingBatch.mockResolvedValue(null)
|
||||
mockUploadResumable.mockResolvedValue(undefined)
|
||||
mockApi.analyzeBulk.mockResolvedValue(analysisResponse())
|
||||
mockApi.createJobWithUploadUrls.mockImplementation(async (_a, _t, _files) => ({
|
||||
status: 'success',
|
||||
job_id: `job-${Math.random().toString(36).slice(2, 8)}`,
|
||||
message: 'ok',
|
||||
upload_urls: [
|
||||
{ file_type: 'audio', gcs_path: 'p1', upload_url: 'https://u/audio', content_type: 'audio/mpeg' },
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'p2', upload_url: 'https://u/inst', content_type: 'audio/mpeg' },
|
||||
],
|
||||
server_version: '1',
|
||||
}))
|
||||
mockApi.uploadToSignedUrl.mockResolvedValue(undefined)
|
||||
mockApi.completeJobUpload.mockResolvedValue({ status: 'success', message: 'started' })
|
||||
})
|
||||
|
||||
it('analyze populates one editable row per proposed pair and lists warnings', async () => {
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
|
||||
await waitFor(() => expect(mockApi.analyzeBulk).toHaveBeenCalledTimes(1))
|
||||
// Two artist inputs (one per row).
|
||||
const artistInputs = await screen.findAllByLabelText('Artist')
|
||||
expect(artistInputs).toHaveLength(2)
|
||||
// The mixed-only orphan is surfaced as a warning (with its reason), not a row.
|
||||
expect(screen.getByText(/Some files need attention/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/no matching instrumental found/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/non-audio files ignored/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('edits a cell, removes a row, and submits the create sequence once per remaining row', async () => {
|
||||
const onJobsChanged = jest.fn()
|
||||
render(<TenantBulkFlow onJobsChanged={onJobsChanged} />)
|
||||
selectFiles()
|
||||
|
||||
await screen.findAllByLabelText('Artist')
|
||||
|
||||
// Edit the first row's artist cell.
|
||||
const artistInputs = screen.getAllByLabelText('Artist') as HTMLInputElement[]
|
||||
fireEvent.change(artistInputs[0], { target: { value: 'Eddy Grant Edited' } })
|
||||
expect(artistInputs[0].value).toBe('Eddy Grant Edited')
|
||||
|
||||
// Remove the second row.
|
||||
const removeButtons = screen.getAllByLabelText('Remove track')
|
||||
expect(removeButtons).toHaveLength(2)
|
||||
fireEvent.click(removeButtons[1])
|
||||
await waitFor(() => expect(screen.getAllByLabelText('Artist')).toHaveLength(1))
|
||||
|
||||
// Submit — one row remains.
|
||||
const submitBtn = screen.getByRole('button', { name: /Submit 1 tracks/i })
|
||||
fireEvent.click(submitBtn)
|
||||
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(1))
|
||||
|
||||
// Exactly one job created, with the edited artist + tenant flags + a batch_id.
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(1)
|
||||
const [artist, title, files, options] = mockApi.createJobWithUploadUrls.mock.calls[0]
|
||||
expect(artist).toBe('Eddy Grant Edited')
|
||||
expect(title).toBe('I Dont Wanna Dance')
|
||||
expect(options).toEqual(expect.objectContaining({ is_private: true, existing_instrumental: true }))
|
||||
expect(typeof (options as any).batch_id).toBe('string')
|
||||
expect((files as any[]).map(f => f.file_type)).toEqual(['audio', 'existing_instrumental'])
|
||||
|
||||
// Two uploads (mixed + instrumental) for the single row.
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledTimes(2)
|
||||
expect(onJobsChanged).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('submits every valid row sharing a single batch_id', async () => {
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 2 tracks/i }))
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(2))
|
||||
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(2)
|
||||
const batchIds = mockApi.createJobWithUploadUrls.mock.calls.map(c => (c[3] as any).batch_id)
|
||||
expect(new Set(batchIds).size).toBe(1)
|
||||
})
|
||||
|
||||
it('retries a failed row by resuming its job, never creating a duplicate', async () => {
|
||||
// First submit: creation succeeds but the upload fails → row goes to error,
|
||||
// keeping its jobId + signed URLs.
|
||||
mockApi.uploadToSignedUrl.mockRejectedValueOnce(new Error('network blip'))
|
||||
|
||||
// Use a single-row analysis for a precise assertion.
|
||||
mockApi.analyzeBulk.mockResolvedValue({
|
||||
rows: [
|
||||
{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'high', warning: null },
|
||||
],
|
||||
unpaired: [],
|
||||
ignored: [],
|
||||
})
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(1))
|
||||
await waitFor(() => expect(screen.getByText(/will retry on submit/i)).toBeInTheDocument())
|
||||
|
||||
// Retry: the row is still submittable and resumes the SAME job (no 2nd create).
|
||||
const retryBtn = screen.getByRole('button', { name: /Submit 1 tracks/i })
|
||||
expect(retryBtn).not.toBeDisabled()
|
||||
fireEvent.click(retryBtn)
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(1))
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(1) // never duplicated
|
||||
})
|
||||
|
||||
it('surfaces a caution for low-confidence / warned rows', async () => {
|
||||
mockApi.analyzeBulk.mockResolvedValue({
|
||||
rows: [
|
||||
{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'low', warning: null },
|
||||
{ artist: 'Smokey', title: 'Some Cats Know', mixed_filename: MIXED_2, instrumental_filename: INST_2, confidence: 'high', warning: 'labels were ambiguous' },
|
||||
],
|
||||
unpaired: [],
|
||||
ignored: [],
|
||||
})
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
|
||||
// Low-confidence row shows the generic double-check caution.
|
||||
expect(screen.getByText(/Low-confidence match/i)).toBeInTheDocument()
|
||||
// Explicit analyzer warning is shown verbatim.
|
||||
expect(screen.getByText(/labels were ambiguous/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('requests resumable mode and uploads via the resumable engine', async () => {
|
||||
mockApi.analyzeBulk.mockResolvedValue({
|
||||
rows: [
|
||||
{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'high', warning: null },
|
||||
],
|
||||
unpaired: [],
|
||||
ignored: [],
|
||||
})
|
||||
mockApi.createJobWithUploadUrls.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'job-resumable',
|
||||
message: 'ok',
|
||||
upload_urls: [
|
||||
{ file_type: 'audio', gcs_path: 'p1', upload_url: 'https://session/audio', content_type: 'audio/mpeg', resumable: true },
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'p2', upload_url: 'https://session/inst', content_type: 'audio/mpeg', resumable: true },
|
||||
],
|
||||
server_version: '1',
|
||||
})
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(1))
|
||||
|
||||
// Backend asked for resumable session URIs.
|
||||
const options = mockApi.createJobWithUploadUrls.mock.calls[0][3] as any
|
||||
expect(options.upload_mode).toBe('resumable')
|
||||
// Both files went through the resumable engine, not the signed-PUT path.
|
||||
expect(mockUploadResumable).toHaveBeenCalledTimes(2)
|
||||
expect(mockUploadResumable.mock.calls.map(c => c[0])).toEqual(['https://session/audio', 'https://session/inst'])
|
||||
expect(mockApi.uploadToSignedUrl).not.toHaveBeenCalled()
|
||||
// Session state persisted for re-pick recovery, then cleaned up on success.
|
||||
expect(saveRowSessions).toHaveBeenCalledTimes(1)
|
||||
expect((saveRowSessions as jest.Mock).mock.calls[0][0]).toMatchObject({
|
||||
jobId: 'job-resumable',
|
||||
files: expect.arrayContaining([expect.objectContaining({ sessionUri: 'https://session/audio' })]),
|
||||
})
|
||||
expect(markRowDone).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('offers to resume an unfinished batch and resumes without re-creating jobs', async () => {
|
||||
const mixedFile = new File(['x'], MIXED_1, { type: 'audio/mpeg', lastModified: 111 })
|
||||
const instFile = new File(['x'], INST_1, { type: 'audio/mpeg', lastModified: 222 })
|
||||
mockLoadPendingBatch.mockResolvedValue({
|
||||
batchId: 'batch-recovered',
|
||||
rows: [
|
||||
{
|
||||
key: 'batch-recovered:row-1',
|
||||
batchId: 'batch-recovered',
|
||||
rowId: 'row-1',
|
||||
jobId: 'job-restored',
|
||||
artist: 'Eddy Grant',
|
||||
title: 'I Dont Wanna Dance',
|
||||
createdAt: Date.now(),
|
||||
files: [
|
||||
{ fileType: 'audio', identity: MIXED_1, name: MIXED_1, size: mixedFile.size, lastModified: 111, sessionUri: 'https://session/audio' },
|
||||
{ fileType: 'existing_instrumental', identity: INST_1, name: INST_1, size: instFile.size, lastModified: 222, sessionUri: 'https://session/inst' },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
|
||||
// Banner appears; choose to resume, then re-pick the folder.
|
||||
await screen.findByTestId('resume-banner')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Choose folder to resume/i }))
|
||||
fireEvent.change(screen.getByTestId('bulk-folder-input'), { target: { files: [mixedFile, instFile] } })
|
||||
|
||||
// Review table rebuilt from the persisted batch — no fresh analyze call.
|
||||
const artistInputs = await screen.findAllByLabelText('Artist') as HTMLInputElement[]
|
||||
expect(artistInputs).toHaveLength(1)
|
||||
expect(artistInputs[0].value).toBe('Eddy Grant')
|
||||
expect(mockApi.analyzeBulk).not.toHaveBeenCalled()
|
||||
|
||||
// Submitting resumes the existing job's sessions — no job creation.
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledWith('job-restored', ['audio', 'existing_instrumental']))
|
||||
expect(mockApi.createJobWithUploadUrls).not.toHaveBeenCalled()
|
||||
expect(mockUploadResumable.mock.calls.map(c => c[0])).toEqual(['https://session/audio', 'https://session/inst'])
|
||||
})
|
||||
|
||||
it('matchRepickedFile requires an exact size and disambiguates by mtime', () => {
|
||||
const { matchRepickedFile } = jest.requireActual('@/lib/upload-recovery')
|
||||
const persisted = { fileType: 'audio', identity: 'a.mp3', name: 'a.mp3', size: 1, lastModified: 111, sessionUri: 's' }
|
||||
const right = new File(['x'], 'a.mp3', { lastModified: 111 })
|
||||
const wrongSize = new File(['xx'], 'a.mp3', { lastModified: 111 })
|
||||
const wrongMtime = new File(['x'], 'a.mp3', { lastModified: 999 })
|
||||
|
||||
expect(matchRepickedFile(persisted, [right])).toBe(right)
|
||||
// Same name but different size = a different file — never resumed.
|
||||
expect(matchRepickedFile(persisted, [wrongSize])).toBeNull()
|
||||
// Ambiguous same-name same-size candidates → mtime decides.
|
||||
expect(matchRepickedFile(persisted, [wrongMtime, right])).toBe(right)
|
||||
})
|
||||
|
||||
it('exports TenantBulkFlow as a named export', () => {
|
||||
expect(typeof TenantBulkFlow).toBe('function')
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Tests for UserEmailsCard — the admin "Emails sent to this user" section and
|
||||
* its inbox-fidelity preview modal.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import { UserEmailsCard } from '@/components/admin/user-emails-card'
|
||||
|
||||
jest.mock('@/lib/api', () => ({
|
||||
adminApi: {
|
||||
getUserEmails: jest.fn(),
|
||||
getEmailDetail: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { adminApi } from '@/lib/api'
|
||||
|
||||
const getUserEmails = adminApi.getUserEmails as jest.Mock
|
||||
const getEmailDetail = adminApi.getEmailDetail as jest.Mock
|
||||
|
||||
describe('UserEmailsCard', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('lists emails returned for the user', async () => {
|
||||
getUserEmails.mockResolvedValue({
|
||||
email: 'u@x.com', count: 2, postmark_available: true,
|
||||
emails: [
|
||||
{ message_id: 'm1', source: 'postmark', subject: 'Welcome to Nomad', sent_at: '2026-08-20T10:00:00Z', status: 'Delivered', email_type: 'welcome' },
|
||||
{ message_id: 'm2', source: 'log', subject: 'Your receipt', sent_at: '2026-08-19T10:00:00Z', email_type: 'credits_added' },
|
||||
],
|
||||
})
|
||||
render(<UserEmailsCard email="u@x.com" />)
|
||||
await waitFor(() => expect(screen.getByText('Welcome to Nomad')).toBeInTheDocument())
|
||||
expect(screen.getByText('Your receipt')).toBeInTheDocument()
|
||||
expect(getUserEmails).toHaveBeenCalledWith('u@x.com')
|
||||
})
|
||||
|
||||
it('shows an empty state when there are no emails', async () => {
|
||||
getUserEmails.mockResolvedValue({ email: 'u@x.com', count: 0, postmark_available: true, emails: [] })
|
||||
render(<UserEmailsCard email="u@x.com" />)
|
||||
await waitFor(() => expect(screen.getByText(/No emails found/i)).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('opens the preview modal and renders the email HTML in an iframe', async () => {
|
||||
getUserEmails.mockResolvedValue({
|
||||
email: 'u@x.com', count: 1, postmark_available: true,
|
||||
emails: [{ message_id: 'm1', source: 'postmark', subject: 'Welcome', sent_at: '2026-08-20T10:00:00Z', status: 'Delivered' }],
|
||||
})
|
||||
getEmailDetail.mockResolvedValue({
|
||||
message_id: 'm1', source: 'postmark', subject: 'Welcome', from_email: 'gen@x.com',
|
||||
to: 'u@x.com', sent_at: '2026-08-20T10:00:00Z', status: 'Delivered',
|
||||
html_body: '<h1>Hello there</h1>', open_count: 2,
|
||||
})
|
||||
|
||||
render(<UserEmailsCard email="u@x.com" />)
|
||||
await waitFor(() => expect(screen.getByText('Welcome')).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByText('Welcome'))
|
||||
|
||||
await waitFor(() => expect(getEmailDetail).toHaveBeenCalledWith('m1', 'postmark'))
|
||||
// Metadata + iframe with the exact HTML the user received.
|
||||
await waitFor(() => {
|
||||
const iframe = document.querySelector('iframe[title="Email preview"]') as HTMLIFrameElement
|
||||
expect(iframe).toBeTruthy()
|
||||
expect(iframe.getAttribute('srcDoc') ?? iframe.getAttribute('srcdoc')).toContain('Hello there')
|
||||
})
|
||||
})
|
||||
|
||||
it('shows an error when loading fails', async () => {
|
||||
getUserEmails.mockRejectedValue(new Error('nope'))
|
||||
render(<UserEmailsCard email="u@x.com" />)
|
||||
await waitFor(() => expect(screen.getByText('nope')).toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
@@ -55,6 +55,13 @@ export function JobRouterClient() {
|
||||
typeof window !== 'undefined' ? window.location.hash : ''
|
||||
)
|
||||
|
||||
// Replay mode: read-only re-open of a COMPLETED job's review UI for the
|
||||
// fully-automated-review recording program. Enabled via ?replay=1 (admin only).
|
||||
const [isReplay] = useState(() =>
|
||||
typeof window !== 'undefined' &&
|
||||
new URLSearchParams(window.location.search).get('replay') === '1'
|
||||
)
|
||||
|
||||
// Listen for hash changes
|
||||
useEffect(() => {
|
||||
const handleHashChange = () => {
|
||||
@@ -125,9 +132,11 @@ export function JobRouterClient() {
|
||||
return
|
||||
}
|
||||
|
||||
// Check job is in correct state
|
||||
// Check job is in correct state.
|
||||
// Replay mode (admin only) bypasses the state gate so a COMPLETED job's
|
||||
// review UI can be re-opened read-only.
|
||||
const expectedStates = getExpectedStates(routeType)
|
||||
if (!expectedStates.includes(job.status)) {
|
||||
if (!(isReplay && isAdmin) && !expectedStates.includes(job.status)) {
|
||||
setAccessState({
|
||||
status: "wrong_state",
|
||||
currentState: job.status,
|
||||
@@ -152,7 +161,7 @@ export function JobRouterClient() {
|
||||
}
|
||||
|
||||
checkAccess()
|
||||
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated])
|
||||
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated, isReplay])
|
||||
|
||||
// Loading state
|
||||
if (accessState.status === "loading") {
|
||||
@@ -281,23 +290,27 @@ export function JobRouterClient() {
|
||||
if (currentRouteType === "instrumental") {
|
||||
return (
|
||||
<CrashReportBoundary source="instrumental-review" backHref="/app">
|
||||
<InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
<InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} isReplay={isReplay} />
|
||||
</CrashReportBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<CrashReportBoundary source="lyrics-review" backHref="/app">
|
||||
<LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
<LyricsReviewWrapper job={job} isLocalMode={inLocalMode} isReplay={isReplay} />
|
||||
</CrashReportBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
// Lyrics Review Component Wrapper
|
||||
function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
|
||||
function LyricsReviewWrapper({ job, isLocalMode = false, isReplay = false }: { job: Job; isLocalMode?: boolean; isReplay?: boolean }) {
|
||||
const [correctionData, setCorrectionData] = useState<CorrectionData | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
// Replay: toggle between the final lyrics and the "post-AI, pre-human" state so
|
||||
// manual edits are obvious. Reset whenever the job changes.
|
||||
const [showPostAi, setShowPostAi] = useState(false)
|
||||
useEffect(() => { setShowPostAi(false) }, [job.job_id])
|
||||
|
||||
// Create the API client for this job
|
||||
const apiClient = createLyricsReviewApiClient(job.job_id)
|
||||
@@ -308,7 +321,7 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
const data = await lyricsReviewApi.getCorrectionData(job.job_id)
|
||||
const data = await lyricsReviewApi.getCorrectionData(job.job_id, { replay: isReplay })
|
||||
setCorrectionData(data)
|
||||
} catch (err) {
|
||||
console.error("Failed to load correction data:", err)
|
||||
@@ -318,7 +331,7 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
}
|
||||
}
|
||||
loadData()
|
||||
}, [job.job_id])
|
||||
}, [job.job_id, isReplay])
|
||||
|
||||
// File load handler (opens file picker for local file)
|
||||
const handleFileLoad = useCallback(() => {
|
||||
@@ -386,7 +399,9 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
alt="Nomad Karaoke"
|
||||
style={{ height: 40 }}
|
||||
/>
|
||||
<h1 className="text-lg font-bold">Lyrics Transcription Review</h1>
|
||||
<h1 className="text-lg font-bold">
|
||||
{isReplay ? "Lyrics Review — Replay (read-only)" : "Lyrics Transcription Review"}
|
||||
</h1>
|
||||
{(job.artist || job.title) && (
|
||||
<span className="text-xs md:text-sm text-muted-foreground truncate">
|
||||
{[job.artist, job.title].filter(Boolean).join(" - ")}
|
||||
@@ -397,13 +412,44 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{isReplay && <ReplayNavBar jobId={job.job_id} screen="review" />}
|
||||
{isReplay && (
|
||||
<ReplayActionLog
|
||||
editLog={correctionData.replay?.edit_log ?? null}
|
||||
instrumentalSelection={correctionData.replay?.instrumental_selection ?? null}
|
||||
jobStatus={correctionData.replay?.job_status ?? job.status}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isReplay && correctionData.replay?.has_manual_edits && correctionData.replay?.post_ai_segments && (
|
||||
<div className="mx-4 mt-2 flex items-center gap-2 rounded-lg border border-amber-400/40 bg-amber-50/40 dark:bg-amber-900/10 px-3 py-2 text-sm">
|
||||
<span className="text-muted-foreground">Viewing lyrics:</span>
|
||||
<button
|
||||
className={`px-3 py-1 rounded font-medium ${!showPostAi ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-muted/70"}`}
|
||||
onClick={() => setShowPostAi(false)}
|
||||
>Final (my result)</button>
|
||||
<button
|
||||
className={`px-3 py-1 rounded font-medium ${showPostAi ? "bg-amber-500 text-white" : "bg-muted text-muted-foreground hover:bg-muted/70"}`}
|
||||
onClick={() => setShowPostAi(true)}
|
||||
>Post-AI (pre-human)</button>
|
||||
<span className="text-xs text-muted-foreground ml-1">
|
||||
{showPostAi ? "← what the AI produced, before your manual edits" : "← your final version"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<main className="px-4 py-2">
|
||||
<LyricsAnalyzer
|
||||
data={correctionData}
|
||||
key={showPostAi ? "postai" : "final"}
|
||||
data={
|
||||
showPostAi && correctionData.replay?.post_ai_segments
|
||||
? { ...correctionData, corrected_segments: correctionData.replay.post_ai_segments }
|
||||
: correctionData
|
||||
}
|
||||
onFileLoad={handleFileLoad}
|
||||
onShowMetadata={handleShowMetadata}
|
||||
apiClient={apiClient}
|
||||
isReadOnly={false}
|
||||
isReadOnly={isReplay}
|
||||
audioHash={correctionData.metadata?.audio_hash || job.audio_hash || job.job_id}
|
||||
isLocalMode={isLocalMode}
|
||||
jobId={job.job_id}
|
||||
@@ -414,12 +460,140 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
)
|
||||
}
|
||||
|
||||
// Instrumental Review Component Wrapper
|
||||
// The InstrumentalSelector component handles its own data fetching and submission
|
||||
// It uses the appropriate API based on isLocalMode
|
||||
function InstrumentalReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
|
||||
/**
|
||||
* ReplayNavBar — replay-only navigation: toggle Lyrics⇄Instrumental for the current
|
||||
* job, and step Prev/Next through the job list (passed as a comma-separated `queue`
|
||||
* URL param). All navigation is hash-only (`#/<id>/<screen>`), so the query params
|
||||
* (baseApiUrl, replay, queue) are preserved and the app re-renders via hashchange.
|
||||
*/
|
||||
function ReplayNavBar({ jobId, screen }: { jobId: string; screen: "review" | "instrumental" }) {
|
||||
const queue = (typeof window !== "undefined"
|
||||
? new URLSearchParams(window.location.search).get("queue")
|
||||
: null)?.split(",").map((s) => s.trim()).filter(Boolean) ?? []
|
||||
const idx = queue.indexOf(jobId)
|
||||
const prev = idx > 0 ? queue[idx - 1] : null
|
||||
const next = idx >= 0 && idx < queue.length - 1 ? queue[idx + 1] : null
|
||||
const go = (id: string, s: "review" | "instrumental") => { window.location.hash = `#/${id}/${s}` }
|
||||
|
||||
const tabCls = (active: boolean) =>
|
||||
`px-3 py-1 rounded text-sm font-medium ${active ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-muted/70"}`
|
||||
const navCls = (enabled: boolean) =>
|
||||
`px-3 py-1 rounded text-sm font-medium border ${enabled ? "hover:bg-muted" : "opacity-40 cursor-not-allowed"}`
|
||||
|
||||
return (
|
||||
<InstrumentalSelector job={job} isLocalMode={isLocalMode} />
|
||||
<div className="mx-4 mt-2 flex items-center gap-2 rounded-lg border bg-card px-3 py-2">
|
||||
<span className="text-xs text-muted-foreground mr-1">Replay:</span>
|
||||
<button className={tabCls(screen === "review")} onClick={() => go(jobId, "review")}>Lyrics</button>
|
||||
<button className={tabCls(screen === "instrumental")} onClick={() => go(jobId, "instrumental")}>Instrumental</button>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<button className={navCls(!!prev)} disabled={!prev} onClick={() => prev && go(prev, "review")}>← Prev</button>
|
||||
{idx >= 0 && queue.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground tabular-nums">{idx + 1} / {queue.length}</span>
|
||||
)}
|
||||
<button className={navCls(!!next)} disabled={!next} onClick={() => next && go(next, "review")}>Next job →</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ReplayActionLog — read-only summary of the reviewer's ordered edit_log for a
|
||||
* completed job, shown in replay mode so Andrew can narrate what he did and why.
|
||||
* Distinguishes AI-accepted / AI-rejected / manual / timing ops. Internal admin
|
||||
* tool (English-only, like /admin).
|
||||
*/
|
||||
function ReplayActionLog({
|
||||
editLog,
|
||||
instrumentalSelection,
|
||||
jobStatus,
|
||||
}: {
|
||||
editLog: import("@/lib/lyrics-review/types").EditLog | null
|
||||
instrumentalSelection: string | null
|
||||
jobStatus: string
|
||||
}) {
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const entries = editLog?.entries ?? []
|
||||
|
||||
const counts = entries.reduce(
|
||||
(acc, e) => {
|
||||
if (e.operation === "ai_suggestion_accept") acc.aiAccept++
|
||||
else if (e.operation === "ai_suggestion_reject") acc.aiReject++
|
||||
else if (e.operation === "timing_change") acc.timing++
|
||||
else if (e.operation === "ai_suggestion_run" || e.operation === "ai_suggestion_undo") acc.other++
|
||||
else acc.manual++
|
||||
return acc
|
||||
},
|
||||
{ aiAccept: 0, aiReject: 0, manual: 0, timing: 0, other: 0 }
|
||||
)
|
||||
|
||||
const badge = (op: string): { label: string; cls: string } => {
|
||||
if (op === "ai_suggestion_accept") return { label: "AI ✓", cls: "bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300" }
|
||||
if (op === "ai_suggestion_reject") return { label: "AI ✗", cls: "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300" }
|
||||
if (op === "timing_change") return { label: "timing", cls: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300" }
|
||||
if (op.startsWith("ai_suggestion")) return { label: op.replace("ai_suggestion_", "AI "), cls: "bg-muted text-muted-foreground" }
|
||||
return { label: "manual", cls: "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300" }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-4 my-2 rounded-lg border bg-card">
|
||||
<button
|
||||
onClick={() => setCollapsed((c) => !c)}
|
||||
className="w-full flex items-center justify-between px-4 py-2 text-sm font-medium"
|
||||
>
|
||||
<span>
|
||||
Replay — actions in this review:{" "}
|
||||
<span className="text-green-700 dark:text-green-400">{counts.aiAccept} AI accepted</span>,{" "}
|
||||
<span className="text-red-700 dark:text-red-400">{counts.aiReject} AI rejected</span>,{" "}
|
||||
<span className="text-amber-700 dark:text-amber-400">{counts.manual} manual</span>,{" "}
|
||||
<span className="text-blue-700 dark:text-blue-400">{counts.timing} timing</span>
|
||||
{" · instrumental: "}
|
||||
<code>{instrumentalSelection ?? "—"}</code>
|
||||
{" · status: "}
|
||||
<code>{jobStatus}</code>
|
||||
</span>
|
||||
<span className="text-muted-foreground">{collapsed ? "▸ show" : "▾ hide"}</span>
|
||||
</button>
|
||||
{!collapsed && (
|
||||
<div className="max-h-64 overflow-y-auto border-t px-2 py-2 text-xs">
|
||||
{entries.length === 0 && (
|
||||
<p className="px-2 py-1 text-muted-foreground">
|
||||
No edit log recorded for this job.
|
||||
</p>
|
||||
)}
|
||||
<ol className="space-y-0.5">
|
||||
{entries.map((e, i) => {
|
||||
const b = badge(e.operation)
|
||||
const cat = (e.details?.category as string) || (e.details?.gap_category as string) || ""
|
||||
return (
|
||||
<li key={e.id || i} className="flex items-start gap-2 px-2 py-1 rounded hover:bg-muted/50">
|
||||
<span className="text-muted-foreground tabular-nums w-6 text-right">{i + 1}</span>
|
||||
<span className={`shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium ${b.cls}`}>{b.label}</span>
|
||||
<span className="flex-1 break-words">
|
||||
{e.text_before && <span className="line-through text-muted-foreground">{e.text_before}</span>}
|
||||
{e.text_before && e.text_after && <span className="mx-1">→</span>}
|
||||
{e.text_after && <span className="font-medium">{e.text_after}</span>}
|
||||
{!e.text_before && !e.text_after && <span className="text-muted-foreground">{e.operation}</span>}
|
||||
{cat && <span className="ml-2 text-muted-foreground">[{cat}]</span>}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Instrumental Review Component Wrapper
|
||||
// The InstrumentalSelector component handles its own data fetching and submission
|
||||
// It uses the appropriate API based on isLocalMode
|
||||
function InstrumentalReviewWrapper({ job, isLocalMode = false, isReplay = false }: { job: Job; isLocalMode?: boolean; isReplay?: boolean }) {
|
||||
return (
|
||||
<>
|
||||
{isReplay && <ReplayNavBar jobId={job.job_id} screen="instrumental" />}
|
||||
<InstrumentalSelector job={job} isLocalMode={isLocalMode} isReadOnly={isReplay} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { BulkMode } from "@/components/job/bulk/BulkMode"
|
||||
import { TenantJobFlow } from "@/components/job/TenantJobFlow"
|
||||
import { TenantBulkFlow } from "@/components/job/TenantBulkFlow"
|
||||
import { AutoProcessor } from "@/components/AutoProcessor"
|
||||
import { VersionFooter } from "@/components/version-footer"
|
||||
import { PushNotificationPrompt } from "@/components/push-notification-prompt"
|
||||
@@ -59,7 +60,10 @@ function AppPageContent() {
|
||||
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { isDefault: isDefaultTenant } = useTenant()
|
||||
const { isDefault: isDefaultTenant, features: tenantFeatures } = useTenant()
|
||||
// Bulk mode is available on the default portal (search-based) and on tenant
|
||||
// portals with the bulk_upload feature (folder upload + auto-pair).
|
||||
const showBulkToggle = isDefaultTenant || tenantFeatures.bulk_upload
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
@@ -365,7 +369,7 @@ function AppPageContent() {
|
||||
: t('submitDescription')}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{isDefaultTenant && (
|
||||
{showBulkToggle && (
|
||||
<div
|
||||
className="shrink-0 inline-flex rounded-md p-0.5"
|
||||
style={{ backgroundColor: 'rgba(255,255,255,0.06)' }}
|
||||
@@ -400,6 +404,8 @@ function AppPageContent() {
|
||||
) : (
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
)
|
||||
) : tenantFeatures.bulk_upload && submitMode === 'bulk' ? (
|
||||
<TenantBulkFlow onJobsChanged={loadJobs} />
|
||||
) : (
|
||||
<TenantJobFlow onJobCreated={loadJobs} />
|
||||
)}
|
||||
|
||||
+234
-105
@@ -55,6 +55,8 @@ import {
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { LocaleBadge } from "@/components/admin/locale-badge"
|
||||
import { IpInfo } from "@/components/admin/ip-info"
|
||||
import {
|
||||
Search,
|
||||
RefreshCw,
|
||||
@@ -101,6 +103,7 @@ const statusOptions = [
|
||||
{ value: "in_review", label: "In Review" },
|
||||
{ value: "rendering_video", label: "Rendering Video" },
|
||||
{ value: "awaiting_instrumental_selection", label: "Awaiting Instrumental" },
|
||||
{ value: "generating_screens", label: "Generating Screens" },
|
||||
{ value: "generating_video", label: "Generating Video" },
|
||||
{ value: "encoding", label: "Encoding" },
|
||||
{ value: "complete", label: "Complete" },
|
||||
@@ -123,6 +126,7 @@ const statusLabels: Record<string, string> = {
|
||||
in_review: "In Review",
|
||||
rendering_video: "Rendering",
|
||||
awaiting_instrumental_selection: "Awaiting Inst.",
|
||||
generating_screens: "Gen. Screens",
|
||||
generating_video: "Generating",
|
||||
encoding: "Encoding",
|
||||
complete: "Complete",
|
||||
@@ -143,7 +147,7 @@ function AdminJobsPageContent() {
|
||||
|
||||
const [jobs, setJobs] = useState<Job[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
const [statusFilter, setStatusFilter] = useState(() => searchParams.get("status") || "all")
|
||||
const [userEmailFilter, setUserEmailFilter] = useState("")
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
|
||||
@@ -202,6 +206,9 @@ function AdminJobsPageContent() {
|
||||
const [overrideAudioDialogOpen, setOverrideAudioDialogOpen] = useState(false)
|
||||
const [overridingAudio, setOverridingAudio] = useState(false)
|
||||
|
||||
// Timeline expand state (long timelines are collapsed by default)
|
||||
const [timelineExpanded, setTimelineExpanded] = useState(false)
|
||||
|
||||
const loadJobs = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
@@ -231,11 +238,14 @@ function AdminJobsPageContent() {
|
||||
setSelectedJob(data)
|
||||
} catch (err: any) {
|
||||
console.error("Failed to load job:", err)
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || "Failed to load job",
|
||||
variant: "destructive",
|
||||
})
|
||||
// A 404 is fully communicated by the "Job not found" view — no toast needed
|
||||
if (err?.status !== 404) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || "Failed to load job",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
setSelectedJob(null)
|
||||
} finally {
|
||||
setDetailLoading(false)
|
||||
@@ -268,10 +278,14 @@ function AdminJobsPageContent() {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadJobs()
|
||||
}, [loadJobs])
|
||||
// Skip the (expensive) list load while a single job is being viewed
|
||||
if (!selectedJobId) {
|
||||
loadJobs()
|
||||
}
|
||||
}, [loadJobs, selectedJobId])
|
||||
|
||||
useEffect(() => {
|
||||
setTimelineExpanded(false)
|
||||
if (selectedJobId) {
|
||||
loadJobDetail(selectedJobId)
|
||||
loadLogs(selectedJobId)
|
||||
@@ -284,7 +298,19 @@ function AdminJobsPageContent() {
|
||||
}, [selectedJobId, loadJobDetail, loadLogs, loadFiles])
|
||||
|
||||
const handleSearch = () => {
|
||||
setUserEmailFilter(searchInput)
|
||||
const query = searchInput.trim()
|
||||
// A bare hex string is a job ID — jump straight to its detail page
|
||||
if (/^[0-9a-f]{8}(-[0-9a-f-]{4,})?$/i.test(query)) {
|
||||
router.push(`/admin/jobs?id=${query}`)
|
||||
return
|
||||
}
|
||||
setUserEmailFilter(query)
|
||||
}
|
||||
|
||||
// Keep the status filter in the URL so dashboard links and reloads work
|
||||
const handleStatusChange = (value: string) => {
|
||||
setStatusFilter(value)
|
||||
router.replace(value !== "all" ? `/admin/jobs?status=${value}` : "/admin/jobs")
|
||||
}
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
@@ -311,15 +337,21 @@ function AdminJobsPageContent() {
|
||||
|
||||
try {
|
||||
setSaving(true)
|
||||
const updates: JobUpdateRequest = { [field]: editValue }
|
||||
await adminApi.updateJob(selectedJobId, updates)
|
||||
// The backend trims + lowercases user_email; mirror that locally so the
|
||||
// displayed value matches what was saved
|
||||
const savedValue = field === "user_email" ? editValue.trim().toLowerCase() : editValue
|
||||
const updates: JobUpdateRequest = { [field]: savedValue }
|
||||
const result = await adminApi.updateJob(selectedJobId, updates)
|
||||
|
||||
// Update local state
|
||||
setSelectedJob({ ...selectedJob, [field]: editValue })
|
||||
setSelectedJob({ ...selectedJob, [field]: savedValue })
|
||||
|
||||
// Surface anything beyond the generic success message (e.g. "Created new
|
||||
// user account for x@y.com" when reassigning user_email)
|
||||
const extra = result?.message?.replace(/^Successfully updated \d+ field\(s\)\.?\s*/, "")
|
||||
toast({
|
||||
title: "Updated",
|
||||
description: `${field} has been updated`,
|
||||
description: extra ? `${field} has been updated. ${extra}` : `${field} has been updated`,
|
||||
})
|
||||
|
||||
setEditingField(null)
|
||||
@@ -434,8 +466,34 @@ function AdminJobsPageContent() {
|
||||
}
|
||||
}
|
||||
|
||||
// Note: handleClearWorkers and handleTriggerWorker removed
|
||||
// These low-level escape hatches are replaced by Full Restart and Regen Screens
|
||||
// Trigger a worker manually (used from the reset-result dialog when
|
||||
// resetting to instrumental_selected didn't auto-trigger the video worker)
|
||||
const handleTriggerWorker = async (workerType: string) => {
|
||||
if (!selectedJobId) return
|
||||
try {
|
||||
const result = await adminApi.triggerWorker(selectedJobId, workerType)
|
||||
if (result.triggered) {
|
||||
toast({
|
||||
title: "Worker Triggered",
|
||||
description: result.message || `${workerType} worker is starting`,
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: "Worker Not Triggered",
|
||||
description: result.error || result.message,
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
loadJobDetail(selectedJobId)
|
||||
loadLogs(selectedJobId)
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || `Failed to trigger ${workerType} worker`,
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Handle regenerate screens - regenerates title/end screens with current metadata
|
||||
const handleRegenerateScreens = async () => {
|
||||
@@ -643,6 +701,16 @@ function AdminJobsPageContent() {
|
||||
return { type: "unknown" as const, icon: FileText, label: "Unknown", detail: undefined }
|
||||
}
|
||||
|
||||
// Build a clickable external URL for the job's audio source, when one exists
|
||||
const getExternalSourceUrl = (job: Job): string | null => {
|
||||
if (job.url) return job.url
|
||||
if (!job.source_id) return null
|
||||
const provider = (job.source_name || "").toLowerCase()
|
||||
if (provider.includes("youtube")) return `https://www.youtube.com/watch?v=${job.source_id}`
|
||||
if (provider.includes("spotify")) return `https://open.spotify.com/track/${job.source_id}`
|
||||
return null
|
||||
}
|
||||
|
||||
// Calculate stage durations from timeline
|
||||
const getStageDurations = (job: Job) => {
|
||||
if (!job?.timeline || job.timeline.length < 2) return []
|
||||
@@ -823,6 +891,15 @@ function AdminJobsPageContent() {
|
||||
const SourceIcon = jobSource.icon
|
||||
const canDeleteOutputs = ["complete", "prep_complete", "failed", "cancelled"].includes(selectedJob.status)
|
||||
|
||||
// Collapse long timelines (retries/edits create many entries) to the most recent stages
|
||||
const TIMELINE_TAIL = 6
|
||||
const timelineCollapsible = stageDurations.length > TIMELINE_TAIL + 2
|
||||
const visibleStages = timelineCollapsible && !timelineExpanded
|
||||
? stageDurations.slice(stageDurations.length - TIMELINE_TAIL)
|
||||
: stageDurations
|
||||
const hiddenStages = stageDurations.slice(0, stageDurations.length - visibleStages.length)
|
||||
const hiddenFailures = hiddenStages.filter((s) => s.status === "failed").length
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="space-y-4">
|
||||
@@ -873,7 +950,7 @@ function AdminJobsPageContent() {
|
||||
</div>
|
||||
|
||||
{/* ===== STICKY ACTION TOOLBAR ===== */}
|
||||
<div className="sticky top-0 z-10 -mx-4 px-4 py-2 bg-background/95 backdrop-blur border-b">
|
||||
<div className="sticky top-0 z-10 -mx-4 px-4 md:-mx-6 md:px-6 py-2 bg-background/95 backdrop-blur border-b">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide mr-1">Reset to:</span>
|
||||
{[
|
||||
@@ -1051,8 +1128,40 @@ function AdminJobsPageContent() {
|
||||
{/* ===== HORIZONTAL TIMELINE ===== */}
|
||||
<div className="py-3 border-b">
|
||||
<div className="flex flex-wrap items-start gap-y-2">
|
||||
{stageDurations.map((stage, i) => {
|
||||
const isLast = i === stageDurations.length - 1
|
||||
{timelineCollapsible && !timelineExpanded && (
|
||||
<div className="flex items-start">
|
||||
<button
|
||||
className="flex flex-col items-center px-2 py-1 rounded-md border border-dashed text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
|
||||
onClick={() => setTimelineExpanded(true)}
|
||||
title="Show all timeline entries"
|
||||
>
|
||||
<span className="text-xs font-medium whitespace-nowrap">
|
||||
+{hiddenStages.length} earlier
|
||||
{hiddenFailures > 0 && (
|
||||
<span className="text-red-500"> ({hiddenFailures} failed)</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-[10px] font-mono mt-0.5">
|
||||
{formatTimeOnly(hiddenStages[0]?.startTime)}
|
||||
</span>
|
||||
</button>
|
||||
<ChevronRight className="w-3 h-3 text-muted-foreground/40 mx-0.5 mt-2" />
|
||||
</div>
|
||||
)}
|
||||
{timelineCollapsible && timelineExpanded && (
|
||||
<div className="flex items-start">
|
||||
<button
|
||||
className="flex items-center px-2 py-2 rounded-md border border-dashed text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
|
||||
onClick={() => setTimelineExpanded(false)}
|
||||
title="Collapse older timeline entries"
|
||||
>
|
||||
<span className="text-xs font-medium whitespace-nowrap">Collapse</span>
|
||||
</button>
|
||||
<ChevronRight className="w-3 h-3 text-muted-foreground/40 mx-0.5 mt-2" />
|
||||
</div>
|
||||
)}
|
||||
{visibleStages.map((stage, i) => {
|
||||
const isLast = i === visibleStages.length - 1
|
||||
const isCurrent = isLast
|
||||
const bgColor = getTimelineStageColor(stage.status, isCurrent)
|
||||
const textColor = getTimelineTextColor(stage.status)
|
||||
@@ -1112,7 +1221,7 @@ function AdminJobsPageContent() {
|
||||
|
||||
{/* ===== JOB INFO GRID ===== */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-4 py-3">
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">User</p>
|
||||
{selectedJob.user_email ? (
|
||||
<p
|
||||
@@ -1126,28 +1235,44 @@ function AdminJobsPageContent() {
|
||||
<p className="text-sm truncate text-muted-foreground">Unknown</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Language</p>
|
||||
{selectedJob.locale ? (
|
||||
<LocaleBadge locale={selectedJob.locale} showName />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">—</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Country</p>
|
||||
{selectedJob.creation_ip ? (
|
||||
<div className="text-sm"><IpInfo ip={selectedJob.creation_ip} compact /></div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">—</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Source</p>
|
||||
<button
|
||||
className="text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer truncate text-left"
|
||||
className="w-full max-w-full min-w-0 text-sm flex items-center gap-1.5 text-primary hover:underline cursor-pointer text-left"
|
||||
title="Click for source details"
|
||||
onClick={() => setSourceModalOpen(true)}
|
||||
>
|
||||
<SourceIcon className="w-3.5 h-3.5 shrink-0" />
|
||||
<span className="truncate">
|
||||
<span className="truncate min-w-0">
|
||||
{jobSource.type === "url" && jobSource.detail
|
||||
? jobSource.detail.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40)
|
||||
? jobSource.detail.replace(/^https?:\/\/(www\.)?/, "")
|
||||
: jobSource.detail || "Unknown"}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Created</p>
|
||||
<p className="text-sm" title={formatDate(selectedJob.created_at)}>
|
||||
{formatDateCompact(selectedJob.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Progress</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden max-w-[60px]">
|
||||
@@ -1160,19 +1285,19 @@ function AdminJobsPageContent() {
|
||||
</div>
|
||||
</div>
|
||||
{/* Timing stats */}
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Total Time</p>
|
||||
<p className="text-sm font-mono">{formatDurationLong(timingStats.total) || "—"}</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Processing</p>
|
||||
<p className="text-sm font-mono text-blue-600 dark:text-blue-400">{formatDurationLong(timingStats.processing) || "—"}</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Waiting</p>
|
||||
<p className="text-sm font-mono text-amber-600 dark:text-amber-400">{formatDurationLong(timingStats.waiting) || "—"}</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Theme</p>
|
||||
<p className="text-sm truncate">{selectedJob.theme_id || "default"}</p>
|
||||
</div>
|
||||
@@ -1232,15 +1357,21 @@ function AdminJobsPageContent() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1 flex-1 min-w-0">
|
||||
<span className="text-xs truncate flex-1">{value || "—"}</span>
|
||||
<button
|
||||
className="text-xs truncate flex-1 text-left rounded px-1 py-0.5 -mx-1 hover:bg-muted/70 cursor-text decoration-dotted underline-offset-2 group-hover:underline min-w-0"
|
||||
onClick={() => startEditing(key, value || "")}
|
||||
title={`Click to edit ${label.toLowerCase()}`}
|
||||
>
|
||||
{value || <span className="text-muted-foreground">— click to set</span>}
|
||||
</button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5 opacity-0 group-hover:opacity-100"
|
||||
className="h-5 w-5 shrink-0 text-muted-foreground/60 hover:text-foreground"
|
||||
onClick={() => startEditing(key, value || "")}
|
||||
title={`Edit ${label}`}
|
||||
>
|
||||
<Pencil className="w-2.5 h-2.5" />
|
||||
<Pencil className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
@@ -1250,7 +1381,7 @@ function AdminJobsPageContent() {
|
||||
{/* Private (non-published) toggle */}
|
||||
<div className="flex items-center gap-2 pt-2 border-t">
|
||||
<span className="text-[10px] font-medium text-muted-foreground uppercase w-20 shrink-0">Private</span>
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="admin-is-private"
|
||||
@@ -1430,7 +1561,7 @@ function AdminJobsPageContent() {
|
||||
|
||||
{/* ===== SOURCE INFO MODAL ===== */}
|
||||
<Dialog open={sourceModalOpen} onOpenChange={setSourceModalOpen}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<SourceIcon className="w-4 h-4" />
|
||||
@@ -1441,69 +1572,62 @@ function AdminJobsPageContent() {
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3 text-sm">
|
||||
{selectedJob.audio_source_type && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Source Type</span>
|
||||
<span className="font-medium">{selectedJob.audio_source_type.replace(/_/g, " ")}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.source_name && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Provider</span>
|
||||
<span className="font-medium">{selectedJob.source_name}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.source_id && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Source ID</span>
|
||||
<span className="font-mono text-xs">{selectedJob.source_id}</span>
|
||||
</div>
|
||||
{(() => {
|
||||
const externalUrl = getExternalSourceUrl(selectedJob)
|
||||
return externalUrl ? (
|
||||
<a
|
||||
href={externalUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-md border bg-muted/40 text-primary hover:bg-muted transition-colors"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4 shrink-0" />
|
||||
<span className="font-medium">
|
||||
Open in {selectedJob.source_name || (selectedJob.url ? "YouTube" : "provider")}
|
||||
</span>
|
||||
<span className="ml-auto font-mono text-xs text-muted-foreground truncate max-w-[50%]">
|
||||
{externalUrl.replace(/^https?:\/\/(www\.)?/, "")}
|
||||
</span>
|
||||
</a>
|
||||
) : null
|
||||
})()}
|
||||
{[
|
||||
{ label: "Source Type", value: selectedJob.audio_source_type?.replace(/_/g, " "), mono: false },
|
||||
{ label: "Provider", value: selectedJob.source_name, mono: false },
|
||||
{ label: "Source ID", value: selectedJob.source_id, mono: true },
|
||||
{ label: "Search Artist", value: selectedJob.audio_search_artist, mono: false },
|
||||
{ label: "Search Title", value: selectedJob.audio_search_title, mono: false },
|
||||
{ label: "Filename", value: selectedJob.filename, mono: true },
|
||||
{
|
||||
label: "Target File",
|
||||
value: selectedJob.target_file !== selectedJob.filename ? selectedJob.target_file : undefined,
|
||||
mono: true,
|
||||
},
|
||||
].map(({ label, value, mono }) =>
|
||||
value ? (
|
||||
<div key={label} className="space-y-0.5">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">{label}</p>
|
||||
<p className={`break-all ${mono ? "font-mono text-xs" : "font-medium"}`}>{value}</p>
|
||||
</div>
|
||||
) : null
|
||||
)}
|
||||
{selectedJob.url && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">URL</span>
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">URL</p>
|
||||
<a
|
||||
href={selectedJob.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline truncate font-mono text-xs"
|
||||
className="block text-primary hover:underline break-all font-mono text-xs"
|
||||
>
|
||||
{selectedJob.url}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.filename && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Filename</span>
|
||||
<span className="truncate font-mono text-xs">{selectedJob.filename}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.target_file && selectedJob.target_file !== selectedJob.filename && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Target File</span>
|
||||
<span className="truncate font-mono text-xs">{selectedJob.target_file}</span>
|
||||
</div>
|
||||
)}
|
||||
{(selectedJob.audio_search_artist || selectedJob.audio_search_title) && (
|
||||
<>
|
||||
{selectedJob.audio_search_artist && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Search Artist</span>
|
||||
<span>{selectedJob.audio_search_artist}</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedJob.audio_search_title && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Search Title</span>
|
||||
<span>{selectedJob.audio_search_title}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{selectedJob.download_url && (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-muted-foreground shrink-0">Download URL</span>
|
||||
<span className="truncate font-mono text-xs">{selectedJob.download_url}</span>
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">Download URL</p>
|
||||
<p className="break-all font-mono text-xs">{selectedJob.download_url}</p>
|
||||
</div>
|
||||
)}
|
||||
{!selectedJob.audio_source_type && !selectedJob.url && !selectedJob.filename && (
|
||||
@@ -2087,7 +2211,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="flex-1 flex gap-2">
|
||||
<Input
|
||||
placeholder="Filter by user email..."
|
||||
placeholder="Filter by email, or paste a job ID..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={handleKeyPress}
|
||||
@@ -2097,7 +2221,7 @@ function AdminJobsPageContent() {
|
||||
<Search className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<Select value={statusFilter} onValueChange={handleStatusChange}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="Filter by status" />
|
||||
</SelectTrigger>
|
||||
@@ -2117,11 +2241,11 @@ function AdminJobsPageContent() {
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Job ID</TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead className="hidden md:table-cell">User</TableHead>
|
||||
<TableHead>Artist / Title</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Progress</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">Progress</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Created</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
@@ -2146,28 +2270,33 @@ function AdminJobsPageContent() {
|
||||
onClick={() => router.push(`/admin/jobs?id=${job.job_id}`)}
|
||||
>
|
||||
<TableCell className="font-mono text-sm">{job.job_id}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground max-w-[150px] truncate">
|
||||
<TableCell className="hidden md:table-cell text-sm text-muted-foreground max-w-[150px] truncate">
|
||||
{job.user_email || "—"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{job.artist && job.title ? (
|
||||
<span className="max-w-[200px] truncate block">
|
||||
{job.artist} - {job.title}
|
||||
</span>
|
||||
) : job.filename ? (
|
||||
<span className="max-w-[200px] truncate block text-muted-foreground">
|
||||
{job.filename}
|
||||
</span>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{job.artist && job.title ? (
|
||||
<span className="max-w-[200px] truncate block">
|
||||
{job.artist} - {job.title}
|
||||
</span>
|
||||
) : job.filename ? (
|
||||
<span className="max-w-[200px] truncate block text-muted-foreground">
|
||||
{job.filename}
|
||||
</span>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
{job.locale && (
|
||||
<LocaleBadge locale={job.locale} className="shrink-0 text-[10px] py-0 px-1.5 h-auto" />
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={getStatusVariant(job.status)}>
|
||||
{job.status.replace(/_/g, " ")}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TableCell className="hidden sm:table-cell">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-16 h-2 bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
@@ -2180,8 +2309,8 @@ function AdminJobsPageContent() {
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{formatDate(job.created_at)}
|
||||
<TableCell className="hidden lg:table-cell text-sm whitespace-nowrap" title={formatDate(job.created_at)}>
|
||||
{formatDateCompact(job.created_at)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1" onClick={(e) => e.stopPropagation()}>
|
||||
|
||||
@@ -40,7 +40,9 @@ function AdminBreadcrumb() {
|
||||
breadcrumbs.push({ label: "Users" })
|
||||
} else {
|
||||
breadcrumbs.push({ label: "Users", href: "/admin/users" })
|
||||
breadcrumbs.push({ label: decodeURIComponent(segments[2]) })
|
||||
breadcrumbs.push({
|
||||
label: segments[2] === "detail" ? "User Detail" : decodeURIComponent(segments[2]),
|
||||
})
|
||||
}
|
||||
} else if (segments[1] === "jobs") {
|
||||
if (segments.length === 2) {
|
||||
@@ -49,18 +51,18 @@ function AdminBreadcrumb() {
|
||||
breadcrumbs.push({ label: "Jobs", href: "/admin/jobs" })
|
||||
breadcrumbs.push({ label: decodeURIComponent(segments[2]) })
|
||||
}
|
||||
} else if (segments[1] === "payments") {
|
||||
breadcrumbs.push({ label: "Payments" })
|
||||
} else if (segments[1] === "referrals") {
|
||||
breadcrumbs.push({ label: "Referrals" })
|
||||
} else if (segments[1] === "searches") {
|
||||
breadcrumbs.push({ label: "Audio Searches" })
|
||||
} else if (segments[1] === "payments") {
|
||||
breadcrumbs.push({ label: "Payments" })
|
||||
} else if (segments[1] === "rate-limits") {
|
||||
breadcrumbs.push({ label: "Rate Limits" })
|
||||
} else if (segments[1] === "abuse") {
|
||||
breadcrumbs.push({ label: "Abuse Investigation" })
|
||||
} else {
|
||||
// Fallback: prettify the URL segment (payments, referrals, rate-limits, ...)
|
||||
breadcrumbs.push({
|
||||
label: segments[1]
|
||||
.split("-")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" "),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,15 +147,18 @@ export default function AdminLayout({
|
||||
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
<AdminBreadcrumb />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<div className="min-w-0 overflow-hidden">
|
||||
<AdminBreadcrumb />
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 shrink-0">
|
||||
<Switch
|
||||
id="show-test-data"
|
||||
checked={showTestData}
|
||||
onCheckedChange={setShowTestData}
|
||||
/>
|
||||
<Label htmlFor="show-test-data" className="text-sm text-muted-foreground cursor-pointer">
|
||||
Show test data
|
||||
<Label htmlFor="show-test-data" className="text-sm text-muted-foreground cursor-pointer whitespace-nowrap">
|
||||
<span className="hidden sm:inline">Show test data</span>
|
||||
<span className="sm:hidden">Test data</span>
|
||||
</Label>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
+28
-50
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { adminApi, AdminStatsOverview, RevenueSummary } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
|
||||
@@ -88,6 +89,7 @@ export default function AdminDashboardPage() {
|
||||
description={`${stats?.active_users_7d ?? 0} active in last 7 days`}
|
||||
icon={Users}
|
||||
loading={loading}
|
||||
href="/admin/users"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Total Jobs"
|
||||
@@ -95,6 +97,7 @@ export default function AdminDashboardPage() {
|
||||
description={`${stats?.jobs_last_7d ?? 0} in last 7 days`}
|
||||
icon={Briefcase}
|
||||
loading={loading}
|
||||
href="/admin/jobs"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Revenue (30d)"
|
||||
@@ -103,6 +106,7 @@ export default function AdminDashboardPage() {
|
||||
icon={DollarSign}
|
||||
loading={loading}
|
||||
valueClassName="text-green-600 dark:text-green-400"
|
||||
href="/admin/payments"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Credits Issued (30d)"
|
||||
@@ -110,6 +114,7 @@ export default function AdminDashboardPage() {
|
||||
description="Credits added to accounts"
|
||||
icon={CreditCard}
|
||||
loading={loading}
|
||||
href="/admin/payments"
|
||||
/>
|
||||
</StatsGrid>
|
||||
|
||||
@@ -127,56 +132,29 @@ export default function AdminDashboardPage() {
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-4 h-4 text-yellow-500" />
|
||||
<span className="text-sm">Pending</span>
|
||||
</div>
|
||||
<Badge variant="secondary">{stats?.jobs_by_status?.pending ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Loader2 className="w-4 h-4 text-blue-500" />
|
||||
<span className="text-sm">Processing</span>
|
||||
</div>
|
||||
<Badge variant="secondary">{stats?.jobs_by_status?.processing ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-orange-500" />
|
||||
<span className="text-sm">Awaiting Review</span>
|
||||
</div>
|
||||
<Badge variant="secondary">{stats?.jobs_by_status?.awaiting_review ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-purple-500" />
|
||||
<span className="text-sm">Awaiting Instrumental</span>
|
||||
</div>
|
||||
<Badge variant="secondary">{stats?.jobs_by_status?.awaiting_instrumental ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500" />
|
||||
<span className="text-sm">Complete</span>
|
||||
</div>
|
||||
<Badge variant="secondary">{stats?.jobs_by_status?.complete ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<XCircle className="w-4 h-4 text-red-500" />
|
||||
<span className="text-sm">Failed</span>
|
||||
</div>
|
||||
<Badge variant="destructive">{stats?.jobs_by_status?.failed ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<XCircle className="w-4 h-4 text-muted-foreground" />
|
||||
<span className="text-sm">Cancelled</span>
|
||||
</div>
|
||||
<Badge variant="outline">{stats?.jobs_by_status?.cancelled ?? 0}</Badge>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{[
|
||||
{ label: "Pending", icon: Clock, iconClass: "text-yellow-500", count: stats?.jobs_by_status?.pending ?? 0, href: "/admin/jobs?status=pending", badge: "secondary" as const },
|
||||
{ label: "Processing", icon: Loader2, iconClass: "text-blue-500", count: stats?.jobs_by_status?.processing ?? 0, href: "/admin/jobs", badge: "secondary" as const },
|
||||
{ label: "Awaiting Review", icon: AlertCircle, iconClass: "text-orange-500", count: stats?.jobs_by_status?.awaiting_review ?? 0, href: "/admin/jobs?status=awaiting_review", badge: "secondary" as const },
|
||||
{ label: "Awaiting Instrumental", icon: AlertCircle, iconClass: "text-purple-500", count: stats?.jobs_by_status?.awaiting_instrumental ?? 0, href: "/admin/jobs?status=awaiting_instrumental_selection", badge: "secondary" as const },
|
||||
{ label: "Complete", icon: CheckCircle, iconClass: "text-green-500", count: stats?.jobs_by_status?.complete ?? 0, href: "/admin/jobs?status=complete", badge: "secondary" as const },
|
||||
{ label: "Failed", icon: XCircle, iconClass: "text-red-500", count: stats?.jobs_by_status?.failed ?? 0, href: "/admin/jobs?status=failed", badge: "destructive" as const },
|
||||
{ label: "Cancelled", icon: XCircle, iconClass: "text-muted-foreground", count: stats?.jobs_by_status?.cancelled ?? 0, href: "/admin/jobs?status=cancelled", badge: "outline" as const },
|
||||
].map(({ label, icon: RowIcon, iconClass, count, href, badge }) => (
|
||||
<Link
|
||||
key={label}
|
||||
href={href}
|
||||
className="flex items-center justify-between rounded-md px-2 py-1.5 -mx-2 hover:bg-muted/60 transition-colors"
|
||||
title={`View ${label.toLowerCase()} jobs`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RowIcon className={`w-4 h-4 ${iconClass}`} />
|
||||
<span className="text-sm">{label}</span>
|
||||
</div>
|
||||
<Badge variant={badge}>{count}</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@@ -70,6 +70,8 @@ import { cn } from "@/lib/utils"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { IpInfo } from "@/components/admin/ip-info"
|
||||
import { LocaleBadge } from "@/components/admin/locale-badge"
|
||||
import { UserEmailsCard } from "@/components/admin/user-emails-card"
|
||||
|
||||
export default function AdminUserDetailPage() {
|
||||
const searchParams = useSearchParams()
|
||||
@@ -333,23 +335,26 @@ export default function AdminUserDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="icon" onClick={() => router.push("/admin/users")} title="Back to users list">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||
<div className="flex items-start gap-2 sm:gap-4 min-w-0">
|
||||
<Button variant="ghost" size="icon" className="shrink-0" onClick={() => router.push("/admin/users")} title="Back to users list">
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
|
||||
{user.display_name || user.email}
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-xl sm:text-2xl font-bold tracking-tight flex items-center gap-2 flex-wrap">
|
||||
<span className="break-all">{user.display_name || user.email}</span>
|
||||
<Badge variant={user.role === "admin" ? "default" : "secondary"}>
|
||||
{user.role}
|
||||
</Badge>
|
||||
{!user.is_active && <Badge variant="destructive">Disabled</Badge>}
|
||||
{/* UI language the user browses in — so support communicates in the
|
||||
right language. Falls back to the email locale if unknown. */}
|
||||
<LocaleBadge locale={user.ui_locale || user.locale} showName />
|
||||
</h1>
|
||||
<p className="text-muted-foreground">{user.email}</p>
|
||||
<p className="text-muted-foreground break-all">{user.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex gap-2 shrink-0">
|
||||
<Button variant="outline" size="sm" onClick={loadUser} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
@@ -422,7 +427,7 @@ export default function AdminUserDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium flex items-center gap-2">
|
||||
@@ -527,9 +532,9 @@ export default function AdminUserDetailPage() {
|
||||
<span className="text-muted-foreground">Signup IP</span>
|
||||
<IpInfo ip={user.signup_ip} />
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Device Fingerprint</span>
|
||||
<code className="text-xs bg-muted px-1.5 py-0.5 rounded">{user.device_fingerprint || "unknown"}</code>
|
||||
<div className="flex justify-between gap-4">
|
||||
<span className="text-muted-foreground shrink-0">Device Fingerprint</span>
|
||||
<code className="text-xs bg-muted px-1.5 py-0.5 rounded break-all text-right">{user.device_fingerprint || "unknown"}</code>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Welcome Credits</span>
|
||||
@@ -696,7 +701,12 @@ export default function AdminUserDetailPage() {
|
||||
>
|
||||
<TableCell className="font-mono text-sm">{job.job_id}</TableCell>
|
||||
<TableCell>
|
||||
{job.artist && job.title ? `${job.artist} - ${job.title}` : "—"}
|
||||
<span className="inline-flex items-center gap-2">
|
||||
{job.artist && job.title ? `${job.artist} - ${job.title}` : "—"}
|
||||
{job.locale && (
|
||||
<LocaleBadge locale={job.locale} className="text-[10px] py-0 px-1.5 h-auto" />
|
||||
)}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={
|
||||
@@ -718,6 +728,9 @@ export default function AdminUserDetailPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Emails sent to this user */}
|
||||
<UserEmailsCard email={email} />
|
||||
|
||||
{/* Add Credits Dialog */}
|
||||
<Dialog open={creditDialogOpen} onOpenChange={setCreditDialogOpen}>
|
||||
<DialogContent>
|
||||
|
||||
Loaded 100 of 3771 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user