Compare commits

..
23 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 b464e40d84 Inline clean-instrumental choice via 3-way audio toggle on the finish modal (#962)
## Summary

On the lyrics-review **finish modal**, when the backing instrumental is
confidently auto-selected, reviewers previously had only a heavyweight
escape hatch ("Let me choose the instrumental myself" → the full
instrumental-review screen). The common override — "the backing vocals
sound bad, just give me the clean instrumental" — is now a **single
click**.

The clean instrumental becomes a **third pill in the "Audio:" preview
toggle** so the two instrumentals can be A/B'd and chosen in one place:

- **`PreviewVideoSection`** — when both stems exist and are meaningfully
different (verdict `with_backing` + a clean stem present), the single
"Instrumental" pill splits into **Instrumental + backing vocals** /
**Clean instrumental**. Selecting a variant both auditions and selects
it (last activated wins); the backing-vocals waveform auditions the
with-backing stem. When clean is already the default (or only one stem
exists), the single "Instrumental" pill is kept — nothing to choose.
- **`LyricsAnalyzer`** submits the reviewer's choice (`clean` vs
`auto`). The backend already accepts an explicit `clean` selection at
`POST /api/review/{id}/complete`, so **no backend change**.
- The confident-box note reflects the current choice, and the
escape-hatch checkbox is reworded to the specific, rarely-used action
(keep BV but mute sections / upload custom), with a clean-case variant.
- **i18n:** reworded + new keys across all 33 locales (`translate.py
--target all`; key parity verified).

## Testing

- `PreviewVideoSection.test.tsx` — 3-way toggle: splits pills when
offered, reports choice + swaps stem on clean click, keeps single pill
when only one stem / not offered.
- `ReviewChangesModal.test.tsx` — note reflects the reported choice;
per-case escape-hatch wording.
- Full frontend suite: **98 suites / 1236 tests pass**. Changed source
files typecheck clean.

## Notes

- New completion toasts are kept in English to match the 7 existing
hardcoded toasts in the same submit function (localizing only the new
ones would be inconsistent; localizing all is out of scope).
- **Pending live-verify (Andrew's ear):** an in-review
confident-`with_backing` job — confirm the 3-pill toggle A/Bs cleanly
and that picking "Clean instrumental" ships the clean stem.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-30 02:09:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e58334e461 Preview modal UX: audio toggle, backing-vocals waveform, cohesive loading & saving flow (#961)
## Summary

Five UX improvements to the lyrics-review **Preview Video** modal (shown
when the reviewer clicks "Preview Video").

1. **Unified loading** — the `generating` and `encoding` states now
share one centred spinner; only the stage message changes ("Preparing
your preview…" → "Encoding preview video…" → slow-encoder hint). No more
janky layout swap.
2. **Audio toggle (Original ↔ auto-selected Instrumental)** — a hidden
stem `<audio>` element (from `instrumental_options`, already in the
review correction-data) is kept in lock-step with the video
(play/pause/seek/rate/drift ≤0.25s). Switchable mid-playback with
position preserved. Title dropped "(With Vocals)" → just "Preview
Video".
3. **Removed low-value text** — deleted "No manual corrections
detected…" and "Total segments: X". The manual-corrections note now only
shows when the reviewer actually edited.
4. **Backing-vocals waveform** (new `BackingVocalsWaveform`) — only when
the auto-selector kept backing vocals (`with_backing`, confident, and
the stem is playable). Thin 35px canvas of the backing stem (from `GET
/api/review/{jobId}/waveform-data`); clicking seeks the video and
switches audio to the instrumental, for quick sanity-checking of the
automatic pick.
5. **"Complete Track" saving flow** — the modal stays in its "Saving…"
state through the slow `completeReview` call, so it no longer flashes
back to the review screen before the "Review Submitted" view.

Also: `getWaveformData` added to the review API client factory; version
`0.209.2 → 0.210.0`.

## i18n
- Keys added
(`previewVideo.audioLabel/audioOriginal/audioInstrumental/backingVocalsWaveformHint`,
`modals.reviewChanges.previewTitle`) and removed (`previewWithVocals`,
`noManualCorrections`, `totalSegments`); all 33 locales synced via
`translate.py`. Keys-only parity passes.

## Testing
- Frontend jest: **1230 passed / 98 suites** (26 in the two touched
modal/preview suites, incl. audio-toggle mute + backing-waveform
gating).
- Manually verified against **real prod jobs** via local dev (proxying
to prod API):
- `ae225662` (clean pick): audio toggle mutes video + plays clean stem
synced to the same position; waveform correctly hidden.
- `370f7b92` (with_backing pick): 35px backing waveform renders;
clicking it seeks the video (102.5s→138.8s) and the instrumental audio
follows in lock-step.
- Local CodeRabbit review run and its 2 minor findings addressed
(playbackRate sync on audio switch; gate waveform on stem availability).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 22:08:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 37b9e6088b ci(pypi): recurring storage-cap prune reminder (fix failing PyPI publish) (#960)
## Problem

The `Deploy - Publish to PyPI` step on `main` has been failing:

```
HTTP Error 400: Project size too large. Limit for project 'karaoke-gen'
total size is 10 GB.
```

This is a recurrence of the known 10 GB PyPI project cap. The project is
at
**10.71 GB / 479 releases**; each release is a ~62 MiB universal wheel
(bundled
33-locale frontend) auto-published on every merge (~3 GB/month), so it
refills
the cap every few months. **Only the public `pip install` publish step
fails** —
Cloud Run and the GCE encoding worker (pulls the wheel from GCS) are
unaffected.

The prior fix (v0.187.5) was wheel-only publishing + a one-time manual
deletion,
which only bought ~2 months. This makes the cleanup **recurring and
durable**.

## Why not just automate deletion in CI?

PyPI has **no deletion API** (upload tokens / Trusted Publishing are
upload-only,
and 2FA is mandatory). Deletion is only possible from a logged-in
browser
session, which can't be safely/durably stored in CI. So we automate the
*decision + reminder* and keep the *deletion* a ~1-minute human step.

## What this adds

- **`scripts/prune_pypi_releases.py`** (stdlib-only) — reads the public
JSON API
and computes a retention plan: **keep last 60 days + newest release per
older
calendar month + latest overall**. Renders a table / JSON / Markdown
report and
a **paste-into-browser-console** deletion snippet. Never deletes
anything
  itself. Today's plan: keep 82, delete 397, **10.71 GB → 4.17 GB**.
- **`.github/workflows/pypi-prune-reminder.yml`** — monthly cron (+
manual
dispatch) that runs the planner and, once the project crosses a 7 GB
watermark,
opens/updates a single tracking issue with the plan + snippet. No
secrets.
- **`docs/PYPI-STORAGE-PRUNE.md`** runbook + a `TROUBLESHOOTING.md`
entry.
- **`tests/unit/test_prune_pypi_releases.py`** — 13 tests covering the
policy
(recency window, per-month keeper, latest-overall, same-day timestamp
ranking,
  empty/undated releases, sizes, rendering).

## Testing

- `pytest tests/unit/test_prune_pypi_releases.py` → 13 passed.
- Ran the planner against live PyPI data; generated JS validated with
`node --check`.
- `black` clean; workflow YAML validated; `should_nag` gate verified.

## Notes

- **No version bump** — tooling/CI/docs only, nothing in the wheel
changes.
Merging therefore **skips** the publish step (tag `v0.209.1` already
exists),
so this PR does not itself add another fat wheel while we're over the
cap.
- **To unblock publishing now:** after merge, run the prune (locally via
the
script or trigger the workflow with `workflow_dispatch`), paste the
snippet on
the logged-in PyPI releases page, then re-run the publish. The monthly
cron
  keeps it under the cap going forward.
- Related: filed
[pypi/support#12050](https://github.com/pypi/support/issues/12050)
requesting a 50 GB limit as a one-off buffer; the recurring prune is the
  durable fix.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 21:46:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 019289cd0b Pre-apply AI corrections on review load too (C2 completeness) — fixes the ~4s flicker on pre-existing jobs (#959)
Follow-up to workstream C (#957). Andrew opened an in-review job
(`c00a06d2`) and still saw the review page show uncorrected AudioShake
lyrics for ~4s before the AI corrections applied — the exact race C2 was
meant to kill.

## Why it still happened
The C2 server-side pre-apply runs in `screens_worker`, right before the
`AWAITING_REVIEW` transition. Jobs processed **before** that code
shipped (or whose suggestion cache landed after that gate) already
passed it, so their `corrections_updated.json` has no `pre_applied`
marker and the frontend falls back to its on-load client-side apply —
the visible flicker.

## Fix
Also pre-apply at the **load event itself** — the `/correction-data`
fetch, which is literally "when the lyrics review page launches":
- The endpoint now calls `ensure_and_pre_apply(job_id,
generate_on_miss=False)`.
- New `generate_on_miss` flag: the load path applies an **existing**
cache only, so the page never blocks on a multi-model LLM call. The
`screens_worker` path keeps `generate_on_miss=True` (generates ahead of
the notification for new jobs).
- Best-effort + idempotent: a no-op when the job was already
pre-applied, already human-edited, or has no cache (then the UI's
client-side apply still runs). Since prod runs proactive auto-correct,
the cache almost always exists → old jobs now load corrected instantly.

## Concurrency (CodeRabbit)
The write is now **create-only** (`upload_json(...,
if_generation_match=0)`); if the executor auto-complete or an edit
submission created `corrections_updated.json` between our existence
check and the upload, GCS raises `PreconditionFailed` and we skip —
their newer state wins.

## Tests
- `test_pre_apply.py`: load-path applies existing cache without
generating; load-path cache-miss doesn't generate or mark; screens-path
still generates on miss; raced concurrent write doesn't clobber. Full
backend suite: 4151 pass.
- Frontend unchanged (the `pre_applied` marker handling from #957
already covers this).

Local CodeRabbit review completed and addressed (create-only write).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 20:58:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a4d9303e8d fix(lyrics-review): Tap To Sync — stop stale-start crush + gap-fill tapped words (#958)
## Summary

Fixes the Tap To Sync bug where re-syncing a segment left a word crushed
to a tiny sliver (job `3ecab928` seg 28: **"call" collapsing to ~0.01s**
with a dead gap before "seems"). Verified live against real prod audio
in the replay UI, for both tap and hold.

Two related fixes in `frontend/hooks/useManualSync.ts`:

### 1. Overlap safety-net no longer crushes against a *stale* next-word
start (root cause)
When advancing to the next word, the overlap `useEffect` compared the
just-synced word's end against the **next word's start** — which still
held its **old** timing because it hadn't been re-tapped yet. For an
adjacent old start (e.g. "seems" at 155.50 right after "call"), it
pulled `call.end` back to that stale value (~0.01s). Taps happened to be
rescued by the keydown gap-fill; **holds** took the shorten-only branch
and stayed crushed.

Fix: track which word indices got a fresh `start_time` in the current
pass (`syncedIndicesRef`) and only let the overlap effect act when the
next word has actually been re-synced this pass. The forward correction
is already handled correctly at the next word's keydown.

### 2. Tapped word fills the gap up to the next onset
A *tapped* word only marks its onset, so it should hold until the next
word starts rather than staying a fixed 0.5s block.
`adjustPreviousWordEnd()` now grows a tapped previous word's end to
`nextStart − buffer`, capped at **`MAX_TAP_GAP_FILL_SECONDS = 1.0s`**.
Holds keep their deliberate release (only shortened on overlap). A
shared helper keeps the keyboard and touch paths in sync.

## Testing
- `frontend/hooks/__tests__/useManualSync.tapSync.test.tsx`: added
gap-fill, 1s-cap, and **hold-crush regression** tests (the hold-crush
test fails without the `syncedIndicesRef` guard — verified).
- 17/17 useManualSync tests green; 210/210 across `hooks` +
`components/lyrics-review`.
- Verified live in the replay UI (real prod job `3ecab928` seg 28): tap
→ "call" fills to onset (0.87s); hold → "call" keeps its held 0.82s, no
crush.
- Preserves all v0.208.0 invariants (no negative durations, lead-in/out
on both paths, auto-stop while spacebar held).

## Version
`0.208.0` → `0.208.1`

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 19:53:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3680ed66b3 Full-auto review: per-screen skip + server-side pre-apply + submission autonomy UI (workstream C) (#957)
Completes the fully-automated-review initiative (workstream C — the
final build item). Three interlocking parts, all shipped in one PR.

## C1 — Per-screen skip
Only show the review screen that actually needs a human.
- **Confident backing → skip the instrumental screen.** Completing the
lyrics review finishes the whole job. The client sends
`instrumental_selection="auto"`; the backend resolves it from the stored
verdict (`resolve_auto_instrumental`), so CLI/tenant clients get the
skip for free.
- **Mirror case (only backing gates) → skip the lyrics screen.** The
router deep-links straight to `#/instrumental`; the server-pre-applied
corrections are the lyrics payload.
- **Escape hatch:** a "let me choose the instrumental myself" toggle in
the finish modal.
- `always_review` jobs never auto-skip (gated server-side in the shared
summary).

## C2 — Server-side pre-apply (kills the on-load edit race)
Andrew's directive: apply the AI/heuristic corrections *before* the
review-ready notification, so the review screen loads one final state.
- New `pre_apply.ensure_and_pre_apply` runs in `screens_worker` before
the `AWAITING_REVIEW` transition: ensures the suggestion cache (bounded,
fail-open), applies with the same machinery the executor uses
(`apply.build_applied_segments`), and writes `corrections_updated.json`
with a `pre_applied` marker.
- `useAutoCorrect` gains a `preApplied` mode: no client-side
auto-run/auto-apply, panel seeded read-only from the server's
applied/rejected ids. Backward compatible (no marker → today's
behavior).

## C3 — Submission autonomy UI
- **Review mode** (fully automatic / always let me review) +
**backing-vocals preference** (keep-where-possible / clean /
let-me-choose) toggles in the guided flow.
- Plumbed through every submission route + `JobCreate`; **33 locales**
translated.

## Shared source of truth
`instrumental.backing_decision` is the one place the executor, the
complete-review `"auto"` resolver, and the UI summary all derive the
instrumental decision — they can't drift.

## Tests
- Backend: `test_instrumental.py` (decision matrix, summary/resolver
incl. always_review gating + stem checks, JobCreate coercion),
`test_pre_apply.py` (apply/marker/fail-open), executor
`backing_preference` cases. Full auto_approval suite: 112 pass. Touched
route suites: green.
- Frontend: `useAutoCorrect.preapplied` + `ReviewChangesModal`
escape-hatch tests. Full Jest suite: 1218 pass.
- i18n completeness enforced by CI.

Local CodeRabbit review completed and addressed (always_review gating,
stem-availability check, out-of-set preference coercion).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 18:58:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 8ce0d39faa fix(lyrics-review): Tap To Sync timing corruption + padded edit-segment timeline (#956)
## Summary

Fixes **Tap To Sync timing corruption** in the Edit Segment modal and
reworks the segment timeline for easier re-timing of the first/last
words.

### Tap To Sync fixes (`useManualSync`)
- **Negative durations on re-sync** — the overlap-correction effect
pulled a just-tapped word's end back to the *next* word's **stale**
start (it hadn't been re-tapped yet), producing `end_time < start_time`.
The sanitizer then reported *"Fixed N word timing(s) that fell outside
this segment"* on reopen. Now guarded + clamped so it never inverts.
- **First word squished / segment start ratcheting** — `clampSyncTime`
forced every tap into the tight `[segStart, segEnd]`, so a legit tap in
the 3s playback lead-in got shoved up to `segStart` and the start could
never be re-synced earlier. Now allows taps in `[segStart − leadIn,
segEnd + leadOut]` (floored at 0).
- **Last word cut off** — symmetric lead-out + auto-stop no longer fires
while the spacebar is held, so the last word can extend the segment
(hold past the end / default-duration overshoot) instead of being
truncated.
- Both keyboard **and touch** sync paths use the widened window.

### Edit Segment timeline UX
- ±1s **greyed context padding** on each side (dashed boundary), **faded
waveform** outside the segment, and **neighbouring segments' words** as
read-only context blocks. Word bars, drag, ruler, cursor and
click-to-scrub all map over the padded view; words can be dragged/synced
into the padding to extend the segment.
- Modal widened `960px → 95vw / max 1400px`.
- Header **play button** starts 1s before and auto-stops 1s after the
segment.

### Dev tooling (dev-gated, no prod impact)
- `&edit=1` makes a replay session editable locally (guarded by
`NODE_ENV !== 'production'`) so the real review UI can be exercised
against real job data + audio. Documented in `docs/REPLAY.md`.
- `review_test_fixtures.py` now serves a synthetic **click-track** so
Tap To Sync is exercisable offline.

## Testing
- New/expanded unit tests in `hooks/__tests__/useManualSync*.ts(x)`:
negative-duration regression (fails on old code, passes on fix),
lead-in/lead-out clamp cases, and segment-end extension. All 13 pass;
178 lyrics-review + hook tests green.
- Typecheck clean on touched files.
- Verified end-to-end in the browser against a real completed job
(replay + real vocals): tap-sync produces valid monotonic timings, no
sanitizer banner, first/last words extend correctly, timeline padding +
fade + neighbour words render as intended.

## Notes
- CodeRabbit reviewed locally; its one finding (touch path missing the
lead window) is fixed.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-29 17:17:10 -04:00
Andrew Beveridge ☄️andClaude Fable 5 7204d945e4 fix: backing-keep enforcement default true in code (audio-worker trigger env gap) (#955)
## Summary

Follow-up to #953. The env-var flip only reached the backend Cloud Run
*service*, but `maybe_auto_complete_review` also runs inside the
**audio-separation Cloud Run Job** (the audio-lags-lyrics second-chance
trigger), whose env is Pulumi-managed and independent — so scorings from
that trigger still read the `false` default and blocked with
`backing_keep_disabled`. Observed live: The xx — Islands scored lyrics
`auto/ai-resolved` + backing `with_backing` but was blocked by the
phantom flag; it would have completed fully auto.

Fix: with shadow validation complete (20-job corpus, live batteries,
human review pass at 10/11 agreement), the default moves into code
(`"true"`), matching the `AUTO_APPROVAL_ENFORCE_ENABLED` pattern — one
deploy covers every environment the executor runs in. Env var remains
the kill switch (must be set `false` in both the ci.yml backend deploy
and the Pulumi job envs, or revert this).

Same gotcha class as the audio-download-job POSTMARK env gap (Cloud Run
Jobs have independent env).

## Testing
- auto_approval + config suites pass (92).
- Live proof after deploy: next candidate batch should auto-complete
confident jobs from either trigger.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 06:30:37 +00:00
Andrew Beveridge ☄️andClaude Fable 5 5d6a6d4f1b fix(review): async preview video generation — survive encoder cold-starts (v0.207.0) (#954)
## Summary

Preview videos in the lyrics review UI got stuck on "Generating preview
video..." whenever the GCE encoding worker needed a cold start (job
`326e1aef`, 2026-08-29): the synchronous `POST /preview-video` held the
connection for 2m36s while three zones were stocked out and a fallback
VM booted — Cloudflare cuts browser connections at ~100s, so the UI
never saw the (successful!) response.

### Backend
- `POST /api/review/{job_id}/preview-video` now returns `{"status":
"generating", "preview_hash"}` immediately after the ASS subtitles are
uploaded; encoding runs in a background asyncio task (established
pattern in this file): GCE encode → local render fallback → GCS error
marker (`previews/{hash}.error.json`) if both fail
- Cache short-circuit: the preview hash is deterministic over the
correction data, so an identical retry returns the existing mp4
instantly as `{"status": "success"}`
- New `GET /api/review/{job_id}/preview-video/{hash}/status` poll
endpoint — GCS-backed (mp4/error-marker existence), so polls work across
Cloud Run instances
- Blocking prep work (GCS downloads, ASS generation) moved to
`asyncio.to_thread` so it no longer stalls the event loop

### Frontend
- `PreviewVideoSection` polls the status endpoint (3s interval, 5-min
cap), escalating to a "starting up an encoding server — this can take a
couple of minutes" message after 30s
- Fixed the Retry button: it previously reset state without
re-triggering generation (spun forever) and was hardcoded English; now
works via a retry nonce and is translated
- Removed the dead `worker_starting` branch (a status the backend never
returned)
- New i18n keys (`encoding`, `timedOut`, `retry`) + updated
`startingEncoder` translated for all 33 locales

## Testing

- 9 new backend tests: cache-hit, generating + background spawn +
stale-marker cleanup, status endpoint (ready/error/generating),
background task (GCE success / local fallback / error marker)
- 7 new Jest tests for `PreviewVideoSection`: cache hit,
poll-until-ready, transient poll failure, terminal error stops polling,
timeout, Retry re-runs, missing hash
- Full suites green: backend 4093 ✓, karaoke_gen unit 1779 ✓, frontend
Jest 1203 ✓, `tsc --noEmit` no new errors vs main, translation
`--keys-only` validation ✓

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 02:14:23 -04:00
Andrew Beveridge ☄️andClaude Fable 5 b45efbdbc5 feat: enable confident backing-keep enforcement in prod (#953)
## Summary

One-line deploy-env change: `AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` on
the backend service. A confident WITH_BACKING verdict from the 3-stem
backing decider (#950) now auto-selects the with-backing instrumental,
letting jobs with confident lyrics AND clear backing vocals complete
fully automatically.

## Shadow validation evidence (why now)

- **20-job replay corpus**: 13/14 true keeps confidently retained (incl.
both jobs the human under-kept); catastrophic backing-is-lead case
gated; zero unsafe outcomes.
- **Live prod battery**: 7/7 keep verdicts on harmony tracks with
consistent signal profiles; the misclassified-lead gate fired correctly
on an adversarial shoegaze track; one job completed fully zero-touch end
to end.
- **Human review pass on 11 fresh jobs (2026-08-29)**: 10/11
instrumental picks matched the shadow verdict. The single
lyrics-auto-eligible job was shipped by the human with **zero manual
edits and the identical instrumental selection** full-auto would have
made. Every job needing real lyric work was correctly gated (up to 127
manual edits on gated jobs; zero false-autos).

Kill switch: set the var to false (or remove it — code default is
false). Per-job opt-out: `review_mode="always_review"`.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 01:17:31 -04:00
Andrew Beveridge ☄️andClaude Fable 5 9d4f70a747 fix: clean up published outputs before job delete; admin orphaned-outputs cleanup (v0.206.0) (#952)
## Summary

Fixes the root cause of tonight's **NOMAD-1583 duplicate brand code**
incident and adds the tooling needed to clean up the orphaned files.

**Incident**: job `e97475ff` (Mazzy Star – Fade Into You) published with
NOMAD-1583 at 02:15 UTC, was deleted at 03:02 via `DELETE
/api/jobs/{id}?delete_files=true` — which recycled the brand code but
left every published output live (GDrive ×3, Dropbox folder, YouTube
video, kjbox mirror ×2). At 04:16, job `326e1aef` (Chase & Status – No
Problem) reused the recycled 1583 → duplicate in all three public share
folders, validator alerting on every subsequent job.

## Changes

- **`DELETE /api/jobs/{id}` no longer blind-recycles brand codes.** When
a job's outputs are still published, it now runs the full distribution
cleanup first (YouTube + Dropbox + GDrive + kjbox GCS mirror) via a
shared `_run_distribution_cleanup()` helper (extracted from
`cleanup-distribution`); recycle stays gated on Dropbox+GDrive success.
Incomplete cleanup aborts the delete (502) so the job record — the only
place holding the file IDs — is preserved for retry.
`delete_files=false` is rejected (400) for published jobs. Jobs whose
outputs were already deleted no longer re-recycle the code.
- **New `POST /api/admin/orphaned-outputs/cleanup`** — removes
distributed outputs by explicit IDs (YouTube video ID, Dropbox path,
GDrive file IDs, mirror filename prefix) when the owning job doc is
gone. Needed to clean up the Mazzy Star orphans.
- **`NomadMasterMirror.delete_track_objects_by_filename_prefix`** —
single-track mirror delete requiring a `NOMAD-#### - Artist...` prefix,
delimiter-bounded so it can never match the other track legitimately
holding a recycled code.
- New i18n key `jobs.deletePublishedRequiresFiles` translated to all 33
locales.
- Runbook + incident history in `docs/GDRIVE-VALIDATOR.md`.

## Testing

- 4111 backend tests pass (18 new: DELETE-route cleanup semantics, admin
endpoint, mirror prefix guardrails/delimiter bounding).
- Local CodeRabbit review: 2 cycles, all 4 findings addressed
(abort-on-incomplete-cleanup, delete_files honored, delimiter-bounded
prefix, unsafe-prefix 400).
- Post-deploy: will run the orphaned-outputs cleanup for the Mazzy Star
files and re-run the GDrive validator to confirm a clean report.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 01:16:47 -04:00
Andrew Beveridge ☄️andClaude Fable 5 d061b480dc feat: auto-complete user-supplied-instrumental jobs with selection=custom (v0.205.0) (#951)
## Summary

Phase 2D of fully-automated review (follows #949/#950) — the
highest-business-value slice: tenant bulk-upload jobs (and any job with
a user-supplied instrumental) can now complete fully automatically.

Jobs with `existing_instrumental_gcs_path` or a `custom_instrumental`
stem have **no instrumental decision to make** — the human
complete-review flow submits `instrumental_selection="custom"`
(review.py validates it exactly under these conditions; the video worker
prefers the user-provided source). The executor previously excluded
these jobs outright via the `custom_instrumental` blocker. Now:

- **Confident lyrics alone auto-complete them** with
`instrumental_selection="custom"`, mirroring the human tenant
complete-review exactly. The backing verdict is moot (no separated-stem
requirements; the video worker validates custom sources itself).
- Non-custom jobs are unchanged: the `overall_auto` intersection
(confident lyrics AND non-subjective backing) still applies.
- `processing_metadata.auto_approval` now records `enforcement_basis`
(`lyrics_only_custom_instrumental` vs `overall_auto`) and
`custom_instrumental` for shadow analysis, and `enforcement_eligible`
now reflects verdict eligibility AND blockers (CodeRabbit catch).
- Per-job opt-out remains `review_mode="always_review"`
(admin-editable). A per-tenant default is future work.

This makes tenant bulk uploads the highest-auto-rate population: their
jobs skip both review screens whenever the scorer is confident in the
lyrics, going straight to render with the instrumental the tenant
supplied.

## Testing

- Executor tests updated: the old `custom_instrumental`-blocks test
replaced by three new tests — auto-complete with selection="custom" even
with NO backing analysis (moot), custom-stem variant without separated
stems, and weak-lyrics still gating to review.
- Full backend suite: 4056 passed, 0 failed. Backend-only change.
- Live validation planned tonight: a Vocal Star tenant bulk upload (~10
tracks) after deploy, watching `enforcement_basis`/outcomes in prod.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 22:12:46 -04:00
Andrew Beveridge ☄️andClaude Fable 5 c2e31a5325 feat: 3-stem backing-vocals decider — confident WITH_BACKING verdict, shadow-first enforcement (v0.204.0) (#950)
## Summary

Phase 2B of fully-automated review (follows #949): the backing-vocals
decision gets a real decider. Today any track with audible ("pink")
backing content goes to human review; per the 20-job replay-review
corpus, pink → KEEP is right essentially always — the human
systematically *under*-keeps — except three detectable "pink but don't
keep" failure modes. This PR builds the 3-stem analysis that detects
them and lets the scorer emit a confident **WITH_BACKING** verdict.

- **New `karaoke_gen/instrumental_review/stem_comparison.py`** (pure
pydub): compares the backing / lead / full-vocals stems — per-stem
audible coverage + coverage ratio, envelope Pearson correlations, median
audible levels, lead-overlap fraction, within-run flatness. Runs in the
existing backing-vocals analysis step (screens_worker →
AudioAnalysisService) and is stored as
`backing_vocals_analysis.stem_comparison` on every new job. Best-effort:
any failure stores an error marker, never blocks the job.
- **Scorer v0.3.0**: the pink-present branch now decides — confident
WITH_BACKING (non-subjective, bias-to-keep per corpus) unless:
- **backing stem IS the lead** (catastrophic if kept): coverage ratio
≥0.80 + backing↔vocals correlation ≥0.80 + backing more audible than the
lead stem (the decisive discriminator — a plain dB-margin rule nearly
misfired on a genuine keep) → review;
- **noise-floor pink** (lo-fi mixes): median ≤ −35 dB across ≥15% of the
track, uncorrelated with the vocal line → review (marginal either way
per corpus);
- **lead bleed** (narrow): ≤3% audible with ≥0.95 lead overlap → review.
- **Executor**: a WITH_BACKING verdict auto-selects the with-backing
instrumental **only** behind `AUTO_APPROVAL_BACKING_KEEP_ENABLED`
(default **false** — shadow-first). While off, such jobs record blocker
`backing_keep_disabled` plus the full verdict/signals in
`processing_metadata.auto_approval`, accumulating prod shadow data
alongside human picks. Also requires the `instrumental_with_backing`
stem.

## Validation (real corpus stems, ~2.4 GB, private harness)

Downloaded all 20 corpus jobs' three stems from GCS and ran the decider
against the replay-review ground truth:

- **13/14 true keeps → confident WITH_BACKING**, including BOTH jobs the
human wrongly cleaned on quick review (44622ffa harmonized ahhs,
35ed9697 self-harmony hooks) — the decider beats the human here.
- 95d8e844 (marginal grungegaze, mostly noise pink) → review. All
clean-correct jobs → clean. **1d45b286 (backing stem is the lead —
worst-case if kept) → review.** Zero unsafe outcomes.
- Lyrics-side corpus validation (validate_scorer.py) unchanged and
green.

## Testing

- 21 new unit tests: synthetic-audio stem-comparison signal tests,
scorer decision branches modeled on the real corpus signal profiles,
executor flag/stem gating.
- Full backend suite: 4056 passed, 0 failed. Backend-only change (no
frontend, no user-facing strings).

## Rollout

Shadow-first: nothing changes for users at deploy. After reviewing prod
shadow verdicts vs human picks, set
`AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` to let confident-keep jobs
(e.g. the Cher-class: lyrics solved, gated only by audible backing)
complete fully auto.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 19:56:45 -04:00
Andrew Beveridge ☄️andClaude Fable 5 b1126583c0 feat: deterministic P4/P1/P5 lyrics auto-fixers in the auto-correct pipeline (v0.203.0) (#949)
## Summary

Phase 2A of fully-automated review (follows #947/#948): the three
mechanical residual-edit classes from the 20-job replay-review corpus
become **deterministic suggestion generators inside the auto-correct
pipeline** — one mechanism feeding the review UI's on-load auto-apply,
the auto-approval executor's server-side apply, the scorer's
gap-coverage signal, and the proactive suggestion cache.

- **P4 — leading-connective over-insertion** (most common residual
class): a segment starting with And/But/So/Oh/A that is a gap word and
unsupported by every reference source's reading of that gap → `delete` +
re-capitalize the next word. Guard: skipped when the next word is a
vocalization token (an "Oh- whoa," run is a musical judgement).
- **P5 — reference-majority resolution**: a gap whose transcription
contains an implausible proper noun (capitalized mid-line token absent
from every reference) 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), and
a spelling-variant guard (similarity ≥0.75 to a reference token) skips
transliteration/truncation cases whose gap alignment is typically junk.
- **P1 — AI self-conflict fixed at source**: conflict grouping now also
unions an `insert_after` with any suggestion targeting/anchored on the
same word whose new_text shares a token, so accept-all picks one winner
instead of double-applying ("you're you're"). The executor's
duplicate-word abort stays as belt-and-braces.

Per-source gap readings come from the gap's own reference alignment,
else are derived by walking the reference stream past the surrounding
anchors (recovers the readings the aligner left empty). Suggestion-cache
key bumped to v2 so pre-fixer cached results aren't served.

## Validation

- **Corpus (private validate_scorer.py, extended with FIXER assertions):
all safety + gate checks still 100%.** P4 fires on all six corpus
examples (8f2305ee, ae0cd7e8, 1d45b286, 5f90b799, 33453fa0, f247364e);
P5 reproduces the human's exact edit on 6d0640fa ("yo Mick," → "Come
here,") and fires nowhere the human deliberately made no edit (507513ba,
d508adb6, and the other 6d0640fa gaps).
- The Miguel corpus job (6d0640fa) now scores lyrics=auto with clean
backing → would fully auto-ship **with the human's exact edit applied**;
the Samson corpus job's P4 edits now get applied rather than skipped.
- `ai-resolved` caps deliberately NOT loosened.

## Testing

- 27 new unit tests
(`backend/tests/services/auto_correct/test_deterministic.py`) covering
both generators, all guards, P1 grouping, and pipeline integration
(append/dedupe/conflict/min-confidence/no-corrections fallback).
- Full backend suite: 4033 passed, 0 failed.
- Backend-only change; no frontend files or user-facing strings.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 16:25:22 -04:00
Andrew Beveridge ☄️andClaude Fable 5 9b6c4f236e fix: Cloud Tasks queue region from GPU workers + REVIEW_COMPLETE lost-trigger recovery (v0.202.1) (#948)
## Summary

Follow-up to #947, found by live-testing auto-approval in prod (job
`b8bda9c2` — the first real fully-auto-approved job).

**Bug:** the GPU `audio-separation-job` sets `GCP_REGION` to its GPU
region, but every Cloud Tasks queue lives in `us-central1`. Any queue
enqueue from inside that worker fails with `404 Queue does not exist` —
which silently dropped the auto-approval render trigger (job
auto-approved perfectly, then sat at `review_complete` forever). This is
also a latent pre-existing bug for any other enqueue attempted from the
GPU job.

**Fixes:**
1. New `settings.cloud_tasks_region` (default `us-central1`, overridable
via `CLOUD_TASKS_REGION`) used for all Cloud Tasks queue paths.
`gcp_region` is still used for Cloud Run Job locations (correct).
2. `recover-stuck-jobs` cron gains a sweep for `REVIEW_COMPLETE` jobs
stalled >10 min with no `render_progress` — re-triggers the render
worker (idempotent via worker-generation fence). This closes the
lost-trigger orphan gap for BOTH the human complete-review
fire-and-forget task and the auto-approval path, and will auto-rescue
`b8bda9c2` on the first tick after deploy.

## Testing
- New unit tests: queue path uses `us-central1` even when
`GCP_REGION=us-east4`; stall detector (stalled / fresh /
render-underway).
- Note: `test_internal_api.py` auth tests fail identically on pristine
`main` in this local env (green in CI) — pre-existing, unrelated.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 05:07:17 -04:00
Andrew Beveridge ☄️andClaude Fable 5 f01213f5cb Fully-auto review for confident jobs: review_mode framework + auto-approval scorer/executor + replay tool (v0.202.0) (#947)
## Summary

Ships the **fully-automated review framework**: jobs now default to
`review_mode="auto"` — when the auto-approval scorer is fully confident
on BOTH axes, the combined review screens are skipped entirely and the
job renders straight through. Everything else falls back to human review
exactly as before.

**The confident class (deliberately narrow to start, ~5% of jobs
expected):**
- **Lyrics**: synced reference present, ≥90-99% anchor coverage, and
every gap word covered by the pre-generated AI auto-correct suggestions
(which the executor applies server-side — a faithful port of the review
UI's on-load auto-apply, including conflict-group resolution) — OR zero
gaps outright.
- **Backing vocals**: non-subjective only — no audible backing content →
clean instrumental.
- **Never-auto gates**: vocalization sections (da-da-dun/woo-woo — P3),
phantom/absurd-duration lines (P8), too-few-words, no/unsynced
reference, errored backing analysis.

**Calibrated against a 20-job human-review corpus** (all recent admin
reviews replayed + annotated): safety 100% (every job that truly needed
a human stays in review), lyrics-auto 3/20, overall-auto 1/20.

## How it works

- `screens_worker` (pre-AWAITING_REVIEW) and `audio_worker` (post-stems,
for the audio-lags-lyrics ordering) both call
`maybe_auto_complete_review()`. Every job gets a verdict recorded in
`processing_metadata.auto_approval` (shadow data keeps accumulating for
calibration); enforcement additionally requires: flag on +
`review_mode="auto"` + not made-for-you + no existing/custom
instrumental + audio complete.
- Enforce path mirrors a human "Complete Review": apply cached AI
suggestions → sanity checks → `corrections_updated.json` →
`instrumental_selection="clean"` → clear progress keys →
`GENERATING_SCREENS→REVIEW_COMPLETE` (new legal edge; no review token or
"ready for review" notification is ever issued) → trigger render worker.
- **Fail-safe everywhere**: stale suggestions, duplicate-word artifacts
(P1 self-conflict signature), state changed mid-enforce (human opened
editor), any exception → normal human review. Auto-approval can never
fail a job.
- Kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false` (scoring
continues). Per-job: `review_mode="always_review"` (admin PATCH,
validated).
- Excluded from enforcement (still shadow-scored): made-for-you orders
(human QC is part of that product), custom-instrumental jobs.

## Also in this PR (sessions 1-3 of the initiative)

- **Review replay tool** (admin-only, prod-inert): `?replay=1` reopens
the real lyrics/instrumental review UIs read-only for completed jobs —
queue nav, Post-AI/Final toggle, edit-log action panel, dev-only audio
byte-proxy (env-gated `REVIEW_AUDIO_PROXY`, path-anchored). This is what
produced the calibration corpus.
- `auto_approval` service package: scorer (anchor/gap/AI-coverage
signals + P3/P8 gate detectors), apply engine, executor, lyrics-diff,
offline capture script.

## Testing

- 100+ new unit tests across scorer/apply/executor/replay routes; full
backend suite 4000+ green locally (8 pre-existing emulator failures
reproduce identically on pristine `main` — local-env only, green in CI).
Frontend: 1196 Jest tests green.
- Scorer validated read-only against the 20 real prod jobs in the
private calibration corpus.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 03:07:33 -04:00
Andrew Beveridge ☄️andClaude Fable 5 70ea964ca9 feat(dev): full local backend for external contributors (no GCP creds needed) (#946)
## Summary

Motivated by external contributor Martín (netux) asking "is there an
easy way to run the full backend without GCS?" — he couldn't test PR
#895's backend changes locally. This PR makes the whole backend runnable
locally against emulators with **zero GCP credentials and zero paid API
keys**.

### What was broken for contributors
- Workers migrated to Cloud Run Jobs for prod robustness
(audio-download, audio-separation, lyrics-transcription, bulk-search)
silently bypassed the direct-HTTP dev mode → local jobs stalled at
PENDING forever
- Signed URL generation called `google.auth.default()` → crashed with no
credentials (review audio, downloads, theme previews, upload URLs)
- Magic-link login 503'd locally (console email provider counted as "not
configured")
- Fresh emulator had no default theme → every job create returned 422
- `docs/DEVELOPMENT.md` told people to `cp .env.example .env` but the
file didn't exist — and nothing loaded `.env` anyway
- `run-backend-local.sh` defaulted to the production GCP project

### Changes
- **worker_service**: CRJ-based workers run as local subprocesses
(`python -m backend.workers.X --job-id Y`, exact CRJ parity) when
`ENABLE_CLOUD_TASKS=false` **and** not `is_production()`
(regression-tested both ways)
- **storage_service**: signed URLs → plain fake-gcs-server URLs when
`STORAGE_EMULATOR_HOST` set (GET via JSON API download path; PUT via
unvalidated-signature path, enabled by `-public-host` on the emulator)
- **users route**: magic-link 503 only in production; dev prints the
link to the console
- **file_upload bugfix**: a theme with style params but no asset files
never got `style_params_gcs_path` written (empty-dict falsiness in `elif
theme_style_assets:`) — surfaced by the minimal seed theme, latent in
prod
- **scripts/seed-local-data.py** (new): creates bucket + default theme;
wired into `run-backend-local.sh --with-emulators`, which now uses
`test-project`
- **config**: `load_dotenv()` so `.env` actually works; new root
`.env.example`
- **CONTRIBUTING.md** (new): no-credentials quickstart; README +
DEVELOPMENT.md link to it

### Verified end-to-end locally (no GCP credentials)
Upload job → local audio separation (real models) → transcription →
screens → `awaiting_review`; review endpoints all working including
`/api/review/{job}/audio/vocals` (the PR #895 endpoint) and 302 →
emulator audio URLs. Magic-link login round-trip via console link.

### Tests
- 224 tests across affected files pass; full backend unit suite: 3969
passed
- `backend/tests/test_emulator_integration.py` has 8 pre-existing
failures that reproduce identically on unmodified `main` locally (broken
theme-service mock in that file) — unrelated to this PR
- New tests: dev-mode subprocess dispatch (audio + bulk-search),
prod-mode never-Popen guard, emulator URL generation (GET + PUT)

@coderabbitai ignore

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 06:48:00 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 79b7c80264 fix(e2e): fill Stripe Checkout name + ZIP fields (daily E2E false alarm) (#945)
## Problem

The daily **E2E Daily Test — Stage 1: Credit Purchase** (run #146) fired
the Discord alert *"🚨 Payment flow is broken. Customers may not be
receiving credits."* on all 3 retries.

This was **test drift, not a production outage.** Stripe's hosted
Checkout now renders **required** *Name on card* and *ZIP code* fields,
but the test helper's fill locators no longer matched their current
accessible names, so both were left blank. Stripe blocked the "Pay"
click (`Please provide the name on your card` / `Your ZIP code is
invalid`), the page never redirected, and the 60s `waitForURL` timed
out.

Root cause confirmed from the failed run's `error-context.md` +
`test-failed-1.png` (both validation errors visible on the stuck
Checkout page). Prod `/api/health` was healthy throughout, and real
customers fill these fields themselves — so checkout is unaffected.

## Fix (`frontend/e2e/helpers/stripe-checkout.ts`, test-only)

- **Name** locator now matches `/name on card|cardholder name/i`,
placeholder `First and last name`, and
`[data-elements-stable-field-name="billingName"]`.
- **ZIP** locator drops the broken `^zip$` anchor (the accessible name
is "ZIP code") → `/zip|postal code/i`.
- Bumped the too-short 2s field-search timeouts to 8s; added WARNING
logs when a field isn't found.
- Defaulted the cardholder name so a missing/empty secret can't silently
reblank it.

## Verification

Ran `credit-purchase-real.spec.ts` against **production with a real $3
charge**: checkout completed, redirected to **"Payment Successful · 2
credits available"**, and the *"1 credits added"* confirmation email
arrived. Old locator regexes tested `false` against the real snapshot
strings; new ones test `true`. Typecheck clean. CodeRabbit local review:
no findings.

> Note: a ~600s "Test timeout exceeded" seen locally *after* the body
passes is an environmental macOS teardown quirk (production config uses
`trace:'on'`+`video:'on'`), reproducible with a bare navigate-and-close
test — it does not occur on CI's Ubuntu runners.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-26 12:38:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 714f3d2ae6 fix: append-after-last segment crash + firestore backup same-day retry collision (#944)
Fixes two independent production issues flagged overnight (2026-08-25).

## 1. Lyrics review crash — `TypeError: Cannot read properties of
undefined (reading 'start_time')`
Error-monitor alert: `frontend` / `onAddSegmentAfter`. Clicking **"Add
segment after"** on the *last* segment calls `addSegmentBefore(data,
beforeIndex)` with `beforeIndex === corrected_segments.length`, so
`corrected_segments[beforeIndex]` is `undefined` and reading
`.start_time` throws.

**Fix** (`frontend/lib/lyrics-review/utils/segmentOperations.ts`): when
`beforeIndex` points past the end (append case), anchor the new
segment's timing/singer off the *previous* segment — start at its
`end_time` (or `0` for an empty list) — instead of dereferencing
`undefined`.

## 2. Nightly backup FAILED — `Firestore: 400 Path already exists`
`export_documents` refuses to write into an output prefix that already
contains an export. The backup Cloud Function returns HTTP 500 if *any*
step fails, so Cloud Scheduler retries the whole function — and the
retry collided with the earlier run's already-written
`firestore/{date}/…overall_export_metadata`. The existing
`_clear_prior_exports` runs *after* export and deliberately keeps
today's, so it never resolved a same-day collision.

**Fix** (`infrastructure/functions/backup_to_aws/firestore_export.py`):
new `_clear_target_prefix()` deletes any leftover `firestore/{date}/`
**before** exporting, making the export idempotent across same-day
retries.

## Tests
- `segmentOperations.test.ts`: append-after-last (`beforeIndex ===
length`) + append-into-empty — 13 passed
- `test_firestore_export.py`: asserts the stale same-day export is
deleted before `export_documents` runs — 5 passed

Version bumped `0.199.4 → 0.199.5`.

Reviewed locally with CodeRabbit CLI (no findings).

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 17:47:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 156d4369f9 Tenant bulk upload: folder pick + LLM pairing + review table + resumable uploads (v0.200.0) (#943)
## Summary

Adds a **Bulk** mode to tenant portals (frog #3, Vocal Star ask): drop a
folder of tracks, automation pairs Mixed vs Instrumental audio and
extracts Artist/Title from filenames, the operator reviews/fixes an
editable table, then submits all as jobs — with uploads that survive
slow/flaky connections.

### Bulk mode
- `POST /api/tenant/bulk/analyze` — authed, gated on new
`TenantFeatures.bulk_upload` (default on), cap 100 audio files. Regex
fast path for the `S####-1/-2 … Guide/BV/Instru` convention +
Vertex-Gemini pass for leftovers
(`backend/services/tenant_bulk/analyze.py`), regex-only fallback if the
model errors. Pure analysis — filenames only, no state written.
- Label parsing: STRONG labels (guide/instru/bv/backing vocals) override
the `-1`/`-2` slot (surfaces the real-world `S1102-2 … Guide` anomaly as
mixed-only unpaired); WEAK words (Off/Lead/Vocals/Karaoke) stay in the
title unless bracketed.
- `TenantBulkFlow.tsx`: folder/file pick → editable review table
(reassignable Mixed/Instrumental dropdowns, warnings strip,
low-confidence cautions) → bounded-concurrency submit reusing the tenant
single-submit sequence. Mixed-only rows blocked + flagged. Jobs stamped
`state_data.batch_id` + `created_from='tenant-bulk'`.

### Resilient uploads (opt-in `upload_mode: "resumable"`)
- Backend returns **GCS resumable session URIs** (created server-side
with the caller's Origin → GCS answers session CORS itself; **no bucket
CORS changes**). Signed PUT stays the default for all existing clients.
- `frontend/lib/resumable-upload.ts` (dependency-free): 256KiB-aligned
adaptive chunks, always-query-offset resume (no persisted byte ever
re-sent), stall detection instead of hard timeouts, backoff+jitter cut
short by online/visibility events, waiting-offline pause, EWMA
throughput + per-row ETA, non-advancing-308 loop guard.
- `frontend/lib/upload-recovery.ts`: IndexedDB persistence → after a
reload/crash a "Resume unfinished batch?" banner lets the operator
re-pick the folder and every upload resumes from its server-side offset
against the same jobs (never duplicates).

### Tests
- Backend: 26 new (real Bulk-Batch-1 fixture incl. S1102 anomaly,
label-in-title regressions, endpoint auth/feature/cap gates, upload_mode
contract)
- Frontend: 22 new (engine chunk choreography/offset recovery/permanent
errors/retry caps; component resumable routing, re-pick recovery,
retry-no-duplicate)
- Full suite green: backend (incl. emulator) + 1194 frontend
- Prod E2E extension of `tenant-happy-path` is a documented follow-up
(needs this deployed first)

### Docs
- `docs/API.md`: new endpoint + `upload_mode`/`batch_id` fields
- Design + decision record: workspace
`docs/archive/2026-08-25-tenant-bulk-upload-plan.md`

Local CodeRabbit review: 3 completed rounds on this branch, all 9
findings fixed.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 17:10:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ed20281ca0 Tenant flow: auto-reset submit form (2s) + "Complete Track" CTA when no instrumental review (#942)
Two tenant-flow streamlining items Andrew raised while validating the
Vocal Star portal (frog #3).

## 1. Auto-reset the Submit form ~2s after success
After a track submits, `TenantJobFlow` shows the confirmation briefly
then auto-returns to a blank form (~2s) so operators can submit one
track after another quickly. The "Submit Another" button stays for
anyone who wants to reset sooner.

## 2. "Complete Track" CTA when there's no instrumental review
Tenant / uploaded-instrumental jobs skip the instrumental-review step,
so the lyrics-review preview modal's CTA "Proceed to Instrumental
Review" was misleading. It now reads **"Complete Track"** whenever the
review completes directly — driven by the existing
`hasExistingInstrumental` signal via a new `completesReview` prop on
`ReviewChangesModal`. Consumer jobs that DO have an instrumental step
are unchanged.

## Details
- Updated the tenant prod E2E to accept either CTA label (`/complete
track|proceed to instrumental/i`) so it's deploy-safe across the
transition.
- Added a `ReviewChangesModal` test for the new label; existing tests
unchanged (default `completesReview=false`).
- New `completeTrack` i18n key translated to all 33 locales.
- Frontend-only. Version 0.199.3 → 0.199.4.
- The larger **bulk-upload mode** Andrew requested is tracked separately
in BACKLOG (not in this PR).
- Merging this to main also re-triggers the backend deploy (now with the
firestore pin from #941), which will ship #939/#940's still-undeployed
backend changes once a self-hosted runner is available (currently
blocked by Spot preemption).

## Testing
- `ReviewChangesModal` tests: 6/6 pass (incl. new "Complete Track"
case).
- `tsc` clean for all changed files; E2E spec compiles.
- CodeRabbit local review: 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 01:32:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 8457a3bfca fix(ci): pin google-cloud-firestore in backend deploy (2.29.0 breaks deploys) (#941)
## Problem — backend deploys are broken

The **Deploy - Backend (Cloud Run)** job's *Read Firestore config* step
crashes:

```
google.api_core.exceptions.InvalidArgument: 400 Invalid database id %28default%29
```

`%28default%29` is URL-encoded `(default)`. **`google-cloud-firestore`
2.29.0** (published 2026-08-24T21:55Z) percent-encodes the default
database id in the resource path. The deploy step ran an **unpinned**
`pip install google-cloud-firestore`, so it started pulling 2.29.0 and
failing.

**Impact:** every backend deploy since 2.29.0 shipped has failed
(post-merge runs for `c36bcb08` and `7a3c1d66`). #939 (worker-trigger
retry) and #940 (job-list summary field) merged but **never reached
Cloud Run** — the active revision is still `00913` from #937.

## Fix

Pin the deploy step to `google-cloud-firestore==2.26.0` — the version
`pyproject.toml` and prod already run (the running backend reads
Firestore fine on 2.26.0). One line + a comment explaining why.

## Testing

- PR CI runs unit tests (deploy jobs are push-to-main only); the pin
doesn't affect them.
- On merge, the backend deploy will run with 2.26.0 and should succeed,
deploying main (0.199.3 = retry fix + summary field).
- Verified 2.29.0 is the regression via PyPI upload timestamps vs the
last good deploy (21:06, used 2.28.1).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Chores**
* Updated the backend deployment to use a fixed Firestore library
version, improving deployment consistency and reliability.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-24 23:32:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7a3c1d6683 Clearer job status labels: 'Preparing your audio' for uploads + fix raw jobStatus.Processing key (#940)
## Why

Two frontend job-status **label** bugs, both surfaced while manually
driving the Vocal Star tenant flow:

1. **Tenant/upload jobs show "Downloading"** even though the operator
uploaded their own audio — there's nothing to download. (Andrew hit this
on a real job: "it's currently Downloading — what is there to download
though, since I uploaded the files?")
2. **Backlog item — raw i18n key rendered verbatim:** status sometimes
reads `[4/10] jobStatus.Processing`.

Both live in `frontend/lib/job-status.ts`.

## Fixes

**1. "Preparing your audio" for upload-based jobs.** The download stage
reused the consumer "Downloading" label. For jobs with a pre-supplied
instrumental (`existing_instrumental_gcs_path`), the staging stage now
shows **"Preparing your audio"**. Added `existing_instrumental_gcs_path`
to the job-list summary projection (`SUMMARY_FIELD_PATHS`) — it's a
top-level field (no `state_data` prune needed), so the list view can
detect upload jobs.

**2. No more raw `jobStatus.X`.** The "downloading + workers running"
path passed the **literal string `"Processing"`** (not a `jobStatus`
key) as the label, so `t("Processing")` missed and rendered
`jobStatus.Processing`. Now it uses a valid `processing` key, and when
only one parallel worker is reporting (tenant jobs run lyrics only — no
separation), it shows that worker's real status (e.g. "Transcribing
lyrics") instead of a generic label.

## Guardrail

Added a regression test asserting **every label `getJobStep` can emit
exists in `en.json` jobStatus** — so this whole class of raw-key bug
can't recur.

## Testing

- Frontend `job-status.test.ts`: 90/90 pass (new cases: upload-job
relabel, downloading_audio, advance-to-transcribing,
no-relabel-for-normal-jobs, raw-key regression, en.json completeness).
- Backend: new `SUMMARY_FIELD_PATHS` projection guard test.
- New keys `jobStatus.preparingAudio` + `jobStatus.processing`
translated to all 33 locales.
- Version bumped 0.199.2 → 0.199.3.
- CodeRabbit local review: 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-24 23:05:41 -04:00
195 changed files with 18158 additions and 943 deletions

No files matched your search

+42
View File
@@ -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=
+6 -2
View File
@@ -1218,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
@@ -1917,7 +1921,7 @@ jobs:
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
- name: Update Cloud Run Jobs with new image
+88
View File
@@ -0,0 +1,88 @@
name: PyPI prune reminder
# PyPI caps total *project* size at 10 GB. karaoke-gen auto-publishes a ~62 MiB
# wheel on every merge to main (~3 GB/month), so the project refills the cap
# every few months and `poetry publish` then fails with "Project size too large".
#
# PyPI has NO deletion API (upload tokens are upload-only), so this can't
# auto-delete. Instead it runs monthly, computes the retention plan
# (scripts/prune_pypi_releases.py), and opens/updates a single tracking issue
# containing a paste-into-browser-console snippet you run on your logged-in PyPI
# releases page to actually prune. No secrets are stored.
#
# See docs/PYPI-STORAGE-PRUNE.md.
on:
schedule:
# 09:00 UTC on the 1st of each month.
- cron: "0 9 1 * *"
workflow_dispatch: {}
permissions:
contents: read
issues: write
jobs:
prune-reminder:
runs-on: ubuntu-latest
timeout-minutes: 5
env:
GH_TOKEN: ${{ github.token }}
PROJECT: karaoke-gen
KEEP_DAYS: "60"
# Only nag once the project crosses this watermark — pruning holds it at
# ~4-7 GB, and there are always old releases to consolidate, so without a
# threshold this would open an issue every month for no real reason. 7 GB
# leaves ~1 month of ~3 GB/month growth before the 10 GB cap.
NAG_THRESHOLD_GB: "7"
ISSUE_TITLE: "🧹 PyPI storage prune due: karaoke-gen"
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.13
uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Compute prune plan
id: plan
run: |
python scripts/prune_pypi_releases.py \
--project "$PROJECT" --keep-days "$KEEP_DAYS" \
--format markdown --output plan.md
python scripts/prune_pypi_releases.py \
--project "$PROJECT" --keep-days "$KEEP_DAYS" \
--format json --output plan.json
python - <<'PY' >> "$GITHUB_OUTPUT"
import json, os
d = json.load(open("plan.json"))
threshold = float(os.environ["NAG_THRESHOLD_GB"])
should_nag = d["delete_count"] > 0 and d["current_gb"] >= threshold
print(f"delete_count={d['delete_count']}")
print(f"reclaimable_gb={d['reclaimable_gb']:.2f}")
print(f"current_gb={d['current_gb']:.2f}")
print(f"should_nag={'true' if should_nag else 'false'}")
PY
- name: Job summary
run: cat plan.md >> "$GITHUB_STEP_SUMMARY"
- name: Open or update tracking issue
if: steps.plan.outputs.should_nag == 'true'
run: |
# Search by a stable ASCII substring (emoji in search queries is
# flaky); the exact-title jq filter below is the real dedupe guard.
existing=$(gh issue list --repo "$GITHUB_REPOSITORY" \
--state open --search "PyPI storage prune due in:title" \
--json number,title \
--jq "map(select(.title == \"$ISSUE_TITLE\")) | .[0].number // empty")
note="🔁 Refreshed $(date -u +%Y-%m-%d): ${{ steps.plan.outputs.delete_count }} releases prunable, ~${{ steps.plan.outputs.reclaimable_gb }} GB reclaimable (project at ${{ steps.plan.outputs.current_gb }} GB)."
if [ -n "$existing" ]; then
echo "Updating existing issue #$existing"
gh issue edit "$existing" --repo "$GITHUB_REPOSITORY" --body-file plan.md
gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" --body "$note"
else
echo "Creating new tracking issue"
gh issue create --repo "$GITHUB_REPOSITORY" \
--title "$ISSUE_TITLE" --body-file plan.md
fi
+3
View File
@@ -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
View File
@@ -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.
+3 -1
View File
@@ -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.
+150
View File
@@ -93,6 +93,10 @@ class JobUpdateRequest(BaseModel):
youtube_description_template: Optional[str] = None
customer_email: Optional[str] = None
customer_notes: Optional[str] = None
# Review autonomy: "auto" (skip review when confident) | "always_review"
review_mode: Optional[str] = None
# Backing-vocals preference: "auto" | "clean" | "review"
backing_preference: Optional[str] = None
# Editable boolean fields
enable_cdg: Optional[bool] = None
@@ -129,6 +133,8 @@ EDITABLE_JOB_FIELDS = {
"non_interactive",
"prep_only",
"is_private",
"review_mode",
"backing_preference",
}
@@ -988,6 +994,23 @@ async def update_job(
f"no account existed, created one"
)
# The executor treats any value other than "auto" as an enforcement blocker,
# so a typo (e.g. "always-review") would silently force human review.
if "review_mode" in updates and updates["review_mode"] not in ("auto", "always_review"):
raise HTTPException(
status_code=400,
detail='review_mode must be "auto" or "always_review"',
)
# backing_preference likewise gates the instrumental decision — reject typos.
if "backing_preference" in updates and updates["backing_preference"] not in (
"auto", "clean", "review",
):
raise HTTPException(
status_code=400,
detail='backing_preference must be "auto", "clean", or "review"',
)
# Check if we're toggling is_private from False to True on a completed job
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
toggling_to_private = (
@@ -1877,6 +1900,133 @@ async def delete_job_outputs(
)
class OrphanedOutputsCleanupRequest(BaseModel):
"""Explicit targets for cleaning up distributed outputs whose owning job doc no
longer exists (e.g. a job deleted before its outputs were cleaned up)."""
youtube_video_id: Optional[str] = None
dropbox_folder_path: Optional[str] = None
gdrive_file_ids: List[str] = []
mirror_filename_prefix: Optional[str] = None # e.g. "NOMAD-1583 - Mazzy Star"
@router.post("/orphaned-outputs/cleanup")
async def cleanup_orphaned_outputs(
req: OrphanedOutputsCleanupRequest,
auth_data: AuthResult = Depends(require_admin),
) -> dict:
"""
Delete distributed outputs that no longer have an owning job doc (admin only).
The per-job cleanup endpoints (delete-outputs, cleanup-distribution) all require
the job document to resolve file IDs and paths. When a job was deleted while its
outputs were still published (the pre-fix DELETE /api/jobs/{id} behavior), those
outputs are orphaned and must be targeted explicitly:
- youtube_video_id: YouTube video to delete (bare video ID)
- dropbox_folder_path: full Dropbox folder path to delete
- gdrive_file_ids: Google Drive file IDs to delete (from upload logs)
- mirror_filename_prefix: "NOMAD-#### - Artist..." prefix for kjbox GCS mirror
objects (masters + vocals guides); must include artist text so it can't match
another track sharing a recycled brand code
Returns per-service results; each requested service reports success/failed/error.
"""
admin_email = auth_data.user_email or "unknown"
if not any([req.youtube_video_id, req.dropbox_folder_path, req.gdrive_file_ids, req.mirror_filename_prefix]):
raise HTTPException(status_code=400, detail="No cleanup targets specified")
if req.mirror_filename_prefix:
from backend.services.nomad_master_mirror import is_safe_track_filename_prefix
if not is_safe_track_filename_prefix(req.mirror_filename_prefix):
raise HTTPException(
status_code=400,
detail=(
f"Unsafe mirror_filename_prefix {req.mirror_filename_prefix!r}: must be "
f"'NOMAD-#### - Artist...' (brand code plus artist text) so it cannot "
f"match another track sharing a recycled brand code"
),
)
logger.info(
f"Admin {admin_email} cleaning up orphaned outputs: "
f"youtube={req.youtube_video_id}, dropbox={req.dropbox_folder_path}, "
f"gdrive={req.gdrive_file_ids}, mirror_prefix={req.mirror_filename_prefix}"
)
results: Dict[str, Any] = {}
if req.youtube_video_id:
try:
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False,
non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict(),
)
success = finalise.delete_youtube_video(req.youtube_video_id)
results["youtube"] = {
"status": "success" if success else "failed",
"video_id": req.youtube_video_id,
}
else:
results["youtube"] = {"status": "failed", "reason": "YouTube credentials not configured"}
except Exception as e:
logger.error(f"Error deleting orphaned YouTube video {req.youtube_video_id}: {e}", exc_info=True)
results["youtube"] = {"status": "error", "error": str(e)}
if req.dropbox_folder_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
success = dropbox.delete_folder(req.dropbox_folder_path)
results["dropbox"] = {
"status": "success" if success else "failed",
"path": req.dropbox_folder_path,
}
else:
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
except Exception as e:
logger.error(f"Error deleting orphaned Dropbox folder {req.dropbox_folder_path}: {e}", exc_info=True)
results["dropbox"] = {"status": "error", "error": str(e)}
if req.gdrive_file_ids:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
delete_results = gdrive.delete_files(req.gdrive_file_ids)
all_success = all(delete_results.values())
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results,
}
else:
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
except Exception as e:
logger.error(f"Error deleting orphaned GDrive files {req.gdrive_file_ids}: {e}", exc_info=True)
results["gdrive"] = {"status": "error", "error": str(e)}
if req.mirror_filename_prefix:
try:
from backend.services.nomad_master_mirror import NomadMasterMirror
counts = NomadMasterMirror().delete_track_objects_by_filename_prefix(req.mirror_filename_prefix)
results["mirror"] = {"status": "success", **counts}
except Exception as e:
logger.error(f"Error deleting orphaned mirror objects for {req.mirror_filename_prefix}: {e}", exc_info=True)
results["mirror"] = {"status": "error", "error": str(e)}
logger.info(f"Orphaned-outputs cleanup by {admin_email} complete: {results}")
return {"status": "complete", "results": results}
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
async def get_job_completion_message(
job_id: str,
+6
View File
@@ -143,6 +143,10 @@ class AudioSearchRequest(BaseModel):
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
@@ -803,6 +807,8 @@ async def search_audio(
auto_download=body.auto_download,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
+5
View File
@@ -258,6 +258,9 @@ class BulkSettings(BaseModel):
is_private: bool = False
skip_audio_edit: bool = True
skip_customization: bool = True
# Full-auto review (workstream C): batch default autonomy + backing preference.
review_mode: str = "auto"
backing_preference: str = "auto"
class BulkSubmitRequest(BaseModel):
@@ -342,6 +345,8 @@ async def bulk_submit(
audio_search_title=song.title.strip(),
auto_download=False,
is_private=body.settings.is_private,
review_mode=body.settings.review_mode,
backing_preference=body.settings.backing_preference,
brand_prefix=settings.default_brand_prefix,
enable_youtube_upload=settings.default_enable_youtube_upload,
youtube_description=settings.default_youtube_description,
+87 -26
View File
@@ -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
@@ -184,6 +185,10 @@ class CreateJobFromUrlRequest(BaseModel):
# Audio editing
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
class CreateJobFromUrlResponse(BaseModel):
"""Response from creating a job from URL."""
@@ -242,19 +247,35 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
prep_only: bool = Field(False, description="Stop after review phase, don't run finalisation")
keep_brand_code: Optional[str] = Field(None, description="Preserve existing brand code instead of generating new one")
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
# Bulk-upload grouping: jobs created from the same tenant bulk batch share a
# batch_id (stamped into state_data) so they can be grouped/filtered later.
batch_id: Optional[str] = Field(None, description="Groups jobs created together in one tenant bulk batch")
# Upload mechanism. "signed_put" (default) returns single-shot signed PUT
# URLs; "resumable" returns GCS resumable session URIs that support chunked
# uploads with mid-file resume after interruptions (flaky connections).
upload_mode: Literal["signed_put", "resumable"] = Field(
"signed_put", description="'signed_put' (default) or 'resumable'"
)
class SignedUploadUrl(BaseModel):
"""Signed URL for uploading a file."""
"""Signed URL (or resumable session URI) for uploading a file."""
file_type: str = Field(..., description="Type of file this URL is for")
gcs_path: str = Field(..., description="The GCS path where file will be stored")
upload_url: str = Field(..., description="Signed URL to PUT the file to")
upload_url: str = Field(..., description="Signed URL to PUT the file to, or a resumable session URI")
content_type: str = Field(..., description="Content-Type header to use when uploading")
resumable: bool = Field(False, description="True when upload_url is a GCS resumable session URI")
class CreateJobWithUploadUrlsResponse(BaseModel):
@@ -453,6 +474,9 @@ async def upload_and_create_job(
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
# Non-interactive mode
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Form("auto", description="'auto' (skip review when confident) or 'always_review'"),
backing_preference: str = Form("auto", description="'auto' (retain backing where safe), 'clean', or 'review'"),
# Private (non-published) track mode
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
# Audio editing
@@ -681,6 +705,9 @@ async def upload_and_create_job(
request_metadata=request_metadata,
# Non-interactive mode
non_interactive=non_interactive,
# Review autonomy + backing-vocals preference (full-auto review)
review_mode=review_mode,
backing_preference=backing_preference,
# Private (non-published) track mode
is_private=is_private,
# Tenant scoping
@@ -801,8 +828,10 @@ async def upload_and_create_job(
update_data['style_assets'] = style_assets
if 'style_params' in style_assets:
update_data['style_params_gcs_path'] = style_assets['style_params']
elif theme_style_assets:
# Theme style assets (no custom uploads)
elif theme_style_assets or theme_style_params_path:
# Theme style assets (no custom uploads). A theme may have style
# params but no asset files (e.g. the minimal local-dev seed theme),
# so the params path must be written even when the assets dict is empty.
update_data['style_assets'] = theme_style_assets
if theme_style_params_path:
update_data['style_params_gcs_path'] = theme_style_params_path
@@ -1268,6 +1297,8 @@ async def create_job_with_upload_urls(
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
is_private=effective_is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
@@ -1285,6 +1316,11 @@ async def create_job_with_upload_urls(
# Record job creation metric
metrics.record_job_created(job_id, source="upload")
# Stamp bulk-batch grouping so jobs created together can be grouped/filtered later.
if body.batch_id:
job_manager.update_state_data(job_id, 'batch_id', body.batch_id)
job_manager.update_state_data(job_id, 'created_from', 'tenant-bulk')
logger.info(f"Created job {job_id} for {body.artist} - {body.title} (signed URL upload flow)")
# If theme is set and no style_params uploaded, prepare theme style now
@@ -1302,27 +1338,50 @@ async def create_job_with_upload_urls(
job_manager.update_job(job_id, update_data)
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
# Generate signed upload URLs for each file
upload_urls = []
for file_info in body.files:
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
# Generate signed upload URL (valid for 60 minutes)
signed_url = storage_service.generate_signed_upload_url(
gcs_path,
content_type=file_info.content_type,
expiration_minutes=60
)
upload_urls.append(SignedUploadUrl(
file_type=file_info.file_type,
gcs_path=gcs_path,
upload_url=signed_url,
content_type=file_info.content_type
))
logger.info(f"Generated signed upload URL for {file_info.file_type}: {gcs_path}")
# Generate upload URLs for each file. Two modes:
# - "signed_put" (default): single-shot signed PUT URL — simple, but an
# interrupted upload restarts the whole file.
# - "resumable": GCS resumable session URI — the client uploads in chunks
# with Content-Range and can resume mid-file after any interruption
# (network switch, sleep, reload). Sessions are created with the
# caller's Origin so GCS handles CORS on the session itself.
use_resumable = body.upload_mode == "resumable"
request_origin = request.headers.get("Origin") if use_resumable else None
def _build_upload_urls() -> list:
urls = []
for file_info in body.files:
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
if use_resumable:
upload_url = storage_service.create_resumable_upload_session(
gcs_path,
content_type=file_info.content_type,
origin=request_origin,
)
else:
# Signed PUT URL (valid for 60 minutes)
upload_url = storage_service.generate_signed_upload_url(
gcs_path,
content_type=file_info.content_type,
expiration_minutes=60
)
urls.append(SignedUploadUrl(
file_type=file_info.file_type,
gcs_path=gcs_path,
upload_url=upload_url,
content_type=file_info.content_type,
resumable=use_resumable,
))
logger.info(
f"Generated {'resumable session' if use_resumable else 'signed upload URL'} "
f"for {file_info.file_type}: {gcs_path}"
)
return urls
# Resumable session creation makes a network round-trip to GCS per file;
# run off the event loop. (Signed URLs sign locally but share the path.)
upload_urls = await asyncio.to_thread(_build_upload_urls)
return CreateJobWithUploadUrlsResponse(
status="success",
job_id=job_id,
@@ -1898,6 +1957,8 @@ async def create_job_from_url(
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
+61 -1
View File
@@ -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/
+88 -41
View File
@@ -813,27 +813,53 @@ async def delete_job(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete"))
# Recycle any unreturned brand code before deleting the job record
# If the job still has published outputs (brand code allocated, outputs never
# cleaned up), delete the distributed files BEFORE deleting the job record.
# The brand code is recycled inside the cleanup only once Dropbox + GDrive are
# confirmed clean: recycling while files remain in the public share hands the
# same NOMAD-#### to a future job and creates duplicate brand codes (NOMAD-1583
# incident, 2026-08-29). If cleanup fails, the code stays allocated — a sequence
# gap the GDrive validator surfaces, which is safe and recoverable.
state_data = job.state_data or {}
brand_code = state_data.get('brand_code')
if brand_code:
if not job.outputs_deleted_at:
logger.warning(
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
f"were not cleaned up first. Brand code will be recycled but "
f"distributed files (GDrive/Dropbox/YouTube) may be orphaned."
distribution_cleanup = None
if brand_code and not job.outputs_deleted_at:
if not delete_files:
# Published outputs cannot be preserved when their job record is
# deleted — the record holds the only file IDs/paths needed to ever
# clean them up or reconcile the brand code.
raise HTTPException(
status_code=400,
detail=t(locale, "jobs.deletePublishedRequiresFiles"),
)
logger.warning(
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
f"were not cleaned up first — running distribution cleanup before delete."
)
distribution_cleanup = _run_distribution_cleanup(job_id, job)
incomplete = [
svc for svc in ("youtube", "dropbox", "gdrive")
if distribution_cleanup.get(svc, {}).get("status") in ("failed", "partial", "error")
]
if incomplete:
# Keep the job record: it holds the file IDs/paths needed to retry.
# Deleting it anyway would orphan the remaining published files with
# no way to resolve them later (NOMAD-1583 incident).
logger.error(
f"Aborting delete of job {job_id}: distribution cleanup incomplete "
f"for {incomplete} — {distribution_cleanup}"
)
raise HTTPException(
status_code=502,
detail=t(locale, "jobs.cleanupFailed", services=", ".join(incomplete)),
)
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(f"Recycled brand code {brand_code} before deleting job {job_id}")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
job_manager.delete_job(job_id, delete_files=delete_files)
return {"status": "success", "message": f"Job {job_id} deleted"}
response = {"status": "success", "message": f"Job {job_id} deleted"}
if distribution_cleanup is not None:
response["distribution_cleanup"] = distribution_cleanup
return response
except HTTPException:
raise
except Exception as e:
@@ -2165,41 +2191,23 @@ async def get_worker_logs(
}
@router.post("/{job_id}/cleanup-distribution")
async def cleanup_distribution(
job_id: str,
request: Request,
delete_job: bool = True,
auth_result: AuthResult = Depends(require_admin)
) -> dict:
def _run_distribution_cleanup(job_id: str, job) -> dict:
"""
Clean up all distributed content for a job (YouTube, Dropbox, Google Drive).
Delete a job's distributed outputs (YouTube video, Dropbox folder, Google Drive
files, kjbox GCS mirror objects) and recycle its brand code once Dropbox AND
GDrive are confirmed clean.
This admin-only endpoint is designed for E2E test cleanup. It:
1. Deletes YouTube video (if uploaded)
2. Deletes Dropbox folder (if uploaded)
3. Deletes Google Drive files (if uploaded)
4. Optionally deletes the job itself
Args:
job_id: Job ID to clean up
delete_job: If True, also delete the job after cleaning up distribution
Returns:
Cleanup results for each service
Shared by the admin cleanup-distribution endpoint and job deletion. Deleting a
job whose outputs are still published MUST run this first: recycling the brand
code while the files remain in the public share hands the same NOMAD-#### to a
future job and creates duplicate brand codes (NOMAD-1583 incident, 2026-08-29).
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
state_data = job.state_data or {}
results = {
"job_id": job_id,
"youtube": {"status": "skipped", "reason": "no youtube_url in state_data"},
"dropbox": {"status": "skipped", "reason": "no brand_code or dropbox_path"},
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
"job_deleted": False
}
# Clean up YouTube
@@ -2358,6 +2366,41 @@ async def cleanup_distribution(
f"collisions with leftover GDrive files."
)
return results
@router.post("/{job_id}/cleanup-distribution")
async def cleanup_distribution(
job_id: str,
request: Request,
delete_job: bool = True,
auth_result: AuthResult = Depends(require_admin)
) -> dict:
"""
Clean up all distributed content for a job (YouTube, Dropbox, Google Drive).
This admin-only endpoint is designed for E2E test cleanup. It:
1. Deletes YouTube video (if uploaded)
2. Deletes Dropbox folder (if uploaded)
3. Deletes Google Drive files (if uploaded)
4. Optionally deletes the job itself
Args:
job_id: Job ID to clean up
delete_job: If True, also delete the job after cleaning up distribution
Returns:
Cleanup results for each service
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
results = _run_distribution_cleanup(job_id, job)
results["job_deleted"] = False
# Delete the job if requested
if delete_job:
try:
@@ -2386,6 +2429,8 @@ class CreateFromSearchRequest(BaseModel):
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
@validator('display_artist', 'display_title')
def strip_whitespace(cls, v):
@@ -2541,6 +2586,8 @@ async def create_job_from_search(
audio_search_title=session_title,
request_metadata=request_metadata,
is_private=body.is_private,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
tenant_id=tenant_id,
locale=get_full_locale_from_request(request),
)
+605 -145
View File
@@ -210,6 +210,156 @@ def _get_audio_hash(job_id: str) -> str:
return hashlib.md5(job_id.encode()).hexdigest()
def _preview_error_marker_path(job_id: str, preview_hash: str) -> str:
"""GCS marker written when a background preview encode fails permanently.
The status-poll endpoint reports it so the review UI can stop polling and
show a real error. GCS (not memory) because polls may hit a different
Cloud Run instance than the one running the encode task.
"""
return f"jobs/{job_id}/previews/{preview_hash}.error.json"
def _record_preview_video(job_id: str, preview_hash: str, gcs_path: str) -> None:
if job_id not in _preview_videos:
_preview_videos[job_id] = {}
_preview_videos[job_id][preview_hash] = gcs_path
def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
"""Download corrections/audio/styles for a preview render into temp_dir.
Returns (correction_result, audio_path, output_config). Blocking (GCS
downloads) — shared by the preview endpoint and the local-encode fallback.
"""
job_id = job.job_id
with create_span("download-corrections-and-audio") as download_span:
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
corrections_path = os.path.join(temp_dir, "corrections.json")
storage.download_file(corrections_gcs, corrections_path)
with open(corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
audio_path = os.path.join(temp_dir, "audio.flac")
storage.download_file(job.input_media_gcs_path, audio_path)
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
correction_result = CorrectionResult.from_dict(original_data)
add_span_event("corrections_loaded")
with create_span("load-styles") as styles_span:
styles_path, _ = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=logger,
)
styles_span.set_attribute("styles_path", styles_path)
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
output_config = OutputConfig(
output_styles_json=styles_path,
output_dir=output_dir,
cache_dir=cache_dir,
video_resolution="360p",
is_duet=is_duet,
)
return correction_result, audio_path, output_config
def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
"""Render the full 360p preview locally and upload it to GCS.
Blocking (downloads + ffmpeg) — call via asyncio.to_thread. Used when GCE
preview encoding is disabled and as the fallback when it fails.
"""
job_id = job.job_id
storage = StorageService()
with tempfile.TemporaryDirectory() as temp_dir:
correction_result, audio_path, output_config = _prepare_preview_inputs(
job=job, temp_dir=temp_dir, storage=storage, is_duet=is_duet
)
with create_span("render-preview-video-local") as render_span:
render_span.set_attribute("resolution", "360p")
result = CorrectionOperations.generate_preview_video(
correction_result=correction_result,
updated_data=updated_data,
output_config=output_config,
audio_filepath=audio_path,
artist=job.artist,
title=job.title,
logger=logger,
ass_only=False,
)
preview_hash = result["preview_hash"]
video_path = result["video_path"]
add_span_event("render_complete")
with create_span("upload-preview-video") as upload_span:
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
storage.upload_file(video_path, preview_gcs_path)
upload_span.set_attribute("gcs_path", preview_gcs_path)
_record_preview_video(job_id, preview_hash, preview_gcs_path)
return preview_hash
async def _encode_preview_in_background(
job,
preview_hash: str,
encode_kwargs: Dict[str, Any],
updated_data: Dict[str, Any],
is_duet: bool,
) -> None:
"""Run the GCE preview encode without holding the HTTP request open.
Cold-starting a fallback encoder VM can take 2-3 minutes — longer than
Cloudflare's ~100s edge timeout — so POST /preview-video returns as soon
as the ASS is uploaded and the browser polls the /status endpoint, which
reports ready once the mp4 exists in GCS. On GCE failure this falls back
to a local render; if that also fails an error marker is written so the
poll can surface the failure instead of spinning until its timeout.
"""
job_id = job.job_id
storage = StorageService()
encoding_service = get_encoding_service()
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
with job_log_context(job_id, worker="preview"):
try:
with create_span("gce-preview-encoding", {"job_id": job_id, "preview_hash": preview_hash}) as gce_span:
gce_result = await encoding_service.encode_preview_video(**encode_kwargs)
gce_span.set_attribute("gce_status", gce_result.get("status"))
_record_preview_video(job_id, preview_hash, preview_gcs_path)
logger.info(f"Job {job_id}: Preview generated via GCE: {preview_hash}")
return
except Exception as gce_error:
logger.warning(f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}")
try:
await asyncio.to_thread(_render_preview_locally, job, updated_data, is_duet)
logger.info(f"Job {job_id}: Preview generated locally after GCE failure: {preview_hash}")
except Exception as local_error:
logger.error(
f"Job {job_id}: Preview generation failed (GCE and local fallback): {local_error}",
exc_info=True,
)
try:
storage.upload_json(
_preview_error_marker_path(job_id, preview_hash),
{"error": str(local_error)},
)
except Exception:
logger.exception(f"Job {job_id}: Failed to write preview error marker")
# Cross-job search endpoint MUST be registered before {job_id} routes
# to avoid FastAPI matching "sessions" as a job_id path parameter.
@router.get("/sessions/search")
@@ -237,9 +387,159 @@ async def ping(job_id: str):
return {"status": "ok"}
def _dev_audio_proxy_enabled() -> bool:
"""True when the backend should proxy review audio bytes instead of returning
GCS signed URLs. Enabled via ``REVIEW_AUDIO_PROXY=1`` on a LOCAL dev backend
that lacks URL-signing credentials (plain user ADC can't sign). Never set in
prod — prod keeps the lighter signed-URL/redirect path.
"""
return os.environ.get("REVIEW_AUDIO_PROXY", "").lower() in ("1", "true", "yes")
def _dev_audio_url(job_id: str, gcs_path: Optional[str], base_url: str = "") -> Optional[str]:
"""Build an ABSOLUTE dev-proxy URL for a review audio/image artifact.
The URL is used directly as an ``<audio>``/``<img>`` src by the frontend, which
resolves relative URLs against the page origin (localhost:3000), not the API host.
So we must return the full backend URL (``request.base_url``, e.g. http://127.0.0.1:8000/).
"""
if not gcs_path:
return None
from urllib.parse import quote
return f"{base_url.rstrip('/')}/api/review/{job_id}/dev-audio?path={quote(gcs_path, safe='')}"
def _reconstruct_post_ai_segments(
raw_segments: List[Dict[str, Any]],
edit_log: Optional[Dict[str, Any]],
) -> Optional[List[Dict[str, Any]]]:
"""Reconstruct the "post-AI, pre-human" lyrics state for replay.
Forward-replays the reviewer's edit log onto the RAW transcription
(``corrections.json`` corrected_segments), applying only the accepted AI
suggestion ops and STOPPING at the first manual op. The result is what the
reviewer saw right after the AI auto-corrections were applied but before they
made any manual edits — so a "Post-AI" toggle vs the final state makes the
human's manual edits obvious (e.g. cleaning up an AI self-conflict that inserted
a duplicate word).
Best-effort: ops that can't be applied are skipped rather than raising. Returns
None if there's no edit log (nothing to reconstruct) or no manual edits at all
(post-AI == final, so a toggle would be pointless).
"""
import copy
if not edit_log:
return None
entries = edit_log.get("entries") or []
if not any(e.get("operation") and not str(e["operation"]).startswith("ai_suggestion") for e in entries):
return None # no manual edits → nothing to distinguish
segments = copy.deepcopy(raw_segments)
def _find(word_id):
for seg in segments:
words = seg.get("words") or []
for i, w in enumerate(words):
if w.get("id") == word_id:
return seg, words, i
return None, None, None
_new_id = [0]
def _gen_id():
_new_id[0] += 1
return f"postai_{_new_id[0]}"
for e in entries:
op = e.get("operation") or ""
if not op.startswith("ai_suggestion"):
break # reached the human's manual edits — stop
if op != "ai_suggestion_accept":
continue # run/reject/undo: not an applied change
details = e.get("details") or {}
sub_op = details.get("op") or "replace"
before_ids = e.get("word_ids_before") or []
text_after = (e.get("text_after") or "").strip()
anchor_id = before_ids[0] if before_ids else None
seg, words, idx = (_find(anchor_id) if anchor_id else (None, None, None))
def _make_words(text, start, end):
# Split the replacement/insertion text into individual words, distributing
# the [start, end] span evenly so multi-word replacements get distinct
# timestamps (not all crammed into one slot with identical timing).
toks = text.split()
n = len(toks) or 1
if end is None or start is None or end < start:
end = start
step = (end - start) / n
out = []
for i, tok in enumerate(toks):
ws = start + i * step
we = start + (i + 1) * step
out.append({"id": _gen_id(), "text": tok, "start_time": ws, "end_time": we,
"ai_corrected": True, "original_text": ""})
return out
try:
if sub_op == "replace":
if words is not None:
# word_ids_before may span MULTIPLE words (e.g.
# 'quite a picket fence' -> 'white picket fences'). Replace the
# whole contiguous span with the space-split replacement text,
# spreading the original span's [start,end] across the new words.
id_set = set(before_ids)
span = [k for k, w in enumerate(words) if w.get("id") in id_set]
if span:
lo, hi = min(span), max(span)
s0 = words[lo].get("start_time", 0.0)
e0 = words[hi].get("end_time", s0)
words[lo:hi + 1] = _make_words(text_after, s0, e0) if text_after else []
elif sub_op in ("insert_after", "insert_before", "insert"):
if words is not None:
at = idx if sub_op == "insert_before" else idx + 1
anchor = words[idx]
a_s = anchor.get("start_time", 0.0)
a_e = anchor.get("end_time", a_s)
words[at:at] = _make_words(text_after, a_s, a_e)
elif sub_op in ("delete", "remove", "adlib_removal"):
if words is not None:
id_set = set(before_ids)
seg["words"] = [w for w in words if w.get("id") not in id_set]
except Exception:
continue # best-effort
# Refresh each segment's joined text for display.
for seg in segments:
seg["text"] = " ".join((w.get("text") or "") for w in (seg.get("words") or [])).strip()
return segments
def _load_edit_log(job, storage) -> Optional[Dict[str, Any]]:
"""Load the reviewer's persisted edit log for replay, or None if absent.
Prefers the ``state_data.last_edit_log_path`` pointer written by the
submit-edit-log endpoint; the file lives at
``jobs/{job_id}/lyrics/edit_log_{session_id}.json`` and holds ordered,
typed ops (``ai_suggestion_accept/reject`` vs manual ``word_*``/``timing_change``).
"""
try:
path = (job.state_data or {}).get('last_edit_log_path')
if not path:
return None
if not storage.file_exists(path):
return None
return storage.download_json(path)
except Exception as e: # never let replay fail on a missing/corrupt log
logger.warning(f"Job {job.job_id}: could not load edit_log for replay: {e}")
return None
@router.get("/{job_id}/correction-data")
async def get_correction_data(
job_id: str,
request: Request,
replay: bool = False,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
@@ -252,6 +552,15 @@ async def get_correction_data(
- All lyrics correction data (segments, reference lyrics, anchors, etc.)
- instrumental_options: List of available instrumental tracks with audio URLs
- backing_vocals_analysis: Analysis data to help users choose instrumental
Replay mode (``?replay=true``, requires full auth — admin/owner, not a
review-token link): serves the SAME payload for a job in ANY status so the
review UI can be re-opened read-only for a completed job. It skips the
AWAITING_REVIEW/IN_REVIEW status gate and the AWAITING_REVIEW→IN_REVIEW
transition side-effect, and additionally attaches the reviewer's ordered
``edit_log`` (AI-accept/reject/manual ops) under ``replay``. Purely read-only;
used for the fully-automated-review recording program. See
docs/archive/2026-08-25-full-auto-review-design.md.
"""
job_manager = JobManager()
storage = StorageService()
@@ -260,12 +569,29 @@ async def get_correction_data(
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
if replay and auth_info[1] != "full":
# Replay reopens completed jobs; restrict to authenticated admin/owner,
# never anonymous review-token links.
raise HTTPException(status_code=403, detail="Replay mode requires admin/owner authentication")
if not replay and job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=t("en", "review.reviewNotReady", status=job.status)
)
# Server-side pre-apply ON LOAD (C2 completeness): jobs processed before the
# screens_worker pre-apply shipped (or whose cache landed after that gate) reach
# this endpoint without a pre_applied marker, so the review UI would still run its
# on-load client-side apply (the visible ~4s "uncorrected -> corrected" flicker).
# Apply here from an EXISTING cache only (generate_on_miss=False so the page never
# blocks on a multi-model LLM call). Best-effort + idempotent: a no-op when the
# job was already pre-applied, already human-edited, or has no cache. The direct
# corrections_updated path below then serves the freshly-written corrected state.
if not replay:
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
await ensure_and_pre_apply(job_id, generate_on_miss=False)
# Check for updated corrections first (from previous review sessions where user edited lyrics)
# This mirrors the logic in render_video_worker.py to ensure consistency
corrections_updated_gcs = job.file_urls.get('lyrics', {}).get('corrections_updated')
@@ -314,18 +640,25 @@ async def get_correction_data(
clean_url = stems.get('instrumental_clean')
backing_url = stems.get('instrumental_with_backing')
# Build instrumental options with transcoded signed URLs (OGG Opus)
# Build instrumental options with transcoded signed URLs (OGG Opus).
# In local dev without signing creds, use same-origin byte-proxy URLs.
instrumental_options = []
url_tasks = {}
if clean_url:
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
if backing_url:
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
signed_urls = {}
if url_tasks:
results = await asyncio.gather(*url_tasks.values())
signed_urls = dict(zip(url_tasks.keys(), results))
if _dev_audio_proxy_enabled():
_base = str(request.base_url)
if clean_url:
signed_urls['clean'] = _dev_audio_url(job_id, clean_url, _base)
if backing_url:
signed_urls['with_backing'] = _dev_audio_url(job_id, backing_url, _base)
else:
url_tasks = {}
if clean_url:
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
if backing_url:
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
if url_tasks:
results = await asyncio.gather(*url_tasks.values())
signed_urls = dict(zip(url_tasks.keys(), results))
if clean_url:
instrumental_options.append({
@@ -348,23 +681,55 @@ async def get_correction_data(
backing_vocals_analysis = job.state_data.get('backing_vocals_analysis', {})
corrections_data['backing_vocals_analysis'] = backing_vocals_analysis
# Per-screen skip (C1): tell the frontend whether each review half is
# confidently auto-resolved, so it can skip the instrumental screen (or the
# lyrics screen). Derived from the stored auto-approval verdict + the job's
# backing_preference — the same decision the executor / complete endpoint use.
from backend.config import get_settings as _get_settings
from backend.services.auto_approval.instrumental import auto_approval_summary
corrections_data['auto_approval'] = auto_approval_summary(job, _get_settings())
# Get waveform URL if available
analysis_files = job.file_urls.get('analysis', {})
waveform_url = analysis_files.get('backing_vocals_waveform')
if waveform_url:
corrections_data['backing_vocals_waveform_url'] = storage.generate_signed_url(
waveform_url, expiration_minutes=120
corrections_data['backing_vocals_waveform_url'] = (
_dev_audio_url(job_id, waveform_url, str(request.base_url)) if _dev_audio_proxy_enabled()
else storage.generate_signed_url(waveform_url, expiration_minutes=120)
)
# Transition to IN_REVIEW if not already
if job.status == JobStatus.AWAITING_REVIEW:
# Transition to IN_REVIEW if not already (never in replay — read-only)
if not replay and job.status == JobStatus.AWAITING_REVIEW:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
message="User opened combined review interface"
)
logger.info(f"Job {job_id}: Serving correction data with instrumental options for combined review")
# Replay: attach the reviewer's ordered edit_log so the UI can show the
# sequence of actions (AI-accept/reject/manual/timing) beside the final state.
if replay:
edit_log = _load_edit_log(job, storage)
post_ai_segments = None
try:
raw_data = storage.download_json(f"jobs/{job_id}/lyrics/corrections.json")
post_ai_segments = _reconstruct_post_ai_segments(
raw_data.get('corrected_segments', []), edit_log
)
except Exception as e:
logger.warning(f"Job {job_id}: could not reconstruct post-AI segments: {e}")
corrections_data['replay'] = {
'is_replay': True,
'job_status': str(job.status),
'instrumental_selection': job.state_data.get('instrumental_selection'),
'edit_log': edit_log,
# Present only when the reviewer made manual edits — lets the UI offer a
# "Post-AI (pre-human)" toggle vs the final state.
'post_ai_segments': post_ai_segments,
'has_manual_edits': post_ai_segments is not None,
}
logger.info(f"Job {job_id}: Serving correction data (replay={replay}) for combined review")
return corrections_data
except Exception as e:
@@ -460,6 +825,13 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
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)
@@ -469,6 +841,68 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
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,
@@ -506,6 +940,21 @@ async def complete_review(
detail=t("en", "review.instrumentalSelectionRequired")
)
# Per-screen skip (C1): a client that skipped the instrumental screen because
# the backing decision was confidently auto-resolved sends "auto"; resolve it
# from the stored verdict here so CLI/tenant clients get the skip for free.
if instrumental_selection == "auto":
from backend.config import get_settings as _get_settings
from backend.services.auto_approval.instrumental import resolve_auto_instrumental
resolved = resolve_auto_instrumental(job, _get_settings())
if not resolved:
raise HTTPException(
status_code=400,
detail=t("en", "review.instrumentalSelectionRequired"),
)
logger.info(f"Job {job_id}: Resolved instrumental_selection='auto' -> '{resolved}'")
instrumental_selection = resolved
valid_selections = ["clean", "with_backing"]
# Allow "custom" for mute-region instrumentals or user-uploaded instrumentals
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
@@ -1131,59 +1580,26 @@ async def generate_preview_video(
with create_span("generate-preview-video", {"job_id": job_id, "use_gce": use_gce_preview}) as span:
with job_log_context(job_id, worker="preview"):
try:
# Create temp directory for this preview operation
with tempfile.TemporaryDirectory() as temp_dir:
# 1. Download original corrections.json (has full structure)
with create_span("download-corrections-and-audio") as download_span:
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
corrections_path = os.path.join(temp_dir, "corrections.json")
storage.download_file(corrections_gcs, corrections_path)
with open(corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 2. Download input audio
audio_path = os.path.join(temp_dir, "audio.flac")
storage.download_file(job.input_media_gcs_path, audio_path)
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
# 3. Load original as CorrectionResult
correction_result = CorrectionResult.from_dict(original_data)
add_span_event("corrections_loaded")
# 4. Get or create styles file for preview using unified style loader
with create_span("load-styles") as styles_span:
styles_path, _ = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=logger,
if use_gce_preview:
# GCE path: prepare inputs and generate ASS subtitles inline
# (fast), then hand the video encode to a background task and
# return immediately. Encoding can take minutes when a worker
# VM cold-starts — longer than Cloudflare's ~100s edge timeout
# — so the request must not wait for it; the frontend polls
# the /status endpoint until the mp4 lands in GCS.
with tempfile.TemporaryDirectory() as temp_dir:
# Blocking work (GCS downloads, ASS generation) runs in a
# worker thread so other requests on this instance don't
# stall behind it.
correction_result, audio_path, output_config = await asyncio.to_thread(
_prepare_preview_inputs,
job=job, temp_dir=temp_dir, storage=storage, is_duet=is_duet,
)
styles_span.set_attribute("styles_path", styles_path)
# 5. Set up output config for preview
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
output_config = OutputConfig(
output_styles_json=styles_path,
output_dir=output_dir,
cache_dir=cache_dir,
video_resolution="360p",
is_duet=is_duet,
)
# 6. Generate preview (ASS-only if using GCE, or full video if local)
preview_gcs_path = None
if use_gce_preview:
# GCE path: Generate ASS only, then offload encoding to GCE
try:
with create_span("generate-ass-subtitles") as ass_span:
result = CorrectionOperations.generate_preview_video(
result = await asyncio.to_thread(
CorrectionOperations.generate_preview_video,
correction_result=correction_result,
updated_data=updated_data,
output_config=output_config,
@@ -1198,94 +1614,95 @@ async def generate_preview_video(
ass_span.set_attribute("ass_path", ass_path)
add_span_event("ass_generated")
span.set_attribute("preview_hash", preview_hash)
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
# The hash is deterministic over the correction data, so
# if this exact preview already exists (e.g. the user
# retried after a dropped connection) skip encoding.
if storage.file_exists(preview_gcs_path):
_record_preview_video(job_id, preview_hash, preview_gcs_path)
span.set_attribute("preview_cache_hit", True)
logger.info(f"Job {job_id}: Preview cache hit: {preview_hash}")
return {"status": "success", "preview_hash": preview_hash}
# Upload ASS to GCS
with create_span("upload-ass-to-gcs") as upload_ass_span:
ass_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.ass"
storage.upload_file(ass_path, ass_gcs_path)
upload_ass_span.set_attribute("ass_gcs_path", ass_gcs_path)
# Call GCE encoding service
with create_span("gce-preview-encoding") as gce_span:
bucket_name = settings.gcs_bucket_name
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
# A stale error marker from an earlier failed attempt at
# this same hash would make the status poll fail instantly.
storage.delete_file(
_preview_error_marker_path(job_id, preview_hash),
ignore_missing=True,
)
# Get background image and font from style assets if available
style_assets = job.style_assets or {}
bucket_name = settings.gcs_bucket_name
style_assets = job.style_assets or {}
# Only use background image if user explicitly requested it
# Default is black background for faster preview generation (~10s vs ~30-60s)
background_image_gcs_path = None
if use_background_image:
for key in ["karaoke_background", "style_karaoke_background"]:
if key in style_assets:
background_image_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
gce_span.set_attribute("background_image", background_image_gcs_path)
break
gce_span.set_attribute("use_background_image", use_background_image)
font_gcs_path = None
for key in ["font", "style_font"]:
# Only use background image if user explicitly requested it.
# Default is black background for faster preview generation.
background_image_gcs_path = None
if use_background_image:
for key in ["karaoke_background", "style_karaoke_background"]:
if key in style_assets:
font_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
gce_span.set_attribute("font", font_gcs_path)
background_image_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
break
span.set_attribute("use_background_image", use_background_image)
gce_result = await encoding_service.encode_preview_video(
job_id=f"preview_{job_id}_{preview_hash}",
ass_gcs_path=f"gs://{bucket_name}/{ass_gcs_path}",
audio_gcs_path=f"gs://{bucket_name}/{job.input_media_gcs_path}",
output_gcs_path=f"gs://{bucket_name}/{preview_gcs_path}",
background_color="black",
background_image_gcs_path=background_image_gcs_path,
font_gcs_path=font_gcs_path,
font_gcs_path = None
for key in ["font", "style_font"]:
if key in style_assets:
font_gcs_path = f"gs://{bucket_name}/{style_assets[key]}"
break
encode_kwargs = {
"job_id": f"preview_{job_id}_{preview_hash}",
"ass_gcs_path": f"gs://{bucket_name}/{ass_gcs_path}",
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
"output_gcs_path": f"gs://{bucket_name}/{preview_gcs_path}",
"background_color": "black",
"background_image_gcs_path": background_image_gcs_path,
"font_gcs_path": font_gcs_path,
}
task = asyncio.create_task(
_encode_preview_in_background(
job=job,
preview_hash=preview_hash,
encode_kwargs=encode_kwargs,
updated_data=updated_data,
is_duet=is_duet,
)
gce_span.set_attribute("gce_status", gce_result.get("status"))
add_span_event("gce_encoding_complete")
)
_background_tasks.add(task)
task.add_done_callback(_background_tasks.discard)
logger.info(f"Job {job_id}: Preview generated via GCE: {preview_hash}")
logger.info(f"Job {job_id}: Preview encode running in background: {preview_hash}")
return {"status": "generating", "preview_hash": preview_hash}
except LyricsTimingError:
raise
except Exception as gce_error:
# Fall back to local encoding if GCE fails
# Fall back to synchronous local encoding if GCE setup fails
logger.warning(
f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}"
f"Job {job_id}: GCE preview setup failed, falling back to local: {gce_error}"
)
span.set_attribute("gce_fallback", True)
use_gce_preview = False # Fall through to local encoding below
if not use_gce_preview:
# Local path: Generate full preview video locally
with create_span("render-preview-video-local") as render_span:
render_span.set_attribute("resolution", "360p")
result = CorrectionOperations.generate_preview_video(
correction_result=correction_result,
updated_data=updated_data,
output_config=output_config,
audio_filepath=audio_path,
artist=job.artist,
title=job.title,
logger=logger,
ass_only=False, # Generate full video locally
)
preview_hash = result["preview_hash"]
video_path = result["video_path"]
add_span_event("render_complete")
# Local path (GCE preview disabled, or GCE setup failed): render
# the full preview synchronously — no cold-start problem, but slow.
preview_hash = await asyncio.to_thread(
_render_preview_locally, job, updated_data, is_duet
)
# Upload preview video to GCS
with create_span("upload-preview-video") as upload_span:
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
storage.upload_file(video_path, preview_gcs_path)
upload_span.set_attribute("gcs_path", preview_gcs_path)
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
span.set_attribute("preview_hash", preview_hash)
span.set_attribute("success", True)
# Store the GCS path for serving
if job_id not in _preview_videos:
_preview_videos[job_id] = {}
_preview_videos[job_id][preview_hash] = preview_gcs_path
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
span.set_attribute("preview_hash", preview_hash)
span.set_attribute("success", True)
return {"status": "success", "preview_hash": preview_hash}
return {"status": "success", "preview_hash": preview_hash}
except LyricsTimingError as timing_err:
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
@@ -1342,6 +1759,41 @@ async def get_preview_video(
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
@router.get("/{job_id}/preview-video/{preview_hash}/status")
async def get_preview_video_status(
job_id: str,
preview_hash: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Poll the state of a background preview encode.
POST /preview-video returns {"status": "generating"} immediately and the
encode runs in a background task (_encode_preview_in_background). The
browser polls this endpoint until the mp4 appears in GCS. GCS is the
source of truth so polls work regardless of which Cloud Run instance
they hit.
"""
storage = StorageService()
if storage.file_exists(f"jobs/{job_id}/previews/{preview_hash}.mp4"):
return {"status": "ready", "preview_hash": preview_hash}
marker_path = _preview_error_marker_path(job_id, preview_hash)
if storage.file_exists(marker_path):
message = None
try:
message = storage.download_json(marker_path).get("error")
except Exception:
logger.warning(f"Job {job_id}: Unreadable preview error marker {marker_path}")
return {
"status": "error",
"preview_hash": preview_hash,
"message": message or t("en", "review.previewVideoGenerationError", error="encoding failed"),
}
return {"status": "generating", "preview_hash": preview_hash}
@router.post("/{job_id}/v1/annotations")
async def submit_annotation(
job_id: str,
@@ -1405,6 +1857,7 @@ async def get_annotation_stats(
@router.get("/{job_id}/instrumental-analysis")
async def get_instrumental_analysis(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
@@ -1434,21 +1887,28 @@ async def get_instrumental_analysis(
backing_url = stems.get('instrumental_with_backing')
backing_vocals_path = stems.get('backing_vocals')
# Build audio URLs with transcoded signed access (OGG Opus, parallel)
url_tasks = {}
if clean_url:
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
if backing_url:
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
if job.input_media_gcs_path:
url_tasks['original'] = transcoding.get_review_audio_url_async(job.input_media_gcs_path, expiration_minutes=120)
if backing_vocals_path:
url_tasks['backing_vocals'] = transcoding.get_review_audio_url_async(backing_vocals_path, expiration_minutes=120)
# Build audio URLs with transcoded signed access (OGG Opus, parallel).
# In local dev without signing creds, use same-origin byte-proxy URLs.
audio_url_sources = {
'clean': clean_url,
'with_backing': backing_url,
'original': job.input_media_gcs_path,
'backing_vocals': backing_vocals_path,
}
audio_urls = {}
if url_tasks:
results = await asyncio.gather(*url_tasks.values())
audio_urls = dict(zip(url_tasks.keys(), results))
if _dev_audio_proxy_enabled():
_base = str(request.base_url)
for key, src in audio_url_sources.items():
if src:
audio_urls[key] = _dev_audio_url(job_id, src, _base)
else:
url_tasks = {
key: transcoding.get_review_audio_url_async(src, expiration_minutes=120)
for key, src in audio_url_sources.items() if src
}
if url_tasks:
results = await asyncio.gather(*url_tasks.values())
audio_urls = dict(zip(url_tasks.keys(), results))
# Format response to match InstrumentalAnalysis type
return {
+89
View File
@@ -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
+5 -2
View File
@@ -36,6 +36,7 @@ def _mask_email(email: str) -> str:
from fastapi import APIRouter, HTTPException, Depends, Request, Header
from pydantic import BaseModel, EmailStr
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 (
@@ -274,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,
+33
View File
@@ -4,9 +4,14 @@ Configuration management for the karaoke generation backend.
import os
import logging
from typing import Optional, Dict
from dotenv import load_dotenv
from pydantic_settings import BaseSettings
from google.cloud import secretmanager
# Load .env for local development (no-op when absent, e.g. in Cloud Run).
# Must run before the Settings class body below, which reads os.getenv at
# class-definition time. Real environment variables take precedence.
load_dotenv()
logger = logging.getLogger(__name__)
@@ -118,6 +123,29 @@ class Settings(BaseSettings):
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
# Auto-approval ENFORCEMENT: when the auto-approval scorer is fully confident
# (see backend/services/auto_approval/), skip the combined review screens and
# go straight to render. Scoring + verdict recording happen on every job
# regardless of this flag; it only gates actually skipping the human.
# Per-job opt-out via Job.review_mode="always_review". Kill switch: false.
auto_approval_enforce_enabled: bool = os.getenv(
"AUTO_APPROVAL_ENFORCE_ENABLED", "true"
).lower() in ("true", "1", "yes")
# Backing decider ENFORCEMENT (Phase 2B): allow a confident WITH_BACKING
# verdict from the 3-stem decider to auto-select the with-backing
# instrumental. Shadow-validated 2026-08-28/29 (20-job corpus + live
# batteries + human review pass: 10/11 pick agreement, the one
# auto-eligible job shipped identically to the human) -> default ON.
# Default lives HERE, not per-environment env vars, because the executor
# runs in BOTH the backend service and the audio-separation Cloud Run Job
# (independent env; a service-only env flip left the audio_worker trigger
# reading false). Kill switch: set false in ci.yml backend deploy env
# AND infrastructure audio-separation-job envs (or revert this default).
auto_approval_backing_keep_enabled: bool = os.getenv(
"AUTO_APPROVAL_BACKING_KEEP_ENABLED", "true"
).lower() in ("true", "1", "yes")
# Match judge — artist/title formatting + match-acceptance for the job
# submission flow. Deterministic + catalog layers always run; the light AI
# layer (Vertex Gemini Flash) fires only when those aren't confident.
@@ -149,6 +177,11 @@ class Settings(BaseSettings):
# When disabled (default), workers are triggered via direct HTTP (for development)
enable_cloud_tasks: bool = os.getenv("ENABLE_CLOUD_TASKS", "false").lower() in ("true", "1", "yes")
gcp_region: str = os.getenv("GCP_REGION", "us-central1")
# ALL Cloud Tasks queues live in us-central1, but workers running in other
# regions (the GPU audio-separation-job sets GCP_REGION to its GPU region)
# must still enqueue to the real queue location — building queue paths from
# gcp_region 404s from those workers ("Queue does not exist").
cloud_tasks_region: str = os.getenv("CLOUD_TASKS_REGION", "us-central1")
# Cloud Run Jobs (for long-running video encoding)
# When enabled AND enable_cloud_tasks is true, video worker uses Cloud Run Jobs
+2 -1
View File
@@ -10,7 +10,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings, validate_production_config
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
from backend.services.spacy_preloader import preload_spacy_model
@@ -203,6 +203,7 @@ app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
app.include_router(tenant_bulk.router) # Tenant bulk-upload filename analysis (router has /api prefix)
# Exception handlers
+39 -2
View File
@@ -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,6 +275,20 @@ class Job(BaseModel):
user_email: Optional[str] = None # Email for notifications
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
# Review autonomy level. "auto" (default): skip the combined review screens
# whenever the auto-approval scorer is fully confident, falling back to human
# review otherwise. "always_review": every job stops at the review screens.
# (Distinct from legacy non_interactive, which is CLI packaging/upload
# semantics and never gated the cloud review flow.)
review_mode: str = "auto"
# Backing-vocals preference chosen up-front at submission. "auto" (default):
# retain backing vocals wherever the 3-stem decider is confident it's safe,
# else fall through to human review. "clean": always use the clean
# instrumental (never retain backing). "review": always let a human pick the
# instrumental. Consumed by the auto-approval instrumental decision.
backing_preference: str = "auto"
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
tenant_id: str = "" # Tenant ID for white-label portal scoping
@@ -557,7 +574,13 @@ class JobCreate(BaseModel):
webhook_url: Optional[str] = None
user_email: Optional[str] = None
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
# "auto" (default) = skip review screens when the auto-approval scorer is
# fully confident; "always_review" = always stop at the review screens.
review_mode: str = "auto"
# "auto" (default) = retain backing vocals where confidently safe; "clean" =
# always strip backing vocals; "review" = always let a human pick the instrumental.
backing_preference: str = "auto"
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
color_overrides: Dict[str, str] = Field(default_factory=dict)
@@ -648,6 +671,20 @@ class JobCreate(BaseModel):
raise ValueError("Field cannot be empty string")
return v.strip() if isinstance(v, str) else v
@validator('review_mode')
def _normalize_review_mode(cls, v):
"""Coerce an out-of-set value to the fail-safe default (always_review =
more human oversight), so a typo can never silently skip review. The
executor already treats any non-"auto" value as an enforcement blocker."""
return v if v in ("auto", "always_review") else "always_review"
@validator('backing_preference')
def _normalize_backing_preference(cls, v):
"""Coerce an out-of-set value to the default. Every creation route passes
the client value straight through, so this is the single choke point that
keeps a typo from reaching the instrumental decision as an unknown value."""
return v if v in ("auto", "clean", "review") else "auto"
@validator('artist', 'title')
def normalize_artist_title(cls, v):
"""Normalize artist/title text to standardize Unicode characters.
+4
View File
@@ -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
+68 -15
View File
@@ -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,
@@ -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",
]
+296
View File
@@ -0,0 +1,296 @@
"""Server-side application of AI auto-correct suggestions.
Faithful port of the review UI's auto-apply (frontend
``lib/lyrics-review/utils/autoCorrectApply.ts`` + ``autoCorrectConflicts.ts`` +
``useAutoCorrect.acceptAll``): the UI auto-applies every pending suggestion on
load (conflict groups resolved by consensus → confidence), so a human reviewer
always starts from the post-AI state. When a job is auto-approved without a
human, this module produces that same post-AI state server-side.
Everything here is pure (dict in, dict out); any anomaly is reported so the
caller can fall back to human review rather than ship a suspect result.
"""
from __future__ import annotations
import re
import uuid
from typing import Any, Dict, List, Optional, Tuple
Segment = Dict[str, Any]
Suggestion = Dict[str, Any]
_WORD_SPLIT_RE = re.compile(r"\s+")
_TOKEN_NORM_RE = re.compile(r"^[^\w]+|[^\w]+$")
def _new_word_id() -> str:
return uuid.uuid4().hex[:8]
def _rebuild_text(words: List[Dict[str, Any]]) -> str:
return " ".join(w.get("text", "") for w in words)
def pick_accept_all_winners(suggestions: List[Suggestion]) -> List[str]:
"""Winner ids for accept-all: one per conflict group (highest consensus,
then confidence); non-conflicting suggestions all win. Original order."""
best_of_group: Dict[str, Suggestion] = {}
for s in suggestions:
group = s.get("conflict_group")
if not group:
continue
current = best_of_group.get(group)
if (
current is None
or (s.get("consensus") or 0) > (current.get("consensus") or 0)
or (
(s.get("consensus") or 0) == (current.get("consensus") or 0)
and (s.get("confidence") or 0) > (current.get("confidence") or 0)
)
):
best_of_group[group] = s
return [
s["id"]
for s in suggestions
if not s.get("conflict_group")
or best_of_group.get(s["conflict_group"], {}).get("id") == s.get("id")
]
def _find_segment_with_words(
segments: List[Segment], word_ids: List[str]
) -> Optional[Tuple[int, List[int]]]:
if not word_ids:
# all([]) is vacuously True — an empty/missing word_ids must read as
# not-found, not as "matches the first segment".
return None
for i, seg in enumerate(segments):
words = seg.get("words") or []
indices = []
for wid in word_ids:
idx = next((j for j, w in enumerate(words) if w.get("id") == wid), -1)
indices.append(idx)
if all(x >= 0 for x in indices):
return i, indices
return None
def is_suggestion_stale(segments: List[Segment], suggestion: Suggestion) -> bool:
"""Stale when the target words no longer exist in one segment, contiguously."""
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
if not found:
return True
_, indices = found
s = sorted(indices)
return any(s[i] != s[i - 1] + 1 for i in range(1, len(s)))
def _distribute_timings(
n: int, start: Optional[float], end: Optional[float]
) -> List[Tuple[Optional[float], Optional[float]]]:
if n <= 0:
return []
if start is None or end is None or end <= start:
return [(start, end)] * n
step = (end - start) / n
return [(start + i * step, start + (i + 1) * step) for i in range(n)]
def _copy_segments(segments: List[Segment]) -> List[Segment]:
return [{**s, "words": [dict(w) for w in (s.get("words") or [])]} for s in segments]
def apply_suggestion(
segments: List[Segment], suggestion: Suggestion
) -> Optional[List[Segment]]:
"""Apply one suggestion; returns new segments or None when stale."""
if is_suggestion_stale(segments, suggestion):
return None
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
if not found:
return None
seg_index, word_indices = found
span_start = min(word_indices)
span_end = max(word_indices)
result = _copy_segments(segments)
seg = result[seg_index]
words = seg["words"]
op = suggestion.get("op")
new_text = suggestion.get("new_text") or ""
if op == "insert_after":
anchor = words[span_end]
nxt = words[span_end + 1] if span_end + 1 < len(words) else None
new_texts = [t for t in _WORD_SPLIT_RE.split(new_text) if t]
window_start = anchor.get("end_time")
if (
nxt is not None
and nxt.get("start_time") is not None
and window_start is not None
and nxt["start_time"] > window_start
):
window_end: Optional[float] = nxt["start_time"]
elif window_start is not None:
window_end = window_start + 0.5 * len(new_texts)
else:
window_end = None
timings = _distribute_timings(len(new_texts), window_start, window_end)
new_words = [
{
"id": _new_word_id(),
"text": text,
"start_time": t[0],
"end_time": t[1],
"confidence": 1,
"created_during_correction": True,
"ai_corrected": True,
# Inserted words have no source transcription -> synthetic timing.
"timing_estimated": True,
"correction_span_id": suggestion.get("id"),
}
for text, t in zip(new_texts, timings)
]
words[span_end + 1 : span_end + 1] = new_words
seg["text"] = _rebuild_text(words)
return result
removed = words[span_start : span_end + 1]
if op == "delete":
del words[span_start : span_start + len(removed)]
if not words:
del result[seg_index]
else:
seg["text"] = _rebuild_text(words)
seg["start_time"] = words[0].get("start_time")
seg["end_time"] = words[-1].get("end_time")
return result
# replace
new_texts = [t for t in _WORD_SPLIT_RE.split(new_text) if t]
timings = _distribute_timings(
len(new_texts),
removed[0].get("start_time") if removed else None,
removed[-1].get("end_time") if removed else None,
)
# >1 replacement word forces an even split of one range -> estimated timing.
timing_estimated = len(new_texts) > 1
original_span_text = suggestion.get("original_text") or _rebuild_text(removed)
new_words = []
for i, (text, t) in enumerate(zip(new_texts, timings)):
w = {
"id": _new_word_id(),
"text": text,
"start_time": t[0],
"end_time": t[1],
"confidence": 1,
"created_during_correction": True,
"ai_corrected": True,
"timing_estimated": timing_estimated,
"correction_span_id": suggestion.get("id"),
}
if i == 0:
w["original_text"] = original_span_text
new_words.append(w)
words[span_start : span_start + len(removed)] = new_words
seg["text"] = _rebuild_text(words)
return result
def apply_all_suggestions(
segments: List[Segment], suggestions: List[Suggestion]
) -> Dict[str, Any]:
"""Accept-all with conflict resolution, mirroring the UI's on-load auto-apply.
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids"}``.
"""
winners = set(pick_accept_all_winners(suggestions))
current = segments
applied: List[str] = []
rejected: List[str] = []
stale: List[str] = []
for s in suggestions:
sid = s.get("id") or ""
if sid not in winners:
rejected.append(sid)
continue
result = apply_suggestion(current, s)
if result is None:
stale.append(sid)
continue
current = result
applied.append(sid)
return {
"segments": current,
"applied_ids": applied,
"rejected_ids": rejected,
"stale_ids": stale,
}
def build_applied_segments(
corrections: Dict[str, Any], ai_suggestions: Optional[List[Suggestion]]
) -> Dict[str, Any]:
"""Apply the AI suggestions to a corrections payload with the safety gates.
Shared by the executor (auto-complete) and the review-gate pre-apply. Returns
``{"aborted": <reason>}`` on any anomaly (caller falls back to human review /
client-side apply), else ``{"segments", "applied_ids", "rejected_ids"}``.
"""
segments = corrections.get("corrected_segments") or []
if not segments:
return {"aborted": "no_segments"}
result = apply_all_suggestions(segments, ai_suggestions or [])
if result["stale_ids"]:
# Nothing edits segments between generation and now, so staleness means
# the cache doesn't match this corrections.json -> don't trust the apply.
return {"aborted": f"stale_suggestions:{len(result['stale_ids'])}"}
new_segments = result["segments"]
if not new_segments or any(not (s.get("words") or []) for s in new_segments):
return {"aborted": "empty_segments_after_apply"}
duplicates = find_suspicious_duplicates(new_segments, corrections.get("reference_lyrics"))
if duplicates:
# P1 signature: overlapping suggestions doubled a word ("you're you're").
return {"aborted": f"duplicate_words:{','.join(duplicates[:5])}"}
return {
"segments": new_segments,
"applied_ids": result["applied_ids"],
"rejected_ids": result["rejected_ids"],
}
def _norm_token(text: str) -> str:
return _TOKEN_NORM_RE.sub("", (text or "").lower())
def find_suspicious_duplicates(
segments: List[Segment], reference_lyrics: Optional[Dict[str, Any]] = None
) -> List[str]:
"""Adjacent identical words that no reference supports (P1 self-conflict
signature — e.g. two overlapping suggestions both adding "you're" produced
"fire, you're you're gasoline"). Returns the offending tokens."""
ref_texts: List[str] = []
for ref in (reference_lyrics or {}).values():
for ref_seg in ref.get("segments") or []:
ref_texts.append(" ".join(
_norm_token(t) for t in _WORD_SPLIT_RE.split(ref_seg.get("text") or "") if t
))
ref_blob = "\n".join(ref_texts)
offenders: List[str] = []
for seg in segments:
words = seg.get("words") or []
for i in range(1, len(words)):
a = _norm_token(words[i - 1].get("text") or "")
b = _norm_token(words[i].get("text") or "")
if a and a == b:
# A doubled word is fine when a reference genuinely repeats it.
if f"{a} {a}" in ref_blob:
continue
offenders.append(a)
return offenders
+333
View File
@@ -0,0 +1,333 @@
"""Auto-approval executor: complete the combined review without a human when safe.
Called from two places (covering both orderings of audio vs lyrics completion):
- ``screens_worker`` just before it would transition to AWAITING_REVIEW
(trigger="screens_worker", job still GENERATING_SCREENS), and
- ``audio_worker`` after stems + backing analysis land, when the job is already
sitting in AWAITING_REVIEW (trigger="audio_worker").
Every call scores the job and records the verdict in
``processing_metadata.auto_approval`` (so shadow data accumulates on every job).
Enforcement — actually skipping the review screens — happens only when ALL of:
- the feature flag is on and the job's ``review_mode`` is "auto" (the default);
- the job is not a made-for-you order (the human QC pass is part of that
product);
- the job is ELIGIBLE: with a user-supplied instrumental (tenant bulk uploads,
the existing-instrumental upload option, mute-region edits) there is no
instrumental decision to make, so confident lyrics alone qualify and the
selection is "custom" — mirroring the human tenant complete-review flow.
Otherwise the scorer's ``overall_auto`` must be True (confident lyrics AND a
non-subjective backing decision);
- audio separation is complete and the required instrumental exists (clean or
with-backing stem; the video worker validates custom sources itself).
The enforce path replicates exactly what a human clicking "Complete Review"
does after the UI's on-load auto-apply: apply the cached AI suggestions
(conflict groups resolved identically), save ``corrections_updated.json``,
store the instrumental selection, clear worker progress keys, transition to
REVIEW_COMPLETE and trigger the render worker.
FAIL-SAFE: any anomaly (stale suggestions, duplicate-word artifacts, missing
data, exceptions) aborts enforcement and the job proceeds to normal human
review. Auto-approval must never be the reason a job fails.
"""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from backend.models.job import JobStatus
from backend.services.auto_approval.instrumental import (
backing_decision,
has_custom_instrumental,
)
from backend.services.auto_approval.models import LyricsVerdict
logger = logging.getLogger(__name__)
CORRECTIONS_PATH = "jobs/{job_id}/lyrics/corrections.json"
CORRECTIONS_UPDATED_PATH = "jobs/{job_id}/lyrics/corrections_updated.json"
AUTO_CORRECT_CACHE_PREFIX = "jobs/{job_id}/lyrics/auto_correct_cache/"
REVIEW_MODE_AUTO = "auto"
REVIEW_MODE_ALWAYS_REVIEW = "always_review"
def _load_ai_suggestions(storage, job_id: str) -> Optional[List[Dict[str, Any]]]:
"""The proactive auto-correct cache the review UI would auto-apply on load."""
try:
prefix = AUTO_CORRECT_CACHE_PREFIX.format(job_id=job_id)
for cache_path in sorted(storage.list_files(prefix)):
cached = storage.download_json(cache_path)
suggestions = cached.get("suggestions")
if isinstance(suggestions, list):
return suggestions
except Exception as e:
logger.info(f"[job:{job_id}] auto-approval: no auto-correct cache readable ({e})")
return None
def _enforcement_blockers(job, settings) -> List[str]:
"""Why this job may not be ENFORCED (shadow scoring still happens)."""
blockers: List[str] = []
if not settings.auto_approval_enforce_enabled:
blockers.append("flag_disabled")
review_mode = getattr(job, "review_mode", REVIEW_MODE_AUTO) or REVIEW_MODE_AUTO
if review_mode != REVIEW_MODE_AUTO:
blockers.append(f"review_mode:{review_mode}")
if getattr(job, "made_for_you", False):
blockers.append("made_for_you")
return blockers
async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any]:
"""Score the job, record the verdict, and auto-complete the review if safe.
Returns a small status dict; ``{"outcome": "auto_completed"}`` means the
review screens were skipped and the render worker has been triggered.
Never raises.
"""
from backend.config import get_settings
from backend.services.auto_approval.scorer import score_job
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
outcome: Dict[str, Any] = {"outcome": "skipped"}
try:
settings = get_settings()
job_manager = JobManager()
storage = StorageService()
job = job_manager.get_job(job_id)
if not job:
return {"outcome": "no_job"}
# Only act on the two known launch points; a human already in the
# editor (IN_REVIEW) or any other state is out of scope.
if trigger == "screens_worker":
expected_statuses = (JobStatus.GENERATING_SCREENS,)
else:
expected_statuses = (JobStatus.AWAITING_REVIEW,)
if job.status not in expected_statuses:
return {"outcome": "wrong_status", "status": str(job.status)}
if job.state_data.get("instrumental_selection"):
return {"outcome": "already_selected"}
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
if not storage.file_exists(corrections_path):
return {"outcome": "no_corrections"}
corrections = storage.download_json(corrections_path)
ai_suggestions = _load_ai_suggestions(storage, job_id)
state_data = job.state_data or {}
backing_analysis = state_data.get("backing_vocals_analysis")
audio_complete = bool(state_data.get("audio_complete", False))
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
verdict = score_job(corrections, backing_analysis, ai_suggestions)
blockers = _enforcement_blockers(job, settings)
custom_instrumental = has_custom_instrumental(job)
backing_preference = getattr(job, "backing_preference", "auto") or "auto"
backing_keep_enabled = getattr(settings, "auto_approval_backing_keep_enabled", False)
# Single source of truth for the instrumental decision (shared with the
# complete-review "auto" resolver and the per-screen-skip UI summary).
decision = backing_decision(
backing_verdict=verdict.backing.verdict.value,
backing_non_subjective=verdict.backing.non_subjective,
backing_preference=backing_preference,
backing_keep_enabled=backing_keep_enabled,
custom_instrumental=custom_instrumental,
)
keep_backing = decision["keep_backing"]
# Eligibility: confident lyrics AND a resolvable instrumental decision.
# With a user-supplied instrumental the backing decision is moot, so
# confident lyrics alone qualify (selection="custom").
lyrics_auto = verdict.lyrics.verdict == LyricsVerdict.AUTO
if custom_instrumental:
eligible = lyrics_auto
enforcement_basis = "lyrics_only_custom_instrumental"
else:
eligible = lyrics_auto and decision["ok"]
enforcement_basis = (
"overall_auto"
if backing_preference == "auto"
else f"lyrics_auto_backing_pref:{backing_preference}"
)
# Stem / audio blockers (the instrumental the selection needs must exist).
if not audio_complete:
blockers.append("audio_incomplete")
elif custom_instrumental:
# User-supplied instrumental -> "custom"; the video worker validates
# the custom source itself, no separated-stem requirements.
pass
elif keep_backing:
# Confident-keep (3-stem decider) selects the with-backing
# instrumental — gated shadow-first behind its own flag.
if not backing_keep_enabled:
blockers.append("backing_keep_disabled")
if not stems.get("instrumental_with_backing"):
blockers.append("no_with_backing_stem")
elif not stems.get("instrumental_clean"):
# Clean selection (auto-clean verdict OR backing_preference="clean").
blockers.append("no_clean_stem")
payload = verdict.to_dict()
payload.update({
"mode": "shadow", # flipped to "enforce" only when we actually enforce
"enforcement_eligible": eligible and not blockers,
"enforcement_basis": enforcement_basis,
"custom_instrumental": custom_instrumental,
"backing_preference": backing_preference,
"resolved_instrumental_selection": decision["selection"],
"trigger": trigger,
"enforcement_blockers": blockers,
"audio_complete_at_scoring": audio_complete,
"backing_analysis_available": backing_analysis is not None,
"ai_suggestions_available": ai_suggestions is not None,
"scored_at": datetime.now(timezone.utc).isoformat(),
})
summary = (
f"auto-approval [{trigger}]: eligible={eligible} ({enforcement_basis}) "
f"lyrics={verdict.lyrics.verdict.value}/{verdict.lyrics.tier} "
f"backing={verdict.backing.verdict.value} blockers={blockers or 'none'} "
f"(scorer v{verdict.scorer_version})"
)
logger.info(f"[job:{job_id}] {summary}")
if not eligible or blockers:
payload["outcome"] = "review"
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
return {"outcome": "review", "overall_auto": verdict.overall_auto,
"blockers": blockers}
# ---- ENFORCE: complete the review exactly like a human would ----
# The status gate above used a snapshot read. Re-read now so a human who
# opened the editor in the meantime (AWAITING_REVIEW -> IN_REVIEW) is not
# overwritten — IN_REVIEW -> REVIEW_COMPLETE is a legal transition and
# would otherwise pass validation mid-edit.
fresh = job_manager.get_job(job_id)
if (
not fresh
or fresh.status not in expected_statuses
or (fresh.state_data or {}).get("instrumental_selection")
):
payload["outcome"] = "aborted"
payload["abort_reason"] = "state_changed_during_enforce"
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
return {"outcome": "aborted", "reason": "state_changed_during_enforce"}
applied_info = _build_auto_corrections(
job_id, corrections, ai_suggestions or [], storage
)
if applied_info.get("aborted"):
payload["outcome"] = "aborted"
payload["abort_reason"] = applied_info["aborted"]
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
logger.warning(
f"[job:{job_id}] auto-approval aborted -> human review "
f"({applied_info['aborted']})"
)
return {"outcome": "aborted", "reason": applied_info["aborted"]}
# Instrumental selection resolved by the shared decision: user-supplied
# instrumental -> "custom"; otherwise the non-subjective backing verdict
# (or the user's backing_preference) picks the separated stem.
selection = decision["selection"] or ("with_backing" if keep_backing else "clean")
job_manager.update_state_data(job_id, "instrumental_selection", selection)
# Clear worker progress keys so downstream workers run fresh (mirrors
# complete_review — idempotency keys would otherwise skip re-runs).
progress_keys = ["render_progress", "video_progress", "encoding_progress"]
job_manager.delete_state_data_keys(job_id, progress_keys)
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.REVIEW_COMPLETE,
progress=70,
message=(
"Auto-approved: lyrics verified against synced references and "
+ (
"using your provided instrumental"
if custom_instrumental
else (
"clear backing vocals retained"
if keep_backing
else "no audible backing vocals"
)
)
+ " — skipping review, rendering video"
),
)
# Record the verdict AFTER the transition so the metadata never claims
# auto-completion for a job that in fact fell back to human review.
payload["mode"] = "enforce"
payload["outcome"] = "auto_completed"
payload["applied_suggestions"] = len(applied_info.get("applied_ids") or [])
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
from backend.services.worker_service import get_worker_service
await get_worker_service().trigger_render_video_worker(job_id)
logger.info(f"[job:{job_id}] auto-approval COMPLETED review "
f"(applied {payload['applied_suggestions']} AI suggestions)")
return {"outcome": "auto_completed"}
except Exception as e:
logger.warning(f"[job:{job_id}] auto-approval failed non-fatally: {e}", exc_info=True)
try:
from backend.services.job_manager import JobManager
JobManager().update_processing_metadata(job_id, "auto_approval", {
"outcome": "error",
"error": str(e),
"trigger": trigger,
"scored_at": datetime.now(timezone.utc).isoformat(),
})
except Exception:
pass
return {"outcome": "error", "error": str(e)}
def _build_auto_corrections(
job_id: str,
corrections: Dict[str, Any],
ai_suggestions: List[Dict[str, Any]],
storage,
) -> Dict[str, Any]:
"""Apply the AI suggestions and save corrections_updated.json.
Returns ``{"aborted": <reason>}`` on any anomaly (caller falls back to
human review), else ``{"applied_ids": [...]}``.
"""
from backend.services.auto_approval.apply import build_applied_segments
result = build_applied_segments(corrections, ai_suggestions)
if result.get("aborted"):
return {"aborted": result["aborted"]}
updated = dict(corrections)
updated["corrected_segments"] = result["segments"]
metadata = dict(updated.get("metadata") or {})
metadata["auto_approval"] = {
"auto_approved": True,
"applied_suggestion_ids": result["applied_ids"],
"rejected_suggestion_ids": result["rejected_ids"],
"applied_at": datetime.now(timezone.utc).isoformat(),
}
updated["metadata"] = metadata
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
storage.upload_json(updated_path, updated)
from backend.services.job_manager import JobManager
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
logger.info(
f"[job:{job_id}] auto-approval saved corrections_updated.json "
f"({len(result['applied_ids'])} suggestions applied, "
f"{len(result['rejected_ids'])} conflict-losers rejected)"
)
return {"applied_ids": result["applied_ids"]}
@@ -0,0 +1,143 @@
"""Single source of truth for the auto instrumental-selection decision.
The backing decision is derived in three places that MUST agree:
- the executor, when auto-completing a job (live verdict object);
- ``POST /review/{id}/complete`` when a client sends ``instrumental_selection="auto"``
(reads the stored ``processing_metadata.auto_approval`` verdict);
- the ``/correction-data`` response summary the frontend uses to decide whether to
show the instrumental screen at all (per-screen skip, C1).
``backing_decision`` is a pure function over primitives so all three can call it with
either the live verdict or the persisted dict. It also folds in the user's up-front
``backing_preference`` (C3): ``clean`` forces a clean instrumental, ``review`` suppresses
the auto backing decision so a human always picks.
"""
from __future__ import annotations
from typing import Any, Dict, Optional
BACKING_PREFERENCE_AUTO = "auto" # retain backing vocals where confidently safe (default)
BACKING_PREFERENCE_CLEAN = "clean" # always use the clean instrumental
BACKING_PREFERENCE_REVIEW = "review" # always let a human pick the instrumental
VALID_BACKING_PREFERENCES = (
BACKING_PREFERENCE_AUTO,
BACKING_PREFERENCE_CLEAN,
BACKING_PREFERENCE_REVIEW,
)
def has_custom_instrumental(job) -> bool:
"""True when the user supplied their own instrumental (tenant bulk uploads,
the upload flow's existing-instrumental option, or a mute-region edit).
For these jobs there is NO instrumental decision to make — the human
complete-review flow submits ``instrumental_selection="custom"``.
"""
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
return bool(
getattr(job, "existing_instrumental_gcs_path", None)
or stems.get("custom_instrumental")
)
def backing_decision(
*,
backing_verdict: Optional[str],
backing_non_subjective: bool,
backing_preference: Optional[str],
backing_keep_enabled: bool,
custom_instrumental: bool,
) -> Dict[str, Any]:
"""Resolve the instrumental decision from a (live or stored) backing verdict.
Returns ``{"ok": bool, "selection": Optional[str], "keep_backing": bool}``:
- ``ok`` — the instrumental can be auto-selected (no human needed for this half).
- ``selection`` — "custom" | "clean" | "with_backing" | None (None ⇒ human must pick).
- ``keep_backing`` — informational: the confident verdict is a with-backing keep
(used by the executor to require the with-backing stem).
"""
if custom_instrumental:
return {"ok": True, "selection": "custom", "keep_backing": False}
pref = backing_preference or BACKING_PREFERENCE_AUTO
if pref == BACKING_PREFERENCE_CLEAN:
# User asked to always strip backing vocals.
return {"ok": True, "selection": "clean", "keep_backing": False}
if pref == BACKING_PREFERENCE_REVIEW:
# User asked to always decide the instrumental themselves.
return {"ok": False, "selection": None, "keep_backing": False}
# pref == auto: rely on the non-subjective backing verdict.
if not backing_non_subjective:
return {"ok": False, "selection": None, "keep_backing": False}
if backing_verdict == "with_backing":
# Confident 3-stem keep — gated shadow-first behind its own flag.
if not backing_keep_enabled:
return {"ok": False, "selection": None, "keep_backing": True}
return {"ok": True, "selection": "with_backing", "keep_backing": True}
# Confident CLEAN ("no audible backing").
return {"ok": True, "selection": "clean", "keep_backing": False}
def auto_approval_summary(job, settings) -> Dict[str, Any]:
"""Compact block for the ``/correction-data`` response (C1 per-screen skip).
Reads the stored ``processing_metadata.auto_approval`` verdict + the job's
``backing_preference`` and tells the frontend whether each review half is
confidently resolved (so it can skip that screen).
"""
aa = (getattr(job, "processing_metadata", None) or {}).get("auto_approval") or {}
backing = aa.get("backing") or {}
lyrics = aa.get("lyrics") or {}
custom = has_custom_instrumental(job)
# ``always_review`` (or any non-"auto" review_mode) means the user asked to
# see every screen — no half is ever "confident" enough to skip.
review_mode = getattr(job, "review_mode", "auto") or "auto"
if review_mode != "auto":
return {
"backing": {"verdict": backing.get("verdict"), "confident": False, "resolved_selection": None},
"lyrics": {"verdict": lyrics.get("verdict"), "confident": False},
"custom_instrumental": custom,
"verdict_present": bool(aa),
}
decision = backing_decision(
backing_verdict=backing.get("verdict"),
backing_non_subjective=bool(backing.get("non_subjective")),
backing_preference=getattr(job, "backing_preference", BACKING_PREFERENCE_AUTO),
backing_keep_enabled=bool(getattr(settings, "auto_approval_backing_keep_enabled", False)),
custom_instrumental=custom,
)
selection = _selection_with_stem_check(job, decision["selection"])
return {
"backing": {
"verdict": backing.get("verdict"),
"confident": selection is not None,
"resolved_selection": selection,
},
"lyrics": {
"verdict": lyrics.get("verdict"),
"confident": lyrics.get("verdict") == "auto",
},
"custom_instrumental": custom,
"verdict_present": bool(aa),
}
def _selection_with_stem_check(job, selection: Optional[str]) -> Optional[str]:
"""None out a separated-stem selection when that stem isn't present, so the
complete endpoint never persists an instrumental the render worker can't use
(mirrors the executor's no_*_stem blockers). "custom" is validated elsewhere."""
if selection in ("clean", "with_backing"):
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
stem_key = "instrumental_with_backing" if selection == "with_backing" else "instrumental_clean"
if not stems.get(stem_key):
return None
return selection
def resolve_auto_instrumental(job, settings) -> Optional[str]:
"""Map a client's ``instrumental_selection="auto"`` to a concrete selection
from the stored verdict, or None when it isn't confidently resolvable."""
return auto_approval_summary(job, settings)["backing"]["resolved_selection"]
@@ -0,0 +1,250 @@
"""Reconstruct exactly what a human changed during lyrics review.
Diffs the raw transcription (``corrections.json`` -> ``corrected_segments``) against
the reviewer's final result (``corrections_updated.json`` -> ``corrected_segments``).
Because production runs with auto-correction disabled, the original ``corrected_segments``
IS the raw AudioShake transcription, so this diff is *exactly* the set of manual edits
Andrew made — the ground truth the recording corpus is built on.
Words carry stable ``id``s, BUT the review UI assigns a NEW id when a word's text is
replaced (rather than mutating in place). It preserves the word's start/end time and line,
though — so a text correction shows up as a delete+insert at the *same timing*. We recover
those as ``replacements`` by pairing a deletion with an insertion sharing (line, start, end).
The diff is keyed on word id and yields:
- ``replacements`` — a word swapped for another at the same time/line (`Carl` → `Karl`);
the common case for mis-transcribed words
- ``text_edits`` — same id, changed text (in-place edit; rare)
- ``timing_changes`` — same id, moved start/end (a sync nudge)
- ``deletions`` — a word removed with no same-timing replacement (adlib/dupe/etc.)
- ``insertions`` — a word added with no same-timing original
- ``segmentation`` — line count changed or a word moved between lines (split/merge/rewrap)
See ``docs/archive/2026-08-25-full-auto-review-design.md``.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from typing import Any, Dict, List, Optional, Tuple
# Minimum start/end move (seconds) to count as a deliberate timing change, not float noise.
TIMING_EPSILON = 0.005
# Max start/end difference (seconds) to treat a delete+insert as an in-place replacement.
REPLACE_TIMING_EPSILON = 0.02
@dataclass
class TextEdit:
word_id: str
original_text: str
final_text: str
segment_index: int
@dataclass
class TimingChange:
word_id: str
text: str
original_start: Optional[float]
original_end: Optional[float]
final_start: Optional[float]
final_end: Optional[float]
start_delta: Optional[float]
end_delta: Optional[float]
@dataclass
class Replacement:
"""A word swapped for another at the same time/line (mis-transcription fix)."""
original_word_id: str
final_word_id: str
original_text: str
final_text: str
segment_index: int
start_time: Optional[float]
@dataclass
class WordRef:
word_id: str
text: str
segment_index: int
@dataclass
class SegmentMove:
"""A word that stayed but moved to a different line (split/merge/rewrap)."""
word_id: str
text: str
original_segment_index: int
final_segment_index: int
@dataclass
class LyricsDiff:
has_changes: bool = False
total_changes: int = 0
original_segment_count: int = 0
final_segment_count: int = 0
original_word_count: int = 0
final_word_count: int = 0
segmentation_changed: bool = False
replacements: List[Replacement] = field(default_factory=list)
text_edits: List[TextEdit] = field(default_factory=list)
timing_changes: List[TimingChange] = field(default_factory=list)
deletions: List[WordRef] = field(default_factory=list)
insertions: List[WordRef] = field(default_factory=list)
segment_moves: List[SegmentMove] = field(default_factory=list)
# The UI-recorded WordCorrection list from corrections_updated.json (supplementary).
ui_recorded_corrections: int = 0
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
def _index_words(segments: List[Dict[str, Any]]) -> Tuple[Dict[str, Dict[str, Any]], int]:
"""Return {word_id: {text,start,end,segment_index}} and total word count."""
by_id: Dict[str, Dict[str, Any]] = {}
count = 0
for seg_index, seg in enumerate(segments or []):
for word in seg.get("words") or []:
wid = word.get("id")
count += 1
if not wid:
continue
by_id[wid] = {
"text": (word.get("text") or "").strip(),
"start": word.get("start_time"),
"end": word.get("end_time"),
"segment_index": seg_index,
}
return by_id, count
def _delta(a: Optional[float], b: Optional[float]) -> Optional[float]:
if a is None or b is None:
return None
return round(b - a, 4)
def compute_lyrics_diff(
original_data: Dict[str, Any],
updated_data: Optional[Dict[str, Any]],
) -> LyricsDiff:
"""Diff raw transcription against the reviewer's final result.
``original_data``: parsed ``corrections.json``.
``updated_data``: parsed ``corrections_updated.json`` (or ``None`` if the job was
never edited — yields an empty diff).
"""
orig_segments = original_data.get("corrected_segments") or []
orig_by_id, orig_count = _index_words(orig_segments)
diff = LyricsDiff(
original_segment_count=len(orig_segments),
original_word_count=orig_count,
)
if not updated_data or "corrected_segments" not in updated_data:
# No human edits recorded — final == raw transcription.
diff.final_segment_count = len(orig_segments)
diff.final_word_count = orig_count
return diff
final_segments = updated_data.get("corrected_segments") or []
final_by_id, final_count = _index_words(final_segments)
diff.final_segment_count = len(final_segments)
diff.final_word_count = final_count
diff.ui_recorded_corrections = len(updated_data.get("corrections") or [])
orig_ids = set(orig_by_id)
final_ids = set(final_by_id)
deleted_ids = sorted(orig_ids - final_ids)
inserted_ids = sorted(final_ids - orig_ids)
# Pair delete+insert at the same line & timing into replacements (mis-transcription
# fixes: the UI re-keys the word but keeps its slot). One-to-one, greedy.
unmatched_inserts = list(inserted_ids)
for did in deleted_ids:
o = orig_by_id[did]
match = None
for iid in unmatched_inserts:
f = final_by_id[iid]
if (
o["segment_index"] == f["segment_index"]
and o["start"] is not None and f["start"] is not None
and abs((o["start"] or 0) - (f["start"] or 0)) <= REPLACE_TIMING_EPSILON
and abs((o["end"] or 0) - (f["end"] or 0)) <= REPLACE_TIMING_EPSILON
):
match = iid
break
if match is not None:
f = final_by_id[match]
unmatched_inserts.remove(match)
diff.replacements.append(
Replacement(
original_word_id=did,
final_word_id=match,
original_text=o["text"],
final_text=f["text"],
segment_index=f["segment_index"],
start_time=f["start"],
)
)
else:
diff.deletions.append(WordRef(did, o["text"], o["segment_index"]))
for iid in unmatched_inserts:
w = final_by_id[iid]
diff.insertions.append(WordRef(iid, w["text"], w["segment_index"]))
for wid in sorted(orig_ids & final_ids):
o = orig_by_id[wid]
f = final_by_id[wid]
if o["text"] != f["text"]:
diff.text_edits.append(
TextEdit(wid, o["text"], f["text"], f["segment_index"])
)
start_d = _delta(o["start"], f["start"])
end_d = _delta(o["end"], f["end"])
if (start_d is not None and abs(start_d) > TIMING_EPSILON) or (
end_d is not None and abs(end_d) > TIMING_EPSILON
):
diff.timing_changes.append(
TimingChange(
word_id=wid,
text=f["text"],
original_start=o["start"],
original_end=o["end"],
final_start=f["start"],
final_end=f["end"],
start_delta=start_d,
end_delta=end_d,
)
)
if o["segment_index"] != f["segment_index"]:
diff.segment_moves.append(
SegmentMove(wid, f["text"], o["segment_index"], f["segment_index"])
)
diff.segmentation_changed = bool(
diff.segment_moves
or diff.original_segment_count != diff.final_segment_count
)
diff.total_changes = (
len(diff.replacements)
+ len(diff.text_edits)
+ len(diff.timing_changes)
+ len(diff.deletions)
+ len(diff.insertions)
+ len(diff.segment_moves)
)
diff.has_changes = diff.total_changes > 0
return diff
+136
View File
@@ -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
},
)
+129
View File
@@ -0,0 +1,129 @@
"""Server-side pre-apply of AI corrections BEFORE the review-ready notification.
Andrew's directive (2026-08-29): *"apply the ai-generated lyrics corrections and any
post-ai heuristic fixes before the user ever sees the notification/button saying the
lyrics review is ready ... it should all be done server-side and loaded as a single
load event when the lyrics review page launches."*
Called from ``screens_worker`` for review-bound jobs (i.e. when the executor did NOT
auto-complete the whole job), just before the AWAITING_REVIEW transition. It applies
the same cached suggestions the review UI would auto-apply on load, using the same
machinery the executor uses (``apply.build_applied_segments``), and writes
``corrections_updated.json`` with a ``pre_applied`` marker so the ``/correction-data``
endpoint serves the already-corrected state in a single load — eliminating the
in-browser auto-apply race.
BEST-EFFORT: never raises, bounded. On any miss (proactive disabled, cache absent,
LLM outage, sanity-check abort) it simply does nothing and the review UI falls back to
its existing client-side on-load auto-apply. Auto-approval must never strand a job.
"""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
CORRECTIONS_PATH = "jobs/{job_id}/lyrics/corrections.json"
CORRECTIONS_UPDATED_PATH = "jobs/{job_id}/lyrics/corrections_updated.json"
async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) -> Dict[str, Any]:
"""Ensure the suggestion cache exists, apply it, and persist the pre-applied
corrections with a ``pre_applied`` marker. Returns a small status dict; never
raises.
``generate_on_miss`` (default True, the screens_worker path): when the proactive
cache is absent, generate it synchronously (bounded) before applying. The
``/correction-data`` load path passes False — it only applies an EXISTING cache
so a review page never blocks on a multi-model LLM call; a cache-miss there
falls through to the UI's own client-side apply.
"""
try:
from backend.config import get_settings
from backend.services.auto_approval.apply import build_applied_segments
from backend.services.auto_approval.executor import _load_ai_suggestions
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
settings = get_settings()
storage = StorageService()
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
if not storage.file_exists(corrections_path):
return {"outcome": "skipped", "reason": "no_corrections"}
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
if storage.file_exists(updated_path):
# Already applied once (executor auto-complete, a prior pre-apply run,
# or a human edit). Never clobber existing corrections_updated.json.
try:
existing = storage.download_json(updated_path)
if ((existing.get("metadata") or {}).get("auto_approval")):
return {"outcome": "skipped", "reason": "already_applied"}
except Exception:
pass
return {"outcome": "skipped", "reason": "corrections_updated_exists"}
corrections = storage.download_json(corrections_path)
# 1) Ensure the proactive suggestion cache exists (generate on miss, unless
# the caller — e.g. the load-time path — asked to only apply an existing
# cache so the request doesn't block on an LLM call).
ai_suggestions = _load_ai_suggestions(storage, job_id)
if ai_suggestions is None and generate_on_miss and settings.auto_correct_proactive_enabled:
logger.info(f"[job:{job_id}] pre-apply: cache miss, generating suggestions synchronously")
from backend.workers.auto_correct_worker import process_proactive_auto_correct
await process_proactive_auto_correct(job_id) # bounded (180s) + best-effort
ai_suggestions = _load_ai_suggestions(storage, job_id)
if ai_suggestions is None:
# Unknown suggestion set (proactive disabled or generation failed) —
# do NOT mark pre_applied; let the UI run its client-side apply.
return {"outcome": "skipped", "reason": "no_suggestions_cache"}
# 2) Apply with the executor's sanity gates.
result = build_applied_segments(corrections, ai_suggestions)
if result.get("aborted"):
logger.info(f"[job:{job_id}] pre-apply aborted ({result['aborted']}) — UI will apply client-side")
return {"outcome": "skipped", "reason": result["aborted"]}
# 3) Persist corrections_updated.json with the pre_applied marker + the
# suggestions themselves (so the review panel renders applied state).
updated = dict(corrections)
updated["corrected_segments"] = result["segments"]
metadata = dict(updated.get("metadata") or {})
metadata["auto_approval"] = {
"pre_applied": True,
"applied_suggestion_ids": result["applied_ids"],
"rejected_suggestion_ids": result["rejected_ids"],
"suggestions": ai_suggestions,
"applied_at": datetime.now(timezone.utc).isoformat(),
}
updated["metadata"] = metadata
# Create-only write: we only reach here when corrections_updated.json was
# absent at the check above, so if_generation_match=0 makes the write atomic —
# a concurrent writer (executor auto-complete, or an edit submission) that
# created it in the meantime wins and we don't clobber their (newer) state.
try:
from google.api_core.exceptions import PreconditionFailed
except Exception: # pragma: no cover - google libs always present in prod
PreconditionFailed = () # type: ignore[assignment]
try:
storage.upload_json(updated_path, updated, if_generation_match=0)
except PreconditionFailed:
logger.info(f"[job:{job_id}] pre-apply raced a concurrent write — theirs wins")
return {"outcome": "skipped", "reason": "raced_concurrent_write"}
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
logger.info(
f"[job:{job_id}] pre-apply saved corrections_updated.json "
f"({len(result['applied_ids'])} applied, {len(result['rejected_ids'])} rejected) "
"before review notification"
)
return {"outcome": "pre_applied", "applied": len(result["applied_ids"])}
except Exception as e: # noqa: BLE001 — best-effort, never fatal
logger.warning(f"[job:{job_id}] pre-apply failed non-fatally: {e}", exc_info=True)
return {"outcome": "error", "error": str(e)}
+600
View File
@@ -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 []
+157 -35
View File
@@ -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(
+2 -1
View File
@@ -201,7 +201,8 @@ class FirestoreService:
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
'made_for_you', 'customer_email', 'locale',
'url', 'filename', 'audio_search_artist', 'audio_search_title',
'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',
+4
View File
@@ -101,6 +101,10 @@ class JobManager:
youtube_description_template=job_create.youtube_description_template, # video_worker reads this
webhook_url=job_create.webhook_url,
user_email=job_create.user_email,
# Review autonomy ("auto" = skip review screens when confident)
review_mode=job_create.review_mode,
# Backing-vocals preference ("auto"=retain-where-safe | clean | review)
backing_preference=job_create.backing_preference,
# Distribution settings
brand_prefix=job_create.brand_prefix,
discord_webhook_url=job_create.discord_webhook_url,
+59
View File
@@ -14,6 +14,7 @@ Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding t
here must never break the distribution pipeline — the nightly VM remains the safety net.
"""
import logging
import re
from typing import Optional
from google.cloud import storage
@@ -23,6 +24,17 @@ from backend.config import settings
logger = logging.getLogger(__name__)
# A single-track filename prefix must be a full public brand code PLUS at least part
# of the artist name ("NOMAD-#### - X..."). Stricter than the by-brand deletes: when a
# recycled brand code is shared by two tracks (orphaned files), this lets cleanup
# target exactly one of them without touching the other.
_TRACK_FILENAME_PREFIX_RE = re.compile(r"^NOMAD-\d{4,} - \S.*")
def is_safe_track_filename_prefix(filename_prefix: Optional[str]) -> bool:
"""True if the prefix is specific enough for a single-track mirror delete."""
return bool(_TRACK_FILENAME_PREFIX_RE.match(filename_prefix or ""))
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
@@ -162,6 +174,53 @@ class NomadMasterMirror:
return deleted
def delete_track_objects_by_filename_prefix(self, filename_prefix: str) -> dict:
"""Delete mirror objects (720p masters + original-vocals guides) whose filename
starts with ``filename_prefix`` — e.g. ``"NOMAD-1583 - Mazzy Star"``.
Used by orphaned-output cleanup when the owning job doc is gone and a recycled
brand code is shared with a live track: the prefix must include artist text
(enforced by ``_TRACK_FILENAME_PREFIX_RE``) so only the orphaned track's
objects match, never the whole brand code. Matching is delimiter-bounded — the
character after the prefix must be a space or ``.`` — so ``"NOMAD-1583 - Mazzy
Star"`` can never match a different track named ``"NOMAD-1583 - Mazzy Starlight
- ..."``. Raises ``ValueError`` for an unsafe prefix (callers validate with
``is_safe_track_filename_prefix``); GCS errors stay best-effort.
"""
if not is_safe_track_filename_prefix(filename_prefix):
raise ValueError(
f"Unsafe mirror track prefix {filename_prefix!r} "
f"(must look like 'NOMAD-#### - Artist...')"
)
counts = {"masters_deleted": 0, "vocals_guides_deleted": 0}
targets = [
("masters_deleted", settings.nomad_master_gcs_prefix.strip("/")),
("vocals_guides_deleted", settings.nomad_vocals_guide_gcs_prefix.strip("/")),
]
for key, gcs_prefix in targets:
prefix = f"{gcs_prefix}/{filename_prefix}"
try:
for blob in self._bucket.list_blobs(prefix=prefix):
remainder = blob.name[len(prefix):]
if remainder and remainder[0] not in " .":
# Prefix ends mid-word (a longer artist/title shares it) —
# this object belongs to a different track.
continue
try:
blob.delete()
counts[key] += 1
logger.info(
"Removed orphaned mirror object gs://%s/%s",
settings.divebar_files_bucket, blob.name,
)
except Exception as e: # noqa: BLE001
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
except Exception as e: # noqa: BLE001 - never fatal to the caller
logger.warning("Mirror track prefix-delete failed for %s: %s", prefix, e)
return counts
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
+77 -5
View File
@@ -113,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)
@@ -230,14 +288,28 @@ class StorageService:
logger.error(f"Error checking file existence {blob_path}: {e}")
raise
def upload_json(self, destination_path: str, data: Dict[str, Any]) -> str:
"""Upload a JSON object to GCS."""
def upload_json(
self,
destination_path: str,
data: Dict[str, Any],
if_generation_match: Optional[int] = None,
) -> str:
"""Upload a JSON object to GCS.
``if_generation_match=0`` makes the write a create-only operation: GCS raises
``PreconditionFailed`` (412) if the object already exists, so concurrent
writers can't clobber each other. Callers that need this must handle the
exception.
"""
try:
blob = self.bucket.blob(destination_path)
blob.content_type = "application/json"
upload_kwargs = {"content_type": "application/json"}
if if_generation_match is not None:
upload_kwargs["if_generation_match"] = if_generation_match
blob.upload_from_string(
json.dumps(data, indent=2, ensure_ascii=False),
content_type="application/json"
**upload_kwargs,
)
logger.info(f"Uploaded JSON to gs://{settings.gcs_bucket_name}/{destination_path}")
return destination_path
+22
View File
@@ -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",
]
+480
View File
@@ -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)
+40 -4
View File
@@ -24,7 +24,7 @@ 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
@@ -249,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)
@@ -404,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
@@ -584,6 +588,29 @@ class WorkerService:
# 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,
@@ -607,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
@@ -718,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)
@@ -807,7 +843,7 @@ class WorkerService:
logger.error("GOOGLE_CLOUD_PROJECT not set")
return False
location = self.settings.gcp_region
location = self.settings.cloud_tasks_region # queues all live here, NOT gcp_region
# Build queue path
parent = self.tasks_client.queue_path(project, location, queue_name)
@@ -0,0 +1,97 @@
"""Tests for POST /api/tenant/bulk/analyze (auth + feature gate + cap)."""
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_auth
from backend.services.auth_service import AuthResult, UserType
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture(autouse=True)
def _auth_override():
async def override_auth():
return AuthResult(
is_valid=True,
user_type=UserType.UNLIMITED,
remaining_uses=-1,
message="Valid",
user_email="op@vocalstar.com",
is_admin=False,
)
app.dependency_overrides[require_auth] = override_auth
yield
app.dependency_overrides.clear()
def _tenant(bulk_upload=True):
return SimpleNamespace(
id="vocalstar", features=SimpleNamespace(bulk_upload=bulk_upload)
)
CLEAN = [
"S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3",
"S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3",
"cover.png",
]
def test_403_when_not_a_tenant(client):
with patch(
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
return_value=None,
):
r = client.post("/api/tenant/bulk/analyze", json={"filenames": CLEAN})
assert r.status_code == 403
def test_403_when_feature_disabled(client):
with patch(
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
return_value=_tenant(bulk_upload=False),
):
r = client.post("/api/tenant/bulk/analyze", json={"filenames": CLEAN})
assert r.status_code == 403
def test_400_when_empty(client):
with patch(
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
return_value=_tenant(),
):
r = client.post("/api/tenant/bulk/analyze", json={"filenames": []})
assert r.status_code == 400
def test_400_when_over_cap(client):
too_many = [f"S{i}-1 A - T Guide.mp3" for i in range(101)]
with patch(
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
return_value=_tenant(),
):
r = client.post("/api/tenant/bulk/analyze", json={"filenames": too_many})
assert r.status_code == 400
assert "at most 100" in r.json()["detail"]
def test_happy_path_returns_rows(client):
# Clean batch has no leftovers, so the LLM generate is never invoked.
with patch(
"backend.api.routes.tenant_bulk.get_tenant_config_from_request",
return_value=_tenant(),
):
r = client.post("/api/tenant/bulk/analyze", json={"filenames": CLEAN})
assert r.status_code == 200
data = r.json()
assert len(data["rows"]) == 1
assert data["rows"][0]["artist"] == "Eddy Grant"
assert {i["filename"] for i in data["ignored"]} == {"cover.png"}
@@ -0,0 +1,105 @@
"""Tests for the opt-in resumable upload mode on create-with-upload-urls.
- upload_mode omitted / "signed_put" → signed PUT URLs (unchanged default path)
- upload_mode "resumable" → GCS resumable session URIs created with the
caller's Origin (so GCS answers CORS on the session itself), resumable=True
"""
import pytest
from unittest.mock import Mock, patch
from backend.api.routes.file_upload import (
CreateJobWithUploadUrlsRequest,
FileUploadRequest,
create_job_with_upload_urls,
)
from backend.services.auth_service import UserType, AuthResult
@pytest.fixture
def auth():
return AuthResult(
is_valid=True,
user_type=UserType.UNLIMITED,
remaining_uses=-1,
message="OK",
user_email="op@vocalstar.com",
is_admin=False,
)
def _request(origin="https://vocalstar.nomadkaraoke.com"):
req = Mock()
req.headers = {"Origin": origin}
req.state = Mock()
return req
def _body(**overrides):
kwargs = dict(
artist="Eddy Grant",
title="I Don't Wanna Dance",
files=[
FileUploadRequest(filename="mixed.mp3", content_type="audio/mpeg", file_type="audio"),
FileUploadRequest(filename="inst.mp3", content_type="audio/mpeg", file_type="existing_instrumental"),
],
is_private=True,
existing_instrumental=True,
)
kwargs.update(overrides)
return CreateJobWithUploadUrlsRequest(**kwargs)
@pytest.fixture
def endpoint_mocks():
"""Patch the endpoint's collaborators down to URL generation."""
with patch("backend.api.routes.file_upload.get_tenant_config_from_request", return_value=None), \
patch("backend.api.routes.file_upload.get_locale_from_request", return_value="en"), \
patch("backend.api.routes.file_upload.get_full_locale_from_request", return_value="en"), \
patch("backend.api.routes.file_upload.extract_request_metadata", return_value={}), \
patch("backend.api.routes.file_upload.get_theme_service") as theme_svc, \
patch("backend.api.routes.file_upload.get_credential_manager") as cred_mgr, \
patch("backend.api.routes.file_upload.get_effective_distribution_settings") as dist, \
patch("backend.api.routes.file_upload.job_manager") as job_manager, \
patch("backend.api.routes.file_upload.storage_service") as storage, \
patch("backend.api.routes.file_upload.metrics"):
theme_svc.return_value.get_default_theme_id.return_value = None
# No distribution targets → no credential checks fire.
dist.return_value = Mock(
brand_prefix=None, dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None
)
cred_mgr.return_value = Mock()
job_manager.create_job.return_value = Mock(job_id="job-123")
storage.generate_signed_upload_url.return_value = "https://signed-put"
storage.create_resumable_upload_session.return_value = "https://session-uri"
yield {"storage": storage, "job_manager": job_manager}
@pytest.mark.asyncio
async def test_default_mode_returns_signed_put_urls(endpoint_mocks, auth):
resp = await create_job_with_upload_urls(_request(), _body(), auth)
assert resp.job_id == "job-123"
assert [u.resumable for u in resp.upload_urls] == [False, False]
assert all(u.upload_url == "https://signed-put" for u in resp.upload_urls)
endpoint_mocks["storage"].create_resumable_upload_session.assert_not_called()
@pytest.mark.asyncio
async def test_resumable_mode_returns_session_uris_with_origin(endpoint_mocks, auth):
resp = await create_job_with_upload_urls(
_request(origin="https://vocalstar.nomadkaraoke.com"),
_body(upload_mode="resumable", batch_id="batch-1"),
auth,
)
assert [u.resumable for u in resp.upload_urls] == [True, True]
assert all(u.upload_url == "https://session-uri" for u in resp.upload_urls)
endpoint_mocks["storage"].generate_signed_upload_url.assert_not_called()
# Sessions created with the caller's Origin so GCS handles session CORS.
for call in endpoint_mocks["storage"].create_resumable_upload_session.call_args_list:
assert call.kwargs["origin"] == "https://vocalstar.nomadkaraoke.com"
# batch_id stamping still applies in resumable mode.
endpoint_mocks["job_manager"].update_state_data.assert_any_call("job-123", "batch_id", "batch-1")
def test_upload_mode_rejects_unknown_values():
with pytest.raises(Exception):
_body(upload_mode="carrier-pigeon")
Whitespace-only changes.
@@ -0,0 +1,183 @@
"""Tests for the server-side AI-suggestion apply engine.
This is a port of the review UI's auto-apply (autoCorrectApply.ts /
autoCorrectConflicts.ts); these tests pin the port to the frontend's observable
behaviour: op semantics, timing distribution, word flags, conflict resolution.
"""
from __future__ import annotations
from typing import Any, Dict, List
from backend.services.auto_approval.apply import (
apply_all_suggestions,
apply_suggestion,
find_suspicious_duplicates,
is_suggestion_stale,
pick_accept_all_winners,
)
def _word(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
return {"id": wid, "text": text, "start_time": start, "end_time": end, "confidence": 0.9}
def _segments() -> List[Dict[str, Any]]:
return [
{
"id": "s0",
"text": "I am a fire",
"words": [
_word("w0", "I", 0.0, 0.3),
_word("w1", "am", 0.3, 0.6),
_word("w2", "a", 0.6, 0.9),
_word("w3", "fire", 0.9, 1.5),
],
"start_time": 0.0,
"end_time": 1.5,
},
{
"id": "s1",
"text": "gasoline",
"words": [_word("w4", "gasoline", 2.0, 2.8)],
"start_time": 2.0,
"end_time": 2.8,
},
]
def _sug(op: str, word_ids: List[str], new_text: str = "", **kw: Any) -> Dict[str, Any]:
return {
"id": kw.pop("id", "sug1"),
"op": op,
"word_ids": word_ids,
"segment_ids": ["s0"],
"original_text": kw.pop("original_text", ""),
"new_text": new_text,
"confidence": kw.pop("confidence", 0.9),
"consensus": kw.pop("consensus", 2),
"total_models": kw.pop("total_models", 2),
"conflict_group": kw.pop("conflict_group", None),
}
# --- replace ---
def test_replace_single_word_inherits_timing_and_flags() -> None:
result = apply_suggestion(_segments(), _sug("replace", ["w1"], "was", original_text="am"))
assert result is not None
words = result[0]["words"]
assert [w["text"] for w in words] == ["I", "was", "a", "fire"]
new = words[1]
assert new["start_time"] == 0.3 and new["end_time"] == 0.6
assert new["ai_corrected"] is True
assert new["created_during_correction"] is True
assert new["timing_estimated"] is False # single word inherits a real range
assert new["original_text"] == "am"
assert result[0]["text"] == "I was a fire"
def test_replace_multi_word_splits_timing_and_marks_estimated() -> None:
result = apply_suggestion(_segments(), _sug("replace", ["w3"], "fire, you're"))
assert result is not None
words = result[0]["words"]
assert [w["text"] for w in words] == ["I", "am", "a", "fire,", "you're"]
a, b = words[3], words[4]
assert a["start_time"] == 0.9 and abs(a["end_time"] - 1.2) < 1e-9
assert abs(b["start_time"] - 1.2) < 1e-9 and b["end_time"] == 1.5
assert a["timing_estimated"] is True and b["timing_estimated"] is True
assert "original_text" in a and "original_text" not in b
# --- insert_after ---
def test_insert_after_uses_gap_to_next_word() -> None:
result = apply_suggestion(_segments(), _sug("insert_after", ["w3"], "burning"))
assert result is not None
words = result[0]["words"]
assert [w["text"] for w in words] == ["I", "am", "a", "fire", "burning"]
new = words[4]
assert new["start_time"] == 1.5 # anchor end
assert new["timing_estimated"] is True
# --- delete ---
def test_delete_word_updates_segment_text_and_timing() -> None:
result = apply_suggestion(_segments(), _sug("delete", ["w0"]))
assert result is not None
seg = result[0]
assert seg["text"] == "am a fire"
assert seg["start_time"] == 0.3
def test_delete_last_word_removes_segment() -> None:
result = apply_suggestion(_segments(), _sug("delete", ["w4"]))
assert result is not None
assert len(result) == 1
assert result[0]["id"] == "s0"
# --- staleness ---
def test_missing_word_is_stale() -> None:
assert is_suggestion_stale(_segments(), _sug("replace", ["nope"], "x"))
assert apply_suggestion(_segments(), _sug("replace", ["nope"], "x")) is None
def test_non_contiguous_words_are_stale() -> None:
assert is_suggestion_stale(_segments(), _sug("replace", ["w0", "w2"], "x"))
def test_empty_word_ids_is_stale_not_crash() -> None:
# all([]) is vacuously True — a cached suggestion with missing/empty
# word_ids must be treated as stale, not crash min() on an empty list.
assert is_suggestion_stale(_segments(), _sug("replace", [], "x"))
assert apply_suggestion(_segments(), _sug("replace", [], "x")) is None
# --- conflict groups / accept-all ---
def test_conflict_group_winner_by_consensus_then_confidence() -> None:
s1 = _sug("replace", ["w1"], "was", id="a", conflict_group="g1", consensus=1, confidence=0.95)
s2 = _sug("replace", ["w1"], "is", id="b", conflict_group="g1", consensus=2, confidence=0.7)
s3 = _sug("replace", ["w0"], "You", id="c")
assert pick_accept_all_winners([s1, s2, s3]) == ["b", "c"]
def test_apply_all_resolves_conflicts_and_reports() -> None:
s1 = _sug("replace", ["w1"], "was", id="a", conflict_group="g1", consensus=1)
s2 = _sug("replace", ["w1"], "is", id="b", conflict_group="g1", consensus=2)
out = apply_all_suggestions(_segments(), [s1, s2])
assert out["applied_ids"] == ["b"]
assert out["rejected_ids"] == ["a"]
assert out["stale_ids"] == []
assert [w["text"] for w in out["segments"][0]["words"]] == ["I", "is", "a", "fire"]
def test_apply_all_flags_stale() -> None:
out = apply_all_suggestions(_segments(), [_sug("replace", ["gone"], "x", id="a")])
assert out["stale_ids"] == ["a"]
assert out["applied_ids"] == []
def test_p1_self_conflict_produces_detectable_duplicate() -> None:
# Corpus f6439692: overlapping suggestions (conflict_group=null) both add
# "you're" -> "fire, you're you're gasoline". The apply engine mirrors the
# UI (both apply); find_suspicious_duplicates must catch the result.
s1 = _sug("insert_after", ["w3"], "you're", id="a")
s2 = _sug("replace", ["w3"], "fire, you're", id="b")
out = apply_all_suggestions(_segments(), [s1, s2])
dups = find_suspicious_duplicates(out["segments"], {})
assert "you're" in dups
def test_duplicates_supported_by_reference_are_ok() -> None:
segments = [{
"id": "s0", "text": "hey hey you",
"words": [_word("w0", "hey", 0.0, 0.2), _word("w1", "hey", 0.2, 0.4),
_word("w2", "you", 0.4, 0.6)],
"start_time": 0.0, "end_time": 0.6,
}]
refs = {"genius": {"segments": [{"text": "Hey hey you"}]}}
assert find_suspicious_duplicates(segments, refs) == []
assert find_suspicious_duplicates(segments, {}) == ["hey"]
@@ -0,0 +1,248 @@
"""Tests for the Phase-2B 3-stem backing decider (scorer branch + executor gating).
Comparison fixtures mirror the real corpus signal profiles (private
validate_backing_decider.py table, 2026-08-28): the catastrophic
backing-stem-is-the-lead job (1d45b286), the noise-floor grungegaze job
(95d8e844), the quiet-genuine-harmonies job (d508adb6), and the high-corr
genuine keep that must NOT trip the lead gate (33453fa0).
"""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any, Dict, Optional
from unittest.mock import MagicMock, patch
import pytest
from backend.services.auto_approval.models import BackingVerdict
from backend.services.auto_approval.scorer import extract_backing_signals, score_backing
def _analysis(
audible_percentage: float = 25.0,
loud: int = 2,
comparison: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
segments = [
{
"start_seconds": 10.0 * i,
"end_seconds": 10.0 * i + 5.0,
"duration_seconds": 5.0,
"avg_amplitude_db": -15.0 if i < loud else -35.0,
"peak_amplitude_db": -10.0,
}
for i in range(4)
]
data: Dict[str, Any] = {
"has_audible_content": True,
"audible_percentage": audible_percentage,
"audible_segments": segments,
"recommended_selection": "with_backing",
}
if comparison is not None:
data["stem_comparison"] = comparison
return data
def _comparison(**overrides: Any) -> Dict[str, Any]:
base = {
"window_ms": 100,
"silence_threshold_db": -40.0,
"duration_seconds": 200.0,
"backing_audible_fraction": 0.30,
"lead_audible_fraction": 0.65,
"vocals_audible_fraction": 0.70,
"coverage_ratio": 0.43,
"corr_backing_vocals": 0.40,
"corr_backing_lead": 0.20,
"backing_median_db": -26.0,
"lead_median_db": -18.0,
"vocals_median_db": -17.0,
"lead_overlap_fraction": 0.80,
"backing_db_std": 4.5,
"flat_fraction": 0.05,
"error": None,
}
base.update(overrides)
return base
def test_genuine_backing_is_confident_keep() -> None:
result = score_backing(_analysis(comparison=_comparison()))
assert result.verdict == BackingVerdict.WITH_BACKING
assert result.non_subjective is True
def test_no_comparison_stays_review() -> None:
result = score_backing(_analysis())
assert result.verdict == BackingVerdict.REVIEW
assert result.non_subjective is False
def test_errored_comparison_reads_as_absent() -> None:
result = score_backing(
_analysis(comparison=_comparison(error="boom"))
)
assert result.verdict == BackingVerdict.REVIEW
assert result.signals.comparison_present is False
def test_backing_stem_is_lead_never_keeps() -> None:
# 1d45b286 profile: covR 0.94, corr 0.95, backing 60% vs lead 18%.
result = score_backing(
_analysis(
audible_percentage=60.0,
comparison=_comparison(
coverage_ratio=0.94,
corr_backing_vocals=0.95,
backing_audible_fraction=0.60,
lead_audible_fraction=0.18,
),
)
)
assert result.verdict == BackingVerdict.REVIEW
assert "BE the lead" in " ".join(result.reasons)
def test_high_corr_keep_with_stronger_lead_does_not_trip_lead_gate() -> None:
# 33453fa0 profile: covR 0.77 / corr 0.86 but backing (28%) < lead (34%).
result = score_backing(
_analysis(
audible_percentage=28.0,
comparison=_comparison(
coverage_ratio=0.77,
corr_backing_vocals=0.86,
backing_audible_fraction=0.28,
lead_audible_fraction=0.34,
backing_median_db=-33.0,
),
)
)
assert result.verdict == BackingVerdict.WITH_BACKING
def test_noise_floor_signature_is_review() -> None:
# 95d8e844 profile: median -38.6 dB over 30% of the track, corr -0.23.
result = score_backing(
_analysis(
audible_percentage=30.0,
comparison=_comparison(
backing_median_db=-38.6,
backing_audible_fraction=0.30,
corr_backing_vocals=-0.23,
coverage_ratio=0.42,
),
)
)
assert result.verdict == BackingVerdict.REVIEW
assert "noise-floor" in " ".join(result.reasons)
def test_quiet_sparse_harmonies_still_keep() -> None:
# d508adb6 profile: 1% audible at -38 dB, overlap 0.89 — genuine harmonies.
result = score_backing(
_analysis(
audible_percentage=1.0,
loud=1,
comparison=_comparison(
backing_median_db=-38.1,
backing_audible_fraction=0.01,
corr_backing_vocals=0.19,
coverage_ratio=0.01,
lead_overlap_fraction=0.89,
),
)
)
assert result.verdict == BackingVerdict.WITH_BACKING
def test_sparse_full_lead_overlap_is_bleed_review() -> None:
result = score_backing(
_analysis(
audible_percentage=2.0,
comparison=_comparison(
backing_audible_fraction=0.02,
coverage_ratio=0.03,
lead_overlap_fraction=0.99,
),
)
)
assert result.verdict == BackingVerdict.REVIEW
assert "bleed" in " ".join(result.reasons)
def test_near_silent_rule_still_wins_over_comparison() -> None:
analysis = _analysis(audible_percentage=0.1, comparison=_comparison())
analysis["audible_segments"] = []
result = score_backing(analysis)
assert result.verdict == BackingVerdict.CLEAN
def test_comparison_signals_extracted() -> None:
s = extract_backing_signals(_analysis(comparison=_comparison()))
assert s.comparison_present is True
assert s.coverage_ratio == 0.43
assert s.corr_backing_vocals == 0.40
assert s.lead_overlap_fraction == 0.80
assert s.backing_median_db == -26.0
assert s.flat_fraction == 0.05
# ---- executor gating for WITH_BACKING enforcement ----
from backend.models.job import JobStatus # noqa: E402
from backend.tests.services.auto_approval.test_executor import ( # noqa: E402
_confident_corrections,
_job,
_run,
)
def _keep_backing_analysis() -> Dict[str, Any]:
return _analysis(comparison=_comparison())
def _keep_job(with_backing_stem: bool = True) -> SimpleNamespace:
job = _job(backing=_keep_backing_analysis())
if with_backing_stem:
job.file_urls["stems"]["instrumental_with_backing"] = (
"jobs/j1/stems/instrumental_with_backing.flac"
)
return job
def _settings(keep_enabled: bool) -> SimpleNamespace:
return SimpleNamespace(
auto_approval_enforce_enabled=True,
auto_approval_backing_keep_enabled=keep_enabled,
)
@pytest.mark.asyncio
async def test_confident_keep_blocked_while_flag_off() -> None:
result, job_manager, *_ = await _run(_keep_job(), settings=_settings(False))
assert result["outcome"] == "review"
assert "backing_keep_disabled" in result["blockers"]
payload = job_manager.update_processing_metadata.call_args[0][2]
assert payload["backing"]["verdict"] == "with_backing"
@pytest.mark.asyncio
async def test_confident_keep_enforced_when_flag_on() -> None:
result, job_manager, _storage, worker = await _run(
_keep_job(), settings=_settings(True)
)
assert result["outcome"] == "auto_completed"
job_manager.update_state_data.assert_any_call(
"j1", "instrumental_selection", "with_backing"
)
worker.trigger_render_video_worker.assert_awaited_once()
@pytest.mark.asyncio
async def test_confident_keep_needs_with_backing_stem() -> None:
result, *_ = await _run(
_keep_job(with_backing_stem=False), settings=_settings(True)
)
assert result["outcome"] == "review"
assert "no_with_backing_stem" in result["blockers"]
@@ -0,0 +1,364 @@
"""Tests for the auto-approval executor.
The executor must (a) record a verdict on every scored job, (b) complete the
review end-to-end ONLY when fully confident and eligible, and (c) fail safe —
any anomaly or error leaves the job on the normal human-review path.
"""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any, Dict, List, Optional
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import JobStatus
from backend.services.auto_approval.executor import maybe_auto_complete_review
def _confident_corrections() -> Dict[str, Any]:
words = [
{"id": f"w{i}", "text": f"word{i}", "start_time": i * 0.5, "end_time": i * 0.5 + 0.4}
for i in range(20)
]
return {
"corrected_segments": [{
"id": "s0",
"text": " ".join(w["text"] for w in words),
"words": words,
"start_time": 0.0,
"end_time": 10.0,
}],
"corrections": [],
"corrections_made": 0,
"reference_lyrics": {"spotify": {"metadata": {"is_synced": True}, "segments": []}},
"anchor_sequences": [{"id": "a0", "transcribed_word_ids": [w["id"] for w in words]}],
"gap_sequences": [],
"metadata": {"total_words": 20, "agentic_routing": "disabled", "correction_type": "none"},
}
def _clean_backing() -> Dict[str, Any]:
return {
"has_audible_content": False,
"audible_percentage": 0.0,
"audible_segments": [],
"recommended_selection": "clean",
}
def _job(
status: JobStatus = JobStatus.GENERATING_SCREENS,
review_mode: str = "auto",
made_for_you: bool = False,
audio_complete: bool = True,
backing: Optional[Dict[str, Any]] = None,
existing_instrumental: Optional[str] = None,
state_extra: Optional[Dict[str, Any]] = None,
) -> SimpleNamespace:
state: Dict[str, Any] = {"audio_complete": audio_complete}
if backing is not None:
state["backing_vocals_analysis"] = backing
state.update(state_extra or {})
return SimpleNamespace(
status=status,
state_data=state,
review_mode=review_mode,
made_for_you=made_for_you,
existing_instrumental_gcs_path=existing_instrumental,
file_urls={"stems": {"instrumental_clean": "jobs/j1/stems/clean.flac"}},
)
def _settings(enforce: bool = True) -> SimpleNamespace:
return SimpleNamespace(auto_approval_enforce_enabled=enforce)
async def _run(job, *, corrections=None, suggestions=None, settings=None):
"""Drive maybe_auto_complete_review with everything mocked; returns
(result, job_manager_mock, storage_mock, worker_service_mock)."""
job_manager = MagicMock()
job_manager.get_job.return_value = job
storage = MagicMock()
corrections = corrections if corrections is not None else _confident_corrections()
storage.file_exists.return_value = True
cache = {"suggestions": suggestions if suggestions is not None else []}
storage.list_files.return_value = ["jobs/j1/lyrics/auto_correct_cache/x.json"]
def _download(path: str):
if "auto_correct_cache" in path:
return cache
return corrections
storage.download_json.side_effect = _download
worker_service = MagicMock()
worker_service.trigger_render_video_worker = AsyncMock(return_value=True)
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService", return_value=storage), \
patch("backend.config.get_settings", return_value=settings or _settings()), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
return result, job_manager, storage, worker_service
@pytest.mark.asyncio
async def test_confident_job_is_auto_completed() -> None:
result, jm, storage, ws = await _run(_job(backing=_clean_backing()))
assert result["outcome"] == "auto_completed"
# corrections_updated.json saved with the auto-approval marker
upload_path, uploaded = storage.upload_json.call_args.args
assert upload_path == "jobs/j1/lyrics/corrections_updated.json"
assert uploaded["metadata"]["auto_approval"]["auto_approved"] is True
# instrumental selection stored, progress keys cleared, transitioned, render triggered
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "clean")
jm.delete_state_data_keys.assert_called_once()
transition_kwargs = jm.transition_to_state.call_args.kwargs
assert transition_kwargs["new_status"] == JobStatus.REVIEW_COMPLETE
ws.trigger_render_video_worker.assert_awaited_once_with("j1")
# verdict recorded with outcome
section, payload = jm.update_processing_metadata.call_args.args[1:3]
assert section == "auto_approval"
assert payload["outcome"] == "auto_completed"
assert payload["mode"] == "enforce"
@pytest.mark.asyncio
async def test_ai_suggestions_are_applied_in_saved_corrections() -> None:
suggestions = [{
"id": "sugA", "op": "replace", "word_ids": ["w3"], "segment_ids": ["s0"],
"original_text": "word3", "new_text": "fixed", "confidence": 0.9,
"consensus": 2, "total_models": 2, "conflict_group": None,
}]
result, jm, storage, _ = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
assert result["outcome"] == "auto_completed"
uploaded = storage.upload_json.call_args.args[1]
texts = [w["text"] for w in uploaded["corrected_segments"][0]["words"]]
assert "fixed" in texts and "word3" not in texts
assert uploaded["metadata"]["auto_approval"]["applied_suggestion_ids"] == ["sugA"]
@pytest.mark.asyncio
async def test_unconfident_job_goes_to_review_with_verdict_recorded() -> None:
audible = {"has_audible_content": True, "audible_percentage": 40.0,
"audible_segments": [{"avg_amplitude_db": -10.0}],
"recommended_selection": "with_backing"}
result, jm, storage, ws = await _run(_job(backing=audible))
assert result["outcome"] == "review"
jm.transition_to_state.assert_not_called()
storage.upload_json.assert_not_called()
ws.trigger_render_video_worker.assert_not_awaited()
payload = jm.update_processing_metadata.call_args.args[2]
assert payload["outcome"] == "review"
assert payload["mode"] == "shadow"
@pytest.mark.asyncio
async def test_always_review_mode_blocks_enforcement() -> None:
result, jm, _, _ = await _run(_job(review_mode="always_review", backing=_clean_backing()))
assert result["outcome"] == "review"
assert "review_mode:always_review" in result["blockers"]
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_made_for_you_blocks_enforcement() -> None:
result, jm, _, _ = await _run(_job(made_for_you=True, backing=_clean_backing()))
assert result["outcome"] == "review"
assert "made_for_you" in result["blockers"]
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_flag_disabled_blocks_enforcement() -> None:
result, jm, _, _ = await _run(
_job(backing=_clean_backing()), settings=_settings(enforce=False)
)
assert result["outcome"] == "review"
assert "flag_disabled" in result["blockers"]
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_incomplete_audio_blocks_enforcement() -> None:
result, jm, _, _ = await _run(_job(audio_complete=False, backing=None))
assert result["outcome"] == "review"
assert "audio_incomplete" in result["blockers"]
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_existing_instrumental_completes_with_custom_selection() -> None:
# Tenant/bulk jobs with a user-supplied instrumental have NO instrumental
# decision — confident lyrics alone auto-complete with selection="custom",
# even with NO backing analysis at all (the backing verdict is moot).
result, jm, _, _ = await _run(
_job(backing=None, existing_instrumental="jobs/j1/custom.flac")
)
assert result["outcome"] == "auto_completed"
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "custom")
payload = jm.update_processing_metadata.call_args.args[2]
assert payload["enforcement_basis"] == "lyrics_only_custom_instrumental"
assert payload["custom_instrumental"] is True
@pytest.mark.asyncio
async def test_custom_instrumental_stem_also_selects_custom() -> None:
job = _job(backing=None)
job.file_urls["stems"]["custom_instrumental"] = "jobs/j1/stems/custom.flac"
# No separated instrumental required for custom jobs.
del job.file_urls["stems"]["instrumental_clean"]
result, jm, _, _ = await _run(job)
assert result["outcome"] == "auto_completed"
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "custom")
@pytest.mark.asyncio
async def test_existing_instrumental_still_requires_confident_lyrics() -> None:
corrections = _confident_corrections()
corrections["reference_lyrics"] = {} # no references -> lyrics review
result, jm, _, _ = await _run(
_job(backing=None, existing_instrumental="jobs/j1/custom.flac"),
corrections=corrections,
)
assert result["outcome"] == "review"
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_wrong_status_is_noop() -> None:
result, jm, _, _ = await _run(_job(status=JobStatus.IN_REVIEW, backing=_clean_backing()))
assert result["outcome"] == "wrong_status"
jm.update_processing_metadata.assert_not_called()
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_existing_selection_is_noop() -> None:
result, jm, _, _ = await _run(
_job(backing=_clean_backing(), state_extra={"instrumental_selection": "clean"})
)
assert result["outcome"] == "already_selected"
jm.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_stale_suggestion_aborts_to_review() -> None:
suggestions = [{
"id": "sugA", "op": "replace", "word_ids": ["not-a-word"], "segment_ids": ["s0"],
"original_text": "x", "new_text": "y", "confidence": 0.9,
"consensus": 2, "total_models": 2, "conflict_group": None,
}]
result, jm, storage, ws = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
assert result["outcome"] == "aborted"
assert "stale_suggestions" in result["reason"]
jm.transition_to_state.assert_not_called()
storage.upload_json.assert_not_called()
ws.trigger_render_video_worker.assert_not_awaited()
payload = jm.update_processing_metadata.call_args.args[2]
assert payload["outcome"] == "aborted"
@pytest.mark.asyncio
async def test_duplicate_word_artifact_aborts_to_review() -> None:
# P1 self-conflict: two overlapping suggestions both add the same token.
suggestions = [
{"id": "a", "op": "insert_after", "word_ids": ["w3"], "segment_ids": ["s0"],
"original_text": "", "new_text": "extra", "confidence": 0.75,
"consensus": 1, "total_models": 2, "conflict_group": None},
{"id": "b", "op": "replace", "word_ids": ["w4"], "segment_ids": ["s0"],
"original_text": "word4", "new_text": "extra word4", "confidence": 0.95,
"consensus": 1, "total_models": 2, "conflict_group": None},
]
result, jm, storage, _ = await _run(_job(backing=_clean_backing()), suggestions=suggestions)
assert result["outcome"] == "aborted"
assert "duplicate_words" in result["reason"]
jm.transition_to_state.assert_not_called()
storage.upload_json.assert_not_called()
@pytest.mark.asyncio
async def test_state_change_during_enforce_aborts() -> None:
# A human opening the editor between the snapshot read and the enforce
# writes (AWAITING_REVIEW -> IN_REVIEW) must abort — IN_REVIEW ->
# REVIEW_COMPLETE is a legal transition, so validation alone won't stop it.
eligible = _job(backing=_clean_backing())
editing = _job(status=JobStatus.IN_REVIEW, backing=_clean_backing())
job_manager = MagicMock()
job_manager.get_job.side_effect = [eligible, editing]
storage = MagicMock()
storage.file_exists.return_value = True
storage.list_files.return_value = []
storage.download_json.return_value = _confident_corrections()
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService", return_value=storage), \
patch("backend.config.get_settings", return_value=_settings()):
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
assert result["outcome"] == "aborted"
assert result["reason"] == "state_changed_during_enforce"
job_manager.transition_to_state.assert_not_called()
storage.upload_json.assert_not_called()
@pytest.mark.asyncio
async def test_missing_corrections_is_noop() -> None:
job_manager = MagicMock()
job_manager.get_job.return_value = _job(backing=_clean_backing())
storage = MagicMock()
storage.file_exists.return_value = False
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService", return_value=storage), \
patch("backend.config.get_settings", return_value=_settings()):
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
assert result["outcome"] == "no_corrections"
job_manager.transition_to_state.assert_not_called()
@pytest.mark.asyncio
async def test_any_exception_is_nonfatal() -> None:
job_manager = MagicMock()
job_manager.get_job.side_effect = Exception("firestore down")
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService", MagicMock()), \
patch("backend.config.get_settings", return_value=_settings()):
result = await maybe_auto_complete_review("j1", trigger="screens_worker")
assert result["outcome"] == "error"
def _audible_backing() -> Dict[str, Any]:
# Pink backing present, no 3-stem comparison -> scorer verdict REVIEW.
return {
"has_audible_content": True,
"audible_percentage": 40.0,
"audible_segments": [{"avg_amplitude_db": -10.0}],
"recommended_selection": "with_backing",
}
@pytest.mark.asyncio
async def test_backing_preference_clean_forces_clean_completion() -> None:
# Backing is subjective (would normally gate), but the user chose "clean"
# up-front -> auto-complete on lyrics alone with a clean instrumental.
job = _job(backing=_audible_backing())
job.backing_preference = "clean"
result, jm, storage, ws = await _run(job)
assert result["outcome"] == "auto_completed"
jm.update_state_data.assert_any_call("j1", "instrumental_selection", "clean")
ws.trigger_render_video_worker.assert_awaited_once_with("j1")
payload = jm.update_processing_metadata.call_args.args[2]
assert payload["enforcement_basis"] == "lyrics_auto_backing_pref:clean"
@pytest.mark.asyncio
async def test_backing_preference_review_blocks_even_confident_clean() -> None:
# User wants to always pick the instrumental -> never auto-skip the backing half.
job = _job(backing=_clean_backing())
job.backing_preference = "review"
result, jm, _, ws = await _run(job)
assert result["outcome"] == "review"
jm.transition_to_state.assert_not_called()
ws.trigger_render_video_worker.assert_not_awaited()
@@ -0,0 +1,193 @@
"""Tests for the shared instrumental-decision helper (workstream C).
``backing_decision`` is the single source of truth used by the executor, the
complete-review "auto" resolver, and the per-screen-skip UI summary — they must
all agree, so the matrix is pinned here.
"""
from __future__ import annotations
from types import SimpleNamespace
from backend.services.auto_approval.instrumental import (
auto_approval_summary,
backing_decision,
has_custom_instrumental,
resolve_auto_instrumental,
)
def _decide(**kw):
base = dict(
backing_verdict="clean",
backing_non_subjective=True,
backing_preference="auto",
backing_keep_enabled=True,
custom_instrumental=False,
)
base.update(kw)
return backing_decision(**base)
# ---- backing_decision matrix ------------------------------------------------
def test_custom_instrumental_always_custom():
d = _decide(custom_instrumental=True, backing_verdict="review", backing_non_subjective=False)
assert d == {"ok": True, "selection": "custom", "keep_backing": False}
def test_clean_verdict_auto_resolves_clean():
assert _decide(backing_verdict="clean")["selection"] == "clean"
assert _decide(backing_verdict="clean")["ok"] is True
def test_with_backing_verdict_keep_enabled_resolves_with_backing():
d = _decide(backing_verdict="with_backing", backing_keep_enabled=True)
assert d == {"ok": True, "selection": "with_backing", "keep_backing": True}
def test_with_backing_verdict_keep_disabled_not_resolvable():
d = _decide(backing_verdict="with_backing", backing_keep_enabled=False)
assert d["ok"] is False and d["selection"] is None and d["keep_backing"] is True
def test_review_verdict_not_resolvable():
d = _decide(backing_verdict="review", backing_non_subjective=False)
assert d["ok"] is False and d["selection"] is None
def test_preference_clean_forces_clean_even_over_review_verdict():
# User explicitly asked to strip backing vocals -> clean regardless of verdict.
d = _decide(backing_verdict="review", backing_non_subjective=False, backing_preference="clean")
assert d == {"ok": True, "selection": "clean", "keep_backing": False}
def test_preference_clean_overrides_with_backing_verdict():
d = _decide(backing_verdict="with_backing", backing_preference="clean")
assert d["selection"] == "clean" and d["keep_backing"] is False
def test_preference_review_suppresses_even_confident_clean():
# User always wants to pick the instrumental themselves.
d = _decide(backing_verdict="clean", backing_preference="review")
assert d["ok"] is False and d["selection"] is None
def test_unknown_preference_falls_back_to_auto():
assert _decide(backing_verdict="clean", backing_preference="garbage")["selection"] == "clean"
# ---- has_custom_instrumental ------------------------------------------------
def test_has_custom_instrumental_from_existing_path():
job = SimpleNamespace(existing_instrumental_gcs_path="jobs/j/inst.flac", file_urls=None)
assert has_custom_instrumental(job) is True
def test_has_custom_instrumental_from_stem():
job = SimpleNamespace(
existing_instrumental_gcs_path=None,
file_urls={"stems": {"custom_instrumental": "jobs/j/custom.flac"}},
)
assert has_custom_instrumental(job) is True
def test_has_custom_instrumental_false():
job = SimpleNamespace(
existing_instrumental_gcs_path=None,
file_urls={"stems": {"instrumental_clean": "jobs/j/clean.flac"}},
)
assert has_custom_instrumental(job) is False
# ---- summary + resolver over stored verdict ---------------------------------
def _job_with_verdict(backing_verdict, non_subjective, lyrics_verdict="auto", pref="auto",
custom=False, review_mode="auto", stems=None):
if stems is None:
stems = {
"instrumental_clean": "jobs/j/clean.flac",
"instrumental_with_backing": "jobs/j/backing.flac",
}
return SimpleNamespace(
processing_metadata={
"auto_approval": {
"backing": {"verdict": backing_verdict, "non_subjective": non_subjective},
"lyrics": {"verdict": lyrics_verdict},
}
},
backing_preference=pref,
review_mode=review_mode,
existing_instrumental_gcs_path=("jobs/j/inst.flac" if custom else None),
file_urls={"stems": stems},
)
def _settings(keep=True):
return SimpleNamespace(auto_approval_backing_keep_enabled=keep)
def test_summary_confident_clean():
s = auto_approval_summary(_job_with_verdict("clean", True), _settings())
assert s["backing"] == {"verdict": "clean", "confident": True, "resolved_selection": "clean"}
assert s["lyrics"] == {"verdict": "auto", "confident": True}
assert s["verdict_present"] is True
def test_summary_backing_needs_review_not_confident():
s = auto_approval_summary(_job_with_verdict("review", False), _settings())
assert s["backing"]["confident"] is False
assert s["backing"]["resolved_selection"] is None
def test_summary_no_verdict_is_safe_default():
job = SimpleNamespace(processing_metadata={}, backing_preference="auto",
existing_instrumental_gcs_path=None, file_urls={"stems": {}})
s = auto_approval_summary(job, _settings())
assert s["verdict_present"] is False
assert s["backing"]["confident"] is False
assert s["lyrics"]["confident"] is False
def test_resolve_auto_instrumental_with_backing_gated():
# keep disabled -> not resolvable
assert resolve_auto_instrumental(_job_with_verdict("with_backing", True), _settings(keep=False)) is None
# keep enabled -> with_backing
assert resolve_auto_instrumental(_job_with_verdict("with_backing", True), _settings(keep=True)) == "with_backing"
def test_resolve_auto_instrumental_custom():
assert resolve_auto_instrumental(_job_with_verdict("review", False, custom=True), _settings()) == "custom"
def test_always_review_never_confident():
# review_mode="always_review" -> the user wants every screen; nothing skips.
s = auto_approval_summary(_job_with_verdict("clean", True, review_mode="always_review"), _settings())
assert s["backing"]["confident"] is False
assert s["backing"]["resolved_selection"] is None
assert s["lyrics"]["confident"] is False
assert resolve_auto_instrumental(
_job_with_verdict("clean", True, review_mode="always_review"), _settings()) is None
def test_resolve_returns_none_when_clean_stem_absent():
# Confident clean verdict but the clean stem isn't present -> a human must pick.
job = _job_with_verdict("clean", True, stems={"instrumental_with_backing": "x"})
assert resolve_auto_instrumental(job, _settings()) is None
assert auto_approval_summary(job, _settings())["backing"]["confident"] is False
def test_resolve_returns_none_when_with_backing_stem_absent():
job = _job_with_verdict("with_backing", True, stems={"instrumental_clean": "x"})
assert resolve_auto_instrumental(job, _settings(keep=True)) is None
# ---- JobCreate coercion (typo must never silently flip intent) ---------------
def test_jobcreate_coerces_out_of_set_preferences():
from backend.models.job import JobCreate
assert JobCreate(backing_preference="cleen").backing_preference == "auto"
assert JobCreate(backing_preference="clean").backing_preference == "clean"
# review_mode fails safe toward MORE review, never toward auto-skip.
assert JobCreate(review_mode="typo").review_mode == "always_review"
assert JobCreate(review_mode="auto").review_mode == "auto"
assert JobCreate().backing_preference == "auto" and JobCreate().review_mode == "auto"
@@ -0,0 +1,106 @@
"""Tests for the review-diff reconstruction."""
from __future__ import annotations
from typing import Any, Dict, List
from backend.services.auto_approval.lyrics_diff import compute_lyrics_diff
def _w(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
return {"id": wid, "text": text, "start_time": start, "end_time": end}
def _seg(sid: str, words: List[Dict[str, Any]]) -> Dict[str, Any]:
return {
"id": sid,
"text": " ".join(w["text"] for w in words),
"words": words,
"start_time": words[0]["start_time"] if words else 0.0,
"end_time": words[-1]["end_time"] if words else 0.0,
}
def _doc(segments: List[Dict[str, Any]], corrections: List[Any] | None = None) -> Dict[str, Any]:
return {"corrected_segments": segments, "corrections": corrections or []}
def test_no_updated_data_means_no_changes() -> None:
orig = _doc([_seg("s0", [_w("w0", "hello", 0.0, 0.5)])])
diff = compute_lyrics_diff(orig, None)
assert diff.has_changes is False
assert diff.total_changes == 0
assert diff.final_word_count == 1
def test_text_edit_detected() -> None:
orig = _doc([_seg("s0", [_w("w0", "helo", 0.0, 0.5), _w("w1", "wrld", 0.5, 1.0)])])
final = _doc([_seg("s0", [_w("w0", "hello", 0.0, 0.5), _w("w1", "world", 0.5, 1.0)])])
diff = compute_lyrics_diff(orig, final)
assert diff.total_changes == 2
assert {e.final_text for e in diff.text_edits} == {"hello", "world"}
assert not diff.timing_changes
def test_replacement_paired_by_timing() -> None:
# UI re-keys a corrected word but keeps its start/end/line -> should pair as replacement.
orig = _doc([_seg("s0", [_w("wA", "Carl", 231.18, 231.80)])])
final = _doc([_seg("s0", [_w("wB", "Karl", 231.18, 231.80)])])
diff = compute_lyrics_diff(orig, final)
assert diff.total_changes == 1
assert len(diff.replacements) == 1
assert not diff.deletions and not diff.insertions
r = diff.replacements[0]
assert (r.original_text, r.final_text) == ("Carl", "Karl")
assert r.original_word_id == "wA" and r.final_word_id == "wB"
def test_replacement_not_paired_when_timing_differs() -> None:
# Different timing -> genuine delete + insert, not a replacement.
orig = _doc([_seg("s0", [_w("wA", "Carl", 231.18, 231.80)])])
final = _doc([_seg("s0", [_w("wB", "Karl", 10.0, 10.5)])])
diff = compute_lyrics_diff(orig, final)
assert not diff.replacements
assert [d.text for d in diff.deletions] == ["Carl"]
assert [i.text for i in diff.insertions] == ["Karl"]
def test_timing_change_respects_epsilon() -> None:
orig = _doc([_seg("s0", [_w("w0", "hey", 1.000, 1.500)])])
# start moved 0.2s (significant), end moved 0.001s (noise, below epsilon)
final = _doc([_seg("s0", [_w("w0", "hey", 1.200, 1.501)])])
diff = compute_lyrics_diff(orig, final)
assert len(diff.timing_changes) == 1
tc = diff.timing_changes[0]
assert tc.start_delta == 0.2
assert not diff.text_edits
def test_deletion_and_insertion() -> None:
orig = _doc([_seg("s0", [_w("w0", "one", 0.0, 0.5), _w("w1", "two", 0.5, 1.0)])])
final = _doc([_seg("s0", [_w("w0", "one", 0.0, 0.5), _w("w2", "three", 1.0, 1.5)])])
diff = compute_lyrics_diff(orig, final)
assert [d.text for d in diff.deletions] == ["two"]
assert [i.text for i in diff.insertions] == ["three"]
assert diff.total_changes == 2
def test_split_detected_as_segmentation_change() -> None:
orig = _doc([_seg("s0", [_w("w0", "a", 0.0, 0.5), _w("w1", "b", 0.5, 1.0)])])
# Same words, now on two lines -> segment move for w1 + segment count change.
final = _doc([
_seg("s0", [_w("w0", "a", 0.0, 0.5)]),
_seg("s1", [_w("w1", "b", 0.5, 1.0)]),
])
diff = compute_lyrics_diff(orig, final)
assert diff.segmentation_changed is True
assert len(diff.segment_moves) == 1
assert diff.segment_moves[0].word_id == "w1"
assert diff.original_segment_count == 1
assert diff.final_segment_count == 2
def test_clean_unedited_job_yields_empty_diff() -> None:
seg = [_seg("s0", [_w("w0", "same", 0.0, 0.5)])]
diff = compute_lyrics_diff(_doc(seg), _doc(seg))
assert diff.has_changes is False
assert diff.total_changes == 0
@@ -0,0 +1,208 @@
"""Tests for the server-side pre-apply (workstream C, C2).
``ensure_and_pre_apply`` applies the cached AI suggestions BEFORE the review-ready
notification and writes ``corrections_updated.json`` with a ``pre_applied`` marker.
It is best-effort: any miss leaves corrections_updated absent so the review UI falls
back to its client-side on-load auto-apply.
"""
from __future__ import annotations
from typing import Any, Dict, List
from unittest.mock import MagicMock, patch
import pytest
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
def _corrections() -> Dict[str, Any]:
words = [
{"id": f"w{i}", "text": t, "start_time": i * 0.5, "end_time": i * 0.5 + 0.4}
for i, t in enumerate(["an", "amateur", "here"])
]
return {
"corrected_segments": [{
"id": "s0",
"text": "an amateur here",
"words": words,
"start_time": 0.0,
"end_time": 2.0,
}],
"reference_lyrics": {"spotify": {"segments": []}},
"metadata": {"total_words": 3},
}
def _replace_suggestion() -> Dict[str, Any]:
# Replace "an amateur" -> "not much" (op=replace on the first two words).
return {
"id": "sug1",
"op": "replace",
"segment_ids": ["s0"],
"word_ids": ["w0", "w1"],
"original_text": "an amateur",
"new_text": "not much",
"category": "mishearing",
"confidence": 0.95,
"models": ["m1"],
"consensus": 1,
"total_models": 1,
}
class _FakeStorage:
def __init__(self, files: Dict[str, Any]):
self._files = dict(files)
self.uploads: Dict[str, Any] = {}
def file_exists(self, path: str) -> bool:
return path in self._files
def download_json(self, path: str):
return self._files[path]
def list_files(self, prefix: str) -> List[str]:
return [p for p in self._files if p.startswith(prefix)]
def upload_json(self, path: str, data: Any, if_generation_match=None):
# Model create-only semantics: if_generation_match=0 fails when the object
# already exists (mirrors GCS raising PreconditionFailed).
if if_generation_match == 0 and path in self._files:
from google.api_core.exceptions import PreconditionFailed
raise PreconditionFailed("object exists")
self.uploads[path] = data
self._files[path] = data
async def _run(storage, *, proactive=True, generate_on_miss=True):
settings = MagicMock(auto_correct_proactive_enabled=proactive)
jm = MagicMock()
generated = {"called": False}
async def _fake_generate(job_id):
generated["called"] = True
return {"status": "generated"}
with patch("backend.config.get_settings", return_value=settings), \
patch("backend.services.storage_service.StorageService", return_value=storage), \
patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.workers.auto_correct_worker.process_proactive_auto_correct", _fake_generate):
result = await ensure_and_pre_apply("j1", generate_on_miss=generate_on_miss)
return result, jm, generated
CORR = "jobs/j1/lyrics/corrections.json"
UPD = "jobs/j1/lyrics/corrections_updated.json"
CACHE = "jobs/j1/lyrics/auto_correct_cache/x.json"
@pytest.mark.asyncio
async def test_pre_apply_writes_marker_and_applies():
storage = _FakeStorage({
CORR: _corrections(),
CACHE: {"suggestions": [_replace_suggestion()]},
})
result, jm, _gen = await _run(storage)
assert result["outcome"] == "pre_applied"
assert result["applied"] == 1
written = storage.uploads[UPD]
aa = written["metadata"]["auto_approval"]
assert aa["pre_applied"] is True
assert aa["applied_suggestion_ids"] == ["sug1"]
assert aa["suggestions"] # carried for the UI panel
# The correction was actually applied to the segments.
assert "not much" in written["corrected_segments"][0]["text"]
jm.update_file_url.assert_called_once()
@pytest.mark.asyncio
async def test_pre_apply_empty_suggestions_still_marks():
# Known-empty cache: mark pre_applied so the UI doesn't run client-side.
storage = _FakeStorage({CORR: _corrections(), CACHE: {"suggestions": []}})
result, _, _gen = await _run(storage)
assert result["outcome"] == "pre_applied"
assert result["applied"] == 0
assert storage.uploads[UPD]["metadata"]["auto_approval"]["pre_applied"] is True
@pytest.mark.asyncio
async def test_pre_apply_no_cache_and_proactive_disabled_is_noop():
# No cache + proactive off -> unknown suggestion set -> do NOT mark (fall back).
storage = _FakeStorage({CORR: _corrections()})
result, _, _gen = await _run(storage, proactive=False)
assert result["outcome"] == "skipped"
assert result["reason"] == "no_suggestions_cache"
assert UPD not in storage.uploads
@pytest.mark.asyncio
async def test_pre_apply_skips_when_already_applied():
storage = _FakeStorage({
CORR: _corrections(),
UPD: {"metadata": {"auto_approval": {"auto_approved": True}}},
CACHE: {"suggestions": [_replace_suggestion()]},
})
result, _, _gen = await _run(storage)
assert result["outcome"] == "skipped"
assert result["reason"] == "already_applied"
@pytest.mark.asyncio
async def test_pre_apply_no_corrections_is_noop():
storage = _FakeStorage({})
result, _, _gen = await _run(storage)
assert result["outcome"] == "skipped"
assert result["reason"] == "no_corrections"
@pytest.mark.asyncio
async def test_load_path_applies_existing_cache_without_generating():
# generate_on_miss=False (the /correction-data load path): an existing cache is
# applied, but generation is never triggered (page must not block on an LLM call).
storage = _FakeStorage({
CORR: _corrections(),
CACHE: {"suggestions": [_replace_suggestion()]},
})
result, jm, gen = await _run(storage, generate_on_miss=False)
assert result["outcome"] == "pre_applied"
assert gen["called"] is False
assert storage.uploads[UPD]["metadata"]["auto_approval"]["pre_applied"] is True
@pytest.mark.asyncio
async def test_load_path_cache_miss_does_not_generate_or_mark():
# No cache + proactive ON but generate_on_miss=False -> no generation, no marker;
# the UI falls back to its client-side apply (no page hang).
storage = _FakeStorage({CORR: _corrections()})
result, _, gen = await _run(storage, proactive=True, generate_on_miss=False)
assert gen["called"] is False
assert result["outcome"] == "skipped"
assert result["reason"] == "no_suggestions_cache"
assert UPD not in storage.uploads
@pytest.mark.asyncio
async def test_screens_path_generates_on_cache_miss():
# Default generate_on_miss=True (screens_worker path): generation IS triggered
# on a cache miss.
storage = _FakeStorage({CORR: _corrections()})
result, _, gen = await _run(storage, proactive=True, generate_on_miss=True)
assert gen["called"] is True
@pytest.mark.asyncio
async def test_pre_apply_raced_concurrent_write_does_not_clobber():
# A concurrent writer created corrections_updated.json AFTER our existence check
# (invisible to the check, present for the create-only upload) -> theirs wins.
storage = _FakeStorage({
CORR: _corrections(),
CACHE: {"suggestions": [_replace_suggestion()]},
UPD: {"metadata": {}, "corrected_segments": [{"id": "s0", "words": [{"id": "x"}]}]},
})
orig_exists = storage.file_exists
storage.file_exists = lambda p: False if p == UPD else orig_exists(p)
result, _, _gen = await _run(storage)
assert result["outcome"] == "skipped"
assert result["reason"] == "raced_concurrent_write"
# The concurrent writer's content is untouched.
assert storage._files[UPD]["metadata"] == {}
@@ -0,0 +1,364 @@
"""Tests for the auto-approvability scorer.
These fixtures mirror the shape of a production ``corrections.json`` built by the
uncorrected controller path (auto-correction disabled): ``corrections_made == 0``,
``confidence == 1.0``, but anchors/gaps/reference_lyrics still populated.
"""
from __future__ import annotations
from typing import Any, Dict, List
from backend.services.auto_approval.models import BackingVerdict, LyricsVerdict
from backend.services.auto_approval.scorer import (
score_backing,
score_job,
score_lyrics,
)
def _word(wid: str, text: str) -> Dict[str, Any]:
return {"id": wid, "text": text, "start_time": 0.0, "end_time": 0.5}
def _segments(n_words: int) -> List[Dict[str, Any]]:
words = [_word(f"w{i}", f"word{i}") for i in range(n_words)]
return [{"id": "s0", "text": " ".join(w["text"] for w in words),
"words": words, "start_time": 0.0, "end_time": 10.0}]
def _corrections_json(
n_words: int = 20,
anchor_words: int = 20,
gap_words: int = 0,
synced: bool = True,
sources: List[str] | None = None,
) -> Dict[str, Any]:
sources = sources if sources is not None else ["spotify", "genius"]
anchor_seq = [{"id": "a0", "transcribed_word_ids": [f"w{i}" for i in range(anchor_words)]}]
gap_seq = (
[{"id": "g0", "transcribed_word_ids": [f"w{i}" for i in range(anchor_words, anchor_words + gap_words)]}]
if gap_words
else []
)
reference_lyrics = {
src: {"metadata": {"is_synced": synced}, "segments": [], "source": src}
for src in sources
}
return {
"corrected_segments": _segments(n_words),
"corrections": [],
"corrections_made": 0,
"confidence": 1.0, # the trap — must not drive AUTO
"reference_lyrics": reference_lyrics,
"anchor_sequences": anchor_seq,
"gap_sequences": gap_seq,
"metadata": {
"correction_type": "none",
"reason": "correction_disabled",
"agentic_routing": "disabled",
"total_words": n_words,
"anchor_sequences_count": len(anchor_seq),
"gap_sequences_count": len(gap_seq),
},
}
# --- Lyrics ---
def test_synced_perfect_is_auto() -> None:
res = score_lyrics(_corrections_json(anchor_words=20, gap_words=0, synced=True))
assert res.verdict == LyricsVerdict.AUTO
assert res.tier == "synced-perfect"
assert res.signals.anchor_word_fraction == 1.0
assert res.signals.uncorrected_gap_fraction == 0.0
def test_confidence_one_alone_does_not_trigger_auto() -> None:
# No reference sources at all -> confidence 1.0 must NOT yield AUTO.
data = _corrections_json(sources=[], anchor_words=0, gap_words=0)
data["anchor_sequences"] = []
res = score_lyrics(data)
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "no-reference"
def test_unsynced_reference_never_auto() -> None:
res = score_lyrics(_corrections_json(anchor_words=20, gap_words=0, synced=False))
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "near-miss"
assert not res.signals.has_synced_reference
def test_gaps_push_to_review() -> None:
# 16 anchored / 4 gap of 20 -> 80% anchor, 20% gap -> needs-review.
res = score_lyrics(_corrections_json(n_words=20, anchor_words=16, gap_words=4, synced=True))
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "needs-review"
def test_single_gap_word_blocks_auto() -> None:
# Regression for job 79c4f60c "Clarity": 241/242 anchored (99.6%), one gap word that
# was a real mis-transcription. A single unresolved gap must NOT be auto-approved.
data = _corrections_json(n_words=242, anchor_words=241, gap_words=1, synced=True)
res = score_lyrics(data)
assert res.verdict == LyricsVerdict.REVIEW
assert res.signals.gap_word_count == 1
def test_near_miss_band() -> None:
# 19 anchored / 1 gap of 20 -> 95% anchor, 5% gap: within near-miss, below AUTO.
res = score_lyrics(_corrections_json(n_words=20, anchor_words=19, gap_words=1, synced=True))
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "near-miss"
def test_too_few_words() -> None:
res = score_lyrics(_corrections_json(n_words=5, anchor_words=5, gap_words=0))
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "too-few-words"
# --- AI-resolved tier (gap words covered by auto-applied suggestions) ---
def _suggestions_for_gaps(data: Dict[str, Any]) -> List[Dict[str, Any]]:
gap_ids = [wid for seq in data["gap_sequences"] for wid in seq["transcribed_word_ids"]]
return [
{"id": f"sug{i}", "op": "replace", "word_ids": [wid], "segment_ids": ["s0"],
"original_text": "x", "new_text": "y", "confidence": 0.9,
"consensus": 2, "total_models": 2}
for i, wid in enumerate(gap_ids)
]
def test_ai_covered_gaps_are_auto_resolved() -> None:
# 95% anchored with 5 gap words, every gap covered by an auto-applied AI
# suggestion -> the post-AI state is clean -> AUTO (ai-resolved tier).
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
res = score_lyrics(data, _suggestions_for_gaps(data))
assert res.verdict == LyricsVerdict.AUTO
assert res.tier == "ai-resolved"
assert res.signals.gap_words_covered_by_ai == 5
assert res.signals.uncovered_gap_word_count == 0
assert res.signals.ai_full_consensus_count == 5
def test_uncovered_gaps_beyond_threshold_stay_review() -> None:
# 10 gaps, none covered -> 10% uncovered -> review.
data = _corrections_json(n_words=100, anchor_words=90, gap_words=10, synced=True)
res = score_lyrics(data, [])
assert res.verdict == LyricsVerdict.REVIEW
assert res.signals.uncovered_gap_word_count == 10
def test_no_suggestion_data_never_ai_resolved() -> None:
# Without the suggestion cache we can't know what the AI will fix -> the
# ai-resolved tier must not apply (only the strict zero-gap tier can).
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
res = score_lyrics(data, None)
assert res.verdict == LyricsVerdict.REVIEW
assert not res.signals.ai_suggestions_available
def test_gates_override_ai_resolution() -> None:
# Even with every gap covered, a vocalization section still gates to human.
data = _corrections_json(n_words=100, anchor_words=95, gap_words=5, synced=True)
voc = [_timed_word(f"v{i}", t, 10.0 + i * 0.4, 10.3 + i * 0.4)
for i, t in enumerate(["Da-", "da-", "dun,", "da-", "da-", "dun"])]
data = _with_extra_segment(data, voc, 10.0, 12.5)
res = score_lyrics(data, _suggestions_for_gaps(data))
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "vocalization-gate"
def test_low_anchor_never_ai_resolved() -> None:
# Heavy correction of a messy transcription (corpus f247364e: 47.6% anchor,
# nearly all gaps covered) still means likely uncaught errors -> review.
data = _corrections_json(n_words=100, anchor_words=48, gap_words=52, synced=True)
sugs = _suggestions_for_gaps(data)[:50] # 50 of 52 covered
res = score_lyrics(data, sugs)
assert res.verdict == LyricsVerdict.REVIEW
# --- Never-auto gating classes (Pattern 3 vocalizations, Pattern 8 phantoms) ---
def _timed_word(wid: str, text: str, start: float, end: float) -> Dict[str, Any]:
return {"id": wid, "text": text, "start_time": start, "end_time": end}
def _with_extra_segment(data: Dict[str, Any], words: List[Dict[str, Any]],
seg_start: float, seg_end: float,
anchored: bool = True) -> Dict[str, Any]:
"""Append a segment and (optionally) anchor its words so gates are the only blocker."""
data["corrected_segments"].append({
"id": f"s{len(data['corrected_segments'])}",
"text": " ".join(w["text"] for w in words),
"words": words,
"start_time": seg_start,
"end_time": seg_end,
})
if anchored:
data["anchor_sequences"][0]["transcribed_word_ids"].extend(w["id"] for w in words)
data["metadata"]["total_words"] += len(words)
return data
def test_vocalization_run_gates_even_when_otherwise_perfect() -> None:
# b5a7b8aa "Two Birds": lines of "Da- da- dun, da- da- dun" — anchored or not,
# the grouping/timing is a musical judgement -> never fully auto.
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
voc = [_timed_word(f"v{i}", t, 10.0 + i * 0.4, 10.3 + i * 0.4)
for i, t in enumerate(["Da-", "da-", "dun,", "da-", "da-", "dun"])]
data = _with_extra_segment(data, voc, 10.0, 12.5)
res = score_lyrics(data)
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "vocalization-gate"
assert res.signals.has_vocalization_section
assert res.signals.vocalization_max_run == 6
def test_single_very_long_vocalization_gates() -> None:
# 8f2305ee seg 35: a single "Ooh," spanning 10.1s = many vocalizations lumped into one.
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
data = _with_extra_segment(data, [_timed_word("v0", "Ooh,", 100.0, 110.1)], 100.0, 110.1)
res = score_lyrics(data)
assert res.tier == "vocalization-gate"
assert res.signals.long_vocalization_word_count == 1
def test_two_multi_second_vocalizations_gate() -> None:
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
data = _with_extra_segment(
data,
[_timed_word("v0", "Ooh,", 100.0, 104.0), _timed_word("v1", "ooh", 105.0, 109.1)],
100.0, 109.1,
)
res = score_lyrics(data)
assert res.tier == "vocalization-gate"
def test_few_normal_vocalization_words_do_not_gate() -> None:
# A couple of short "oh yeah"s in a normal song must not trip the gate.
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
data = _with_extra_segment(
data,
[_timed_word("v0", "Oh,", 50.0, 50.4), _timed_word("v1", "yeah", 50.4, 50.9)],
50.0, 50.9,
)
res = score_lyrics(data)
assert res.verdict == LyricsVerdict.AUTO
assert not res.signals.has_vocalization_section
def test_absurd_word_duration_is_phantom_gate() -> None:
# 33453fa0 "Angel": phantom "(I'm sorry)" line with a 7.4s word.
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
data = _with_extra_segment(
data, [_timed_word("p0", "sorry", 0.0, 7.4)], 0.0, 7.4,
)
res = score_lyrics(data)
assert res.verdict == LyricsVerdict.REVIEW
assert res.tier == "phantom-gate"
assert res.signals.absurd_duration_word_count == 1
assert res.signals.max_word_duration_s == 7.4
def test_stretched_short_parenthetical_is_phantom_gate() -> None:
# Short parenthetical line spanning several seconds, individual words normal-length.
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
data = _with_extra_segment(
data,
[_timed_word("p0", "(I'm", 0.0, 0.4), _timed_word("p1", "sorry)", 4.4, 4.8)],
0.0, 4.8,
)
res = score_lyrics(data)
assert res.tier == "phantom-gate"
assert res.signals.suspicious_parenthetical_count == 1
def test_normal_parenthetical_backing_bit_does_not_gate() -> None:
# Pattern 7 trailing "(Dreaming)" bits are left alone — a short parenthetical with
# a normal duration must not be treated as a phantom.
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
data = _with_extra_segment(
data, [_timed_word("p0", "(Dreaming)", 60.0, 61.2)], 60.0, 61.2,
)
res = score_lyrics(data)
assert res.verdict == LyricsVerdict.AUTO
def test_verdict_to_dict_is_json_safe() -> None:
import json
v = score_job(
_corrections_json(anchor_words=20, gap_words=0, synced=True),
{"has_audible_content": False, "audible_percentage": 0.0, "audible_segments": []},
)
d = v.to_dict()
json.dumps(d) # must not raise (enums converted to plain strings)
assert d["lyrics"]["verdict"] == "auto"
assert d["backing"]["verdict"] == "clean"
# --- Backing ---
def test_no_audible_backing_is_non_subjective_clean() -> None:
res = score_backing({"has_audible_content": False, "audible_percentage": 0.0,
"audible_segments": [], "recommended_selection": "clean"})
assert res.verdict == BackingVerdict.CLEAN
assert res.non_subjective is True
def test_near_silent_backing_is_clean() -> None:
res = score_backing({"has_audible_content": True, "audible_percentage": 0.3,
"audible_segments": [{"avg_amplitude_db": -35.0}],
"recommended_selection": "clean"})
assert res.verdict == BackingVerdict.CLEAN
assert res.non_subjective is True
def test_audible_backing_is_subjective_review() -> None:
res = score_backing({"has_audible_content": True, "audible_percentage": 42.0,
"audible_segments": [{"avg_amplitude_db": -12.0, "peak_amplitude_db": -6.0}],
"recommended_selection": "with_backing"})
assert res.verdict == BackingVerdict.REVIEW
assert res.non_subjective is False
assert res.signals.loud_segment_count == 1
def test_missing_backing_analysis_is_review() -> None:
res = score_backing(None)
assert res.verdict == BackingVerdict.REVIEW
assert res.non_subjective is False
def test_errored_backing_analysis_is_review_not_clean() -> None:
# A failed analysis stores has_audible_content=None + analysis_error; it
# must NOT read as "no audible content" (that would wrongly auto-pick clean).
res = score_backing({
"has_audible_content": None,
"analysis_error": "download failed",
"recommended_selection": "clean",
})
assert res.verdict == BackingVerdict.REVIEW
assert res.non_subjective is False
assert res.signals.analysis_present is False
# --- Combined ---
def test_overall_auto_requires_both() -> None:
v = score_job(
_corrections_json(anchor_words=20, gap_words=0, synced=True),
{"has_audible_content": False, "audible_percentage": 0.0, "audible_segments": []},
)
assert v.overall_auto is True
def test_overall_not_auto_when_backing_subjective() -> None:
v = score_job(
_corrections_json(anchor_words=20, gap_words=0, synced=True),
{"has_audible_content": True, "audible_percentage": 30.0,
"audible_segments": [{"avg_amplitude_db": -10.0}]},
)
assert v.lyrics.verdict == LyricsVerdict.AUTO
assert v.overall_auto is False
@@ -0,0 +1,105 @@
"""Tests for the pure 3-stem comparison signal extraction.
Synthesizes tiny WAVs with pydub so the signal math is exercised on real
audio decoding, not mocks.
"""
from __future__ import annotations
import os
import pytest
from pydub import AudioSegment
from pydub.generators import Sine, WhiteNoise
from karaoke_gen.instrumental_review.stem_comparison import (
StemComparison,
compare_stems,
)
def _silence(ms: int = 4000) -> AudioSegment:
return AudioSegment.silent(duration=ms, frame_rate=16000)
def _tone_bursts(ms: int = 4000, *, burst_ms: int = 500, gain_db: float = -10.0) -> AudioSegment:
"""Alternating 500ms tone / 500ms silence."""
out = AudioSegment.silent(duration=0, frame_rate=16000)
tone = Sine(440, sample_rate=16000).to_audio_segment(duration=burst_ms).apply_gain(gain_db)
quiet = AudioSegment.silent(duration=burst_ms, frame_rate=16000)
while len(out) < ms:
out += tone + quiet
return out[:ms]
def _write(tmp_path, name: str, audio: AudioSegment) -> str:
path = os.path.join(tmp_path, name)
audio.export(path, format="wav")
return path
def test_silent_backing_has_zero_fractions(tmp_path) -> None:
backing = _write(tmp_path, "b.wav", _silence())
lead = _write(tmp_path, "l.wav", _tone_bursts())
vocals = _write(tmp_path, "v.wav", _tone_bursts())
c = compare_stems(backing, lead, vocals)
assert c.error is None
assert c.backing_audible_fraction == 0.0
assert c.coverage_ratio == 0.0
assert c.lead_overlap_fraction == 0.0
assert c.lead_audible_fraction > 0.3
def test_backing_identical_to_vocals_is_high_corr_full_coverage(tmp_path) -> None:
# The backing-stem-is-the-lead shape: backing tracks the whole vocal line
# while the lead stem is empty.
bursts = _tone_bursts()
backing = _write(tmp_path, "b.wav", bursts)
lead = _write(tmp_path, "l.wav", _silence())
vocals = _write(tmp_path, "v.wav", bursts)
c = compare_stems(backing, lead, vocals)
assert c.error is None
assert c.coverage_ratio == 1.0
assert c.corr_backing_vocals > 0.95
assert c.backing_audible_fraction > c.lead_audible_fraction
assert c.lead_overlap_fraction == 0.0
def test_offset_backing_has_low_overlap_and_corr(tmp_path) -> None:
# Backing sings only in the lead's gaps (genuine call-and-response shape).
bursts = _tone_bursts()
offset = _silence(500) + bursts
backing = _write(tmp_path, "b.wav", offset[: len(bursts)])
lead = _write(tmp_path, "l.wav", bursts)
vocals = _write(tmp_path, "v.wav", bursts)
c = compare_stems(backing, lead, vocals)
assert c.error is None
assert c.corr_backing_vocals < 0.0 # anti-phase with the vocal line
assert c.lead_overlap_fraction < 0.2
def test_continuous_noise_floor_is_flat(tmp_path) -> None:
noise = WhiteNoise(sample_rate=16000).to_audio_segment(duration=8000).apply_gain(-25.0)
backing = _write(tmp_path, "b.wav", noise)
lead = _write(tmp_path, "l.wav", _tone_bursts(8000))
vocals = _write(tmp_path, "v.wav", _tone_bursts(8000))
c = compare_stems(backing, lead, vocals)
assert c.error is None
assert c.backing_audible_fraction == 1.0
assert c.flat_fraction > 0.9 # sustained low-variance content
assert c.backing_db_std < 2.5
def test_missing_file_reports_error_not_raise(tmp_path) -> None:
lead = _write(tmp_path, "l.wav", _silence(500))
c = compare_stems(os.path.join(tmp_path, "nope.wav"), lead, lead)
assert isinstance(c, StemComparison)
assert c.error is not None
def test_to_dict_round_trips_json_safe(tmp_path) -> None:
import json
p = _write(tmp_path, "a.wav", _tone_bursts(1000))
c = compare_stems(p, p, p)
payload = c.to_dict()
assert json.loads(json.dumps(payload)) == payload
@@ -0,0 +1,481 @@
"""Tests for the deterministic (no-LLM) suggestion generators + P1 conflict grouping.
Scenarios mirror the 2026-08 replay-review corpus jobs that motivated each
pattern: P4 leading-connective over-insertion (8f2305ee "And they" -> "They"),
P5 reference-majority resolution (6d0640fa "yo Mick," -> "Come here,"), and the
P1 AI self-conflict (f6439692 insert+replace both adding "you're").
"""
from __future__ import annotations
from unittest.mock import patch
from backend.services.auto_correct.deterministic import (
deterministic_suggestions,
leading_connective_suggestions,
reference_majority_suggestions,
_ref_word_streams,
)
from backend.services.auto_correct.service import (
AutoCorrectService,
Suggestion,
_assign_conflict_groups,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
def _ref_source(word_texts, prefix):
"""A reference source with ids <prefix>0, <prefix>1, ..."""
return {
"segments": [
{
"text": " ".join(word_texts),
"words": [
{"id": f"{prefix}{i}", "text": t} for i, t in enumerate(word_texts)
],
}
]
}
def _seg(seg_id, words):
return {
"id": seg_id,
"text": " ".join(t for _, t in words),
"words": [{"id": wid, "text": t} for wid, t in words],
}
# ---- Pattern 4: leading connective ----
def _p4_fixture(ref_line="They count everything", gap_ref_ids=None):
"""Segment "And they count ..." where "And" is a gap word.
The single reference reads "They count everything" — no "And" — with the
gap aligned to reference word r0 ("They") unless overridden.
"""
segments = [
_seg("seg-0", [("w0", "And"), ("w1", "they"), ("w2", "count"), ("w3", "everything")])
]
refs = {"genius": _ref_source(ref_line.split(), "r")}
correction_data = {
"gap_sequences": [
{
"id": "gap-0",
"transcribed_word_ids": ["w0"],
"reference_word_ids": {"genius": gap_ref_ids if gap_ref_ids is not None else ["r0"]},
}
],
"anchor_sequences": [],
}
return segments, refs, correction_data
def test_p4_deletes_unsupported_leading_connective_and_recapitalizes() -> None:
segments, refs, cd = _p4_fixture()
out = deterministic_suggestions(segments, refs, cd)
assert [s["op"] for s in out] == ["delete", "replace"]
delete, recap = out
assert delete["word_ids"] == ["w0"]
assert delete["new_text"] == ""
assert recap["word_ids"] == ["w1"]
assert recap["new_text"] == "They"
assert all(s["models"] == ["deterministic"] for s in out)
def test_p4_skips_when_a_reference_supports_the_connective() -> None:
segments, refs, cd = _p4_fixture(ref_line="And they count everything")
out = deterministic_suggestions(segments, refs, cd)
assert out == []
def test_p4_skips_when_no_reference_evidence() -> None:
# Gap aligned to nothing and no usable anchors -> no reading -> no delete.
segments, refs, cd = _p4_fixture(gap_ref_ids=[])
out = deterministic_suggestions(segments, refs, cd)
assert out == []
def test_p4_skips_anchored_leading_connective() -> None:
segments, refs, cd = _p4_fixture()
cd["gap_sequences"] = [] # "And" is not a gap word
assert deterministic_suggestions(segments, refs, cd) == []
def test_p4_skips_vocalization_run() -> None:
# "Oh- whoa whoa whoa" — grouping vocalizations is a musical judgement.
segments = [
_seg("seg-0", [("w0", "Oh-"), ("w1", "whoa,"), ("w2", "whoa,"), ("w3", "whoa")])
]
refs = {"genius": _ref_source(["Whoa,", "whoa,", "whoa"], "r")}
cd = {
"gap_sequences": [
{
"id": "gap-0",
"transcribed_word_ids": ["w0"],
"reference_word_ids": {"genius": ["r0"]},
}
],
"anchor_sequences": [],
}
assert deterministic_suggestions(segments, refs, cd) == []
def test_p4_skips_two_word_segment() -> None:
segments = [_seg("seg-0", [("w0", "And"), ("w1", "run")])]
refs = {"genius": _ref_source(["Run"], "r")}
cd = {
"gap_sequences": [
{"id": "g", "transcribed_word_ids": ["w0"], "reference_word_ids": {"genius": ["r0"]}}
],
"anchor_sequences": [],
}
assert deterministic_suggestions(segments, refs, cd) == []
def test_p4_already_capitalized_next_word_gets_no_recap_suggestion() -> None:
segments = [
_seg("seg-0", [("w0", "And"), ("w1", "Mary"), ("w2", "sings"), ("w3", "loud")])
]
refs = {"genius": _ref_source(["Mary", "sings", "loud"], "r")}
cd = {
"gap_sequences": [
{"id": "g", "transcribed_word_ids": ["w0"], "reference_word_ids": {"genius": ["r0"]}}
],
"anchor_sequences": [],
}
out = deterministic_suggestions(segments, refs, cd)
assert [s["op"] for s in out] == ["delete"]
# ---- Pattern 5: reference majority ----
def _p5_fixture():
"""The 6d0640fa shape: transcription "yo Mick," where genius aligned
"My man," on the gap, and lrclib/spotify (unaligned on the gap) read
"Come here," after the preceding anchor."""
segments = [
_seg(
"seg-0",
[
("w0", "Hit"),
("w1", "the"),
("w2", "button,"),
("w3", "yo"),
("w4", "Mick,"),
("w5", "come"),
("w6", "on"),
],
)
]
refs = {
"lrclib": _ref_source(["Hit", "the", "button,", "Come", "here,", "come", "on"], "l"),
"spotify": _ref_source(["Hit", "the", "button,", "Come", "here,", "come", "on"], "s"),
"genius": _ref_source(["Hit", "the", "button,", "My", "man,", "come", "on"], "g"),
}
correction_data = {
"gap_sequences": [
{
"id": "gap-0",
"transcribed_word_ids": ["w3", "w4"],
"preceding_anchor_id": "anchor-0",
"following_anchor_id": None,
"reference_word_ids": {"lrclib": [], "spotify": [], "genius": ["g3", "g4"]},
}
],
"anchor_sequences": [
{
"id": "anchor-0",
"transcribed_word_ids": ["w0", "w1", "w2"],
"reference_word_ids": {
"lrclib": ["l0", "l1", "l2"],
"spotify": ["s0", "s1", "s2"],
"genius": ["g0", "g1", "g2"],
},
}
],
}
return segments, refs, correction_data
def test_p5_replaces_implausible_proper_noun_with_majority_reading() -> None:
segments, refs, cd = _p5_fixture()
out = deterministic_suggestions(segments, refs, cd)
assert len(out) == 1
s = out[0]
assert s["op"] == "replace"
assert s["word_ids"] == ["w3", "w4"]
assert s["new_text"] == "Come here,"
assert "Mick," in s["reason"]
def test_p5_requires_the_red_flag_token() -> None:
# Same majority disagreement but the transcription is plausible lowercase
# ("though" vs 2/3 "dog") -> the human deliberately leaves these; so do we.
segments, refs, cd = _p5_fixture()
segments[0]["words"][3]["text"] = "yo"
segments[0]["words"][4]["text"] = "mick,"
assert deterministic_suggestions(segments, refs, cd) == []
def test_p5_skips_spelling_variant_of_reference_token() -> None:
# "Crick" ~ "Cricket": a truncation/spelling variant, the LLM's fix.
segments, refs, cd = _p5_fixture()
segments[0]["words"][4]["text"] = "Herre," # close to reference "here,"
assert deterministic_suggestions(segments, refs, cd) == []
def test_p5_requires_two_thirds_majority() -> None:
segments, refs, cd = _p5_fixture()
# Make spotify read something else -> no 2/3 agreement.
for w, t in zip(refs["spotify"]["segments"][0]["words"][3:5], ["Over", "there,"]):
w["text"] = t
assert deterministic_suggestions(segments, refs, cd) == []
def test_p5_ignores_segment_initial_capitalization() -> None:
# A capitalized SEGMENT-FIRST word is sentence case, not a proper noun.
segments = [_seg("seg-0", [("w0", "Mick,"), ("w1", "come"), ("w2", "on")])]
refs = {
"lrclib": _ref_source(["Quick,", "come", "on"], "l"),
"spotify": _ref_source(["Quick,", "come", "on"], "s"),
"genius": _ref_source(["Slick,", "come", "on"], "g"),
}
cd = {
"gap_sequences": [
{
"id": "gap-0",
"transcribed_word_ids": ["w0"],
"reference_word_ids": {"lrclib": ["l0"], "spotify": ["s0"], "genius": ["g0"]},
}
],
"anchor_sequences": [],
}
assert deterministic_suggestions(segments, refs, cd) == []
def test_p5_skips_stale_gap_word_ids() -> None:
segments, refs, cd = _p5_fixture()
cd["gap_sequences"][0]["transcribed_word_ids"] = ["w3", "gone"]
assert deterministic_suggestions(segments, refs, cd) == []
def test_generators_never_raise_on_garbage() -> None:
assert deterministic_suggestions([], {}, None) == []
assert deterministic_suggestions([{"weird": True}], {"x": {}}, {"gap_sequences": [{}]}) == []
# ---- Pattern 1: insert/replace self-conflict grouping ----
def _s(id_, op, word_ids, new_text, confidence=0.9, consensus=1):
return Suggestion(
id=id_,
op=op,
word_ids=word_ids,
segment_ids=["seg-0"],
original_text="fire" if op != "insert_after" else "",
new_text=new_text,
reason="r",
category="mishearing",
confidence=confidence,
models=["m"],
consensus=consensus,
total_models=1,
conflict_group=None,
)
def test_p1_insert_and_replace_adding_same_token_share_a_group() -> None:
# f6439692: insert_after "fire" -> "you're" AND replace "fire" ->
# "fire, you're" both applied -> "you're you're". Must become a conflict.
insert = _s("i", "insert_after", ["w-fire"], "you're", confidence=0.75)
replace = _s("r", "replace", ["w-fire"], "fire, you're", confidence=0.95)
suggestions = [insert, replace]
_assign_conflict_groups(suggestions)
assert insert.conflict_group is not None
assert insert.conflict_group == replace.conflict_group
def test_p1_disjoint_tokens_stay_independent() -> None:
# Replacing a word AND inserting different text after it is legitimate.
insert = _s("i", "insert_after", ["w-fire"], "gasoline")
replace = _s("r", "replace", ["w-fire"], "fire,")
suggestions = [insert, replace]
_assign_conflict_groups(suggestions)
assert insert.conflict_group is None
assert replace.conflict_group is None
def test_p1_two_inserts_same_anchor_same_token_share_a_group() -> None:
a = _s("a", "insert_after", ["w-fire"], "you're")
b = _s("b", "insert_after", ["w-fire"], "you're baby")
suggestions = [a, b]
_assign_conflict_groups(suggestions)
assert a.conflict_group is not None
assert a.conflict_group == b.conflict_group
def test_p1_insert_vs_delete_not_grouped() -> None:
insert = _s("i", "insert_after", ["w-fire"], "you're")
delete = _s("d", "delete", ["w-fire"], "")
suggestions = [insert, delete]
_assign_conflict_groups(suggestions)
assert insert.conflict_group is None
def test_assign_conflict_groups_is_idempotent_and_resets() -> None:
a = _s("a", "replace", ["w1"], "x")
b = _s("b", "replace", ["w2"], "y")
a.conflict_group = b.conflict_group = "stale-group"
suggestions = [a, b]
_assign_conflict_groups(suggestions)
assert a.conflict_group is None
assert b.conflict_group is None
def test_word_overlap_grouping_still_works() -> None:
a = _s("a", "replace", ["w1", "w2"], "x")
b = _s("b", "delete", ["w2"], "")
suggestions = [a, b]
_assign_conflict_groups(suggestions)
assert a.conflict_group is not None
assert a.conflict_group == b.conflict_group
# ---- pipeline integration: suggest() folds deterministic suggestions in ----
def _run_single_model(llm_suggestions, segments, refs, correction_data):
service = AutoCorrectService()
def fake_call(model, system_prompt, user_prompt, *, job_id):
return {"suggestions": llm_suggestions}, None
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", side_effect=fake_call):
return service.suggest(
job_id="job-1",
segments=segments,
reference_lyrics=refs,
artist="A",
title="T",
settings=AutoCorrectSettings(),
correction_data=correction_data,
)
def test_suggest_appends_deterministic_suggestions() -> None:
segments, refs, cd = _p4_fixture()
result = _run_single_model([], segments, refs, cd)
assert [s.op for s in result.suggestions] == ["delete", "replace"]
assert all(s.models == ["deterministic"] for s in result.suggestions)
def test_suggest_dedupes_identical_llm_and_deterministic() -> None:
segments, refs, cd = _p4_fixture()
llm = [
{
"op": "delete",
"start_idx": 0,
"end_idx": 0,
"new_text": "",
"reason": "spurious leading word",
"category": "mishearing",
"confidence": 0.8,
}
]
result = _run_single_model(llm, segments, refs, cd)
deletes = [s for s in result.suggestions if s.op == "delete"]
assert len(deletes) == 1
assert "deterministic" in deletes[0].models
assert deletes[0].confidence == 0.9 # bumped to the deterministic confidence
# The deterministic generator counts as an agreeing source.
assert deletes[0].consensus == 2
assert deletes[0].total_models == 2
assert deletes[0].consensus == len(deletes[0].models)
def test_suggest_groups_conflicting_llm_and_deterministic() -> None:
segments, refs, cd = _p4_fixture()
llm = [
{
"op": "replace",
"start_idx": 0,
"end_idx": 0,
"new_text": "And,",
"reason": "punctuation",
"category": "formatting",
"confidence": 0.7,
}
]
result = _run_single_model(llm, segments, refs, cd)
on_w0 = [s for s in result.suggestions if s.word_ids == ["w0"]]
assert len(on_w0) == 2
assert on_w0[0].conflict_group is not None
assert on_w0[0].conflict_group == on_w0[1].conflict_group
def test_suggest_without_correction_data_still_works() -> None:
segments, refs, _ = _p4_fixture()
service = AutoCorrectService()
def fake_call(model, system_prompt, user_prompt, *, job_id):
return {"suggestions": []}, None
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
patch.object(service, "_call_model", side_effect=fake_call):
result = service.suggest(
job_id="job-1",
segments=segments,
reference_lyrics=refs,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
assert result.suggestions == []
def test_deterministic_respects_min_confidence_setting() -> None:
segments, refs, cd = _p4_fixture()
service = AutoCorrectService()
def fake_call(model, system_prompt, user_prompt, *, job_id):
return {"suggestions": []}, None
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", side_effect=fake_call):
result = service.suggest(
job_id="job-1",
segments=segments,
reference_lyrics=refs,
artist="A",
title="T",
settings=AutoCorrectSettings(min_confidence=0.95),
correction_data=cd,
)
assert result.suggestions == []
# ---- module-level helpers ----
def test_ref_word_streams_indexes_ids() -> None:
streams = _ref_word_streams({"genius": _ref_source(["a", "b"], "g")})
texts, index = streams["genius"]
assert texts == ["a", "b"]
assert index == {"g0": 0, "g1": 1}
def test_direct_generator_calls_share_stream_shape() -> None:
segments, refs, cd = _p4_fixture()
streams = _ref_word_streams(refs)
assert leading_connective_suggestions(segments, cd, streams)
segments5, refs5, cd5 = _p5_fixture()
streams5 = _ref_word_streams(refs5)
assert reference_majority_suggestions(segments5, cd5, streams5)
Whitespace-only changes.
@@ -0,0 +1,202 @@
"""Tests for tenant bulk-upload filename analysis.
The regex fast path is deterministic and covers the real Vocal Star convention,
so most assertions run with ``generate=None`` (no LLM). A couple of tests inject
a fake ``generate`` to exercise the LLM merge + hallucination guards.
"""
from backend.services.tenant_bulk import analyze_filenames
# The real "Bulk-Batch-1-Inputs" folder listing (see BACKLOG.md INBOX spec).
BULK_BATCH_1 = [
"S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3",
"S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3",
"S1101-1 Smokey Joes Cafe - Some Cats Know Guide.mp3",
"S1101-2 Smokey Joes Cafe - Some Cats Know Instru.mp3",
"S1102-2 The Brian Setzer Orchestra - Straight Up Guide.mp3", # anomaly: -2 but Guide, no pair
"S1103-1 Cyndi Lauper - Girls Just Want to Have Fun Guide.mp3",
"S1103-2 Cyndi Lauper - Girls Just Want to Have Fun BV.mp3",
"S1104-1 Herman's Hermits - There's a Kind of Hush Guide.mp3",
"S1104-2 Herman's Hermits - There's a Kind of Hush BV.mp3",
"S1105-1 Nat King Cole - Smile Guide.mp3",
"S1105-2 Nat King Cole - Smile Instru.mp3",
]
class TestRegexFastPath:
def test_pairs_clean_batch(self):
result = analyze_filenames(BULK_BATCH_1).to_dict()
rows = result["rows"]
# 5 complete pairs (1100, 1101, 1103, 1104, 1105); 1102 is unpaired.
assert len(rows) == 5
by_mixed = {r["mixed_filename"]: r for r in rows}
eddy = by_mixed["S1100-1 Eddy Grant - I Don't Wanna Dance Guide.mp3"]
assert eddy["artist"] == "Eddy Grant"
assert eddy["title"] == "I Don't Wanna Dance"
assert eddy["instrumental_filename"] == "S1100-2 Eddy Grant - I Don't Wanna Dance BV.mp3"
assert eddy["confidence"] == "high"
# "Instru" label is recognised as instrumental, not just "-2".
smokey = by_mixed["S1101-1 Smokey Joes Cafe - Some Cats Know Guide.mp3"]
assert smokey["instrumental_filename"] == "S1101-2 Smokey Joes Cafe - Some Cats Know Instru.mp3"
# Apostrophes / punctuation preserved in title extraction.
herman = by_mixed["S1104-1 Herman's Hermits - There's a Kind of Hush Guide.mp3"]
assert herman["artist"] == "Herman's Hermits"
assert herman["title"] == "There's a Kind of Hush"
def test_s1102_anomaly_flagged_unpaired_not_mispaired(self):
result = analyze_filenames(BULK_BATCH_1).to_dict()
unpaired = result["unpaired"]
assert len(unpaired) == 1
u = unpaired[0]
assert u["filename"] == "S1102-2 The Brian Setzer Orchestra - Straight Up Guide.mp3"
# Guide label -> treated as MIXED with no instrumental partner.
assert u["role"] == "mixed"
assert u["reason"] == "no_instrumental"
assert u["artist"] == "The Brian Setzer Orchestra"
assert u["title"] == "Straight Up"
def test_non_audio_files_ignored(self):
files = BULK_BATCH_1 + [
"ALWAYS REMEMBER US THIS WAY CDG.fw.png",
"prepped", # a subfolder entry, no extension
"notes.txt",
]
result = analyze_filenames(files).to_dict()
ignored = {i["filename"] for i in result["ignored"]}
assert "ALWAYS REMEMBER US THIS WAY CDG.fw.png" in ignored
assert "notes.txt" in ignored
assert "prepped" in ignored
# Audio pairing unaffected by the extra junk.
assert len(result["rows"]) == 5
def test_duplicate_filenames_deduped(self):
files = BULK_BATCH_1 + [BULK_BATCH_1[0], BULK_BATCH_1[1]]
result = analyze_filenames(files).to_dict()
assert len(result["rows"]) == 5
def test_no_scode_prefix_pairs_by_artist_title(self):
files = [
"Adele - Hello (Guide).mp3",
"Adele - Hello (Instrumental).mp3",
]
result = analyze_filenames(files).to_dict()
assert len(result["rows"]) == 1
row = result["rows"][0]
assert row["artist"] == "Adele"
assert row["title"] == "Hello"
def test_empty_input(self):
result = analyze_filenames([]).to_dict()
assert result == {"rows": [], "unpaired": [], "ignored": []}
def test_title_ending_in_weak_label_word_is_not_mis_roled(self):
# "Off" is a title word here, not an instrumental label; the -1/-2 slots
# must still pair these correctly and keep the full title.
files = [
"S2000-1 The Artist - Turn It Off Guide.mp3", # mixed (Guide strong)
"S2000-2 The Artist - Turn It Off Instru.mp3", # instrumental
]
result = analyze_filenames(files).to_dict()
assert len(result["rows"]) == 1
row = result["rows"][0]
assert row["title"] == "Turn It Off"
assert row["mixed_filename"] == "S2000-1 The Artist - Turn It Off Guide.mp3"
def test_bare_weak_label_falls_back_to_slot(self):
# No strong label / brackets: "Off" and "Lead" stay in the title and the
# slot decides the role, so the pair is preserved.
files = [
"S2001-1 Band - Show Off.mp3", # slot 1 -> mixed, title keeps "Off"
"S2001-2 Band - Show Off.mp3", # slot 2 -> instrumental
]
result = analyze_filenames(files).to_dict()
assert len(result["rows"]) == 1
assert result["rows"][0]["title"] == "Show Off"
def test_bracketed_weak_label_is_trusted(self):
files = [
"Adele - Hello (Vocals).mp3",
"Adele - Hello (Karaoke).mp3",
]
result = analyze_filenames(files).to_dict()
assert len(result["rows"]) == 1
row = result["rows"][0]
assert row["title"] == "Hello"
assert row["mixed_filename"] == "Adele - Hello (Vocals).mp3"
def test_scode_file_with_subfolder_path_still_parses(self):
# Frontend may send a webkitRelativePath; Path().stem uses the basename.
files = [
"batch/S3000-1 A - Song Guide.mp3",
"batch/S3000-2 A - Song Instru.mp3",
]
result = analyze_filenames(files).to_dict()
assert len(result["rows"]) == 1
assert result["rows"][0]["instrumental_filename"] == "batch/S3000-2 A - Song Instru.mp3"
class TestLLMPass:
def test_llm_pairs_leftovers_regex_missed(self):
# Two files the regex can't confidently pair (no label, no S-code).
files = [
"eddygrant_dance_vox.mp3",
"eddygrant_dance_backing.mp3",
]
def fake_generate(system_prompt, user_prompt):
assert "eddygrant_dance_vox.mp3" in user_prompt
return {
"rows": [
{
"artist": "Eddy Grant",
"title": "I Don't Wanna Dance",
"mixed_filename": "eddygrant_dance_vox.mp3",
"instrumental_filename": "eddygrant_dance_backing.mp3",
"confidence": "medium",
}
],
"unpaired": [],
}
result = analyze_filenames(files, generate=fake_generate).to_dict()
assert len(result["rows"]) == 1
row = result["rows"][0]
assert row["mixed_filename"] == "eddygrant_dance_vox.mp3"
assert row["confidence"] == "medium"
assert result["unpaired"] == []
def test_llm_hallucinated_filenames_rejected(self):
files = ["mystery_track.mp3"]
def fake_generate(system_prompt, user_prompt):
return {
"rows": [
{
"artist": "Made",
"title": "Up",
"mixed_filename": "mystery_track.mp3",
"instrumental_filename": "does_not_exist.mp3", # hallucinated
}
],
"unpaired": [],
}
result = analyze_filenames(files, generate=fake_generate).to_dict()
# Row rejected because the instrumental isn't a real input file.
assert result["rows"] == []
assert len(result["unpaired"]) == 1
assert result["unpaired"][0]["filename"] == "mystery_track.mp3"
def test_llm_error_falls_back_to_regex(self):
def boom(system_prompt, user_prompt):
raise RuntimeError("model unavailable")
# Regex handles the clean batch; LLM only runs on leftovers (none here),
# but even a raising generate must never break analysis.
files = BULK_BATCH_1 + ["weird_unparseable_name.mp3"]
result = analyze_filenames(files, generate=boom).to_dict()
assert len(result["rows"]) == 5
leftover = {u["filename"] for u in result["unpaired"]}
assert "weird_unparseable_name.mp3" in leftover
@@ -0,0 +1,190 @@
"""
Tests for POST /api/admin/orphaned-outputs/cleanup.
This endpoint deletes distributed outputs whose owning job doc no longer exists
(a job deleted while its outputs were still published). Targets are explicit —
YouTube video ID, Dropbox folder path, GDrive file IDs, kjbox mirror filename
prefix — because there is no job doc left to resolve them from.
Origin: NOMAD-1583 duplicate incident (2026-08-29) — a job was deleted with its
outputs still live, the brand code was recycled and reused, and the orphaned files
had to be removed without any job record.
"""
from unittest.mock import MagicMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.admin import router
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult, UserType
def get_mock_admin():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Admin authenticated",
user_email="admin@example.com",
is_admin=True,
)
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[require_admin] = get_mock_admin
@pytest.fixture
def client():
return TestClient(app)
URL = "/api/admin/orphaned-outputs/cleanup"
class TestOrphanedOutputsCleanupValidation:
def test_no_targets_returns_400(self, client):
response = client.post(URL, json={})
assert response.status_code == 400
assert "No cleanup targets" in response.json()["detail"]
@pytest.mark.parametrize("prefix", ["NOMAD-1583", "NOMAD-1583 - ", "Mazzy Star"])
def test_unsafe_mirror_prefix_returns_400_before_any_cleanup(self, client, prefix):
"""An unsafe mirror prefix fails the whole request up front — even the other
(valid) targets must not run, so a bad call can be corrected and retried
atomically."""
with patch("backend.services.youtube_service.get_youtube_service") as mock_get_yt:
response = client.post(URL, json={
"youtube_video_id": "vid",
"mirror_filename_prefix": prefix,
})
assert response.status_code == 400
assert "mirror_filename_prefix" in response.json()["detail"]
mock_get_yt.assert_not_called()
class TestOrphanedOutputsCleanupYouTube:
def test_deletes_youtube_video_by_id(self, client):
mock_finalise = MagicMock()
mock_finalise.delete_youtube_video.return_value = True
mock_yt = MagicMock()
mock_yt.is_configured = True
mock_yt.get_credentials_dict.return_value = {"token": "x"}
with patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", return_value=mock_finalise), \
patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt):
response = client.post(URL, json={"youtube_video_id": "R3QZm8yXqvw"})
assert response.status_code == 200
assert response.json()["results"]["youtube"] == {"status": "success", "video_id": "R3QZm8yXqvw"}
mock_finalise.delete_youtube_video.assert_called_once_with("R3QZm8yXqvw")
def test_youtube_not_configured_reports_failed(self, client):
mock_yt = MagicMock()
mock_yt.is_configured = False
with patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt):
response = client.post(URL, json={"youtube_video_id": "abc123"})
assert response.status_code == 200
assert response.json()["results"]["youtube"]["status"] == "failed"
def test_youtube_error_is_captured_not_raised(self, client):
with patch("backend.services.youtube_service.get_youtube_service", side_effect=RuntimeError("boom")):
response = client.post(URL, json={"youtube_video_id": "abc123"})
assert response.status_code == 200
assert response.json()["results"]["youtube"]["status"] == "error"
class TestOrphanedOutputsCleanupDropbox:
def test_deletes_dropbox_folder(self, client):
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = True
path = "/MediaUnsynced/Karaoke/Tracks-Organized/NOMAD-1583 - Mazzy Star - Fade Into You"
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox):
response = client.post(URL, json={"dropbox_folder_path": path})
assert response.status_code == 200
assert response.json()["results"]["dropbox"] == {"status": "success", "path": path}
mock_dropbox.delete_folder.assert_called_once_with(path)
def test_dropbox_delete_failure_reported(self, client):
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.delete_folder.return_value = False
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox):
response = client.post(URL, json={"dropbox_folder_path": "/x/y"})
assert response.json()["results"]["dropbox"]["status"] == "failed"
class TestOrphanedOutputsCleanupGDrive:
def test_deletes_gdrive_files_by_id(self, client):
mock_gdrive = MagicMock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {"id1": True, "id2": True}
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive):
response = client.post(URL, json={"gdrive_file_ids": ["id1", "id2"]})
assert response.status_code == 200
assert response.json()["results"]["gdrive"]["status"] == "success"
mock_gdrive.delete_files.assert_called_once_with(["id1", "id2"])
def test_partial_gdrive_failure_reported(self, client):
mock_gdrive = MagicMock()
mock_gdrive.is_configured = True
mock_gdrive.delete_files.return_value = {"id1": True, "id2": False}
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive):
response = client.post(URL, json={"gdrive_file_ids": ["id1", "id2"]})
assert response.json()["results"]["gdrive"]["status"] == "partial"
class TestOrphanedOutputsCleanupMirror:
def test_deletes_mirror_objects_by_track_prefix(self, client):
mock_mirror = MagicMock()
mock_mirror.delete_track_objects_by_filename_prefix.return_value = {
"masters_deleted": 1, "vocals_guides_deleted": 1,
}
with patch("backend.services.nomad_master_mirror.NomadMasterMirror", return_value=mock_mirror):
response = client.post(URL, json={"mirror_filename_prefix": "NOMAD-1583 - Mazzy Star"})
assert response.status_code == 200
assert response.json()["results"]["mirror"] == {
"status": "success", "masters_deleted": 1, "vocals_guides_deleted": 1,
}
mock_mirror.delete_track_objects_by_filename_prefix.assert_called_once_with("NOMAD-1583 - Mazzy Star")
class TestOrphanedOutputsCleanupCombined:
def test_all_targets_cleaned_in_one_call(self, client):
mock_finalise = MagicMock()
mock_finalise.delete_youtube_video.return_value = True
mock_yt = MagicMock(is_configured=True)
mock_yt.get_credentials_dict.return_value = {}
mock_dropbox = MagicMock(is_configured=True)
mock_dropbox.delete_folder.return_value = True
mock_gdrive = MagicMock(is_configured=True)
mock_gdrive.delete_files.return_value = {"id1": True}
mock_mirror = MagicMock()
mock_mirror.delete_track_objects_by_filename_prefix.return_value = {
"masters_deleted": 1, "vocals_guides_deleted": 0,
}
with patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", return_value=mock_finalise), \
patch("backend.services.youtube_service.get_youtube_service", return_value=mock_yt), \
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror", return_value=mock_mirror):
response = client.post(URL, json={
"youtube_video_id": "vid",
"dropbox_folder_path": "/a/b",
"gdrive_file_ids": ["id1"],
"mirror_filename_prefix": "NOMAD-1583 - Mazzy Star",
})
assert response.status_code == 200
results = response.json()["results"]
assert {results[k]["status"] for k in ("youtube", "dropbox", "gdrive", "mirror")} == {"success"}
+2 -1
View File
@@ -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()
+64 -3
View File
@@ -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
+101 -50
View File
@@ -215,61 +215,30 @@ class TestDeleteJob:
class TestDeleteJobBrandCodeRecycling:
"""Tests for brand code recycling in DELETE /api/jobs/{job_id}."""
"""Tests for published-output cleanup + brand code recycling in DELETE /api/jobs/{job_id}.
def test_brand_code_recycled_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""Test that brand code is recycled before the job is deleted."""
mock_job_manager = MagicMock()
job_with_brand = Job(
job_id="test-bc-123",
Recycling must ONLY happen via the distribution cleanup (which gates it on
Dropbox + GDrive success). Blind-recycling on delete hands the same NOMAD-####
to a future job while the old files are still in the public share (duplicate
brand code incident, NOMAD-1583, 2026-08-29).
"""
@staticmethod
def _job_with_brand(job_id, outputs_deleted_at=None):
return Job(
job_id=job_id,
status=JobStatus.COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
state_data={"brand_code": "NOMAD-0042"},
outputs_deleted_at=datetime.now(UTC),
outputs_deleted_at=outputs_deleted_at,
)
mock_job_manager.get_job.return_value = job_with_brand
mock_job_manager.delete_job.return_value = True
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', return_value=("NOMAD", 42)) as mock_parse, \
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
mock_svc = MagicMock()
mock_get_svc.return_value = mock_svc
from backend.main import app
client = TestClient(app)
response = client.delete("/api/jobs/test-bc-123", headers=auth_headers)
assert response.status_code == 200
mock_parse.assert_called_once_with("NOMAD-0042")
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
mock_job_manager.delete_job.assert_called_once()
def test_recycling_failure_does_not_prevent_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""Test that job deletion proceeds even if brand code recycling fails."""
def _delete(self, job, auth_headers, mock_worker_service, mock_theme_service, cleanup_patch):
mock_job_manager = MagicMock()
job_with_brand = Job(
job_id="test-bc-456",
status=JobStatus.COMPLETE,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Test",
state_data={"brand_code": "NOMAD-0099"},
outputs_deleted_at=datetime.now(UTC),
)
mock_job_manager.get_job.return_value = job_with_brand
mock_job_manager.get_job.return_value = job
mock_job_manager.delete_job.return_value = True
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
@@ -281,14 +250,96 @@ class TestDeleteJobBrandCodeRecycling:
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', side_effect=ValueError("Bad format")):
patch('backend.api.routes.jobs._run_distribution_cleanup', cleanup_patch) as mock_cleanup:
from backend.main import app
client = TestClient(app)
response = client.delete("/api/jobs/test-bc-456", headers=auth_headers)
response = client.delete(f"/api/jobs/{job.job_id}", headers=auth_headers)
return response, mock_job_manager, mock_cleanup
assert response.status_code == 200
# Job should still be deleted despite recycling failure
mock_job_manager.delete_job.assert_called_once()
def test_published_outputs_cleaned_up_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""A job with a brand code and outputs never cleaned up gets full distribution
cleanup (which owns the gated recycle) before the record is deleted."""
job = self._job_with_brand("test-bc-123", outputs_deleted_at=None)
cleanup = MagicMock(return_value={"youtube": {"status": "success"}})
response, mock_job_manager, mock_cleanup = self._delete(
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
assert response.status_code == 200
mock_cleanup.assert_called_once_with("test-bc-123", job)
mock_job_manager.delete_job.assert_called_once()
assert response.json()["distribution_cleanup"] == {"youtube": {"status": "success"}}
def test_outputs_already_deleted_skips_cleanup_and_recycle(self, mock_worker_service, mock_theme_service, auth_headers):
"""A job whose outputs were already deleted (admin delete-outputs recycled the
code then) must NOT be cleaned up or recycled again — re-recycling a code that
a new job may have since claimed would create duplicates."""
job = self._job_with_brand("test-bc-456", outputs_deleted_at=datetime.now(UTC))
cleanup = MagicMock()
response, mock_job_manager, mock_cleanup = self._delete(
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
assert response.status_code == 200
mock_cleanup.assert_not_called()
mock_job_manager.delete_job.assert_called_once()
assert "distribution_cleanup" not in response.json()
def test_delete_files_false_rejected_for_published_job(self, mock_worker_service, mock_theme_service, auth_headers):
"""Published outputs can't be preserved when their job record is deleted —
the record holds the only file IDs/paths needed to ever clean them up."""
job = self._job_with_brand("test-bc-df", outputs_deleted_at=None)
cleanup = MagicMock()
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
patch('backend.api.routes.jobs._run_distribution_cleanup', cleanup):
from backend.main import app
client = TestClient(app)
response = client.delete("/api/jobs/test-bc-df?delete_files=false", headers=auth_headers)
assert response.status_code == 400
cleanup.assert_not_called()
mock_job_manager.delete_job.assert_not_called()
def test_incomplete_cleanup_aborts_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""If any provider cleanup reports failed/partial/error, the job record must
be kept so the cleanup can be retried with its IDs intact."""
job = self._job_with_brand("test-bc-incomplete", outputs_deleted_at=None)
cleanup = MagicMock(return_value={
"youtube": {"status": "success"},
"dropbox": {"status": "failed", "path": "/x"},
"gdrive": {"status": "success"},
})
response, mock_job_manager, _mock_cleanup = self._delete(
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
assert response.status_code == 502
assert "dropbox" in response.json()["detail"]
mock_job_manager.delete_job.assert_not_called()
def test_unexpected_cleanup_error_aborts_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
"""If cleanup crashes outright (per-service failures are handled internally),
the job record must be preserved — deleting it would orphan the outputs with
no way to resolve their IDs later."""
job = self._job_with_brand("test-bc-789", outputs_deleted_at=None)
cleanup = MagicMock(side_effect=RuntimeError("boom"))
response, mock_job_manager, _mock_cleanup = self._delete(
job, auth_headers, mock_worker_service, mock_theme_service, cleanup)
assert response.status_code == 500
mock_job_manager.delete_job.assert_not_called()
def test_no_brand_code_skips_recycling(self, client, mock_job_manager, auth_headers):
"""Test that deletion without brand code doesn't attempt recycling."""
+89
View File
@@ -206,3 +206,92 @@ def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
assert mod.cleanup_nomad_masters(brand) == 0
# --- delete_track_objects_by_filename_prefix (single-track orphan cleanup) ---
def _blob(name):
b = MagicMock()
b.name = name
return b
def _mirror_with_blobs_per_prefix(blobs_by_prefix):
"""Mirror whose bucket.list_blobs returns blobs matching the requested prefix,
like real GCS (the shared-list shortcut breaks delimiter-bound tests)."""
bucket = MagicMock()
def list_blobs(prefix):
return [b for b in blobs_by_prefix if b.name.startswith(prefix)]
bucket.list_blobs.side_effect = list_blobs
client = MagicMock()
client.bucket.return_value = bucket
return NomadMasterMirror(client=client), bucket
def test_delete_track_objects_by_filename_prefix_deletes_from_both_prefixes():
# One master + one vocals guide for the orphaned track; both must go.
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
guide = _blob("files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star - Fade Into You.flac")
mirror, bucket = _mirror_with_blobs_per_prefix([master, guide])
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 1}
prefixes = [c.kwargs.get("prefix") or c.args[0] for c in bucket.list_blobs.call_args_list]
assert prefixes == [
"files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star",
"files/Nomad Karaoke/vocals-padded/NOMAD-1583 - Mazzy Star",
]
master.delete.assert_called_once()
guide.delete.assert_called_once()
def test_delete_track_objects_by_filename_prefix_is_delimiter_bounded():
# "NOMAD-1583 - Mazzy Star" must NOT match a different track by a longer-named
# artist that happens to share the recycled brand code and the string prefix.
orphan = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
other = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Starlight - Other Song.mp4")
mirror, _bucket = _mirror_with_blobs_per_prefix([orphan, other])
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
orphan.delete.assert_called_once()
other.delete.assert_not_called()
def test_delete_track_objects_full_stem_matches_extension_boundary():
# A full "brand - artist - title" stem must still match its own files (".mp4").
master = _blob("files/Nomad Karaoke/MP4-720p/NOMAD-1583 - Mazzy Star - Fade Into You.mp4")
mirror, _bucket = _mirror_with_blobs_per_prefix([master])
counts = mirror.delete_track_objects_by_filename_prefix(
"NOMAD-1583 - Mazzy Star - Fade Into You"
)
assert counts == {"masters_deleted": 1, "vocals_guides_deleted": 0}
master.delete.assert_called_once()
@pytest.mark.parametrize("prefix", [
"NOMAD-1583", # bare brand code — would match BOTH tracks sharing it
"NOMAD-1583 - ", # brand code + separator but no artist text
"NOMADNP-0001 - X", # private prefix
"Mazzy Star", # no brand code
"",
None,
])
def test_delete_track_objects_by_filename_prefix_refuses_unsafe_prefixes(prefix):
mirror, bucket, _blobs = _mirror_with_blobs([])
with pytest.raises(ValueError):
mirror.delete_track_objects_by_filename_prefix(prefix)
bucket.list_blobs.assert_not_called()
def test_delete_track_objects_by_filename_prefix_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
counts = mirror.delete_track_objects_by_filename_prefix("NOMAD-1583 - Mazzy Star")
assert counts == {"masters_deleted": 0, "vocals_guides_deleted": 0}
@@ -55,16 +55,19 @@ def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=No
)
def _mock_jm(*, downloading=None, pending=None, rendering=None, jobs=None):
"""Wire a JobManager mock for the endpoint's 3 status queries.
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None, jobs=None):
"""Wire a JobManager mock for the endpoint's 4 status queries.
downloading/rendering use .where().stream(); pending uses .where().limit().stream().
`jobs` maps job_id -> Job returned by get_job().
downloading/rendering/review_complete use .where().stream(); pending uses
.where().limit().stream(). `jobs` maps job_id -> Job returned by get_job().
"""
mock_jm = MagicMock()
where = mock_jm.firestore.db.collection.return_value.where.return_value
# Two non-limited .stream() calls in order: downloading_audio, rendering_video
where.stream.side_effect = [iter(downloading or []), iter(rendering or [])]
# Non-limited .stream() calls in order: downloading_audio, rendering_video,
# review_complete (lost-render-trigger sweep)
where.stream.side_effect = [
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
]
# One .limit().stream() call: download_pending_retry
where.limit.return_value.stream.return_value = iter(pending or [])
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
@@ -175,3 +178,38 @@ def test_fresh_render_not_reparked(client):
resp, _ = _run(client, mock_jm)
assert resp.json()["reparked_render_count"] == 0
mock_jm.transition_to_state.assert_not_called()
def test_stalled_review_complete_render_is_retriggered(client):
"""REVIEW_COMPLETE >10 min with no render_progress = lost render trigger
(e.g. Cloud Tasks enqueue failed from the GPU worker) -> re-trigger."""
job = _job("rc1", JobStatus.REVIEW_COMPLETE, minutes_stale=30)
mock_jm = _mock_jm(
review_complete=[_doc("rc1", JobStatus.REVIEW_COMPLETE)],
jobs={"rc1": job},
)
mock_ws = MagicMock()
mock_ws.trigger_audio_download_worker = AsyncMock(return_value=True)
mock_ws.trigger_render_video_worker = AsyncMock(return_value=True)
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
resp = client.post("/api/internal/recover-stuck-jobs")
assert resp.status_code == 200
assert resp.json()["render_retriggered_jobs"] == ["rc1"]
mock_ws.trigger_render_video_worker.assert_awaited_once_with("rc1")
def test_fresh_review_complete_is_left_alone(client):
job = _job("rc2", JobStatus.REVIEW_COMPLETE, minutes_stale=1)
mock_jm = _mock_jm(
review_complete=[_doc("rc2", JobStatus.REVIEW_COMPLETE)],
jobs={"rc2": job},
)
mock_ws = MagicMock()
mock_ws.trigger_render_video_worker = AsyncMock(return_value=True)
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
resp = client.post("/api/internal/recover-stuck-jobs")
assert resp.status_code == 200
assert resp.json()["render_retriggered_jobs"] == []
mock_ws.trigger_render_video_worker.assert_not_awaited()
+7
View File
@@ -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
+306
View File
@@ -1325,3 +1325,309 @@ class TestGetVocalsAudio:
with pytest.raises(HTTPException) as exc_info:
self._call({}, audio_complete=True)
assert exc_info.value.status_code == 404
class TestReplayCorrectionData:
"""Replay mode for correction-data: re-open a COMPLETED job read-only.
Verifies the status gate is bypassed with ?replay=true (full auth only), the
AWAITING_REVIEW->IN_REVIEW transition is skipped, and the edit_log is attached.
"""
def _client_with_auth(self, auth_type: str = "full"):
from backend.main import app
from backend.api.dependencies import require_review_auth
from fastapi.testclient import TestClient
async def _mock_auth(job_id: str = "job1"):
return (job_id, auth_type)
app.dependency_overrides[require_review_auth] = _mock_auth
return TestClient(app)
def _teardown(self):
from backend.main import app
from backend.api.dependencies import require_review_auth
app.dependency_overrides.pop(require_review_auth, None)
def _completed_job(self):
from backend.models.job import JobStatus
job = MagicMock()
job.status = JobStatus.COMPLETE
job.job_id = "job1"
job.artist = "A"
job.title = "T"
job.input_media_gcs_path = "jobs/job1/input/audio.flac"
job.file_urls = {"lyrics": {"corrections_updated": "jobs/job1/lyrics/corrections_updated.json"},
"stems": {}, "analysis": {}}
job.state_data = {"instrumental_selection": "with_backing",
"last_edit_log_path": "jobs/job1/lyrics/edit_log_x.json"}
return job
def test_replay_bypasses_status_gate_and_attaches_edit_log(self):
client = self._client_with_auth("full")
try:
with patch("backend.api.routes.review.JobManager") as jm, \
patch("backend.api.routes.review.StorageService") as storage_cls, \
patch("backend.api.routes.review._get_audio_hash", return_value="h1"):
jm.return_value.get_job.return_value = self._completed_job()
storage = storage_cls.return_value
storage.file_exists.return_value = True
storage.download_json.side_effect = lambda p: (
{"entries": [{"operation": "ai_suggestion_accept"}]}
if p.endswith("edit_log_x.json")
else {"corrected_segments": [], "metadata": {}}
)
resp = client.get("/api/review/job1/correction-data?replay=true")
assert resp.status_code == 200
body = resp.json()
assert body["replay"]["is_replay"] is True
assert body["replay"]["instrumental_selection"] == "with_backing"
assert body["replay"]["job_status"] # some status string
assert len(body["replay"]["edit_log"]["entries"]) == 1
# Read-only: must NOT transition state.
jm.return_value.transition_to_state.assert_not_called()
finally:
self._teardown()
def test_non_replay_completed_job_is_rejected(self):
client = self._client_with_auth("full")
try:
with patch("backend.api.routes.review.JobManager") as jm, \
patch("backend.api.routes.review.StorageService"):
jm.return_value.get_job.return_value = self._completed_job()
resp = client.get("/api/review/job1/correction-data")
assert resp.status_code == 400
finally:
self._teardown()
def test_replay_requires_full_auth(self):
client = self._client_with_auth("review_token")
try:
with patch("backend.api.routes.review.JobManager") as jm, \
patch("backend.api.routes.review.StorageService"):
jm.return_value.get_job.return_value = self._completed_job()
resp = client.get("/api/review/job1/correction-data?replay=true")
assert resp.status_code == 403
finally:
self._teardown()
class TestDevAudioProxy:
"""The dev-only audio byte-proxy is inert unless REVIEW_AUDIO_PROXY is set."""
def test_dev_audio_404_when_flag_disabled(self, monkeypatch):
from backend.main import app
from fastapi.testclient import TestClient
monkeypatch.delenv("REVIEW_AUDIO_PROXY", raising=False)
client = TestClient(app)
resp = client.get("/api/review/job1/dev-audio?path=jobs/job1/stems/x.flac")
assert resp.status_code == 404
def test_dev_audio_rejects_out_of_scope_path(self, monkeypatch):
from backend.main import app
from fastapi.testclient import TestClient
monkeypatch.setenv("REVIEW_AUDIO_PROXY", "1")
client = TestClient(app)
resp = client.get("/api/review/job1/dev-audio?path=jobs/other/stems/x.flac")
assert resp.status_code == 400
def test_dev_audio_rejects_prefix_bypass_shapes(self, monkeypatch):
# The path must be anchored at jobs/{job_id}/ — a job_id that merely
# appears somewhere in the path (e.g. job_id="jobs") must not pass.
from backend.main import app
from fastapi.testclient import TestClient
monkeypatch.setenv("REVIEW_AUDIO_PROXY", "1")
client = TestClient(app)
resp = client.get("/api/review/jobs/dev-audio?path=jobs/other/stems/x.flac")
assert resp.status_code == 400
resp = client.get("/api/review/job1/dev-audio?path=jobs/job1/../other/x.flac")
assert resp.status_code == 400
class TestPreviewVideoAsyncFlow:
"""Tests for the async (non-blocking) GCE preview flow.
POST /preview-video must NOT wait for GCE encoding — cold-starting a
fallback encoder VM can take 2-3 minutes, longer than Cloudflare's ~100s
edge timeout (incident 2026-08-29, job 326e1aef: preview encoded fine but
the browser connection was cut and the UI spun forever). Instead the
endpoint returns {"status": "generating"} immediately and the browser
polls the /status endpoint until the mp4 exists in GCS.
"""
@pytest.fixture
def mock_job(self):
from backend.models.job import Job, JobStatus
job = MagicMock(spec=Job)
job.job_id = "job-preview-async"
job.status = JobStatus.AWAITING_REVIEW
job.input_media_gcs_path = "jobs/job-preview-async/audio/input.flac"
job.style_params_gcs_path = None
job.style_assets = {}
job.artist = "Test Artist"
job.title = "Test Song"
return job
def _run_gce_preview(self, mock_job, *, mp4_exists, background_mock):
"""Run generate_preview_video with GCE enabled and heavy deps mocked."""
import asyncio
from backend.api.routes.review import generate_preview_video
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = mock_job
mock_storage = MagicMock()
mock_storage.file_exists.return_value = mp4_exists
mock_encoding_service = MagicMock()
mock_encoding_service.is_preview_enabled = True
mock_settings = MagicMock()
mock_settings.gcs_bucket_name = "test-bucket"
async def _run():
result = await generate_preview_video(
job_id=mock_job.job_id,
updated_data={},
auth_info=("user@test.com", "job_owner"),
)
# Let any create_task'd background coroutine start
await asyncio.sleep(0)
return result
with patch("backend.api.routes.review.JobManager", return_value=mock_job_manager), \
patch("backend.api.routes.review.StorageService", return_value=mock_storage), \
patch("backend.api.routes.review.get_encoding_service", return_value=mock_encoding_service), \
patch("backend.api.routes.review.get_settings", return_value=mock_settings), \
patch("backend.api.routes.review._prepare_preview_inputs",
return_value=(MagicMock(), "/tmp/audio.flac", MagicMock())), \
patch("backend.api.routes.review._encode_preview_in_background", background_mock), \
patch("backend.api.routes.review.CorrectionOperations") as mock_co, \
patch("tempfile.TemporaryDirectory") as mock_tmpdir:
mock_tmpdir.return_value.__enter__ = MagicMock(return_value="/tmp/preview_test")
mock_tmpdir.return_value.__exit__ = MagicMock(return_value=False)
mock_co.generate_preview_video.return_value = {
"preview_hash": "hash123",
"ass_path": "/tmp/preview.ass",
}
result = asyncio.run(_run())
return result, mock_storage, mock_co
def test_cache_hit_returns_success_without_encoding(self, mock_job):
"""Same edits → same hash: if the mp4 already exists (e.g. user retried
after a dropped connection), return success immediately."""
background_mock = AsyncMock()
result, mock_storage, mock_co = self._run_gce_preview(
mock_job, mp4_exists=True, background_mock=background_mock)
assert result == {"status": "success", "preview_hash": "hash123"}
background_mock.assert_not_called()
# ASS is generated with ass_only=True (no local video render)
assert mock_co.generate_preview_video.call_args.kwargs["ass_only"] is True
def test_cache_miss_returns_generating_and_spawns_background_encode(self, mock_job):
"""When the mp4 doesn't exist, the endpoint must return immediately
with status=generating and hand encoding to a background task."""
background_mock = AsyncMock()
result, mock_storage, _ = self._run_gce_preview(
mock_job, mp4_exists=False, background_mock=background_mock)
assert result == {"status": "generating", "preview_hash": "hash123"}
background_mock.assert_called_once()
kwargs = background_mock.call_args.kwargs
assert kwargs["preview_hash"] == "hash123"
assert kwargs["encode_kwargs"]["job_id"] == "preview_job-preview-async_hash123"
assert kwargs["encode_kwargs"]["output_gcs_path"] == \
"gs://test-bucket/jobs/job-preview-async/previews/hash123.mp4"
# Stale error marker from a previous failed attempt must be cleared
mock_storage.delete_file.assert_called_once_with(
"jobs/job-preview-async/previews/hash123.error.json", ignore_missing=True)
class TestPreviewVideoStatusEndpoint:
"""GET /{job_id}/preview-video/{hash}/status — poll target for async encodes."""
def _call(self, mock_storage, job_id="job-x", preview_hash="abc123"):
import asyncio
from backend.api.routes.review import get_preview_video_status
with patch("backend.api.routes.review.StorageService", return_value=mock_storage):
return asyncio.run(get_preview_video_status(
job_id=job_id,
preview_hash=preview_hash,
auth_info=("user@test.com", "job_owner"),
))
def test_ready_when_mp4_exists(self):
mock_storage = MagicMock()
mock_storage.file_exists.side_effect = lambda p: p.endswith(".mp4")
result = self._call(mock_storage)
assert result == {"status": "ready", "preview_hash": "abc123"}
def test_error_when_marker_exists(self):
mock_storage = MagicMock()
mock_storage.file_exists.side_effect = lambda p: p.endswith(".error.json")
mock_storage.download_json.return_value = {"error": "encoder exploded"}
result = self._call(mock_storage)
assert result["status"] == "error"
assert result["message"] == "encoder exploded"
def test_generating_when_neither_exists(self):
mock_storage = MagicMock()
mock_storage.file_exists.return_value = False
result = self._call(mock_storage)
assert result == {"status": "generating", "preview_hash": "abc123"}
class TestEncodePreviewInBackground:
"""The background encode task: GCE first, local fallback, error marker last."""
@pytest.fixture
def mock_job(self):
from backend.models.job import Job
job = MagicMock(spec=Job)
job.job_id = "job-bg"
return job
def _run(self, mock_job, encoding_service, storage, local_render):
import asyncio
from backend.api.routes.review import _encode_preview_in_background
with patch("backend.api.routes.review.get_encoding_service", return_value=encoding_service), \
patch("backend.api.routes.review.StorageService", return_value=storage), \
patch("backend.api.routes.review._render_preview_locally", local_render):
asyncio.run(_encode_preview_in_background(
job=mock_job,
preview_hash="h1",
encode_kwargs={"job_id": "preview_job-bg_h1"},
updated_data={},
is_duet=False,
))
def test_gce_success_skips_local_fallback(self, mock_job):
encoding_service = MagicMock()
encoding_service.encode_preview_video = AsyncMock(return_value={"status": "complete"})
storage = MagicMock()
local_render = MagicMock()
self._run(mock_job, encoding_service, storage, local_render)
local_render.assert_not_called()
storage.upload_json.assert_not_called()
def test_gce_failure_falls_back_to_local(self, mock_job):
encoding_service = MagicMock()
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
storage = MagicMock()
local_render = MagicMock(return_value="h1")
self._run(mock_job, encoding_service, storage, local_render)
local_render.assert_called_once()
storage.upload_json.assert_not_called()
def test_both_failures_write_error_marker(self, mock_job):
"""If GCE and the local fallback both fail, an error marker must land in
GCS so the status poll surfaces the failure instead of timing out."""
encoding_service = MagicMock()
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
storage = MagicMock()
local_render = MagicMock(side_effect=RuntimeError("ffmpeg died"))
self._run(mock_job, encoding_service, storage, local_render)
storage.upload_json.assert_called_once_with(
"jobs/job-bg/previews/h1.error.json",
{"error": "ffmpeg died"},
)
+77 -5
View File
@@ -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
@@ -245,6 +245,78 @@ class TestWorkerService:
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()
@@ -269,7 +341,7 @@ class TestWorkerService:
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 = 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
@@ -304,7 +376,7 @@ class TestWorkerService:
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 = 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
@@ -332,7 +404,7 @@ class TestWorkerService:
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 = 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
+47 -1
View File
@@ -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
@@ -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
+2 -1
View File
@@ -48,7 +48,8 @@
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
"instrumentalSelected": "Instrumental selected. Video generation started.",
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
"downloadUrlsError": "Error getting download URLs: {error}"
"downloadUrlsError": "Error getting download URLs: {error}",
"deletePublishedRequiresFiles": "This track's published files must be removed when the job is deleted. Retry the delete without delete_files=false."
},
"review": {
"jobNotFound": "Job not found",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}",
"fileNoLongerAvailable": "الملف لم يعد متاحاً"
"fileNoLongerAvailable": "الملف لم يعد متاحاً",
"deletePublishedRequiresFiles": "يجب إزالة الملفات المنشورة لهذا المسار عند حذف المهمة. يُرجى إعادة محاولة الحذف بدون delete_files=false."
},
"review": {
"jobNotFound": "المهمة غير موجودة",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}",
"fileNoLongerAvailable": "El fitxer ja no està disponible"
"fileNoLongerAvailable": "El fitxer ja no està disponible",
"deletePublishedRequiresFiles": "Els fitxers publicats d'aquesta pista s'han d'eliminar quan s'elimini la tasca. Torna a intentar l'eliminació sense delete_files=false."
},
"review": {
"jobNotFound": "Tasca no trobada",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}",
"fileNoLongerAvailable": "Soubor již není dostupný"
"fileNoLongerAvailable": "Soubor již není dostupný",
"deletePublishedRequiresFiles": "Při mazání úlohy je nutné odstranit i publikované soubory této skladby. Zkus to smazat znovu bez delete_files=false."
},
"review": {
"jobNotFound": "Úloha nebyla nalezena",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}",
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig"
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig",
"deletePublishedRequiresFiles": "Dette spors udgivne filer skal fjernes, når jobbet slettes. Prøv at slette igen uden delete_files=false."
},
"review": {
"jobNotFound": "Jobbet blev ikke fundet",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}",
"fileNoLongerAvailable": "Datei nicht mehr verfügbar"
"fileNoLongerAvailable": "Datei nicht mehr verfügbar",
"deletePublishedRequiresFiles": "Die veröffentlichten Dateien dieses Tracks müssen entfernt werden, wenn der Auftrag gelöscht wird. Versuche den Löschvorgang ohne delete_files=false erneut."
},
"review": {
"jobNotFound": "Auftrag nicht gefunden",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}",
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο"
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο",
"deletePublishedRequiresFiles": "Τα δημοσιευμένα αρχεία αυτού του κομματιού πρέπει να αφαιρεθούν όταν διαγράφεται η εργασία. Δοκίμασε ξανά τη διαγραφή χωρίς το delete_files=false."
},
"review": {
"jobNotFound": "Η εργασία δεν βρέθηκε",
+2 -1
View File
@@ -48,7 +48,8 @@
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
"instrumentalSelected": "Instrumental selected. Video generation started.",
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
"downloadUrlsError": "Error getting download URLs: {error}"
"downloadUrlsError": "Error getting download URLs: {error}",
"deletePublishedRequiresFiles": "This track's published files must be removed when the job is deleted. Retry the delete without delete_files=false."
},
"review": {
"jobNotFound": "Job not found",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}",
"fileNoLongerAvailable": "El archivo ya no está disponible"
"fileNoLongerAvailable": "El archivo ya no está disponible",
"deletePublishedRequiresFiles": "Los archivos publicados de esta pista deben eliminarse cuando se elimine el trabajo. Vuelve a intentar la eliminación sin delete_files=false."
},
"review": {
"jobNotFound": "Trabajo no encontrado",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}",
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla"
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla",
"deletePublishedRequiresFiles": "Tämän kappaleen julkaistut tiedostot täytyy poistaa työn poistamisen yhteydessä. Yritä poistoa uudelleen ilman delete_files=false -määritystä."
},
"review": {
"jobNotFound": "Työtä ei löytynyt",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}",
"fileNoLongerAvailable": "Le fichier n'est plus disponible"
"fileNoLongerAvailable": "Le fichier n'est plus disponible",
"deletePublishedRequiresFiles": "Les fichiers publiés de cette piste doivent être supprimés en même temps que la tâche. Réessaie la suppression sans delete_files=false."
},
"review": {
"jobNotFound": "Tâche introuvable",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}",
"fileNoLongerAvailable": "הקובץ אינו זמין יותר"
"fileNoLongerAvailable": "הקובץ אינו זמין יותר",
"deletePublishedRequiresFiles": "יש להסיר את הקבצים שפורסמו עבור רצועה זו בעת מחיקת המשימה. נסה שוב את המחיקה ללא delete_files=false."
},
"review": {
"jobNotFound": "המשימה לא נמצאה",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}",
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है"
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है",
"deletePublishedRequiresFiles": "जॉब डिलीट करते समय इस ट्रैक की पब्लिश की गई फ़ाइलों को हटाना ज़रूरी है। delete_files=false के बिना डिलीट करने की दोबारा कोशिश करो।"
},
"review": {
"jobNotFound": "जॉब नहीं मिली",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}",
"fileNoLongerAvailable": "Datoteka više nije dostupna"
"fileNoLongerAvailable": "Datoteka više nije dostupna",
"deletePublishedRequiresFiles": "Objavljene datoteke ove pjesme moraju se ukloniti kada se zadatak izbriše. Pokušaj ponovno obrisati bez delete_files=false."
},
"review": {
"jobNotFound": "Zadatak nije pronađen",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}",
"fileNoLongerAvailable": "A fájl már nem elérhető"
"fileNoLongerAvailable": "A fájl már nem elérhető",
"deletePublishedRequiresFiles": "Ennek a számnak a közzétett fájljait el kell távolítani a feladat törlésekor. Próbáld újra a törlést a delete_files=false nélkül."
},
"review": {
"jobNotFound": "A feladat nem található",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}",
"fileNoLongerAvailable": "File sudah tidak tersedia"
"fileNoLongerAvailable": "File sudah tidak tersedia",
"deletePublishedRequiresFiles": "File yang telah dipublikasikan dari trek ini harus ikut dihapus saat tugas dihapus. Silakan ulangi penghapusan tanpa delete_files=false."
},
"review": {
"jobNotFound": "Tugas tidak ditemukan",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}",
"fileNoLongerAvailable": "File non più disponibile"
"fileNoLongerAvailable": "File non più disponibile",
"deletePublishedRequiresFiles": "I file pubblicati di questa traccia devono essere rimossi quando il lavoro viene eliminato. Riprova l'eliminazione senza delete_files=false."
},
"review": {
"jobNotFound": "Lavoro non trovato",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}",
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました"
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました",
"deletePublishedRequiresFiles": "ジョブを削除する際は、このトラックの公開済みファイルも削除する必要があります。delete_files=false を指定せずに、削除を再試行してください。"
},
"review": {
"jobNotFound": "ジョブが見つかりません",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}",
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다"
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다",
"deletePublishedRequiresFiles": "작업을 삭제할 때 이 트랙에 게시된 파일도 함께 삭제해야 합니다. delete_files=false 없이 삭제를 다시 시도해 주세요."
},
"review": {
"jobNotFound": "작업을 찾을 수 없습니다",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}",
"fileNoLongerAvailable": "Fail tidak lagi tersedia"
"fileNoLongerAvailable": "Fail tidak lagi tersedia",
"deletePublishedRequiresFiles": "Fail terbitan trek ini mesti dipadamkan apabila tugas dipadamkan. Sila cuba padam semula tanpa delete_files=false."
},
"review": {
"jobNotFound": "Tugasan tidak dijumpai",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental valgt. Videogenerering startet.",
"instrumentalSelectionError": "Feil ved valg av instrumental for jobb {job_id}: {error}",
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}",
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig"
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig",
"deletePublishedRequiresFiles": "De publiserte filene for dette sporet må fjernes når jobben slettes. Prøv å slette på nytt uten delete_files=false."
},
"review": {
"jobNotFound": "Jobben ble ikke funnet",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental geselecteerd. Videogeneratie is gestart.",
"instrumentalSelectionError": "Fout bij het selecteren van instrumental voor taak {job_id}: {error}",
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}",
"fileNoLongerAvailable": "Bestand niet meer beschikbaar"
"fileNoLongerAvailable": "Bestand niet meer beschikbaar",
"deletePublishedRequiresFiles": "De gepubliceerde bestanden van deze track moeten worden verwijderd als de taak wordt verwijderd. Probeer het verwijderen opnieuw zonder delete_files=false."
},
"review": {
"jobNotFound": "Taak niet gevonden",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Wybrano podkład. Rozpoczęto generowanie wideo.",
"instrumentalSelectionError": "Błąd podczas wybierania podkładu dla zadania {job_id}: {error}",
"downloadUrlsError": "Błąd podczas pobierania linków: {error}",
"fileNoLongerAvailable": "Plik nie jest już dostępny"
"fileNoLongerAvailable": "Plik nie jest już dostępny",
"deletePublishedRequiresFiles": "Opublikowane pliki tego utworu muszą zostać usunięte podczas usuwania zadania. Spróbuj usunąć ponownie bez delete_files=false."
},
"review": {
"jobNotFound": "Nie znaleziono zadania",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental selecionado. Geração de vídeo iniciada.",
"instrumentalSelectionError": "Erro ao selecionar instrumental para o job {job_id}: {error}",
"downloadUrlsError": "Erro ao obter URLs de download: {error}",
"fileNoLongerAvailable": "O arquivo não está mais disponível"
"fileNoLongerAvailable": "O arquivo não está mais disponível",
"deletePublishedRequiresFiles": "Os arquivos publicados desta faixa devem ser removidos quando a tarefa for excluída. Tente excluir novamente sem delete_files=false."
},
"review": {
"jobNotFound": "Job não encontrado",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental selectat. A început generarea videoclipului.",
"instrumentalSelectionError": "Eroare la selectarea instrumentalului pentru jobul {job_id}: {error}",
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}",
"fileNoLongerAvailable": "Fișierul nu mai este disponibil"
"fileNoLongerAvailable": "Fișierul nu mai este disponibil",
"deletePublishedRequiresFiles": "Fișierele publicate ale acestei piese trebuie eliminate la ștergerea jobului. Încearcă din nou ștergerea fără delete_files=false."
},
"review": {
"jobNotFound": "Jobul nu a fost găsit",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Инструментал выбран. Началась генерация видео.",
"instrumentalSelectionError": "Ошибка при выборе инструментала для задачи {job_id}: {error}",
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}",
"fileNoLongerAvailable": "Файл больше недоступен"
"fileNoLongerAvailable": "Файл больше недоступен",
"deletePublishedRequiresFiles": "Опубликованные файлы этого трека нужно удалить вместе с задачей. Повтори удаление без delete_files=false."
},
"review": {
"jobNotFound": "Задача не найдена",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Inštrumentál bol vybraný. Začalo sa generovanie videa.",
"instrumentalSelectionError": "Chyba pri výbere inštrumentálu pre úlohu {job_id}: {error}",
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}",
"fileNoLongerAvailable": "Súbor už nie je dostupný"
"fileNoLongerAvailable": "Súbor už nie je dostupný",
"deletePublishedRequiresFiles": "Publikované súbory tejto skladby musia byť pri odstránení úlohy vymazané. Zopakuj odstránenie bez delete_files=false."
},
"review": {
"jobNotFound": "Úloha sa nenašla",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Instrumental vald. Videogenereringen har startat.",
"instrumentalSelectionError": "Fel vid val av instrumental för jobb {job_id}: {error}",
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}",
"fileNoLongerAvailable": "Filen är inte längre tillgänglig"
"fileNoLongerAvailable": "Filen är inte längre tillgänglig",
"deletePublishedRequiresFiles": "Det här spårets publicerade filer måste tas bort när jobbet raderas. Försök att radera igen utan delete_files=false."
},
"review": {
"jobNotFound": "Jobbet hittades inte",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "เลือกดนตรีบรรเลงแล้ว กำลังเริ่มสร้างวิดีโอ",
"instrumentalSelectionError": "เกิดข้อผิดพลาดในการเลือกดนตรีบรรเลงสำหรับงาน {job_id}: {error}",
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}",
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว"
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว",
"deletePublishedRequiresFiles": "ไฟล์ที่เผยแพร่แล้วของแทร็กนี้ต้องถูกลบออกเมื่อลบงาน โปรดลองลบใหม่อีกครั้งโดยไม่ใช้ delete_files=false"
},
"review": {
"jobNotFound": "ไม่พบงาน",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Napili na ang instrumental. Nagsimula na ang paggawa ng video.",
"instrumentalSelectionError": "Error sa pagpili ng instrumental para sa job {job_id}: {error}",
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}",
"fileNoLongerAvailable": "Hindi na available ang file"
"fileNoLongerAvailable": "Hindi na available ang file",
"deletePublishedRequiresFiles": "Kailangang tanggalin ang mga na-publish na file ng track na ito kapag na-delete ang job. Subukang i-delete muli nang walang delete_files=false."
},
"review": {
"jobNotFound": "Hindi nahanap ang job",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Enstrümantal seçildi. Video oluşturma başladı.",
"instrumentalSelectionError": "{job_id} işi için enstrümantal seçme hatası: {error}",
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}",
"fileNoLongerAvailable": "Dosya artık mevcut değil"
"fileNoLongerAvailable": "Dosya artık mevcut değil",
"deletePublishedRequiresFiles": "İş silindiğinde bu parçanın yayınlanmış dosyaları da kaldırılmalıdır. Silme işlemini delete_files=false olmadan tekrar dene."
},
"review": {
"jobNotFound": "İş bulunamadı",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Інструментал вибрано. Розпочато генерацію відео.",
"instrumentalSelectionError": "Помилка вибору інструменталу для завдання {job_id}: {error}",
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}",
"fileNoLongerAvailable": "Файл більше недоступний"
"fileNoLongerAvailable": "Файл більше недоступний",
"deletePublishedRequiresFiles": "Опубліковані файли цього треку потрібно видалити під час видалення завдання. Повтори спробу видалення без delete_files=false."
},
"review": {
"jobNotFound": "Завдання не знайдено",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "Đã chọn nhạc nền. Đã bắt đầu tạo video.",
"instrumentalSelectionError": "Lỗi khi chọn nhạc nền cho công việc {job_id}: {error}",
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}",
"fileNoLongerAvailable": "Tệp không còn khả dụng"
"fileNoLongerAvailable": "Tệp không còn khả dụng",
"deletePublishedRequiresFiles": "Các tệp đã xuất bản của bài hát này phải được xóa khi xóa tác vụ. Vui lòng thử xóa lại mà không có delete_files=false."
},
"review": {
"jobNotFound": "Không tìm thấy công việc",
+2 -1
View File
@@ -48,7 +48,8 @@
"instrumentalSelected": "已选择伴奏。已开始生成视频。",
"instrumentalSelectionError": "为任务 {job_id} 选择伴奏时出错:{error}",
"downloadUrlsError": "获取下载 URL 时出错:{error}",
"fileNoLongerAvailable": "文件已不可用"
"fileNoLongerAvailable": "文件已不可用",
"deletePublishedRequiresFiles": "删除任务时,必须移除此曲目已发布的文件。请去掉 delete_files=false 后重试删除。"
},
"review": {
"jobNotFound": "未找到任务",
+13
View File
@@ -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
+3
View File
@@ -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,
)
+47 -11
View File
@@ -209,14 +209,42 @@ 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:
# Server-side pre-apply: apply the AI corrections + heuristic
# fixes BEFORE the review-ready notification fires, so the
# review screen loads one final state (no in-browser auto-apply
# race). Best-effort + bounded: on any miss the UI falls back to
# its client-side on-load apply.
from backend.services.auto_approval.pre_apply import ensure_and_pre_apply
with job_span("pre-apply-corrections", job_id):
pre_apply_result = await ensure_and_pre_apply(job_id)
if pre_apply_result.get("outcome") == "pre_applied":
job_log.info(
f"Pre-applied {pre_apply_result.get('applied', 0)} AI corrections "
"server-side before review notification"
)
# 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 +589,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 +603,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 +634,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)
+66 -1
View File
@@ -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
@@ -326,7 +346,17 @@ Content-Type: application/json
}
```
Generates preview video during review. The `use_background_image` option controls whether the preview renders with the theme's background image (slower, ~30-60s) or a solid black background (faster, ~10s). Defaults to black background for speed.
Generates a preview video during review. Returns `{"status": "success", "preview_hash": "..."}` when the video is immediately available (cache hit — the hash is deterministic over the correction data — or local render), or `{"status": "generating", "preview_hash": "..."}` when encoding continues in the background on a GCE worker. In the generating case, poll the status endpoint below; the request never waits for the encoder (cold-starting a worker VM can take minutes, longer than Cloudflare's edge timeout).
The `use_background_image` option controls whether the preview renders with the theme's background image (slower, ~30-60s) or a solid black background (faster, ~10s). Defaults to black background for speed.
#### Poll Preview Status
```http
GET /api/review/{job_id}/preview-video/{preview_hash}/status
```
Returns `{"status": "ready" | "generating" | "error", "preview_hash": "...", "message"?: "..."}`. Backed by GCS (mp4 existence / error marker), so polls work across Cloud Run instances. Once ready, fetch the video via `GET /api/review/{job_id}/preview-video/{preview_hash}`.
#### Stream Audio
@@ -1144,6 +1174,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.
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more