Compare commits

...
20 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 113197293b fix: restore missing (Title/End).mov + original audio in Dropbox folders (#842)
## Summary
- Organised Dropbox track folders stopped containing the 5-second screen
videos (`(Title).mov`/`(End).mov`) and the original input audio
(`(flacfetch).flac` / `(uploaded).mp3`). Root cause:
`_upload_to_dropbox` uploads the whole `output_dir`, and the
monolith→distributed-GCE migration quietly narrowed what lands there.
- Restores both file types for new jobs, adds an audio-only backfill for
past jobs, and adds a daily-E2E guard so this regression class is caught
automatically.
- Bundles a CLI fix for an ffmpeg interactive-prompt hang in
`--finalise-only` (found while regenerating the missing files locally).

## Changes
**Screen `.mov`s (forward):** GCE encoder copies its generated
`title/end.mov` into `outputs/` with canonical names → plumbed via
`EncodingOutput.title_mov_path`/`end_mov_path`, the `GCEEncodingBackend`
filename mapping, and `_download_gce_encoded_files` back into
`output_dir`.

**Original audio (forward):** new `backend/services/original_audio.py`
(source tag `(uploaded)`/`(flacfetch)`/`(YouTube)` + GCS path +
filename); orchestrator `_stage_original_audio_for_upload()` fetches it
into `output_dir` before folder uploads (non-fatal, only when a folder
upload will occur).

**Backfill (audio only):** `backend/scripts/backfill_original_audio.py`
— dry-run by default, `--live` to upload, skips when audio is gone from
GCS or already present. `.mov` can't be backfilled (needs re-encode).
Adds `DropboxService.file_exists` (re-raises non-not-found `ApiError`).

**Daily E2E guard:** `audio_download_worker` records original audio in
`file_urls['input']['audio']`; `_upload_results` registers
`title_mov`/`end_mov` under `file_urls['finals']`;
`happy-path-real-user.spec.ts` STEP 10.5 asserts the admin files
manifest contains `finals/title_mov`, `finals/end_mov`, `input/audio`,
`finals/lossless_4k_mp4`.

**CLI ffmpeg-hang fix:** `karaoke_finalise` only added `-y` in
non-interactive mode, so a pre-existing output made ffmpeg block on an
invisible `Overwrite? [y/N]` prompt until the 600s timeout (silently
aborting at step 2/6). `-y` is now unconditional +
`stdin=subprocess.DEVNULL` on all ffmpeg `subprocess.run` calls.

## Testing
- [x] 38 new/updated unit tests; all affected suites green
(`encoding_interface`, `video_worker_orchestrator`,
`gce_encoding_worker`, `original_audio`, `backfill_original_audio`,
`dropbox_service`, `upload_results_screen_movs`,
`audio_download_worker`, full `karaoke_finalise` suite)
- [x] Full backend suite: +38 passing vs main, 0 new failures (12
pre-existing `asyncio.get_event_loop()` ordering failures on main,
unrelated)
- [x] Output-file completeness now verified by the daily GHA E2E (STEP
10.5)

## Review
- [x] Local CodeRabbit review completed (scoped to this branch) — 1
major finding fixed (`file_exists` masking non-not-found errors),
re-review clean (0 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-06-17 17:11:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b6dcf6602d feat: match-judge improvements — parallel tidy + hard gate, two-way toggle, weak-tier AI verify, preview perf (#841)
## Summary

Four follow-ups to the artist/title **match judge** (shipped in
v0.184.1), per
`docs/archive/2026-06-16-match-judge-improvements-prompt.md`:

### 1. Race fix — parallel tidy + hard gate
The judge previously ran only *after* the audio search resolved, leaving
a window where a user could select audio with un-tidied metadata (or
have a late verdict clobber their pick).
- Split into a **`fast`** catalog-only pass (fired on mount, parallel
with the audio search) and a **`full`** pass (with the tier, may use
AI). New `stage` field + `needs_ai` marker on
`/api/catalog/match-judge`.
- **Hard-gate** all audio-selection buttons until the judge settles,
with a subtle "Checking song details…" indicator. A 12s safety timeout
guarantees release. Impossible to reach Step 3 with un-tidied metadata
in the normal flow.

### 2. Two-way tidy/correction toggle
The notice now switches **both directions** — canonical ⇄ what-you-typed
— instead of a one-way undo. The current value is always clear.

### 3. Title-screen preview performance
`TitleCardPreview` + `KaraokeBackgroundPreview` rendered a 3840×2160
(4K) canvas and loaded a 2.7 MB 4K PNG for a small thumbnail.
- Render at preview resolution (960×540, dpr-aware) via a scale
transform.
- Low-res background assets (~540 KB) for the preview; 4K stays for the
real render path.
- Preload backgrounds at Step 2; show a loading spinner.

### 4. Catalog-match trust — verify weak matches with AI
A confident catalog match could land on a junk/misspelled Spotify entry
(prod: `Queen / Bohemian Rapsody` → wrongly "already canonical"). Now,
when audio results are weak (tier 3), the AI judge verifies the catalog
match and can override. Extra cost (~$0.0003/call) only on weak-result
cases.

## Testing
- **Backend:** new unit tests for `fast`/`full` staging, `needs_ai`,
weak-tier AI override + keep-catalog-on-unconfident/failure/disabled;
route tests for `stage` forwarding. Full suite green (3510 passed).
- **Frontend:** Jest coverage for fast-on-mount, gate disable→enable,
12s timeout release, full-pass-only-when-needed, two-way toggle;
`TitleCardPreview` preview-resolution canvas + low-res bg + spinner.
Full unit suite green (1024 passed).
- `make test` green; `tsc` introduces zero net-new errors; ESLint clean.

## i18n
6 new keys (`matchUsingTyped`, `matchUseTidied`, `matchUseCorrection`,
`matchChecking`, `titleCardPreview.loading`,
`karaokeBackgroundPreview.loading`) translated to all 32 locales.

## Notes
Preserves all "constraints from history": no Step-1 autocomplete,
cosmetic never restarts the audio search, deferred job creation, public
brand rule, audio-before-customize ordering.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 02:15:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a0b94f95a2 fix(encoding): pin in-flight render polls to the submission worker (#840)
## Problem

A blue-green encoding-worker deploy that swaps the Firestore primary
pointer (`active_url`) **mid-render** caused in-flight status polls to
migrate from the worker actually encoding the job to the just-swapped
new primary, which returns 404 `Encoding job <ID> not found`. After 5
consecutive poll failures the render was failed — even though the
original worker finished the encode fine.

**Incident 2026-06-16, job `d3af33ae`** (error-monitor alert). Confirmed
from logs + Firestore:
- 04:31:39 render submitted to worker-a; encoding begins
- 04:33:46.985 deploy swaps `primary_vm` worker-a → worker-b
(`last_swap_at`)
- 04:33:53–04:34:33 polls hit worker-b (never had the job) → 404 ×5 →
render failed
- worker-a was alive and finished the encode the whole time; user
retried 12 min later and it succeeded

The 4 poll failures happened **before** worker-a was stopped (04:34:33),
proving the orphaning is at the **poll layer** — the 2026-06-15 drain
fix (which keeps the old VM alive) can't catch it.

## Fix

Pin in-flight polls to the worker that accepted the job — the poll
follows the job, not the floating primary pointer.

- `_request_with_retry(..., allow_failover=True)` — gates the
fallback-VM warmup + URL re-resolution (default `True` keeps capacity
fallback unchanged).
- `get_job_status(job_id, worker_url=None)` — pinned polls target the
given worker with `allow_failover=False` (never re-route / never spin up
a fallback VM — a fresh VM can't have the in-flight job).
- `wait_for_completion(..., worker_url=None)` — threads the pinned URL
into every poll.
- `render_video_on_gce` / `encode_videos` / `encode_preview_video` —
capture the worker URL **after** submit (reflects a capacity-fallback
re-route, precedes any later swap) and pin the wait to it.

URL re-resolution stays correct for capacity fallback (dead primary,
fresh submission); it's only suppressed for in-flight polls.

## Tests

New `TestWorkerUrlPinning` in `test_encoding_service.py`, including an
**end-to-end swap regression** where `active_url` has swapped to a
404'ing worker and the render still completes by polling the submission
worker (fails before the fix, passes after). Plus pinned-vs-active
resolution, failover suppression, and poll threading.

`391 passed` across encoding / render-worker / review suites. No
regressions.

## Docs / version
- `docs/LESSONS-LEARNED.md` + `docs/TROUBLESHOOTING.md` (runbook note) +
plan doc in `docs/archive/`
- version `0.184.1 → 0.184.2`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 01:53:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 654e331dd4 docs: match-judge improvements prompt doc (next session) (#839)
Prompt doc for a fresh session to implement 4 match-judge follow-ups
(decisions already captured from Andrew):

1. **Race** — tidy in parallel with audio search + hard-gate 'Use This
Audio' until both search & judge resolve.
2. **Reversible 'keep what I typed'** — two-way toggle showing both
values.
3. **Title-screen preview perf** — render at display res, low-res bg,
preload at step 2, spinner.
4. **Catalog trust** — when audio results are weak (tier 3), run the AI
even if the catalog 'matched' (fixes junk Spotify entries
short-circuiting the judge).

Docs-only, no version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 04:27:19 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 4a550c34cd fix(match-judge): raise AI timeout to fix Vertex 504 DEADLINE_EXCEEDED (#838)
Bumps the match-judge AI timeout from 3s to 12s.

Prod verification of #836 confirmed the endpoint works (cosmetic tidy +
catalog canonical correct, graceful fallback, no crashes), but the AI
judge layer was failing with **504 DEADLINE_EXCEEDED** —
`gemini-3.5-flash` could not finish generation within the 3s deadline.
The model id is valid; the timeout was just too tight.

Fix: `MATCH_JUDGE_TIMEOUT_MS` default 3000 -> 12000ms. Still bounded and
off the critical path (the call degrades to a `none` verdict on
timeout); for comparison the auto_correct service uses 120s.

Verified locally: backend match-judge tests still green. Will re-verify
the AI path live after deploy.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 23:07:21 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 ffa9558db5 feat: artist/title match-judge — auto-tidy formatting, replace 'database' panel (#836)
## Summary

Reworks the **artist/title matching, suggestions & auto-correction** on
Step 2 of the Create Karaoke Video flow. The confusing green **"Song
found in our database"** panel is gone; formatting is now tidied
intelligently and (mostly) invisibly.

Driven by a new backend **match judge**: a deterministic normalizer +
the karaoke-decide catalog run first, and a light Vertex Gemini model
(`gemini-3.5-flash`) is consulted **only** when those aren't confident.

### Behaviour (Step 2)
- **Cosmetic** fix (casing/punctuation/diacritics, same song) → applied
**silently**, with a quiet *"Tidied to X · keep what I typed"* line.
**Never** re-runs the audio search.
- **Confident content** fix (e.g. `Yesteray → Yesterday`) → applied with
a *"Corrected to X · Undo"* line, and re-runs the audio search **only
when the original results were weak** (tier 3).
- **Ambiguous** → ask-first *"Did you mean…?"* prompt before changing
anything.
- **None** → no change.

Resilient by design: the judge never blocks job creation — on
timeout/error it returns `none`. Kill switch:
`MATCH_JUDGE_ENABLED=false` (deterministic + catalog still run).

## Why
The catalog panel existed only to nudge official formatting (quality bar
for published tracks), but read like "we already have this karaoke
video." User feedback flagged it as confusing. This preserves the
formatting-hygiene benefit while removing the friction/confusion. Design
+ history review in
`docs/archive/2026-06-15-artist-title-matching-rework-plan.md`.

## Preserved (hard-won lessons honoured)
- No Step-1 autocomplete; suggestions stay on Step 2.
- Cosmetic correction never restarts the audio search (existing
`onArtistTitleCorrection` no-restart path reused).
- Deferred job-creation / search-session pattern untouched.
- `stringSimilarity`/`findFuzzyMatches` kept as pure utils (existing
tests green).
- No changes to step structure, visibility/customize ordering, or the
public-style brand rule.

## Changes
- **Backend**: `backend/services/match_judge/` (classifier → AI judge →
orchestration), `POST /api/catalog/match-judge`, config
(`MATCH_JUDGE_ENABLED`/`MATCH_JUDGE_MODEL`/`MATCH_JUDGE_TIMEOUT_MS`).
- **Frontend**: `api.matchJudge`, Step 2 rewired, green panel removed,
new `MatchNotice` component; 5 `jobFlow` i18n keys across all 33
locales.
- **Docs**: API.md endpoint section + design/plan doc. Version →
0.183.0.

## Testing
- Full suite green: backend (unit + integration + emulator, coverage
gate passed) + **1008 frontend tests** + e2e.
- New: 20 backend tests (classifier, AI mapping, orchestration,
endpoint) + updated `AudioSourceStep` tests (cosmetic tidy, ambiguous
ask, none, failure-silent) + preserved fuzzy-matching tests.
- CodeRabbit: 1 finding fixed (Literal types), 1 false positive.

## Follow-ups (separate PRs)
- Title-screen preview perf (4K canvas/bg → low-res + preload +
spinner).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 18:02:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 2002b5eddf ci(tenant-e2e): move daily run to ~8pm US Eastern (#837)
## Summary
- Moves the tenant-portal daily E2E from **07:37 UTC** (~3:37am ET) to
**00:07 UTC** (~8pm US Eastern — 8:07pm EDT / 7:07pm EST), so the soak
runs land in the evening when they can be watched / manually tested
alongside.
- Cron is fixed-UTC, so the local time shifts 1h across DST (noted in
the comment). Minute kept off the :00 mark.

CI-config only (one-line cron change).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 21:49:35 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 814ac50aca fix(encoder): fail-safe the active-jobs guards so a busy VM isn't stopped mid-render (#835)
## Summary
- The GCE encoder VMs have two stop paths that guard against killing a
busy worker by checking `/health`'s `active_jobs` — but **both fail
OPEN**, treating an unreachable/slow `/health` as "0 active jobs" and
stopping the VM anyway.
- Under load a busy encoder runs a 4K ffmpeg on all 32 cores and shares
uvicorn with the encode, so `/health` can miss its window *while the VM
is hard at work*. Combined with blue/green deploy churn (every merge
cycles the VMs) + the 5-min idle check, this stopped VMs **mid-render**,
orphaning the in-memory job → backend polls got 404 → "lost contact with
worker ... not found".
- **Incident 2026-06-15:** 12 occurrences, all self-inflicted by rapid
PR merges (#831–#834) during the tenant E2E retries; **0 in the prior
48h**. Not tenant-specific; affects consumer renders too in the same
deploy/idle-during-render window.

## Changes
- **`infrastructure/functions/encoding_worker_idle/main.py`** —
`check_active_jobs()` now returns `None` (not `0`) on any failure, with
3 retries. The idle loop keeps a VM alive for the cycle when the count
is unconfirmed or the VM has no reachable IP; it only stops on a
**confirmed** `active_jobs == 0`. A genuinely idle VM answers `/health`
fast and is still reclaimed next run.
- **`.github/workflows/ci.yml`** ("Drain and stop old primary") — new
`probe_active_jobs` helper distinguishes a real integer from
`"unknown"`; the drain loop only stops on a definitive `0`, or after a
bounded **20-min** timeout (was 10) so a render finishes comfortably
while a wedged worker still can't block the deploy forever. Dropped an
unused `API_KEY` fetch.
- **`docs/LESSONS-LEARNED.md`** — "Is It Busy?" guards must fail safe,
not fail open.

## Testing
- [x] Idle-shutdown unit tests pass (24, incl. new fail-safe cases +
direct `check_active_jobs` contract tests)
- [x] Bash `probe_active_jobs` classification unit-checked (curl-fail /
missing-field / garbage → `unknown`; only real int → number)
- [x] `ci.yml` YAML + actionlint clean (no new findings in the changed
step)
- [x] CodeRabbit CLI review: 0 findings
- No backend/frontend wheel code changed → no version bump (avoids an
unnecessary encoder redeploy)

## Review
- [x] Local CodeRabbit review completed (0 findings)

## Deploy note
The idle Cloud Function deploys via Pulumi (`infrastructure/`); the
`ci.yml` change takes effect on the next workflow run. Per repo
convention, run `pulumi up` locally before merging.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:03:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 21e8a05c61 test(tenant): retry daily E2E once on transient encoder failure (#834)
@coderabbitai ignore

The shared GCE encoder intermittently drops a job mid-encode ("lost
contact with worker ... not found") — a pre-existing,
**non-tenant-specific** transient (it hit the daily E2E twice but not
the manual runs; both tenants complete when the encoder cooperates). The
daily health check now detects that specific error and retries the whole
job once, so it doesn't false-alarm on encoder flakiness. Other failures
still fail immediately. Test-script only.

Separately worth a look (out of scope here): the encoder "lost contact /
job not found" reliability affects consumer renders too.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 10:28:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 460f18d47d fix(ci): run tenant E2E matrix sequentially (#833)
@coderabbitai ignore

The daily tenant E2E ran both tenants concurrently and overwhelmed the
single shared GCE encoder ("Encoding job lost contact with worker... not
found"). Both tenants pass individually (verified). Serialize the matrix
(`max-parallel: 1`) so the daily run doesn't self-inflict encoder
contention. CI-config only.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 09:58:49 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 defaf85230 fix(ci): tenant E2E workflow — drop invalid matrix-context job 'if' (#832)
@coderabbitai ignore

The daily tenant E2E workflow used the `matrix` context in a job-level
`if`, which GitHub Actions rejects ("Unrecognized named-value:
'matrix'") — so the workflow (incl. the scheduled run) failed to parse.
Removed the per-tenant dispatch filter; the workflow always runs both
tenants (the intended daily behavior). `workflow_dispatch` takes no
inputs.

CI/workflow-config only.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 09:47:37 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1218337346 test(tenant): daily E2E asserts portal downloads via file_urls (#831)
@coderabbitai ignore

The daily tenant E2E asserted on `job.download_urls` (backed by
`output_files`, which the orchestrator pipeline never populates), so it
failed even on fully-successful jobs. The `OutputLinks` UI reads
`job.file_urls` (finals/packages) — assert that instead.

Confirmed in prod: **both vocalstar and singa pass the full E2E** — job
completes, Dropbox link present, no YouTube, and all downloads available
(4K / 720p / with-vocals MP4 + CDG + TXT). Doc updated with the final
outcome.

Test/docs only — no production code change.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 09:44:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6fe01f2d6f fix(tenant): stage instrumental under the name the GCE encoder globs for (#830)
@coderabbitai ignore

Third and decisive iteration on the GCE encode of existing-instrumental
(tenant) jobs.

#828/#829 staged the instrumental but under names the **running**
encoder doesn't look for. The live encoder VM (`encoding-worker-b`)
boots the **2026-01-23 image**, whose `custom` instrumental branch globs
only for `*custom_instrumental*.{flac,mp3}` / `*Instrumental Custom*` —
**not** `*existing_instrumental*` / `*Instrumental User*` (those
patterns were added 2026-03-04, after the image). Tenant jobs run with
`instrumental_selection='custom'`, so they hit that branch and failed
"No instrumental audio found".

**Fix:** in the orchestrator's `_run_encoding`, server-side copy the
supplied instrumental from `uploads/{job}/audio/existing_instrumental.*`
→ `jobs/{job}/custom_instrumental.<ext>` — a name the encoder's `custom`
branch finds — sourced from the authoritative GCS object (no local-temp
dependency). Image-agnostic and verified against the old image's actual
glob patterns.

> The encoder VM is also 5 months stale (boots a
pre-existing-instrumental image). Recreating the `encoding-worker` VMs
from the image family's newest image is a worthwhile separate Pulumi
pass, but this fix unblocks tenant jobs on the current VM.

Validated by re-running the full prod E2E to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 08:37:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 66dcfd7d19 fix(tenant): stage instrumental in the orchestrator encode path (#829)
@coderabbitai ignore

Follow-up to #828. That PR staged the instrumental in `_encode_via_gce`
(legacy `video_worker.py`), but production jobs run the **orchestrator**
pipeline (`video_worker_orchestrator.py`), whose `_run_encoding` builds
its own `EncodingInput` and never made the user-supplied instrumental
available under `jobs/{job_id}/`. Tenant jobs still failed at the GCE
encoder with "No instrumental audio found" (confirmed — the "Staged
existing instrumental" log never appeared).

**Fix:** in the orchestrator's `_run_encoding`, when using the GCE
backend, upload the local instrumental (existing/custom — identified by
the `(Instrumental User)` / `(Instrumental Custom)` filename) into
`jobs/{job_id}/` so the encoder's recursive `find_file` locates it.
Consumer `clean`/`backing` jobs are untouched (their stems already live
under `jobs/{job_id}/`).

Also: the daily E2E uses a tenant-specific title so the two matrix
tenants don't share a `base_name` (the GCE encoder caches by base_name).

Validated by re-running the full prod E2E to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 07:44:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 40c7960854 fix(tenant): stage instrumental for the GCE encoder + daily tenant E2E (#828)
@coderabbitai ignore

## Final render blocker (bug #8)

With #824/#825/#826/#827, tenant jobs now render the karaoke video — but
the GCE encoder failed with **"No instrumental audio found"**.

**Root cause:** the user-supplied instrumental lives under
`uploads/{job}/audio/`, but the encoder only pulls input from
`jobs/{job}/` (`input_gcs_path`) and locates the instrumental via
`find_file("*existing_instrumental*", "*Instrumental User*")`. On top of
that, the running encoder VM (`encoding-worker-b`) boots a **2026-01-23
image** that predates the encoder's own `existing_instrumental`
config-download path (added 2026-03-04), so it could never fetch it from
`uploads/` either.

**Fix (image-agnostic — no risky shared-VM recreation, no consumer
impact):** `_encode_via_gce` server-side copies the instrumental into
`jobs/{job_id}/existing_instrumental.<ext>` before submitting. The
encoder downloads `jobs/{job}/` and its **recursive** `find_file` then
locates it on any image version. Added `StorageService.copy_blob` + unit
test.

> Note: the stale encoder VM image is a separate infra item — the
`encoding-worker` VMs should be recreated from the image family's newest
image (which has 3 months of encoder fixes). Tracked for a Pulumi pass;
not required for this fix.

## Daily tenant E2E (second ask)
- `scripts/e2e/tenant_e2e.py` — full per-tenant prod health check:
submit → approve review → render → assert (completes, Dropbox link
present, no YouTube, downloads available) → clean up job + uploads.
- `.github/workflows/e2e-tenant-daily.yml` — daily matrix (vocalstar,
singa), WIF auth, Discord + email on failure.
- `docs/archive/2026-06-15-tenant-portals-e2e.md` — the full story (8
bugs, all fixed).

## Testing
- `copy_blob` unit test; storage suite green (20).
- Full tenant E2E re-run to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 06:49:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d6bd2f1787 fix(tenant): complete the render for jobs that supply their own instrumental (#827)
@coderabbitai ignore

## Two final render blockers (found by the Vocal Star E2E)

With attribution (#824), the audio slot (#825), and transcription
padding (#826) fixed, the first real tenant job advanced through
transcription → screens → review → render, surfacing the last two
never-exercised issues:

### 1. Render prerequisites — "No instrumental selected"
existing-instrumental jobs (every tenant submission) have no
instrumental-selection UI step, so `instrumental_selection` was never
written to state_data. The video orchestrator then defaults to `'clean'`
(a separated stem that was never produced for these jobs), and
`_validate_prerequisites` rejects the job, leaving it stuck retrying.

**Fix:** `complete-review` now defaults `instrumental_selection` to
`'custom'` (use the provided instrumental) when
`existing_instrumental_gcs_path` is set. An explicit request value still
wins. The render path already supports `'custom'`.

### 2. Theme asset paths (reproducibility)
The tenant setup scripts wrote full `gs://bucket/themes/.../assets/X`
URLs, but `theme_service._build_style_assets_mapping` only resolves bare
basenames (the consumer convention). With `gs://` URLs, `style_assets`
came back empty → assets never downloaded → encoder failed with "Video
background image not found". Scripts now emit basenames, and add the
newly-required `extra_text_text_transform` field the strict theme
validator expects.

(The two live GCS themes — vocalstar, singa — were corrected out-of-band
to match.)

## Testing
- New regression tests: complete-review defaults to `custom` for
existing-instrumental jobs; explicit selection still wins.
- Review suites green (102). Full E2E re-run to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 05:34:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c94a5b8754 fix(audioshake): remux user audio with leading null padding before transcription (#826)
@coderabbitai ignore

## Problem (found by the real Vocal Star E2E)

After #824/#825, the first real Vocal Star job reached transcription but
**AudioShake rejected the asset**: `400 ... "Error fetching or
processing asset"`.

Root cause: the supplied MP3 — and **Vocal Star's entire bulk batch** —
begins with ~731 leading `0x00` bytes before the first ID3/MPEG frame.
`ffmpeg`/`ffprobe` tolerate it (the audio decodes fine), but
AudioShake's asset processing does not.

Consumer jobs never hit this because their audio is re-encoded into
clean stems by the separator before transcription. Tenant /
existing-instrumental jobs upload the user's **raw** file straight to
AudioShake.

## Fix
`AudioUploadOptimizer.prepare_for_upload` now detects leading null
padding on padding-prone compressed formats (`.mp3/.aac/.mp4a` — **not**
container formats like `.mp4/.mov`, which legitimately start with a null
box-size prefix) and **losslessly remuxes** (`ffmpeg -c copy`, no
re-encode) before upload.

## Verified against the real AudioShake API
- padded file → `create_task` **400** ("Error fetching or processing
asset")
- remuxed file (same upload path) → `create_task` **200** ✓

Regression tests added (detection + routing + container-format safety).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 04:12:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 829ff02bdb fix(tenant): transcribe the mixed audio, not the supplied instrumental (#825)
@coderabbitai ignore

## Problem (found by the first real tenant E2E)

After #824 made tenant jobs attribute correctly, the first real Vocal
Star job **failed at transcription**: `Lyrics transcription failed: 400
... audioshake.ai/tasks`. Firestore showed `input_media_gcs_path`
pointing at `existing_instrumental.mp3` — transcription was running on
the **instrumental**, not the vocals.

**Root cause:** in the `existing_instrumental` flow (every tenant
submission), the mixed audio and the instrumental are uploaded into the
**same** `uploads/{job_id}/audio/` directory:
- mixed → `audio/<filename>`
- instrumental → `audio/existing_instrumental.*`

On `uploads-complete`, resolving the `'audio'` slot listed the whole
`audio/` dir and took `files[0]` — which sorts to
`existing_instrumental.mp3` (`e` < most letters). So the instrumental
became the transcription input.

This was a **latent bug never hit in prod** because no
existing-instrumental job had ever run end-to-end (0 tenant jobs ever,
per #824).

## Fix
Extract `_select_mixed_audio_files()` to exclude the
existing-instrumental file when selecting the `'audio'` (mixed,
with-vocals) input. Regression tests added (incl. real filenames).

## Testing
- New regression tests + `test_file_upload.py`/`test_upload_api.py`
green (156).
- Re-running the real Vocal Star E2E to completion after this deploys.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 03:22:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fea6ebec1a fix(tenant): make white-label B2B portals attribute jobs to the tenant (Vocal Star + Singa) (#824)
@coderabbitai ignore

## Problem

The white-label tenant portals (`vocalstar.nomadkaraoke.com`,
`singa.nomadkaraoke.com`) looked "done" but **had never worked
end-to-end**: 0 of the last 484 production jobs carried a `tenant_id`.
No tenant job had ever run.

**Root cause:** the frontend API client never sent the `X-Tenant-ID`
header. Tenant portals call the shared `api.nomadkaraoke.com`, whose
Host isn't the tenant subdomain, and the `?tenant=` query param is
disabled in prod — so the backend could never detect the tenant. Every
tenant sign-in and job submission silently fell back to consumer
behavior (default theme, no tenant Dropbox, etc.). The
`getTenantHeaders()` helper existed and was unit-tested, but was never
wired into requests.

## Changes

**Frontend** (`lib/api.ts`, `lib/tenant.ts`)
- Attach `X-Tenant-ID` on all authenticated requests **and** the
magic-link request, sourced from `window.__TENANT_CONFIG__`
(edge-injected by the Cloudflare function; mirrored from the tenant
store for dev/preview). Consumer build resolves no tenant → no header →
**behavior unchanged**.

**Backend** (`_apply_tenant_overrides` in `file_upload.py`)
- Make tenant config **authoritative** over global distribution
defaults. Prod sets `DEFAULT_DROPBOX_PATH` / `DEFAULT_GDRIVE_FOLDER_ID`
/ `DEFAULT_BRAND_PREFIX` globally; these seed `dist`, and the old "fill
only when unset" overlay let them leak — so every tenant job would have
landed in the **shared consumer Dropbox folder** and uploaded to the
**global Google Drive**. Now Dropbox/GDrive routing is gated by the
tenant feature flags and cleared when disabled.

**Tenant configs** (GCS + setup scripts, Vocal Star + Singa)
- Disable Google Drive (`gdrive_upload=false`, `gdrive_folder_id=null`),
keep YouTube off, enable Dropbox to each tenant's own folder. B2B =
locked theme, no YouTube/GDrive, Dropbox + portal download only.

## Why it's consumer-safe
- Frontend: header only attached when a tenant is resolved (never on
`gen.nomadkaraoke.com`).
- Backend: `_apply_tenant_overrides` early-returns when `tenant_config
is None` (all consumer jobs).

## Testing
- New: frontend header-attachment tests (tenant build vs consumer);
backend authoritative-override + feature-flag-gating regression guards
(incl. the global-default-leak case).
- Full suites green: **3466 backend**, **1013 frontend**.
- Verified live tenant configs via API after update.

Manual prod E2E (real track through each portal) + a daily per-tenant
E2E workflow follow in a second PR, once this deploys and is verified in
prod.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 02:40:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fd331a643f infra: GCP cost reductions (artifact cleanup, NAT egress, weekly backup) (#823)
Part of the June 2026 cost-reduction effort
(`docs/archive/2026-06-14-gcp-cost-reduction-plan.md`). Targets the
post-credit-expiry (2026-09-19) bill.

## Changes
- **Item 4 — Artifact Registry cleanup** (~$6/mo + caps growth): keep 10
most-recent versions + delete untagged digests >7d, on all 3 repos
(karaoke-repo, karaoke-backend-gpu, audio-separator; 92 GiB, previously
no policy). In-place update.
- **Item 5 — NAT egress** (~$26/mo): ephemeral GHA runners now always
get an external IP, so egress bypasses the Cloud NAT data-processing
charge (runners were the NAT's only user; us-central1 IN_USE_ADDRESSES
quota is 69, usage 1).
- **Item 6 — backup cadence** (~$15/mo): Firestore export stays nightly
to GCS (1-day local restore point) but uploads to S3 only on Sundays
(1-week off-site RPO) — Firestore is the bulk of the cross-cloud egress.
Staging keeps only the latest export so the weekly upload ships exactly
one.
- **Item 1 — encoding disks** (~$35/mo): pinned the 4 worker hyperdisks
to the free baseline (3000 IOPS / 140 MB/s) **live via `gcloud`**, not
IaC — setting it in IaC forces a capacity-risky VM replacement. A code
comment documents this.

## Deploy status
- `pulumi up` (artifact policies + runner function): **applied** locally
(prod, update 751).
- Backup function source: shipped via
`functions/backup_to_aws/deploy.sh` (pulumi doesn't manage the source
zip).
- Encoding disks: tuned live via gcloud.

## Tests
- `backup_to_aws`: 13 pass (added firestore-cleanup + s3-exclude
coverage).
- `runner_manager/ephemeral`: 32 pass (updated external-IP assertion).

Item 7 (fallback disks on-demand) intentionally deferred — reliability
tradeoff not worth ~$20/mo. See plan doc.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 17:11:18 -04:00
116 changed files with 5517 additions and 601 deletions

No files matched your search

+38 -20
View File
@@ -1399,29 +1399,47 @@ jobs:
run: |
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
# Probe the worker's active_jobs. Echoes a non-negative integer on a
# successful /health response, or "unknown" if /health can't be
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
# encoder running a 4K render pins all 32 cores and can miss the 5s
# health window, and treating that as idle previously let us stop the
# VM mid-render — orphaning the job and surfacing as "lost contact
# with worker ... not found" (incident 2026-06-15).
probe_active_jobs() {
local body n
body=$(curl -sf --connect-timeout 3 --max-time 5 \
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
case "$n" in
''|*[!0-9]*) echo "unknown" ;;
*) echo "$n" ;;
esac
}
if [ "$ACTIVE_JOBS" -gt 0 ]; then
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
DRAIN_TIMEOUT=600
ELAPSED=0
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
if [ "$ACTIVE_JOBS" -eq 0 ]; then
break
fi
done
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
# waiting — we only stop on a definitive 0 (or after the timeout, so
# a wedged worker can't block the deploy forever). 20 min comfortably
# covers a full 4K render; the old primary only drains in-flight work
# since new renders already route to the just-swapped new primary.
DRAIN_TIMEOUT=1200
ELAPSED=0
ACTIVE_JOBS=$(probe_active_jobs)
echo "Initial active_jobs: $ACTIVE_JOBS"
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(probe_active_jobs)
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
done
if [ "$ACTIVE_JOBS" = "0" ]; then
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
else
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
fi
echo "Stopping old primary: $OLD_PRIMARY"
gcloud compute instances stop "$OLD_PRIMARY" \
--zone=us-central1-c --project=nomadkaraoke || true
+104
View File
@@ -0,0 +1,104 @@
name: E2E Daily Test (Tenant Portals)
# Full production E2E per white-label tenant: submit a job with the tenant's own
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
on:
schedule:
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
# top-of-hour scheduler herd.
- cron: '7 0 * * *'
workflow_dispatch: {}
permissions:
contents: read
id-token: write # for Workload Identity Federation
jobs:
e2e-tenant:
name: "Tenant E2E: ${{ matrix.tenant }}"
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
max-parallel: 1
matrix:
tenant: [vocalstar, singa]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Authenticate to GCP
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Install dependencies
run: pip install google-cloud-storage google-cloud-secret-manager
- name: Run tenant E2E
id: run_test
env:
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
run: |
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Upload logs
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
path: e2e-output.log
retention-days: 14
- name: Discord notification (failure)
if: ${{ steps.run_test.outputs.exit_code != '0' }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
run: |
if [ -n "$DISCORD_WEBHOOK" ]; then
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
"$DISCORD_WEBHOOK" || true
fi
- name: Fail the job if the test failed
if: ${{ steps.run_test.outputs.exit_code != '0' }}
run: exit 1
notify-email:
name: "Email summary"
runs-on: ubuntu-latest
needs: e2e-tenant
if: ${{ always() && github.event_name == 'schedule' }}
steps:
- name: Send email notification
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.postmarkapp.com
server_port: 587
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
body: |
Tenant E2E Daily Test (Vocal Star + Singa)
Result: ${{ needs.e2e-tenant.result }}
Run: #${{ github.run_number }}
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
+61 -1
View File
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
import logging
import time
from typing import Optional
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
@@ -103,6 +103,38 @@ class CommunityCheckResponse(BaseModel):
best_youtube_url: Optional[str] = None
class MatchJudgeRequest(BaseModel):
"""Request body for the artist/title match judge."""
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
# The audio search's confidence tier (1=strong..3=weak), so the judge can
# tell whether weak results hint at a typo. Optional.
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
# parallel with the audio search; "full" = complete pipeline once the tier is
# known. Defaults to "full" so a single legacy call still works.
stage: Literal["fast", "full"] = "full"
class MatchJudgeAlternative(BaseModel):
artist: str
title: str
class MatchJudgeResponse(BaseModel):
"""Verdict on a typed artist/title — formatting + match acceptance."""
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
confident: bool
canonical_artist: str
canonical_title: str
alternatives: list[MatchJudgeAlternative] = []
engine: str # "deterministic" | "catalog" | "ai"
reason: str = ""
# Set by a "fast" pass that couldn't decide — the client should follow up with
# a "full" call once the audio tier is known.
needs_ai: bool = False
# --- Routes ---
@@ -161,3 +193,31 @@ async def check_community_versions(
from backend.services.karaokenerds_service import check_community_versions
result = await check_community_versions(body.artist, body.title)
return result
@router.post("/match-judge", response_model=MatchJudgeResponse)
async def match_judge(
request: Request,
body: MatchJudgeRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Judge a typed artist/title: decide official formatting + whether it matches a
real song. Deterministic + catalog layers run first; a light AI model fires
only when those aren't confident. Never blocks the submission flow — failures
degrade to a "none" verdict.
"""
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.match_judge.service import judge_match
verdict = await judge_match(
body.artist, body.title,
audio_tier=body.audio_confidence_tier,
stage=body.stage,
)
logger.info(
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
)
return verdict.to_dict()
+32 -11
View File
@@ -57,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
router = APIRouter(tags=["jobs"])
def _select_mixed_audio_files(files):
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
the instrumental — so transcription would run on the backing track instead of the
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
"""
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
def _apply_tenant_overrides(
dist: EffectiveDistributionSettings,
tenant_config,
@@ -67,12 +80,20 @@ def _apply_tenant_overrides(
"""
Apply tenant-specific overrides to distribution settings and job options.
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
distribution settings, so tenant outputs never inherit the global consumer defaults
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
tenant job would land in the shared consumer Dropbox folder and upload to the global
Google Drive, regardless of the tenant's own config.
For tenant jobs:
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
(only when not already set in the request body / dist)
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
otherwise disables that channel entirely (no global-default leak)
- Forces is_private = True
- Applies locked_theme as effective theme
- Disables YouTube upload
- Disables YouTube upload (tenants never publish to YouTube)
Returns:
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
@@ -81,14 +102,12 @@ def _apply_tenant_overrides(
return dist, effective_theme_id, is_private, enable_youtube_upload
defaults = tenant_config.defaults
features = tenant_config.features
# Overlay tenant distribution defaults (request-level values take precedence)
if defaults.brand_prefix and not dist.brand_prefix:
dist.brand_prefix = defaults.brand_prefix
if defaults.dropbox_path and not dist.dropbox_path:
dist.dropbox_path = defaults.dropbox_path
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
dist.gdrive_folder_id = defaults.gdrive_folder_id
# Authoritative distribution routing (overrides any global defaults in `dist`).
dist.brand_prefix = defaults.brand_prefix
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
# Force private for all tenant jobs
is_private = True
@@ -1382,12 +1401,14 @@ async def mark_uploads_complete(
# List files with this prefix to find the actual uploaded file
files = storage_service.list_files(prefix)
if file_type == 'audio':
files = _select_mixed_audio_files(files)
if not files:
raise HTTPException(
status_code=400,
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
)
# Use the first (and should be only) file found
gcs_path = files[0]
+7
View File
@@ -1475,6 +1475,13 @@ async def complete_review(
try:
# Store instrumental selection if provided (combined review flow)
instrumental_selection = body.instrumental_selection if body else None
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
# render uses the provided instrumental instead of a separated stem that was never
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
instrumental_selection = 'custom'
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
if instrumental_selection:
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
+13
View File
@@ -104,6 +104,19 @@ class Settings(BaseSettings):
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
# Match judge — artist/title formatting + match-acceptance for the job
# submission flow. Deterministic + catalog layers always run; the light AI
# layer (Vertex Gemini Flash) fires only when those aren't confident.
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
"true", "1", "yes",
)
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
# Bounds the AI call so a hung model never strands the submission UI. Kept
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
# call still runs off the critical path and degrades to "none" on timeout.
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
# Cloud Tasks (for scalable worker coordination)
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
# When disabled (default), workers are triggered via direct HTTP (for development)
+1
View File
@@ -0,0 +1 @@
"""Operational and maintenance scripts for the karaoke-gen backend."""
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""Backfill original input audio into past jobs' Dropbox folders.
Restores files like ``<artist> - <title> (flacfetch).flac`` / ``(uploaded).mp3`` to
the organised Dropbox track folders for completed jobs that predate the pipeline fix
(the distributed pipeline stopped copying the source audio into the output folder).
Dry-run by default; pass ``--live`` to actually upload. NOTE: this cannot backfill the
screen ``.mov`` files — those require re-encoding the job.
Usage:
python -m backend.scripts.backfill_original_audio # dry-run, since 2026-03-01
python -m backend.scripts.backfill_original_audio --live # actually upload
python -m backend.scripts.backfill_original_audio --since 2026-02-01 --limit 50 -v
"""
import argparse
import logging
import os
import tempfile
from datetime import datetime, timezone
from backend.models.job import JobStatus
from backend.services.original_audio import (
original_audio_gcs_path,
original_audio_output_filename,
)
logger = logging.getLogger("backfill_original_audio")
# The regression window: screen/audio files stopped reaching Dropbox once the
# distributed pipeline took over (last known-good folder ~Feb; PR #647/#650 Mar 31).
DEFAULT_SINCE = "2026-03-01"
def plan_job_backfill(job, *, storage, dropbox):
"""Decide what to do for one job (existence checks only — no uploads).
Returns ``(action, detail)`` where action is one of:
- ``"skip-no-dropbox"`` — job was never uploaded to Dropbox
- ``"skip-no-audio-record"`` — no original-audio reference on the job
- ``"skip-audio-missing-gcs"`` — original audio no longer in GCS (detail=gcs_path)
- ``"skip-already-present"`` — file already in the Dropbox folder (detail=remote_path)
- ``"upload"`` — detail={gcs_path, remote_path, filename}
"""
from karaoke_gen.utils import sanitize_filename
state = getattr(job, "state_data", None) or {}
brand_code = state.get("brand_code")
dropbox_path = getattr(job, "dropbox_path", None)
if not brand_code or not dropbox_path:
return ("skip-no-dropbox", None)
gcs_path = original_audio_gcs_path(job)
if not gcs_path:
return ("skip-no-audio-record", None)
if not storage.file_exists(gcs_path):
return ("skip-audio-missing-gcs", gcs_path)
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
base_name = f"{safe_artist} - {safe_title}"
filename = original_audio_output_filename(job, base_name)
folder = f"{dropbox_path.rstrip('/')}/{brand_code} - {base_name}"
remote_path = f"{folder}/{filename}"
if dropbox.file_exists(remote_path):
return ("skip-already-present", remote_path)
return ("upload", {"gcs_path": gcs_path, "remote_path": remote_path, "filename": filename})
def _execute_upload(detail, *, storage, dropbox):
"""Download the original audio from GCS and upload it to the Dropbox folder."""
with tempfile.TemporaryDirectory() as td:
local = os.path.join(td, detail["filename"])
storage.download_file(detail["gcs_path"], local)
dropbox.upload_file(local, detail["remote_path"])
def run_backfill(*, since, until=None, limit, environment, live):
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.dropbox_service import get_dropbox_service
jm = JobManager()
storage = StorageService()
dropbox = get_dropbox_service()
if not dropbox.is_configured:
logger.error("Dropbox not configured; aborting.")
return
jobs = jm.list_jobs(
status=JobStatus.COMPLETE,
environment=environment,
created_after=since,
created_before=until,
limit=limit,
)
logger.info(
"Considering %d completed jobs since %s (env=%s)",
len(jobs), since.date(), environment,
)
tally = {}
for job in jobs:
try:
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
except Exception as e:
# A transient GCS/Dropbox error while planning shouldn't abort the whole run.
logger.error(" planning failed for %s: %s", getattr(job, "job_id", "?"), e)
tally["error"] = tally.get("error", 0) + 1
continue
tally[action] = tally.get(action, 0) + 1
if action == "upload":
verb = "uploading" if live else "[DRY-RUN] would upload"
logger.info("%s: %s -> %s", verb, job.job_id, detail["remote_path"])
if live:
try:
_execute_upload(detail, storage=storage, dropbox=dropbox)
except Exception as e:
logger.error(" upload failed for %s: %s", job.job_id, e)
tally["upload"] -= 1
tally["error"] = tally.get("error", 0) + 1
else:
logger.debug("%s: %s (%s)", action, job.job_id, detail)
logger.info("=== Backfill summary (%s) ===", "LIVE" if live else "DRY-RUN")
for k in sorted(tally):
logger.info(" %-24s %d", k, tally[k])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--since", default=DEFAULT_SINCE, help="Only jobs created on/after YYYY-MM-DD")
parser.add_argument("--until", default=None, help="Only jobs created before YYYY-MM-DD")
parser.add_argument("--limit", type=int, default=1000)
parser.add_argument("--env", default="production", dest="environment")
parser.add_argument("--live", action="store_true", help="Actually upload (default: dry-run)")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(message)s",
)
since = datetime.strptime(args.since, "%Y-%m-%d").replace(tzinfo=timezone.utc)
until = (
datetime.strptime(args.until, "%Y-%m-%d").replace(tzinfo=timezone.utc)
if args.until else None
)
run_backfill(since=since, until=until, limit=args.limit, environment=args.environment, live=args.live)
if __name__ == "__main__":
main()
+31
View File
@@ -151,6 +151,37 @@ class DropboxService:
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
return next_code
def file_exists(self, remote_path: str) -> bool:
"""
Check whether a file exists at the given Dropbox path.
Args:
remote_path: Dropbox path (must start with /)
Returns:
True if a file exists at the path, False otherwise.
"""
from dropbox.exceptions import ApiError
if not remote_path.startswith("/"):
remote_path = f"/{remote_path}"
try:
self.client.files_get_metadata(remote_path)
return True
except ApiError as e:
# Only a genuine "not found" means the file is absent. Re-raise other
# API errors (auth, network, rate limit) so callers don't mistake a
# transient failure for "missing" (e.g. the backfill uploading a dup).
err = e.error
if (
hasattr(err, "is_path")
and err.is_path()
and err.get_path().is_not_found()
):
return False
raise
def upload_file(self, local_path: str, remote_path: str) -> None:
"""
Upload a single file to Dropbox.
+12
View File
@@ -65,6 +65,12 @@ class EncodingOutput:
lossless_mkv_path: Optional[str] = None # MKV with FLAC (for YouTube)
lossy_720p_mp4_path: Optional[str] = None # 720p web version
# Standalone 5-second screen videos generated from the title/end images.
# Kept so they land in the Dropbox folder (regression after #647/#650 moved
# screen generation to the encoder). Not used downstream.
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
# All output files as a dict for convenience
output_files: Dict[str, str] = field(default_factory=dict)
@@ -385,6 +391,10 @@ class GCEEncodingBackend(EncodingBackend):
output_files["mp4_720p"] = path
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
output_files["with_vocals_mp4"] = path
elif filename_lower.endswith("(title).mov"):
output_files["title_mov"] = path
elif filename_lower.endswith("(end).mov"):
output_files["end_mov"] = path
self.logger.info(f"Converted output_files list to dict: {output_files}")
else:
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
@@ -396,6 +406,8 @@ class GCEEncodingBackend(EncodingBackend):
lossless_mkv_path=output_files.get("mkv_4k"),
lossy_720p_mp4_path=output_files.get("mp4_720p"),
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
title_mov_path=output_files.get("title_mov"),
end_mov_path=output_files.get("end_mov"),
output_files=output_files,
encoding_time_seconds=encoding_time,
encoding_backend=self.name
+53 -8
View File
@@ -350,6 +350,7 @@ class EncodingService:
timeout: float = 30.0,
job_id: str = "unknown",
path: Optional[str] = None,
allow_failover: bool = True,
) -> Dict[str, Any]:
"""
Make an HTTP request with retry logic for transient failures.
@@ -371,6 +372,13 @@ class EncodingService:
fallback VM in another zone) and invalidate the URL cache; the
next retry then targets the freshly-routed URL instead of the
original primary which is dead.
allow_failover: When True (default), a connection error fires the
fallback-VM warmup and lets retries re-resolve the URL. Set False
for requests pinned to a specific worker (in-flight status polls):
a pinned poll must never re-route to active_url nor spin up a
fallback VM, because a different/fresh VM cannot have the job — it
would only return "not found" and orphan a render that is actually
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
Returns:
Dict with keys:
@@ -392,7 +400,7 @@ class EncodingService:
# active_override change made by the warmup actually takes effect.
# Without this, all 8 retry attempts hammer the original (dead)
# URL even though the warmup successfully routed to a fallback VM.
if path and warmup_ran and self._worker_manager is not None:
if allow_failover and path and warmup_ran and self._worker_manager is not None:
resolved = f"{self._get_worker_url()}{path}"
if resolved != url:
logger.info(
@@ -424,7 +432,7 @@ class EncodingService:
}
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
last_exception = e
if attempt == 0:
if allow_failover and attempt == 0:
try:
await self._warmup_encoding_worker_fallback(job_id)
warmup_ran = True
@@ -530,12 +538,23 @@ class EncodingService:
return resp["json"]
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
async def get_job_status(
self, job_id: str, worker_url: Optional[str] = None
) -> Dict[str, Any]:
"""
Get the status of an encoding job.
Args:
job_id: Job identifier
worker_url: When set, pin the request to this worker base URL instead
of resolving the current active_url. In-flight polls must stay on
the worker that accepted the job: a blue-green deploy can swap the
active_url primary pointer mid-render, and an unpinned poll would
migrate to the new primary — which never received the job and 404s
"not found", orphaning a render that is succeeding on the original
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
disables failover (allow_failover=False) so it never re-routes nor
starts a fallback VM.
Returns:
Job status including: status, progress, error, output_files
@@ -546,7 +565,10 @@ class EncodingService:
raise RuntimeError("Encoding service not configured")
path = f"/status/{job_id}"
url = f"{self._get_worker_url()}{path}"
if worker_url:
url = f"{worker_url}{path}"
else:
url = f"{self._get_worker_url()}{path}"
headers = {"X-API-Key": self._api_key}
resp = await self._request_with_retry(
@@ -555,7 +577,10 @@ class EncodingService:
headers=headers,
timeout=30.0,
job_id=job_id,
path=path,
# When pinned, never re-resolve or fail over — the job lives on this
# exact worker; do not pass `path` (which drives re-resolution).
path=None if worker_url else path,
allow_failover=not worker_url,
)
if resp["status"] == 401:
@@ -573,6 +598,7 @@ class EncodingService:
poll_interval: float = 10.0,
timeout: float = 3600.0,
progress_callback=None,
worker_url: Optional[str] = None,
) -> Dict[str, Any]:
"""
Poll for encoding job completion with tolerance for transient failures.
@@ -587,6 +613,11 @@ class EncodingService:
poll_interval: Seconds between status checks
timeout: Maximum time to wait (default 1 hour)
progress_callback: Optional callback(progress: int) for progress updates
worker_url: Worker base URL the job was submitted to. When set, every
poll is pinned to this worker (see get_job_status) so a mid-render
blue-green primary swap can't migrate the poll to a worker that
never received the job. When None, polls resolve active_url (legacy
behaviour, e.g. direct callers/tests).
Returns:
Final job status with output files
@@ -607,7 +638,7 @@ class EncodingService:
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
try:
status = await self.get_job_status(job_id)
status = await self.get_job_status(job_id, worker_url=worker_url)
# Reset failure counter on successful poll
consecutive_failures = 0
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
@@ -708,11 +739,14 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion (still holding the slot — the worker is
# actually doing CPU work for `job_id` until poll returns
# complete/failed).
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
job_id, progress_callback=progress_callback, worker_url=pinned_url
)
async def submit_preview_encoding_job(
@@ -837,11 +871,15 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion with shorter timeout
return await self.wait_for_completion(
job_id=job_id,
poll_interval=poll_interval,
timeout=timeout,
worker_url=pinned_url,
)
async def submit_render_video_job(
@@ -961,11 +999,18 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# Pin status polls to the worker the job actually landed on. Resolving
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
# the URL cache) while being BEFORE any later blue-green deploy swap —
# so the poll follows the job, not the floating active_url primary
# pointer (incident 2026-06-16, job d3af33ae).
pinned_url = self._get_worker_url()
# Wait for completion (still holding the slot — the worker is
# actively rendering for `job_id` until poll returns
# complete/failed).
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
job_id, progress_callback=progress_callback, worker_url=pinned_url
)
async def health_check(self) -> Dict[str, Any]:
+14
View File
@@ -827,6 +827,20 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
jobs[job_id]["progress"] = 90
# Include the standalone 5-second screen videos in the uploaded outputs so they
# land in the Dropbox folder. They are generated above (or passed in) purely as
# concat inputs and used to live only in screens/; copy them into outputs/ with
# the canonical names. Regression fix: screen MOVs disappeared from Dropbox after
# #647/#650 moved screen generation to this encoder.
for screen_video, suffix in ((title_video, "Title"), (end_video, "End")):
if screen_video and Path(screen_video).is_file():
dest = output_dir / f"{base_name} ({suffix}).mov"
try:
shutil.copy2(screen_video, dest)
logger.info(f"Staged screen video for upload: {dest.name}")
except Exception as e:
logger.warning(f"Failed to stage {suffix} MOV into outputs: {e}")
# Collect output files
output_files = [str(f) for f in output_dir.glob("*") if f.is_file()]
jobs[job_id]["output_files"] = output_files
+8
View File
@@ -0,0 +1,8 @@
"""Artist/title match-judge: deterministic + catalog + light-AI formatting and
match-acceptance decisions for the job-submission flow.
See docs/archive/2026-06-15-artist-title-matching-rework-plan.md.
"""
from backend.services.match_judge.verdict import MatchVerdict
__all__ = ["MatchVerdict"]
+174
View File
@@ -0,0 +1,174 @@
"""The light-AI layer of the match judge.
Invoked only when the deterministic+catalog classifier can't decide. Uses a
small Vertex Gemini model to judge whether the typed artist/title is a real
song, what its canonical formatting is, and whether any change is cosmetic,
content-level, or ambiguous. The model call is injectable for testing.
"""
from __future__ import annotations
import asyncio
import json
import logging
from typing import Awaitable, Callable, Optional
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_CONTENT,
KIND_COSMETIC,
KIND_NONE,
MatchVerdict,
)
logger = logging.getLogger(__name__)
_VALID_KINDS = {KIND_COSMETIC, KIND_CONTENT, KIND_AMBIGUOUS}
Generate = Callable[[str, str, str], Awaitable[dict]]
_SYSTEM_PROMPT = (
"You normalise song metadata for a karaoke service. Given what a user typed "
"for an artist and title (plus optional catalog candidates), decide whether it "
"refers to a real, released song and how its artist/title should be formatted.\n"
"Return JSON with: kind, confident, canonical_artist, canonical_title, "
"alternatives, reason.\n"
"kind:\n"
" 'cosmetic' – same song, only formatting/casing/punctuation/diacritics differ.\n"
" 'content' – the user made a typo or used a wrong/variant title; the correct "
"song text differs in actual characters.\n"
" 'ambiguous' – more than one plausible song matches; list them in alternatives.\n"
" 'none' – already correct, or you cannot confidently suggest anything.\n"
"confident: true only when you are sure. Never invent songs. Prefer the user's "
"input when unsure (kind='none'). canonical_artist/canonical_title must use "
"official formatting. alternatives is a list of {artist,title}."
)
# OpenAPI-style schema handed to the Vertex genai client at runtime.
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
"confident": {"type": "boolean"},
"canonical_artist": {"type": "string"},
"canonical_title": {"type": "string"},
"alternatives": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artist": {"type": "string"},
"title": {"type": "string"},
},
},
},
"reason": {"type": "string"},
},
"required": ["kind", "confident"],
}
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
except Exception: # pragma: no cover - config import guard
return "gemini-3.5-flash"
def build_prompts(
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
) -> tuple[str, str]:
lines = [f'User typed: artist="{artist}" title="{title}"']
if audio_tier is not None:
lines.append(
f"Audio-search confidence tier: {audio_tier} "
"(1 = strong match found, 3 = weak/no results — a weak tier hints the "
"title may be misspelled)."
)
if candidates:
lines.append("Catalog candidates (canonical formatting):")
for c in candidates:
lines.append(f'- {c.get("artist_name", "")} — {c.get("track_name", "")}')
else:
lines.append("No catalog candidates were found.")
return _SYSTEM_PROMPT, "\n".join(lines)
def _verdict_from_response(
data: object, *, fallback_artist: str, fallback_title: str
) -> MatchVerdict:
if not isinstance(data, dict):
data = {}
kind = data.get("kind")
if kind not in _VALID_KINDS:
return MatchVerdict(
KIND_NONE, True, fallback_artist, fallback_title,
engine="ai", reason="no suggestion",
)
canonical_artist = (data.get("canonical_artist") or "").strip() or fallback_artist
canonical_title = (data.get("canonical_title") or "").strip() or fallback_title
alternatives = []
for alt in data.get("alternatives") or []:
if isinstance(alt, dict) and alt.get("artist") and alt.get("title"):
alternatives.append(
{"artist": str(alt["artist"]), "title": str(alt["title"])}
)
return MatchVerdict(
kind=kind,
confident=bool(data.get("confident", False)),
canonical_artist=canonical_artist,
canonical_title=canonical_title,
alternatives=alternatives,
engine="ai",
reason=str(data.get("reason") or ""),
)
async def ai_judge_match(
artist: str,
title: str,
candidates: list[dict],
audio_tier: Optional[int],
*,
model: Optional[str] = None,
generate: Optional[Generate] = None,
) -> MatchVerdict:
model = model or _model()
gen = generate or _default_generate
system_prompt, user_prompt = build_prompts(artist, title, candidates, audio_tier)
data = await gen(model, system_prompt, user_prompt)
return _verdict_from_response(
data, fallback_artist=artist, fallback_title=title
)
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
import copy
from google import genai
from google.genai import types
from backend.config import settings
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
response = client.models.generate_content(
model=model,
contents=[user_prompt],
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
),
)
return json.loads(response.text)
@@ -0,0 +1,82 @@
"""Deterministic + catalog match classification (no AI, no network).
`classify_catalog_match` returns a confident :class:`MatchVerdict` when the
typed artist/title clearly correspond to a catalog candidate (a cosmetic
formatting fix, or nothing to change). When it cannot confidently decide, it
returns ``None`` — the caller should then escalate to the AI judge.
"""
from __future__ import annotations
import re
import unicodedata
from typing import Optional
from karaoke_gen.utils import normalize_text
from backend.services.match_judge.verdict import (
KIND_COSMETIC,
KIND_NONE,
MatchVerdict,
)
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
_WS = re.compile(r"\s+")
def _fold_accents(text: str) -> str:
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
decomposed = unicodedata.normalize("NFKD", text)
return "".join(c for c in decomposed if not unicodedata.combining(c))
def normalize_for_match(text: str) -> str:
"""Aggressive key used only for equality comparison (never displayed).
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
"""
s = normalize_text(text or "")
s = s.replace("&", " and ")
s = _fold_accents(s)
s = s.casefold()
s = _NON_ALNUM.sub(" ", s)
s = _WS.sub(" ", s).strip()
return s
def classify_catalog_match(
artist: str, title: str, candidates: list[dict]
) -> Optional[MatchVerdict]:
"""Return a confident verdict from catalog candidates, or None to escalate.
candidates: dicts with ``artist_name`` and ``track_name`` (Spotify/MB canonical).
"""
key_artist = normalize_for_match(artist)
key_title = normalize_for_match(title)
for cand in candidates:
cand_artist = cand.get("artist_name") or ""
cand_title = cand.get("track_name") or ""
if (
normalize_for_match(cand_artist) == key_artist
and normalize_for_match(cand_title) == key_title
):
# Same song. Cosmetic fix unless the user already typed it exactly.
if cand_artist == artist and cand_title == title:
return MatchVerdict(
kind=KIND_NONE,
confident=True,
canonical_artist=artist,
canonical_title=title,
engine="catalog",
reason="already canonical",
)
return MatchVerdict(
kind=KIND_COSMETIC,
confident=True,
canonical_artist=cand_artist,
canonical_title=cand_title,
engine="catalog",
reason="formatting differs from catalog",
)
return None
+128
View File
@@ -0,0 +1,128 @@
"""Match-judge orchestration.
Composes the deterministic+catalog classifier with the AI judge. The AI judge
runs ONLY when the classifier can't confidently decide, and never blocks or
errors the caller — any failure degrades to "no suggestion".
"""
from __future__ import annotations
import logging
from typing import Awaitable, Callable, Literal, Optional
from backend.services.match_judge.classifier import classify_catalog_match
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
logger = logging.getLogger(__name__)
CATALOG_CANDIDATE_LIMIT = 8
Stage = Literal["fast", "full"]
# Audio tiers at or above this are "weak" (poor / no results). A weak tier hints
# the typed title may be a typo, so even a confident catalog match is verified
# with the AI judge (it can be a junk/misspelled Spotify entry).
WEAK_TIER = 3
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
from backend.services.catalog_proxy_service import search_tracks
return await search_tracks(query, artist, limit)
async def _default_ai_judge(
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
) -> MatchVerdict:
from backend.services.match_judge.ai import ai_judge_match
return await ai_judge_match(artist, title, candidates, audio_tier)
def _default_enabled() -> bool:
try:
from backend.config import settings
return bool(getattr(settings, "match_judge_enabled", True))
except Exception: # pragma: no cover - config import guard
return True
async def judge_match(
artist: str,
title: str,
audio_tier: Optional[int] = None,
*,
stage: Stage = "full",
search_tracks: Optional[SearchTracks] = None,
ai_judge: Optional[AiJudge] = None,
enabled: Optional[bool] = None,
) -> MatchVerdict:
"""Return a :class:`MatchVerdict` for the typed artist/title.
audio_tier: the audio search's confidence tier (1=best..3=poor), used by the
AI judge to decide whether weak results suggest a typo. May be None.
stage:
"fast" — catalog-only pass (no AI, tier ignored). Runs in parallel with the
audio search so the common cosmetic tidy is ready before results render.
Returns the catalog verdict if confident, else a ``needs_ai=True`` marker
telling the caller to make a "full" call once the tier is known.
"full" — the complete pipeline: catalog, then the AI judge when catalog isn't
confident OR (item 4) when a confident catalog match coincides with a weak
audio tier (the match may be a junk/typo'd entry — let AI override).
"""
search = search_tracks or _default_search_tracks
ai = ai_judge or _default_ai_judge
if enabled is None:
enabled = _default_enabled()
try:
candidates = await search(title, artist, CATALOG_CANDIDATE_LIMIT)
except Exception:
logger.warning(
"match-judge catalog search failed; continuing without candidates",
exc_info=True,
)
candidates = []
catalog_verdict = classify_catalog_match(artist, title, candidates)
# Fast pass: catalog only. Never touches the AI layer.
if stage == "fast":
if catalog_verdict is not None:
return catalog_verdict
return MatchVerdict(
KIND_NONE, False, artist, title,
engine="catalog", reason="needs ai", needs_ai=True,
)
# Full pass.
if catalog_verdict is not None:
weak = audio_tier is not None and audio_tier >= WEAK_TIER
if not (enabled and weak):
return catalog_verdict
# Item 4: weak audio results make the typo hypothesis plausible even though
# the catalog "matched" — verify with AI and let a confident verdict override.
try:
ai_verdict = await ai(artist, title, candidates, audio_tier)
except Exception:
logger.exception(
"match-judge AI verification failed; keeping catalog verdict"
)
return catalog_verdict
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
return ai_verdict
return catalog_verdict
if not enabled:
return MatchVerdict(
KIND_NONE, True, artist, title, engine="deterministic", reason="ai disabled"
)
try:
return await ai(artist, title, candidates, audio_tier)
except Exception:
logger.exception("match-judge AI call failed; returning no-suggestion")
return MatchVerdict(
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
)
+47
View File
@@ -0,0 +1,47 @@
"""The verdict returned by the match judge."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Literal
# kind values:
# "cosmetic" – same song, formatting-only fix → apply invisibly
# "content" – actual characters change (typo/different title) → surface + maybe re-search
# "ambiguous" – more than one plausible song → ask the user first
# "none" – nothing to change (already correct, or no confident suggestion)
KIND_COSMETIC = "cosmetic"
KIND_CONTENT = "content"
KIND_AMBIGUOUS = "ambiguous"
KIND_NONE = "none"
Kind = Literal["cosmetic", "content", "ambiguous", "none"]
Engine = Literal["deterministic", "catalog", "ai"]
@dataclass(frozen=True)
class MatchVerdict:
kind: Kind
confident: bool
canonical_artist: str
canonical_title: str
alternatives: list[dict] = field(default_factory=list) # [{"artist","title"}]
engine: Engine = "deterministic"
reason: str = ""
# True only from a "fast" (catalog-only) pass that couldn't confidently decide:
# the caller should escalate to a "full" pass (with the audio tier) for an AI
# verdict. Always False on a full-pass verdict.
needs_ai: bool = False
def to_dict(self) -> dict:
return {
"kind": self.kind,
"confident": self.confident,
"canonical_artist": self.canonical_artist,
"canonical_title": self.canonical_title,
"alternatives": self.alternatives,
"engine": self.engine,
"reason": self.reason,
"needs_ai": self.needs_ai,
}
+73
View File
@@ -0,0 +1,73 @@
"""Helpers for locating and naming a job's original input audio.
The original downloaded/uploaded audio (the source used for separation,
transcription and the With Vocals video) is stored in GCS but is no longer
copied into the final output folder by the distributed pipeline. These helpers
let the orchestrator (and the backfill script) restore it to the Dropbox track
folder with the historical source-tagged name, e.g.::
<artist> - <title> (flacfetch).flac
<artist> - <title> (uploaded).mp3
<artist> - <title> (YouTube).webm
The naming mirrors the legacy monolith convention.
"""
import os
from typing import Optional
# Map a job's audio_source_type to the historical filename suffix.
_SOURCE_TAGS = {
"file_upload": "uploaded",
"youtube_url": "YouTube",
"audio_search": "flacfetch",
}
def original_audio_source_tag(job) -> str:
"""Return the parenthesised source suffix for a job's original audio.
Falls back gracefully for older jobs that predate ``audio_source_type``.
"""
tag = _SOURCE_TAGS.get(getattr(job, "audio_source_type", None))
if tag:
return tag
# Fallbacks for legacy jobs without an explicit source type.
if getattr(job, "url", None):
return "YouTube"
if getattr(job, "filename", None) or getattr(job, "input_media_gcs_path", None):
return "uploaded"
return "input"
def original_audio_gcs_path(job) -> Optional[str]:
"""Return the GCS blob path of the original input audio, or None.
Prefers ``input_media_gcs_path`` (uploads are persisted under jobs/ and URL
jobs record their downloaded file here), then falls back to
``file_urls['input']`` which may be a plain string or a nested
``{'audio': ...}`` dict depending on the code path that wrote it.
"""
path = getattr(job, "input_media_gcs_path", None)
if path:
return path
file_urls = getattr(job, "file_urls", None) or {}
inp = file_urls.get("input")
if isinstance(inp, dict):
return inp.get("audio")
if isinstance(inp, str):
return inp
return None
def original_audio_output_filename(job, base_name: str) -> Optional[str]:
"""Return the output filename for the original audio, or None if absent.
e.g. ``"<artist> - <title> (flacfetch).flac"``. The extension is preserved
from the GCS path.
"""
gcs_path = original_audio_gcs_path(job)
if not gcs_path:
return None
ext = os.path.splitext(gcs_path)[1]
return f"{base_name} ({original_audio_source_tag(job)}){ext}"
+11
View File
@@ -59,6 +59,17 @@ class StorageService:
logger.error(f"Error downloading file {source_path}: {e}")
raise
def copy_blob(self, source_path: str, destination_path: str) -> str:
"""Server-side copy of a blob within the bucket (no download/upload)."""
try:
src = self.bucket.blob(source_path)
self.bucket.copy_blob(src, self.bucket, destination_path)
logger.info(f"Copied gs://{settings.gcs_bucket_name}/{source_path} -> {destination_path}")
return destination_path
except Exception as e:
logger.error(f"Error copying blob {source_path} -> {destination_path}: {e}")
raise
def generate_signed_url(self, blob_path: str, expiration_minutes: int = 60) -> str:
"""Generate a signed URL for downloading a file.
Whitespace-only changes.
@@ -0,0 +1,103 @@
"""Tests for the AI judge: prompt construction + response→verdict mapping.
The model call (`generate`) is injected, so these tests are offline and
deterministic. The real `generate` wraps the Vertex genai client.
"""
import pytest
from backend.services.match_judge.ai import ai_judge_match, build_prompts
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_CONTENT,
KIND_NONE,
)
def _gen(response: dict):
async def generate(model, system_prompt, user_prompt):
return response
return generate
class TestBuildPrompts:
def test_prompt_includes_input_candidates_and_tier(self):
system, user = build_prompts(
"queen",
"bohemian rapsody",
[{"artist_name": "Queen", "track_name": "Bohemian Rhapsody"}],
audio_tier=3,
)
assert "bohemian rapsody" in user
assert "Bohemian Rhapsody" in user # candidate shown
# The poor-results signal must reach the model so it can favour a typo fix.
assert "3" in user
class TestResponseMapping:
@pytest.mark.asyncio
async def test_confident_content_correction(self):
verdict = await ai_judge_match(
"queen",
"bohemian rapsody",
[],
3,
generate=_gen(
{
"kind": "content",
"confident": True,
"canonical_artist": "Queen",
"canonical_title": "Bohemian Rhapsody",
"alternatives": [],
"reason": "typo",
}
),
)
assert verdict.kind == KIND_CONTENT
assert verdict.confident is True
assert verdict.canonical_title == "Bohemian Rhapsody"
assert verdict.engine == "ai"
@pytest.mark.asyncio
async def test_ambiguous_carries_alternatives(self):
verdict = await ai_judge_match(
"",
"bruises",
[],
3,
generate=_gen(
{
"kind": "ambiguous",
"confident": False,
"canonical_artist": "Lewis Capaldi",
"canonical_title": "Bruises",
"alternatives": [{"artist": "Fox Stevenson", "title": "Bruises"}],
"reason": "multiple artists",
}
),
)
assert verdict.kind == KIND_AMBIGUOUS
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
@pytest.mark.asyncio
async def test_unknown_kind_is_treated_as_none(self):
verdict = await ai_judge_match(
"queen",
"bohemian rhapsody",
[],
1,
generate=_gen({"kind": "garbage", "confident": True}),
)
assert verdict.kind == KIND_NONE
assert verdict.canonical_artist == "queen" # falls back to user input
@pytest.mark.asyncio
async def test_missing_canonical_falls_back_to_input(self):
verdict = await ai_judge_match(
"queen",
"bohemian rhapsody",
[],
1,
generate=_gen({"kind": "content", "confident": True}),
)
assert verdict.canonical_artist == "queen"
assert verdict.canonical_title == "bohemian rhapsody"
@@ -0,0 +1,66 @@
"""Tests for the deterministic + catalog match classifier.
The classifier decides, WITHOUT any AI/network call, whether a typed
artist/title cosmetically matches a catalog candidate (so we can silently
tidy formatting) or whether the decision must be escalated to the AI judge.
"""
from backend.services.match_judge.classifier import (
normalize_for_match,
classify_catalog_match,
)
def _cand(artist: str, title: str) -> dict:
return {"artist_name": artist, "track_name": title}
class TestNormalizeForMatch:
def test_casing_and_whitespace_collapse_to_same_key(self):
assert normalize_for_match("Paramore") == normalize_for_match(" paramore ")
def test_punctuation_is_ignored(self):
assert normalize_for_match("Big Man, Little Dignity") == normalize_for_match(
"big man little dignity"
)
def test_ampersand_and_and_are_equivalent(self):
assert normalize_for_match("Jay-Z & Beyonce") == normalize_for_match(
"Jay Z and Beyonce"
)
class TestClassifyCatalogMatch:
def test_casing_only_difference_is_cosmetic(self):
verdict = classify_catalog_match(
"paramore",
"big man, little dignity",
[_cand("Paramore", "Big Man, Little Dignity")],
)
assert verdict is not None
assert verdict.kind == "cosmetic"
assert verdict.confident is True
assert verdict.canonical_artist == "Paramore"
assert verdict.canonical_title == "Big Man, Little Dignity"
assert verdict.engine == "catalog"
def test_exact_match_needs_no_change(self):
verdict = classify_catalog_match(
"Paramore",
"Big Man, Little Dignity",
[_cand("Paramore", "Big Man, Little Dignity")],
)
assert verdict is not None
assert verdict.kind == "none"
assert verdict.confident is True
def test_no_catalog_match_escalates_to_ai(self):
# Returns None => the service should call the AI judge.
verdict = classify_catalog_match(
"queen",
"bohemian rhapsody",
[_cand("Paramore", "Big Man, Little Dignity")],
)
assert verdict is None
def test_empty_candidates_escalates_to_ai(self):
assert classify_catalog_match("queen", "bohemian rhapsody", []) is None
@@ -0,0 +1,272 @@
"""Orchestration tests for the match-judge service.
The service composes the deterministic+catalog classifier with the AI judge:
the AI judge is invoked ONLY when the classifier can't confidently decide.
Catalog search and the AI judge are injected so these tests touch no network.
"""
import pytest
from backend.services.match_judge.service import judge_match
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_COSMETIC,
KIND_CONTENT,
KIND_NONE,
MatchVerdict,
)
def _candidates(*pairs):
async def _search(query, artist, limit):
return [{"artist_name": a, "track_name": t} for a, t in pairs]
return _search
def _ai_never(*_a, **_k):
raise AssertionError("AI judge must not be called")
@pytest.mark.asyncio
async def test_catalog_cosmetic_match_skips_ai():
calls = {"ai": 0}
async def ai(*_a, **_k):
calls["ai"] += 1
raise AssertionError("should not run")
verdict = await judge_match(
"paramore",
"big man, little dignity",
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
assert calls["ai"] == 0
@pytest.mark.asyncio
async def test_no_catalog_match_calls_ai():
seen = {}
async def ai(artist, title, candidates, audio_tier):
seen["candidates"] = candidates
seen["tier"] = audio_tier
return MatchVerdict(
kind=KIND_CONTENT,
confident=True,
canonical_artist="Queen",
canonical_title="Bohemian Rhapsody",
engine="ai",
reason="typo fix",
)
verdict = await judge_match(
"queen",
"bohemian rapsody",
audio_tier=3,
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_CONTENT
assert verdict.engine == "ai"
assert seen["tier"] == 3
assert seen["candidates"] == [{"artist_name": "Queen", "track_name": "Radio Ga Ga"}]
@pytest.mark.asyncio
async def test_disabled_flag_skips_ai_and_returns_none():
verdict = await judge_match(
"queen",
"bohemian rapsody",
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=_ai_never,
enabled=False,
)
assert verdict.kind == KIND_NONE
assert verdict.confident is True
assert verdict.canonical_artist == "queen" # leaves user input untouched
@pytest.mark.asyncio
async def test_ai_failure_falls_back_to_none():
async def ai(*_a, **_k):
raise RuntimeError("model exploded")
verdict = await judge_match(
"queen",
"bohemian rapsody",
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_NONE
assert verdict.canonical_title == "bohemian rapsody"
# --- Fast stage (catalog-only parallel pass) ---
@pytest.mark.asyncio
async def test_fast_stage_returns_catalog_verdict_without_ai():
verdict = await judge_match(
"paramore",
"big man, little dignity",
stage="fast",
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=_ai_never,
enabled=True,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
assert verdict.needs_ai is False
@pytest.mark.asyncio
async def test_fast_stage_undecided_signals_needs_ai_without_calling_ai():
verdict = await judge_match(
"queen",
"bohemian rapsody",
stage="fast",
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=_ai_never,
enabled=True,
)
assert verdict.kind == KIND_NONE
assert verdict.needs_ai is True
assert verdict.confident is False
@pytest.mark.asyncio
async def test_fast_stage_never_calls_ai_even_when_undecided():
# _ai_never raises if called; reaching here proves the fast pass skipped AI.
verdict = await judge_match(
"queen", "bohemian rapsody", stage="fast",
search_tracks=_candidates(), ai_judge=_ai_never, enabled=True,
)
assert verdict.needs_ai is True
# --- Item 4: verify a confident catalog match with AI when the audio tier is weak ---
@pytest.mark.asyncio
async def test_weak_tier_catalog_match_is_verified_and_overridden_by_ai():
async def ai(artist, title, candidates, audio_tier):
return MatchVerdict(
KIND_CONTENT, True, "Queen", "Bohemian Rhapsody",
engine="ai", reason="typo",
)
# Catalog "matched" the user's exact typo (junk entry) → would normally be
# 'none'/already-canonical. Weak tier (3) makes us verify with AI, which overrides.
verdict = await judge_match(
"Queen", "Bohemian Rapsody",
audio_tier=3,
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_CONTENT
assert verdict.canonical_title == "Bohemian Rhapsody"
assert verdict.engine == "ai"
@pytest.mark.asyncio
async def test_strong_tier_catalog_match_still_skips_ai():
verdict = await judge_match(
"Queen", "Bohemian Rapsody",
audio_tier=1,
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
ai_judge=_ai_never,
enabled=True,
)
# Strong audio results → trust the catalog match, no AI.
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_keeps_catalog_verdict_when_ai_unconfident():
async def ai(artist, title, candidates, audio_tier):
return MatchVerdict(KIND_NONE, False, artist, title, engine="ai")
verdict = await judge_match(
"paramore", "big man, little dignity",
audio_tier=3,
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=ai,
enabled=True,
)
# AI wasn't confident about a change → keep the cosmetic catalog tidy.
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_keeps_catalog_verdict_when_ai_fails():
async def ai(*_a, **_k):
raise RuntimeError("model exploded")
verdict = await judge_match(
"paramore", "big man, little dignity",
audio_tier=3,
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_does_not_verify_when_ai_disabled():
verdict = await judge_match(
"paramore", "big man, little dignity",
audio_tier=3,
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=_ai_never,
enabled=False,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_ai_can_escalate_to_ambiguous():
async def ai(artist, title, candidates, audio_tier):
return MatchVerdict(
KIND_AMBIGUOUS, True, "Lewis Capaldi", "Bruises",
alternatives=[{"artist": "Fox Stevenson", "title": "Bruises"}],
engine="ai",
)
verdict = await judge_match(
"capaldi", "bruises",
audio_tier=3,
search_tracks=_candidates(("Lewis Capaldi", "Bruises")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_AMBIGUOUS
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
@pytest.mark.asyncio
async def test_catalog_search_failure_still_lets_ai_run():
async def failing_search(query, artist, limit):
raise RuntimeError("catalog down")
async def ai(artist, title, candidates, audio_tier):
assert candidates == [] # gracefully degraded to no candidates
return MatchVerdict(KIND_NONE, True, artist, title, engine="ai")
verdict = await judge_match(
"queen",
"bohemian rhapsody",
search_tracks=failing_search,
ai_judge=ai,
enabled=True,
)
assert verdict.engine == "ai"
@@ -124,6 +124,11 @@ class TestProcessAudioDownload:
'input_media_gcs_path': "uploads/test-job-123/audio/song.mp3",
'filename': "song.mp3",
})
# Original audio recorded in file_urls so it shows in the admin files
# manifest (and can be staged into the Dropbox folder) for URL/search jobs.
mock_jm.update_file_url.assert_any_call(
"test-job-123", 'input', 'audio', "uploads/test-job-123/audio/song.mp3"
)
mock_jm.transition_to_state.assert_called_once()
mock_ws.trigger_audio_worker.assert_awaited_once_with("test-job-123")
mock_ws.trigger_lyrics_worker.assert_awaited_once_with("test-job-123")
+67
View File
@@ -0,0 +1,67 @@
"""
Regression tests for AudioShake leading-padding handling.
Some user-provided audio (e.g. the Vocal Star bulk-batch MP3s) begins with a block of
null bytes before the first ID3/MPEG frame. ffmpeg tolerates it, but AudioShake rejects
the asset with "Error fetching or processing asset" (400 on /tasks). The AudioUploadOptimizer
must detect this and losslessly remux before upload — while leaving clean files and
container formats (.mp4/.mov, which legitimately start with null box-size bytes) untouched.
"""
import os
import tempfile
from unittest.mock import MagicMock, patch
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioUploadOptimizer
def _write(tmp_path, name, head: bytes):
p = os.path.join(tmp_path, name)
with open(p, "wb") as f:
f.write(head + b"\x00" * 2048)
return p
def test_has_leading_padding_detects_null_start(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
assert opt._has_leading_padding(padded) is True
def test_has_leading_padding_false_for_id3(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
assert opt._has_leading_padding(clean) is False
def test_has_leading_padding_false_for_frame_sync(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "sync.mp3", b"\xff\xfb\xc0\x04")
assert opt._has_leading_padding(clean) is False
def test_padded_mp3_is_remuxed(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
with patch.object(opt, "_remux_clean", return_value=("/tmp/clean.mp3", "/tmp/clean.mp3")) as remux:
result = opt.prepare_for_upload(padded)
remux.assert_called_once()
assert result == ("/tmp/clean.mp3", "/tmp/clean.mp3")
def test_clean_mp3_uploaded_directly(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
with patch.object(opt, "_remux_clean") as remux:
result = opt.prepare_for_upload(clean)
remux.assert_not_called()
assert result == (clean, None)
def test_container_format_not_remuxed_despite_null_start(tmp_path):
""".mp4/.mov begin with a null box-size prefix — must NOT be treated as padding."""
opt = AudioUploadOptimizer(MagicMock())
mp4 = _write(str(tmp_path), "video.mp4", b"\x00\x00\x00\x20ftyp")
with patch.object(opt, "_remux_clean") as remux:
result = opt.prepare_for_upload(mp4)
remux.assert_not_called()
assert result == (mp4, None)
@@ -0,0 +1,80 @@
"""Tests for the original-audio backfill planner (backend/scripts/backfill_original_audio.py)."""
from types import SimpleNamespace
from unittest.mock import MagicMock
from backend.scripts.backfill_original_audio import plan_job_backfill
def _job(**kwargs):
base = dict(
job_id="job-1",
artist="Eddie Money",
title="I'll Get By",
audio_source_type="audio_search",
url=None,
filename=None,
input_media_gcs_path="jobs/job-1/input/track.flac",
file_urls={},
dropbox_path="/Karaoke/Tracks-Organized",
state_data={"brand_code": "NOMAD-1184"},
)
base.update(kwargs)
return SimpleNamespace(**base)
def _services(gcs_exists=True, dropbox_exists=False):
storage = MagicMock()
storage.file_exists.return_value = gcs_exists
dropbox = MagicMock()
dropbox.file_exists.return_value = dropbox_exists
return storage, dropbox
class TestPlanJobBackfill:
def test_upload_when_audio_present_and_not_yet_uploaded(self):
storage, dropbox = _services(gcs_exists=True, dropbox_exists=False)
action, detail = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
assert action == "upload"
assert detail["gcs_path"] == "jobs/job-1/input/track.flac"
assert detail["remote_path"] == (
"/Karaoke/Tracks-Organized/NOMAD-1184 - Eddie Money - I'll Get By/"
"Eddie Money - I'll Get By (flacfetch).flac"
)
assert detail["filename"] == "Eddie Money - I'll Get By (flacfetch).flac"
def test_skip_when_no_brand_code(self):
storage, dropbox = _services()
action, _ = plan_job_backfill(_job(state_data={}), storage=storage, dropbox=dropbox)
assert action == "skip-no-dropbox"
def test_skip_when_no_dropbox_path(self):
storage, dropbox = _services()
action, _ = plan_job_backfill(_job(dropbox_path=None), storage=storage, dropbox=dropbox)
assert action == "skip-no-dropbox"
def test_skip_when_no_audio_record(self):
storage, dropbox = _services()
job = _job(input_media_gcs_path=None, file_urls={})
action, _ = plan_job_backfill(job, storage=storage, dropbox=dropbox)
assert action == "skip-no-audio-record"
def test_skip_when_audio_missing_from_gcs(self):
storage, dropbox = _services(gcs_exists=False)
action, detail = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
assert action == "skip-audio-missing-gcs"
assert detail == "jobs/job-1/input/track.flac"
def test_skip_when_already_present_in_dropbox(self):
storage, dropbox = _services(gcs_exists=True, dropbox_exists=True)
action, _ = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
assert action == "skip-already-present"
def test_sanitizes_artist_title_for_paths(self):
storage, dropbox = _services(gcs_exists=True, dropbox_exists=False)
job = _job(artist="AC/DC", title="T:N/T")
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
assert action == "upload"
# No raw slashes/colons leak into the Dropbox path beyond real separators
tail = detail["remote_path"].split("/NOMAD-1184 - ", 1)[1]
assert ":" not in tail
+60
View File
@@ -471,3 +471,63 @@ class TestCreateSharedLink:
assert url == "https://dropbox.com/s/existing/file.mp4"
class TestFileExists:
"""Test DropboxService.file_exists (used by the original-audio backfill)."""
def test_returns_true_when_metadata_found(self):
from backend.services.dropbox_service import DropboxService
service = DropboxService()
mock_client = MagicMock()
service._client = mock_client
assert service.file_exists("/Karaoke/NOMAD-1 - A - B/A - B (flacfetch).flac") is True
mock_client.files_get_metadata.assert_called_once_with(
"/Karaoke/NOMAD-1 - A - B/A - B (flacfetch).flac"
)
def test_returns_false_on_not_found(self):
from dropbox.exceptions import ApiError
from backend.services.dropbox_service import DropboxService
service = DropboxService()
mock_client = MagicMock()
# Genuine "not found": is_path() -> get_path().is_not_found() == True
not_found_err = MagicMock()
not_found_err.is_path.return_value = True
not_found_err.get_path.return_value.is_not_found.return_value = True
mock_client.files_get_metadata.side_effect = ApiError(
request_id="r", error=not_found_err, user_message_text=None, user_message_locale=None
)
service._client = mock_client
assert service.file_exists("/missing.flac") is False
def test_reraises_non_not_found_api_error(self):
"""Auth/network/rate-limit errors must NOT be masked as 'file missing'."""
from dropbox.exceptions import ApiError
from backend.services.dropbox_service import DropboxService
service = DropboxService()
mock_client = MagicMock()
other_err = MagicMock()
other_err.is_path.return_value = False
mock_client.files_get_metadata.side_effect = ApiError(
request_id="r", error=other_err, user_message_text=None, user_message_locale=None
)
service._client = mock_client
with pytest.raises(ApiError):
service.file_exists("/some.flac")
def test_prepends_leading_slash(self):
from backend.services.dropbox_service import DropboxService
service = DropboxService()
mock_client = MagicMock()
service._client = mock_client
service.file_exists("Karaoke/x.flac")
mock_client.files_get_metadata.assert_called_once_with("/Karaoke/x.flac")
+42
View File
@@ -394,6 +394,48 @@ class TestGCEEncodingBackend:
assert output.lossless_mkv_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv"
assert output.lossy_720p_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4"
@patch.object(GCEEncodingBackend, "_get_service")
@pytest.mark.asyncio
async def test_encode_maps_screen_movs_from_list(self, mock_get_service):
"""Test GCE encoding maps the standalone (Title).mov / (End).mov from output_files list.
The GCE worker now copies the 5-second screen videos into its outputs/ dir so they
upload to GCS finals. The mapper must recognise them and populate
title_mov_path / end_mov_path so the orchestrator downloads them into output_dir
(and thus into the Dropbox folder). Regression for: screen MOVs lost from Dropbox
after #647/#650 moved screen generation to the encoder.
"""
mock_service = MagicMock()
mock_service.encode_videos = AsyncMock(return_value={
"status": "complete",
"output_files": [
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
"jobs/test/finals/Artist - Title (Title).mov",
"jobs/test/finals/Artist - Title (End).mov",
]
})
mock_get_service.return_value = mock_service
backend = GCEEncodingBackend()
input_config = EncodingInput(
title_video_path="/input/title.png",
karaoke_video_path="/input/karaoke.mkv",
instrumental_audio_path="/input/audio.flac",
artist="Artist",
title="Title",
options={
"job_id": "test-job",
"input_gcs_path": "gs://bucket/input/",
"output_gcs_path": "gs://bucket/output/",
}
)
output = await backend.encode(input_config)
assert output.success is True
assert output.title_mov_path == "jobs/test/finals/Artist - Title (Title).mov"
assert output.end_mov_path == "jobs/test/finals/Artist - Title (End).mov"
class TestGetEncodingBackend:
"""Test encoding backend factory function."""
+128 -3
View File
@@ -601,7 +601,7 @@ class TestWaitForCompletionPollTolerance:
"""Tolerates up to MAX_CONSECUTIVE_POLL_FAILURES-1 consecutive failures."""
call_count = 0
async def mock_get_status(job_id):
async def mock_get_status(job_id, worker_url=None):
nonlocal call_count
call_count += 1
if call_count <= 2:
@@ -623,7 +623,7 @@ class TestWaitForCompletionPollTolerance:
@pytest.mark.asyncio
async def test_fails_after_max_consecutive_poll_failures(self, encoding_service):
"""Fails after MAX_CONSECUTIVE_POLL_FAILURES consecutive failures."""
async def always_fail(job_id):
async def always_fail(job_id, worker_url=None):
raise aiohttp.ClientConnectorError(
connection_key=MagicMock(), os_error=OSError("Connection refused")
)
@@ -640,7 +640,7 @@ class TestWaitForCompletionPollTolerance:
"""A successful poll resets the consecutive failure counter."""
call_count = 0
async def intermittent_failures(job_id):
async def intermittent_failures(job_id, worker_url=None):
nonlocal call_count
call_count += 1
# Fail for 2, succeed (running), fail for 2 more, succeed (complete)
@@ -752,3 +752,128 @@ class TestFormatException:
e = aiohttp.ClientConnectorError(MagicMock(), OSError())
# Type name should always appear
assert "ClientConnectorError" in _format_exception(e)
class TestWorkerUrlPinning:
"""Status polls must stay pinned to the worker that ACCEPTED the job.
Regression for incident 2026-06-16 (job d3af33ae): a blue-green deploy
swapped the primary pointer mid-render, and because status polls re-resolved
`active_url` on every call, they migrated from the worker actually encoding
the job (old primary) to the freshly-swapped new primary — which 404'd
"Encoding job ... not found" and failed the render after 5 polls, even though
the original worker finished the encode fine.
"""
@pytest.mark.asyncio
async def test_get_job_status_targets_pinned_url(self, encoding_service):
"""A pinned poll hits the given worker_url, not active_url, and disables
failover (a pinned poll must never re-resolve or spin up a fallback VM —
a fresh VM cannot have the in-flight job)."""
# active_url would resolve to worker-b, but the job lives on worker-a.
captured = {}
async def fake_request(**kwargs):
captured.update(kwargs)
return {"status": 200, "json": {"status": "running", "progress": 40}, "text": None}
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
result = await encoding_service.get_job_status("d3af33ae", worker_url="http://worker-a:8080")
assert result["status"] == "running"
assert captured["url"] == "http://worker-a:8080/status/d3af33ae"
assert captured["allow_failover"] is False
@pytest.mark.asyncio
async def test_get_job_status_without_pin_uses_active_url(self, encoding_service):
"""Regression: unpinned polls still resolve the current active_url."""
captured = {}
async def fake_request(**kwargs):
captured.update(kwargs)
return {"status": 200, "json": {"status": "running"}, "text": None}
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
await encoding_service.get_job_status("d3af33ae")
assert captured["url"] == "http://worker-b:8080/status/d3af33ae"
# Unpinned keeps the existing failover/re-resolution behaviour.
assert captured.get("allow_failover", True) is True
@pytest.mark.asyncio
async def test_wait_for_completion_threads_pinned_url_into_polls(self, encoding_service):
"""wait_for_completion forwards its worker_url to every status poll."""
seen_urls = []
async def mock_get_status(job_id, worker_url=None):
seen_urls.append(worker_url)
return {"status": "complete", "output_files": ["a.mp4"]}
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
result = await encoding_service.wait_for_completion(
"d3af33ae", worker_url="http://worker-a:8080"
)
assert result["status"] == "complete"
assert seen_urls == ["http://worker-a:8080"]
@pytest.mark.asyncio
async def test_request_with_retry_no_failover_when_disabled(self, encoding_service):
"""With allow_failover=False, a connection error must NOT trigger the
fallback-VM warmup nor URL re-resolution — it just retries the same URL
and surfaces the failure to the caller's own poll-tolerance loop."""
encoding_service.set_worker_manager(MagicMock())
warmup = AsyncMock()
with patch.object(encoding_service, "_warmup_encoding_worker_fallback", warmup), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("aiohttp.ClientSession") as mock_session:
mock_session.side_effect = aiohttp.ClientConnectorError(
MagicMock(), OSError("Connection refused")
)
with pytest.raises(aiohttp.ClientConnectorError):
await encoding_service._request_with_retry(
method="GET",
url="http://worker-a:8080/status/j1",
headers={},
job_id="j1",
path=None,
allow_failover=False,
)
warmup.assert_not_called()
@pytest.mark.asyncio
async def test_render_video_keeps_polling_submission_worker_after_swap(self, encoding_service):
"""End-to-end: when active_url has swapped to a worker that 404s, the
render keeps polling the worker the job was submitted to and completes.
This FAILS before the fix (the poll follows active_url to worker-b and
gets "not found"), and PASSES after (the poll is pinned to worker-a)."""
encoding_service.set_worker_manager(MagicMock())
async def fake_submit(job_id, render_config):
return {"status": "accepted", "job_id": job_id}
async def fake_get_status(job_id, worker_url=None):
# worker-a owns the job; the post-swap active worker (worker-b, or an
# unpinned None) has never seen it.
if worker_url == "http://worker-a:8080":
return {"status": "complete", "output_files": ["4k.mp4"]}
raise RuntimeError(f"Encoding job {job_id} not found")
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-a:8080"), \
patch.object(encoding_service, "submit_render_video_job", side_effect=fake_submit), \
patch.object(encoding_service, "get_job_status", side_effect=fake_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
result = await encoding_service.render_video_on_gce("d3af33ae", {"foo": "bar"})
assert result["status"] == "complete"
assert result["output_files"] == ["4k.mp4"]
+47
View File
@@ -508,3 +508,50 @@ class TestWheelVersionSorting:
wheels = ["/tmp/karaoke_gen-current.whl"]
latest = self.select_latest_wheel(wheels)
assert latest is None
class TestScreenVideoStaging:
"""Test that the standalone screen MOVs are copied into outputs/ for upload.
Mirrors the copy logic in run_encoding (kept self-contained, like the other
tests in this file). Regression: (Title).mov / (End).mov disappeared from the
Dropbox folder after #647/#650 moved screen generation into this encoder.
"""
@staticmethod
def stage_screen_videos(title_video, end_video, output_dir: Path, base_name: str):
"""Replicates run_encoding's screen-video staging step."""
import shutil
for screen_video, suffix in ((title_video, "Title"), (end_video, "End")):
if screen_video and Path(screen_video).is_file():
dest = output_dir / f"{base_name} ({suffix}).mov"
shutil.copy2(screen_video, dest)
def test_copies_title_and_end_with_canonical_names(self, tmp_path):
screens = tmp_path / "screens"
screens.mkdir()
title = screens / "title.mov"
end = screens / "end.mov"
title.write_bytes(b"title-mov-bytes")
end.write_bytes(b"end-mov-bytes")
outputs = tmp_path / "outputs"
outputs.mkdir()
self.stage_screen_videos(title, end, outputs, "Artist - Title")
assert (outputs / "Artist - Title (Title).mov").read_bytes() == b"title-mov-bytes"
assert (outputs / "Artist - Title (End).mov").read_bytes() == b"end-mov-bytes"
def test_skips_missing_end_video(self, tmp_path):
screens = tmp_path / "screens"
screens.mkdir()
title = screens / "title.mov"
title.write_bytes(b"title-mov-bytes")
outputs = tmp_path / "outputs"
outputs.mkdir()
# end_video is None (no end screen) — must not raise
self.stage_screen_videos(title, None, outputs, "Artist - Title")
assert (outputs / "Artist - Title (Title).mov").is_file()
assert not (outputs / "Artist - Title (End).mov").exists()
+120
View File
@@ -0,0 +1,120 @@
"""Tests for POST /api/catalog/match-judge."""
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from fastapi.testclient import TestClient
from backend.main import app
from backend.services.match_judge.verdict import MatchVerdict, KIND_COSMETIC, KIND_NONE
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def auth_headers():
return {"Authorization": "Bearer test-admin-token"}
@pytest.fixture(autouse=True)
def clear_rate_limits():
from backend.api.routes.catalog import _rate_limit_windows
_rate_limit_windows.clear()
yield
_rate_limit_windows.clear()
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_returns_verdict(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict(
kind=KIND_COSMETIC,
confident=True,
canonical_artist="Paramore",
canonical_title="Big Man, Little Dignity",
engine="catalog",
reason="casing",
)
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "paramore", "title": "big man, little dignity"},
headers=auth_headers,
)
assert resp.status_code == 200
data = resp.json()
assert data["kind"] == "cosmetic"
assert data["confident"] is True
assert data["canonical_artist"] == "Paramore"
assert data["canonical_title"] == "Big Man, Little Dignity"
assert data["engine"] == "catalog"
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_passes_audio_tier(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b", "audio_confidence_tier": 3},
headers=auth_headers,
)
# judge_match(artist, title, audio_tier=...) — tier forwarded
_, kwargs = mock_judge.call_args
assert kwargs.get("audio_tier") == 3 or mock_judge.call_args.args[2] == 3
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_defaults_to_full_stage(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b"},
headers=auth_headers,
)
_, kwargs = mock_judge.call_args
assert kwargs.get("stage") == "full"
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_forwards_fast_stage(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict(
KIND_NONE, False, "q", "b", engine="catalog", reason="needs ai", needs_ai=True
)
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b", "stage": "fast"},
headers=auth_headers,
)
assert resp.status_code == 200
assert resp.json()["needs_ai"] is True
_, kwargs = mock_judge.call_args
assert kwargs.get("stage") == "fast"
def test_match_judge_rejects_unknown_stage(client, auth_headers):
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b", "stage": "turbo"},
headers=auth_headers,
)
assert resp.status_code == 422
def test_match_judge_validation_error(client, auth_headers):
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "", "title": "Dreams"},
headers=auth_headers,
)
assert resp.status_code == 422
+78
View File
@@ -0,0 +1,78 @@
"""Tests for original-audio naming/location helpers (backend/services/original_audio.py).
These back the regression fix that restores the original input audio
(e.g. '<artist> - <title> (flacfetch).flac') to the Dropbox track folder.
"""
from types import SimpleNamespace
from backend.services.original_audio import (
original_audio_source_tag,
original_audio_gcs_path,
original_audio_output_filename,
)
def _job(**kwargs):
base = dict(
audio_source_type=None,
url=None,
filename=None,
input_media_gcs_path=None,
file_urls={},
)
base.update(kwargs)
return SimpleNamespace(**base)
class TestSourceTag:
def test_file_upload_maps_to_uploaded(self):
assert original_audio_source_tag(_job(audio_source_type="file_upload")) == "uploaded"
def test_youtube_url_maps_to_youtube(self):
assert original_audio_source_tag(_job(audio_source_type="youtube_url")) == "YouTube"
def test_audio_search_maps_to_flacfetch(self):
assert original_audio_source_tag(_job(audio_source_type="audio_search")) == "flacfetch"
def test_legacy_url_job_without_source_type(self):
assert original_audio_source_tag(_job(url="https://youtu.be/x")) == "YouTube"
def test_legacy_upload_without_source_type(self):
assert original_audio_source_tag(_job(filename="song.mp3")) == "uploaded"
def test_unknown_falls_back_to_input(self):
assert original_audio_source_tag(_job()) == "input"
class TestGcsPath:
def test_prefers_input_media_gcs_path(self):
job = _job(input_media_gcs_path="jobs/j1/input/song.mp3",
file_urls={"input": "jobs/j1/other.flac"})
assert original_audio_gcs_path(job) == "jobs/j1/input/song.mp3"
def test_file_urls_input_as_string(self):
job = _job(file_urls={"input": "jobs/j1/input.flac"})
assert original_audio_gcs_path(job) == "jobs/j1/input.flac"
def test_file_urls_input_as_dict(self):
job = _job(file_urls={"input": {"audio": "jobs/j1/input/song.flac"}})
assert original_audio_gcs_path(job) == "jobs/j1/input/song.flac"
def test_none_when_no_source(self):
assert original_audio_gcs_path(_job()) is None
class TestOutputFilename:
def test_flacfetch_flac(self):
job = _job(audio_source_type="audio_search",
input_media_gcs_path="jobs/j1/input/track.flac")
assert original_audio_output_filename(job, "Artist - Title") == "Artist - Title (flacfetch).flac"
def test_uploaded_mp3(self):
job = _job(audio_source_type="file_upload",
input_media_gcs_path="jobs/j1/input/My Song.mp3")
assert original_audio_output_filename(job, "Artist - Title") == "Artist - Title (uploaded).mp3"
def test_none_when_no_audio(self):
assert original_audio_output_filename(_job(), "Artist - Title") is None
+38
View File
@@ -365,6 +365,44 @@ class TestCompleteReviewZeroSegmentValidation:
assert response.status_code == 200
def test_existing_instrumental_defaults_selection_to_custom(self, _patched_client):
"""Jobs that supplied their own instrumental (tenant/existing_instrumental flow)
have no instrumental-selection UI step, so complete-review must default the
selection to 'custom' — otherwise the render defaults to 'clean' (a separated
stem that was never produced) and fails the prerequisite check."""
client, mock_jm = _patched_client
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
mock_jm.update_state_data.assert_any_call(
"job-zero-seg", "instrumental_selection", "custom"
)
def test_existing_instrumental_does_not_override_explicit_selection(self, _patched_client):
"""An explicit instrumental_selection in the request still wins over the default."""
client, mock_jm = _patched_client
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
json={"instrumental_selection": "clean"},
)
assert response.status_code == 200
mock_jm.update_state_data.assert_any_call(
"job-zero-seg", "instrumental_selection", "clean"
)
class TestPreviewStyleLoading:
"""Tests for the unified style loader used in preview video generation.
+28 -1
View File
@@ -38,9 +38,36 @@ class TestStorageServiceInit:
assert service.bucket == mock_bucket
class TestStorageServiceCopy:
"""Test server-side copy (used to stage the tenant instrumental for the GCE encoder)."""
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_copy_blob(self, mock_settings, mock_client_class):
mock_settings.gcs_bucket_name = "test-bucket"
mock_src_blob = Mock()
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_src_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
result = service.copy_blob(
"uploads/job123/audio/existing_instrumental.mp3",
"jobs/job123/existing_instrumental.mp3",
)
mock_bucket.blob.assert_called_once_with("uploads/job123/audio/existing_instrumental.mp3")
mock_bucket.copy_blob.assert_called_once_with(
mock_src_blob, mock_bucket, "jobs/job123/existing_instrumental.mp3"
)
assert result == "jobs/job123/existing_instrumental.mp3"
class TestStorageServiceUpload:
"""Test upload operations."""
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_upload_file(self, mock_settings, mock_client_class):
+91 -8
View File
@@ -56,6 +56,43 @@ def _make_job_mock(**kwargs):
return job
class TestSelectMixedAudioFiles:
"""Regression tests for _select_mixed_audio_files() in file_upload.py.
The existing-instrumental file shares the uploads/{job}/audio/ directory with the
mixed audio, so the 'audio/' prefix matches both. Before the fix, files[0] resolved to
'existing_instrumental.mp3' (it sorts first) and transcription ran on the instrumental.
"""
def _fn(self):
from backend.api.routes.file_upload import _select_mixed_audio_files
return _select_mixed_audio_files
def test_excludes_existing_instrumental(self):
fn = self._fn()
# Listing is sorted alphabetically by GCS, so the instrumental comes first.
files = [
"uploads/job123/audio/existing_instrumental.mp3",
"uploads/job123/audio/mixed.mp3",
]
result = fn(files)
assert result == ["uploads/job123/audio/mixed.mp3"]
assert result[0] == "uploads/job123/audio/mixed.mp3"
def test_plain_audio_only_unchanged(self):
fn = self._fn()
files = ["uploads/job123/audio/My Song.flac"]
assert fn(files) == files
def test_real_filenames_with_instrumental(self):
fn = self._fn()
files = [
"uploads/job123/audio/existing_instrumental.mp3",
"uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3",
]
assert fn(files) == ["uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3"]
class TestApplyTenantOverrides:
"""Tests for _apply_tenant_overrides() in file_upload.py."""
@@ -125,24 +162,70 @@ class TestApplyTenantOverrides:
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
assert yt_upload is False
def test_request_values_take_precedence(self):
"""Explicit request-level values are not overridden by tenant defaults."""
def test_tenant_config_overrides_global_defaults(self):
"""Tenant config is authoritative: it overrides any global/consumer default
distribution settings already seeded into `dist`.
Regression guard: prod sets DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID /
DEFAULT_BRAND_PREFIX globally, which get_effective_distribution_settings seeds
into `dist`. If tenant overrides only filled in *unset* fields, every tenant job
would leak into the shared consumer Dropbox folder and global Google Drive.
"""
apply_fn = self._get_apply_fn()
tenant_config = _make_tenant_config()
# `dist` arrives pre-seeded with the GLOBAL consumer defaults.
dist = EffectiveDistributionSettings(
dropbox_path="/Custom/Path",
gdrive_folder_id="custom-folder",
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized", # global default
gdrive_folder_id="global-consumer-folder", # global default
discord_webhook_url=None,
brand_prefix="CUSTOM",
brand_prefix="NOMAD", # global default
enable_youtube_upload=True,
youtube_description=None,
)
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.brand_prefix == "CUSTOM"
assert new_dist.dropbox_path == "/Custom/Path"
assert new_dist.gdrive_folder_id == "custom-folder"
# Tenant config wins on every distribution field.
assert new_dist.brand_prefix == "VSTAR"
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
def test_gdrive_disabled_clears_global_default(self):
"""When the tenant disables gdrive_upload, the global default GDrive folder is
cleared so the tenant job never publishes to Google Drive (the B2B requirement)."""
apply_fn = self._get_apply_fn()
# Tenant has a gdrive folder configured but the feature is OFF — the disabled
# flag must win, clearing both the configured folder and any global default.
tenant_config = _make_tenant_config()
tenant_config.features.gdrive_upload = False
dist = EffectiveDistributionSettings(
dropbox_path=None,
gdrive_folder_id="global-consumer-folder", # would otherwise leak
discord_webhook_url=None,
brand_prefix=None,
enable_youtube_upload=True,
youtube_description=None,
)
new_dist, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.gdrive_folder_id is None
assert yt_upload is False
def test_dropbox_disabled_clears_path(self):
"""When the tenant disables dropbox_upload, the Dropbox path is cleared."""
apply_fn = self._get_apply_fn()
tenant_config = _make_tenant_config()
tenant_config.features.dropbox_upload = False
dist = EffectiveDistributionSettings(
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized",
gdrive_folder_id=None, discord_webhook_url=None,
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
)
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.dropbox_path is None
def test_no_tenant_config_passthrough(self):
"""When no tenant config, all values pass through unchanged."""
@@ -0,0 +1,72 @@
"""Test that _upload_results registers the standalone screen MOVs in file_urls.
This makes (Title).mov / (End).mov appear in the admin files manifest and verifiable
by the daily E2E. Regression: the screen MOVs were absent from Dropbox track folders.
"""
import os
import tempfile
import pytest
from backend.workers.video_worker import _upload_results
@pytest.mark.asyncio
async def test_upload_results_registers_screen_movs():
with tempfile.TemporaryDirectory() as temp_dir:
# Create local files the orchestrator would have downloaded into output_dir
title_mov = os.path.join(temp_dir, "Artist - Title (Title).mov")
end_mov = os.path.join(temp_dir, "Artist - Title (End).mov")
lossless = os.path.join(temp_dir, "Artist - Title (Final Karaoke Lossless 4k).mp4")
for p in (title_mov, end_mov, lossless):
with open(p, "wb") as f:
f.write(b"x")
from unittest.mock import MagicMock
job_manager = MagicMock()
storage = MagicMock()
storage.upload_file.side_effect = lambda local, gcs: f"gs://bucket/{gcs}"
result = {
"final_video": lossless,
"title_mov": title_mov,
"end_mov": end_mov,
}
await _upload_results("job-1", job_manager, storage, temp_dir, result)
# The screen MOVs are uploaded under finals/ and recorded in file_urls
registered = {
(c.args[1], c.args[2]) for c in job_manager.update_file_url.call_args_list
}
assert ("finals", "title_mov") in registered
assert ("finals", "end_mov") in registered
uploaded_gcs = {c.args[1] for c in storage.upload_file.call_args_list}
assert "jobs/job-1/finals/title_mov.mov" in uploaded_gcs
assert "jobs/job-1/finals/end_mov.mov" in uploaded_gcs
@pytest.mark.asyncio
async def test_upload_results_skips_missing_screen_movs():
"""Jobs without screen MOVs (legacy/None) must not error or register them."""
with tempfile.TemporaryDirectory() as temp_dir:
lossless = os.path.join(temp_dir, "Artist - Title (Final Karaoke Lossless 4k).mp4")
with open(lossless, "wb") as f:
f.write(b"x")
from unittest.mock import MagicMock
job_manager = MagicMock()
storage = MagicMock()
storage.upload_file.side_effect = lambda local, gcs: f"gs://bucket/{gcs}"
result = {"final_video": lossless, "title_mov": None} # end_mov absent entirely
await _upload_results("job-1", job_manager, storage, temp_dir, result)
registered = {
(c.args[1], c.args[2]) for c in job_manager.update_file_url.call_args_list
}
assert ("finals", "title_mov") not in registered
assert ("finals", "end_mov") not in registered
@@ -1058,6 +1058,52 @@ class TestVideoWorkerOrchestratorEncoding:
with pytest.raises(RuntimeError, match="stale"):
await orchestrator._download_gce_encoded_files(output)
@pytest.mark.asyncio
async def test_download_gce_includes_screen_movs(self):
"""Screen MOVs returned by the encoder are downloaded into output_dir.
Regression: the standalone (Title).mov / (End).mov stopped reaching the
Dropbox folder after #647/#650. They must be pulled back like other finals.
"""
with tempfile.TemporaryDirectory() as temp_dir:
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path=os.path.join(temp_dir, "title.png"),
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
output_dir=temp_dir,
)
mock_storage = MagicMock()
mock_storage.download_file = MagicMock()
orchestrator = VideoWorkerOrchestrator(config, storage=mock_storage)
from backend.services.encoding_interface import EncodingOutput
output = EncodingOutput(
success=True,
lossless_4k_mp4_path="jobs/test-job/finals/Test Artist - Test Title (Final Karaoke Lossless 4k).mp4",
title_mov_path="jobs/test-job/finals/Test Artist - Test Title (Title).mov",
end_mov_path="jobs/test-job/finals/Test Artist - Test Title (End).mov",
encoding_time_seconds=0.0,
encoding_backend="gce",
)
await orchestrator._download_gce_encoded_files(output)
downloaded = {os.path.basename(c.args[0]) for c in mock_storage.download_file.call_args_list}
assert "Test Artist - Test Title (Title).mov" in downloaded
assert "Test Artist - Test Title (End).mov" in downloaded
# Result points the screen MOVs at their local copies in output_dir
assert orchestrator.result.title_mov == os.path.join(
temp_dir, "Test Artist - Test Title (Title).mov"
)
assert orchestrator.result.end_mov == os.path.join(
temp_dir, "Test Artist - Test Title (End).mov"
)
class TestVideoWorkerOrchestratorOrganization:
"""Test organization stage."""
@@ -1405,6 +1451,36 @@ class TestCreateOrchestratorConfigFromJob:
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental User).mp3"
def test_create_config_includes_original_audio(self):
"""Config carries the original input audio so it can be staged into the
Dropbox folder. Regression: source audio stopped reaching organised outputs.
"""
job = MagicMock()
job.job_id = "test-123"
job.artist = "Test Artist"
job.title = "Test Title"
job.state_data = {"instrumental_selection": "clean"}
job.enable_cdg = False
job.enable_txt = False
job.enable_youtube_upload = False
job.is_private = False
job.brand_prefix = "NOMAD"
job.discord_webhook_url = None
job.youtube_description_template = None
job.dropbox_path = "/Karaoke"
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
# flacfetch (audio_search) download
job.audio_source_type = "audio_search"
job.input_media_gcs_path = "jobs/test-123/input/track.flac"
config = create_orchestrator_config_from_job(job=job, temp_dir="/tmp/test")
assert config.original_audio_gcs_path == "jobs/test-123/input/track.flac"
assert config.original_audio_filename == "Test Artist - Test Title (flacfetch).flac"
def test_create_config_passes_instrumental_selection(self):
"""Test that instrumental_selection is passed through to OrchestratorConfig.
@@ -1903,3 +1979,73 @@ class TestLrcHasLyricsContent:
lrc_file.write_text("[ti:Song Title]\n[ar:Artist Name]\n[re:MidiCo]\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is False
class TestStageOriginalAudio:
"""Original input audio is staged into output_dir before folder uploads.
Regression: the source audio ((flacfetch).flac / (uploaded).mp3) stopped
appearing in the Dropbox track folder after the move to the distributed
pipeline. It must be fetched from GCS into output_dir before upload.
"""
def _make(self, temp_dir, **overrides):
cfg = dict(
job_id="job-1",
artist="Test Artist",
title="Test Title",
title_video_path=os.path.join(temp_dir, "title.png"),
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
output_dir=temp_dir,
)
cfg.update(overrides)
config = OrchestratorConfig(**cfg)
storage = MagicMock()
return VideoWorkerOrchestrator(config, storage=storage), storage
def test_downloads_original_audio_into_output_dir(self):
with tempfile.TemporaryDirectory() as temp_dir:
orch, storage = self._make(
temp_dir,
original_audio_gcs_path="jobs/job-1/input/track.flac",
original_audio_filename="Test Artist - Test Title (flacfetch).flac",
)
orch._stage_original_audio_for_upload()
storage.download_file.assert_called_once()
args = storage.download_file.call_args.args
assert args[0] == "jobs/job-1/input/track.flac"
assert args[1] == os.path.join(temp_dir, "Test Artist - Test Title (flacfetch).flac")
def test_noop_when_no_original_audio_configured(self):
with tempfile.TemporaryDirectory() as temp_dir:
orch, storage = self._make(temp_dir)
orch._stage_original_audio_for_upload()
storage.download_file.assert_not_called()
def test_skips_when_already_present(self):
with tempfile.TemporaryDirectory() as temp_dir:
fname = "Test Artist - Test Title (uploaded).mp3"
# File already in output_dir (e.g. legacy/local run)
with open(os.path.join(temp_dir, fname), "wb") as f:
f.write(b"existing")
orch, storage = self._make(
temp_dir,
original_audio_gcs_path="jobs/job-1/input/song.mp3",
original_audio_filename=fname,
)
orch._stage_original_audio_for_upload()
storage.download_file.assert_not_called()
def test_download_failure_is_non_fatal(self):
with tempfile.TemporaryDirectory() as temp_dir:
orch, storage = self._make(
temp_dir,
original_audio_gcs_path="jobs/job-1/input/track.flac",
original_audio_filename="Test Artist - Test Title (flacfetch).flac",
)
storage.download_file.side_effect = Exception("gcs boom")
# Must not raise
orch._stage_original_audio_for_upload()
assert any("Original audio" in w for w in orch.result.distribution_warnings)
+4
View File
@@ -232,6 +232,10 @@ async def process_audio_download(job_id: str) -> bool:
'input_media_gcs_path': audio_gcs_path,
'filename': filename,
})
# Record the original input audio in file_urls too (the upload path does this
# in audio_worker), so it appears in the admin files manifest consistently
# across all source types and can be staged into the output folder.
job_manager.update_file_url(job_id, 'input', 'audio', audio_gcs_path)
# Download succeeded — clear any stale retry-pending marker and
# previous error so the UI stops showing a resolved failure.
+21
View File
@@ -107,6 +107,21 @@ async def _encode_via_gce(
instrumental_selection = job.state_data.get('instrumental_selection', 'clean')
existing_instrumental = getattr(job, 'existing_instrumental_gcs_path', None)
# Stage the user-provided instrumental into the encoder's input prefix (jobs/{job_id}/).
# It is uploaded under uploads/, which the GCE encoder does NOT pull via input_gcs_path;
# copying it here makes the encoder's recursive find_file("*existing_instrumental*")
# locate it regardless of the worker image version (older encoder images predate the
# encoding_config "existing_instrumental" download path). Without this, tenant /
# existing-instrumental jobs fail with "No instrumental audio found".
if existing_instrumental:
try:
ext = os.path.splitext(existing_instrumental)[1].lower() or ".mp3"
staged_path = f"jobs/{job_id}/existing_instrumental{ext}"
storage.copy_blob(existing_instrumental, staged_path)
job_log.info(f"Staged existing instrumental for encoder: {staged_path}")
except Exception as e:
job_log.warning(f"Failed to stage existing instrumental into jobs/ prefix: {e}")
encoding_config = {
"formats": ["mp4_4k_lossless", "mp4_4k_lossy", "mp4_720p"],
"base_name": base_name,
@@ -344,6 +359,8 @@ async def generate_video_orchestrated(job_id: str) -> bool:
'final_with_vocals_mp4': result.final_with_vocals_mp4,
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
'final_karaoke_txt_zip': result.final_karaoke_txt_zip,
'title_mov': result.title_mov,
'end_mov': result.end_mov,
})
# Store result metadata in job BEFORE transitioning to COMPLETE
@@ -1589,6 +1606,10 @@ async def _upload_results(
('final_with_vocals_mp4', 'finals', 'with_vocals_mp4'),
('final_karaoke_cdg_zip', 'packages', 'cdg_zip'),
('final_karaoke_txt_zip', 'packages', 'txt_zip'),
# Standalone screen videos — recorded so they appear in the admin files
# manifest and are verifiable (regression: missing from Dropbox folders)
('title_mov', 'finals', 'title_mov'),
('end_mov', 'finals', 'end_mov'),
]
for result_key, category, file_key in file_mappings:
@@ -28,6 +28,10 @@ from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.tracing import job_span, add_span_event
from backend.services.original_audio import (
original_audio_gcs_path,
original_audio_output_filename,
)
from karaoke_gen.utils import sanitize_filename
logger = logging.getLogger(__name__)
@@ -67,6 +71,11 @@ class OrchestratorConfig:
dropbox_path: Optional[str] = None
gdrive_folder_id: Optional[str] = None
# Original input audio to include in the uploaded folder (the archival master,
# e.g. "<artist> - <title> (flacfetch).flac"). GCS blob path + target filename.
original_audio_gcs_path: Optional[str] = None
original_audio_filename: Optional[str] = None
# Keep existing brand code (for re-processing)
keep_brand_code: Optional[str] = None
@@ -112,6 +121,11 @@ class OrchestratorResult:
final_karaoke_cdg_zip: Optional[str] = None
final_karaoke_txt_zip: Optional[str] = None
# Standalone 5-second screen videos (downloaded from GCE finals so they land in
# the Dropbox folder). Not used downstream — kept for archival/upload only.
title_mov: Optional[str] = None
end_mov: Optional[str] = None
# Organization
brand_code: Optional[str] = None
@@ -452,6 +466,27 @@ class VideoWorkerOrchestrator:
if self.config.countdown_padding_seconds:
self.job_log.info(f"Countdown padding: {self.config.countdown_padding_seconds}s - instrumental will be padded")
# The GCE encoder downloads its inputs from input_gcs_path (jobs/{job_id}/) and resolves
# the instrumental via find_file. For jobs that supply their own instrumental
# (existing_instrumental flow, e.g. tenant submissions), the file lives under
# uploads/{job_id}/audio/existing_instrumental.* — which is NOT under jobs/{job_id}/ and
# is NOT a name the encoder's 'custom' branch looks for. The encoder's 'custom' branch
# globs for "*custom_instrumental*.{flac,mp3}" / "*Instrumental Custom*", so copy the
# supplied instrumental into jobs/{job_id}/custom_instrumental.<ext> (server-side, from
# the authoritative GCS source — no dependency on local temp files). Without this,
# existing-instrumental jobs fail at the encoder with "No instrumental audio found".
if encoding_backend.name == "gce" and self.storage:
try:
srcs = self.storage.list_files(f"uploads/{self.config.job_id}/audio/existing_instrumental")
if srcs:
src = srcs[0]
ext = os.path.splitext(src)[1].lower() or ".mp3"
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
self.storage.copy_blob(src, dest)
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
except Exception as e:
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
# Run encoding
with job_span("encoding", self.config.job_id) as span:
add_span_event("encoding_started", {"backend": encoding_backend.name})
@@ -532,6 +567,9 @@ class VideoWorkerOrchestrator:
('lossy_4k_mp4_path', 'final_video_lossy'),
('lossy_720p_mp4_path', 'final_video_720p'),
('with_vocals_mp4_path', 'final_with_vocals_mp4'),
# Standalone screen videos — pulled back so they reach the Dropbox folder
('title_mov_path', 'title_mov'),
('end_mov_path', 'end_mov'),
]
downloaded_count = 0
@@ -602,6 +640,16 @@ class VideoWorkerOrchestrator:
self.job_log.info("Starting distribution stage")
self._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
# Stage the original input audio into output_dir before any folder upload
# (Dropbox/GDrive upload the whole directory). Only worth the GCS fetch when
# such an upload will actually happen.
will_upload_folder = (
(self.config.dropbox_path and self.config.brand_prefix)
or self.config.gdrive_folder_id
)
if will_upload_folder:
self._stage_original_audio_for_upload()
# YouTube upload
if self.config.enable_youtube_upload and self.config.youtube_credentials:
await self._upload_to_youtube()
@@ -738,6 +786,32 @@ class VideoWorkerOrchestrator:
f"YouTube upload skipped (quota exceeded) and failed to queue: {e}"
)
def _stage_original_audio_for_upload(self):
"""Copy the original input audio into output_dir so uploads include it.
The source audio (e.g. "<artist> - <title> (flacfetch).flac" /
"(uploaded).mp3") is the archival master used for separation/transcription.
The distributed pipeline otherwise leaves it in GCS only, so it stopped
appearing in the Dropbox track folder. Best-effort: never fail the pipeline.
"""
gcs_path = self.config.original_audio_gcs_path
filename = self.config.original_audio_filename
if not gcs_path or not filename:
return
dest = os.path.join(self.config.output_dir, filename)
if os.path.exists(dest):
self.job_log.info(f"Original audio already present, skipping: {filename}")
return
try:
self.job_log.info(f"Staging original audio for upload: {filename}")
self.storage.download_file(gcs_path, dest)
self.job_log.info(f"Staged original audio: {dest}")
except Exception as e:
self.job_log.warning(f"Failed to stage original audio ({filename}): {e}")
self.result.distribution_warnings.append(f"Original audio not included: {e}")
async def _upload_to_dropbox(self):
"""Upload files to Dropbox."""
self.job_log.info("Uploading to Dropbox")
@@ -974,6 +1048,10 @@ def create_orchestrator_config_from_job(
dropbox_path=dist.dropbox_path,
gdrive_folder_id=dist.gdrive_folder_id,
# Original input audio to include in the uploaded folder (archival master)
original_audio_gcs_path=original_audio_gcs_path(job),
original_audio_filename=original_audio_output_filename(job, base_name),
# Keep existing brand code
keep_brand_code=getattr(job, 'keep_brand_code', None),
+59
View File
@@ -831,6 +831,65 @@ Response:
When `has_community` is true, the frontend shows a dismissible green banner suggesting the user check existing versions before creating a new one.
#### Match Judge (artist/title formatting + match acceptance)
```http
POST /api/catalog/match-judge
Content-Type: application/json
{
"artist": "paramore",
"title": "big man, little dignity",
"audio_confidence_tier": 1,
"stage": "full"
}
```
Decides the official formatting for a typed artist/title and whether it matches a
real song. A deterministic normalizer + the catalog run first; a light Vertex
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.5-flash`) is consulted
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
optional) lets the judge tell whether weak audio results hint at a typo. The call
never blocks job creation — on timeout/error it returns a `none` verdict. Disable
the AI layer with `MATCH_JUDGE_ENABLED=false` (deterministic+catalog still run).
`stage` (optional, `"fast"` | `"full"`, default `"full"`) supports a two-call
pattern the frontend uses to keep the tidy off the critical path:
- `"fast"` — catalog-only pass (no AI, `audio_confidence_tier` ignored). The
client fires this on mount, in parallel with the audio search. Returns a
confident catalog verdict when it can, otherwise `needs_ai: true` (a marker
telling the client to follow up with a `"full"` call once the tier is known).
- `"full"` — the complete pipeline. Runs the AI judge when the catalog isn't
confident, **and** when a confident catalog match coincides with a weak audio
tier (`>= 3`) — a weak tier means the match may be a junk/typo'd entry, so the
AI verifies it and can override.
Response:
```json
{
"kind": "cosmetic",
"confident": true,
"canonical_artist": "Paramore",
"canonical_title": "Big Man, Little Dignity",
"alternatives": [],
"engine": "catalog",
"reason": "formatting differs from catalog",
"needs_ai": false
}
```
`kind` drives the Step 2 UI: `cosmetic` → silent tidy with a two-way toggle
("keep what I typed" ⇄ "use tidied version"); `content` (confident) → applied
with a "Corrected … · Undo" toggle, re-searching audio only when the original
results were weak; `ambiguous` (or unconfident `content`) → an ask-first "Did you
mean?" prompt; `none` → no change. `needs_ai` is only ever `true` on a `"fast"`
verdict that couldn't decide; it is always `false` on a `"full"` verdict.
Until the judge settles, the Step 2 audio-selection buttons are disabled with a
subtle "Checking song details…" indicator, so a user can never advance with
un-tidied metadata; a 12s timeout guarantees the gate releases.
### Audio Search
#### Search for Audio
+7
View File
@@ -72,6 +72,13 @@ When a metadata key is missing, don't set it to "now" and skip the action — th
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
### "Is It Busy?" Guards Must Fail SAFE, Not Fail Open (Jun 2026)
Both stop paths for the GCE encoder VMs guarded against killing a busy worker by checking `/health`'s `active_jobs` — but both defaulted to **0 (= idle)** when `/health` was unreachable or slow (CI drain: `... || echo "0"`; idle Cloud Function: `except: return 0`). A busy encoder runs a 4K ffmpeg on all 32 cores and shares uvicorn with the encode subprocess, so `/health` can miss its timeout *while the VM is hard at work*. Combined with blue/green deploy churn (every merge cycles the VMs) and the 5-min idle check, this stopped VMs **mid-render**, orphaning the in-memory job so backend polls got 404 → "lost contact with worker ... not found" (incident 2026-06-15; the burst was self-inflicted by rapid PR merges during the tenant E2E, 0 in the prior 48h). **Rule:** a guard that decides whether to destroy work must treat "couldn't confirm" as "assume busy / don't act," never as the permissive default. Retry the probe, and only act on a *confirmed* safe signal (here: a real `active_jobs == 0` from a 200 response), with a bounded timeout so a wedged worker can't block forever.
### In-Flight Status Polls Must Be Pinned to the Worker, Not the Floating Primary (Jun 2026)
The day after the drain fix above, the **same** "lost contact ... not found" error recurred (incident 2026-06-16, job d3af33ae) — but this time the VM was *never* stopped mid-render. `EncodingService.get_job_status()` re-resolved the worker URL on **every poll** via `_get_worker_url()` → `config.active_url`. A blue-green deploy swapped the Firestore `primary_vm` pointer at 04:33:46 (worker-a → worker-b); 7s later the in-flight render's polls started hitting worker-b, which had never received the job → 404 → 5 failures → render failed. Worker-a was alive and finished the encode the whole time; nobody was listening. The drain (which keeps the old VM *alive*) can't help — the job is orphaned at the **poll layer** the instant the pointer swaps, 47s before any VM stop. **Rule:** once a job is accepted by a specific worker, every subsequent poll for that job must target *that* worker until terminal — the poll follows the job, not the floating primary pointer. URL re-resolution is correct for *capacity fallback* (dead primary → start fallback → re-route a fresh submission) but wrong for an *in-flight poll* (a different/fresh VM can't have the job; re-routing only yields 404). Fix: capture the worker URL **after** submit (reflects a fallback re-route, precedes any later swap) and pass it as `worker_url=` through `wait_for_completion` → `get_job_status`, which then pins the request and sets `allow_failover=False`. v0.184.2.
### Cloud Run GPU: Let the Platform Scale, Not Your Code (Mar 2026)
**Don't use fire-and-forget + semaphore on Cloud Run.** We tried making the `/separate` endpoint return immediately (fire-and-forget background thread) with a `threading.Semaphore(1)` to serialize GPU work. Cloud Run couldn't see background threads as "busy", so it routed ALL requests to one instance where they queued behind the semaphore — causing 30-minute timeouts in production.
+2
View File
@@ -58,6 +58,8 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
**Prevention:** The video worker now runs as a **Cloud Run Job** (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`), which runs to completion and is immune to Cloud Run Service deployment rollouts. This replaces the `BackgroundTask` pattern that was vulnerable to instance termination during deployments. Additionally, CI performs a graceful drain before restarting the GCE encoding worker, the encoding client retries for ~90s, and status polling tolerates up to 5 consecutive failures.
Since v0.184.2, in-flight status polls are also **pinned to the worker that accepted the job** (`get_job_status(..., worker_url=)`), so a blue-green deploy that swaps the `active_url` primary pointer mid-render no longer migrates the poll to a worker that never received the job. If you still see `lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`, confirm via step 2 above that the worker the job was submitted to (not necessarily the current primary) still has the job — a `not found` from the *current* primary while the job is alive on the old primary was the pre-v0.184.2 failure mode (incident 2026-06-16, job d3af33ae).
---
## CDG/TXT packages missing from completed job
@@ -0,0 +1,105 @@
# Artist/Title Matching, Suggestions & Auto-Correction Rework (Phase 1)
**Date:** 2026-06-15
**Worktree:** `karaoke-gen-submission-form-simplify`
**Branch:** `feat/sess-20260615-0101-submission-form-simplify`
**Status:** Design + plan — pending implementation
## Problem
On Step 2 ("Choose Audio") the wizard stacks two green "success" cards: the **"Song found in our database"** catalog panel and the **"Perfect match found"** audio card. User feedback: the first reads like "we already have this karaoke video," when its only real job is to nudge the user toward **official artist/title formatting** (a quality-bar concern for *published* tracks). It's confusing, and the underlying case-insensitive match is imperfect.
This phase reworks **only** the artist/title matching → suggestion → auto-correction behavior. The broader flow structure is deliberately left intact (see "Constraints from history"). The title-screen preview perf fix is tracked separately.
## Decisions (from 2026-06-15 brainstorm with Andrew)
1. **Invisible cosmetic tidy.** When formatting differs only cosmetically (casing, spacing, punctuation, diacritics, `&`/`feat.` conventions) and we're confident it's the same song, **silently apply** the official formatting. No green "database" card. Show only a faint, dismissible line: *"Tidied to **Paramore — Big Man, Little Dignity** · keep what I typed"*.
2. **Confident content correction → auto-apply + surface + smart re-search.** When the correction changes actual characters (e.g. `Yesteray → Yesterday`) and we're confident, apply it **and** surface it with one-tap Undo: *"Corrected to **Yesterday** — you typed 'Yesteray' · Undo"*. Because characters changed, the original audio search may be poor, so **re-run the audio search** — automatically **only when the original results were weak** (tier 3 / empty); otherwise offer a quiet "Search again" link.
3. **Ambiguous → ask first.** When the judge isn't confident which song is meant (multiple plausible candidates), show an ask-first prompt: *"Did you mean **X**? [Use this] [Keep mine]"* before changing anything.
4. **Three-layer engine, all in v1.** Deterministic rules → catalog canonical → light AI judge. **The AI judge fires only when the deterministic + catalog layers are not confident** (cheap; happy path never invokes it).
## Constraints from history (do NOT regress)
From `docs/archive/2026-02-28-ux-*`, `2026-03-02-decouple-search-from-job-creation.md`, `2026-03-08-step2-song-suggestions.plan.md`, `2026-03-08-fuzzy-did-you-mean.plan.md`, `docs/LESSONS-LEARNED.md`, PRs #444/#451/#480/#495/#512:
- **No Step-1 autocomplete.** It was added (PR #451) then removed (PR #512) because users didn't understand it. Suggestions belong on Step 2, in parallel with the audio search.
- **Cosmetic correction must NOT restart the audio search.** Already a documented decision — the existing catalog `onArtistTitleCorrection` updates artist/title without re-searching. Preserve this. (Content corrections that change characters MAY re-search — see decision 2.)
- **Deferred job creation (search-session pattern).** No job is created until the final confirm step. Don't move creation earlier. The tidied artist/title is passed at `create-from-search` time; the audio `search_session_id` is unaffected by a metadata tidy.
- **Preserve the fuzzy artist-tiebreaker lesson:** when title-matching returns multiple artists with the same song name, use the user's (possibly garbled) artist input as a tiebreaker. And the gating: fuzzy/"did you mean" only triggers when audio results are poor.
- **`display_artist`/`display_title`** stay distinct from matching `artist`/`title`; they're set at creation time. The tidy applies to the **matching** artist/title (what drives search, lyrics, and published metadata).
- **Public vs private brand rule, audio-before-customize ordering, combined review flow** — untouched by this phase.
## Architecture
Consolidate today's scattered client-side matching (case-insensitive exact match in `SongSuggestionPanel` + LCS fuzzy in `audio-search-utils.ts`) into **one backend "match judge" service**, called from Step 2 in parallel with the audio search (replacing the current `searchCatalogTracks` + client fuzzy effect). Rationale: testable, consistent canonical formatting, and the AI layer needs the backend's LLM clients/keys.
### Backend: `POST /api/catalog/match-judge`
Request: `{ artist, title, audio_confidence_tier?: 1|2|3 }`
(The frontend passes the audio search's computed confidence tier so the judge knows whether weak results suggest a typo.)
Pipeline (server-side):
1. **Deterministic normalize** (reuse/extend `karaoke_gen.utils.normalize_text`): trim, collapse whitespace, fix obvious casing (title-case with small-word handling), straighten quotes, standardize `feat.`/`ft.` → `(feat. …)` and `and`↔`&` per house style.
2. **Catalog lookup** (existing `search_tracks` via `catalog_proxy_service`). If a candidate matches the normalized input under a strict normalized-equality test → **confident cosmetic**: return the catalog's canonical `artist_name`/`track_name`.
3. **AI judge — only if (1)+(2) not confident.** Invoke a light model (see "Model") with the typed input, the top catalog candidates, and the audio tier. It returns a structured verdict.
Response:
```json
{
"kind": "cosmetic | content | ambiguous | none",
"confident": true,
"canonical_artist": "Paramore",
"canonical_title": "Big Man, Little Dignity",
"alternatives": [{"artist": "...", "title": "..."}],
"engine": "deterministic | catalog | ai",
"reason": "casing only"
}
```
- `kind=cosmetic` → frontend applies invisibly + faint line (no re-search).
- `kind=content` + `confident` → frontend auto-applies + Undo line; re-search if audio tier was weak.
- `kind=ambiguous` (or `content` not confident) → frontend shows ask-first "Did you mean?" with `alternatives`.
- `kind=none` → no suggestion (leave user input as typed).
**Resilience:** AI judge runs under a short timeout (~2–3s) and is fully optional — on timeout/error/unparseable output, fall back to deterministic+catalog result (or `kind=none`). Never block the audio search; never error the request. Mirror `auto_correct`'s greppable usage/cost logging (`match-judge usage/cost job/session=…`).
### Model (decided)
Reuse `auto_correct` dispatch (`claude*` → Anthropic, else Gemini via `genai.Client(vertexai=True, project=…, location="global").models.generate_content(model=…)`).
**Decision (Andrew, 2026-06-15):** default `MATCH_JUDGE_MODEL=gemini-3.5-flash` — the latest Vertex Gemini Flash (https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-5-flash). Passed bare to the genai Vertex client exactly like `auto_correct` passes `gemini-3.1-pro-preview`. No `ANTHROPIC_API_KEY` needed. Env-configurable, so if Vertex requires a version suffix it's a one-line env change (an invalid id surfaces as a loud error on first call). Add `gemini-3.5-flash` pricing to `pricing.py` for cost logging.
### Frontend (`AudioSourceStep.tsx`)
- Replace the parallel `searchCatalogTracks` + client fuzzy `useEffect` with a single `api.matchJudge(artist, title, tier)` call fired in parallel on mount (after the audio tier is known, or fired and reconciled when the tier resolves).
- **Remove** the green `SongSuggestionPanel`. Add a quiet `TidyNotice` (cosmetic) and reuse/restyle `DidYouMeanBanner` for the surfaced-content (Undo) and ambiguous (ask) cases.
- Wire cosmetic/confident-content application through the existing `onArtistTitleCorrection` (no restart). Add a `reSearch()` path (reuse `handleFuzzyAccept`'s restart logic) gated on weak prior results for content corrections.
- Keep the `confidence.tier` gating and artist-tiebreaker semantics (now enforced server-side, but the frontend still passes the tier).
## Out of scope (this phase)
- Title-screen preview perf (separate task: smaller canvas + low-res bg + preload at step 2 + spinner).
- Any change to step count / visibility / customize / job-creation timing.
- Auto-selecting audio on a Tier-1 match (possible later, separately).
## Testing strategy
Per `docs/TESTING.md`:
- **Backend unit:** deterministic normalizer rule table (casing, spacing, punctuation, feat./&, quotes); judge response parsing; confidence/kind classification; AI-failure fallback; "only call AI when not confident" gating.
- **Backend integration:** `/api/catalog/match-judge` happy/edge paths with catalog mocked and AI mocked.
- **Frontend unit (Jest):** TidyNotice rendering + Undo; content-correction auto-apply + smart re-search gating (weak vs ok results); ambiguous ask-first; preserve "no restart on cosmetic".
- **E2E (Playwright) + prod E2E:** end-to-end on a real song (cosmetic case), a typo case (content + re-search), and an ambiguous case.
## Telemetry
- Log judge decisions + engine used + latency + token cost (greppable, like `auto-correct usage/cost`).
- Count cosmetic / content / ambiguous / none and Undo clicks to measure real-world correction quality (informs whether thresholds need tuning).
## Open decisions
1. ~~Judge model default~~ — DECIDED: `gemini-3.5-flash` (Vertex), configurable via `MATCH_JUDGE_MODEL`.
2. Confidence thresholds for cosmetic vs content vs ambiguous (start conservative; tune from telemetry).
3. Whether to keep a tiny instant frontend normalizer for immediate display, or rely solely on the judge response (~sub-second). Lean: rely on judge for v1; add instant normalize later if the delay is noticeable.
## Rollout
- `MATCH_JUDGE_ENABLED` env flag (default on) so the AI layer can be disabled without a deploy; deterministic+catalog still function if AI is off.
- Bump `pyproject.toml` version. Ship behind normal CI; Andrew reviews locally (localhost:3000 → prod backend) before merge/deploy.
@@ -0,0 +1,98 @@
# White-Label Tenant Portals: Made Working End-to-End (Jun 2026)
## Context
The two B2B white-label tenant portals (`vocalstar.nomadkaraoke.com`, `singa.nomadkaraoke.com`)
had full data models, middleware, GCS config, themes, a simplified job form, a separate
Cloudflare deployment, and 280+ unit tests — and were documented as "production ready."
**But no tenant job had ever actually completed:** 0 of the 484 most recent prod jobs
carried a `tenant_id`. The feature looked done but was broken at every stage that had
never been exercised by a real end-to-end tenant job.
This session drove a real Vocal Star track (`Eddy Grant - I Don't Wanna Dance`, from their
bulk batch) through the full pipeline in production, fixing each blocker in turn, until a
tenant job completed: correct attribution → transcription → screens → review → render →
Dropbox delivery, with the locked theme and **no** YouTube / Google Drive.
## The seven blockers (each was the next never-exercised stage)
1. **Tenant attribution never happened (root cause).** The frontend API client never sent
the `X-Tenant-ID` header (`getTenantHeaders()` existed but was unwired). Tenant portals
call the shared `api.nomadkaraoke.com`, whose Host isn't the tenant subdomain, and the
`?tenant=` param is prod-disabled — so the backend never detected the tenant and every
sign-in/job silently became a consumer job. Fix: attach `X-Tenant-ID` from
`window.__TENANT_CONFIG__` in `lib/api.ts` (`getBaseHeaders`), incl. the magic-link
request. PR #824.
2. **Tenant config not authoritative.** Prod sets global `DEFAULT_DROPBOX_PATH` /
`DEFAULT_GDRIVE_FOLDER_ID` / `DEFAULT_BRAND_PREFIX`; `_apply_tenant_overrides` only
filled unset fields, so tenant jobs leaked into the shared consumer Dropbox folder and
uploaded to the global Google Drive. Fix: tenant config is authoritative, gated by
feature flags (gdrive/dropbox cleared when disabled). PR #824.
3. **Wrong file transcribed.** existing-instrumental jobs upload mixed + instrumental into
the same `uploads/{job}/audio/` dir; `uploads-complete` resolved the `audio` slot via
`files[0]`, which sorts to `existing_instrumental.mp3`. Transcription ran on the
instrumental. Fix: `_select_mixed_audio_files` excludes the instrumental. PR #825.
4. **AudioShake rejected the audio.** Vocal Star's MP3s begin with ~731 leading null bytes
before the first frame; ffmpeg tolerates it, AudioShake 400s ("Error fetching or
processing asset"). Consumer jobs never hit this (they transcribe re-encoded stems).
Fix: detect leading null padding on `.mp3/.aac` and losslessly remux (`ffmpeg -c copy`)
before upload. Verified against the live AudioShake API. PR #826.
5. **Theme incomplete.** The strict theme validator requires every field; the tenant
themes (created Jan 2026) were missing `extra_text_text_transform` (intro + end),
added to the schema later → "Title screen generation failed." Fix: added the field to
the live GCS themes and the setup scripts. PR #827.
6. **Theme assets not downloaded.** The setup scripts wrote full `gs://bucket/themes/.../assets/X`
URLs, but `theme_service._build_style_assets_mapping` only resolves bare basenames (the
consumer convention) → `style_assets` empty → assets never localized → encoder failed
with "Video background image not found". Fix: rewrote the live themes + setup scripts to
bare basenames. PR #827.
7. **Render prerequisites — "No instrumental selected".** existing-instrumental jobs have
no instrumental-selection UI step; the orchestrator defaults to `'clean'` (a stem never
produced) and `_validate_prerequisites` rejected the job. Fix: `complete-review`
defaults `instrumental_selection` to `'custom'` when `existing_instrumental_gcs_path`
is set. PR #827.
## Tenant config (final, both tenants)
- Locked theme (`vocalstar` / `singa`), no theme selection.
- `youtube_upload=false`, `gdrive_upload=false` (folder cleared), `dropbox_upload=true`.
- Dropbox: `/MediaUnsynced/Karaoke/Tracks-VocalStar`, `/MediaUnsynced/Karaoke/Tracks-Singa`.
- Jobs forced `is_private=true`; CDG + 4K enabled.
## Daily E2E
`scripts/e2e/tenant_e2e.py` + `.github/workflows/e2e-tenant-daily.yml` run a full job per
tenant daily (07:37 UTC, matrix vocalstar/singa): submit → approve review → render →
assert (completes, Dropbox link present, no YouTube, downloads available) → clean up the
job + uploads. Auth via WIF + `E2E_ADMIN_TOKEN`; test audio in `gs://.../e2e-tests/shared/`.
## Outcome
Both tenants pass the full prod E2E (PRs #824–#830): log in → submit (artist, title, mixed,
instrumental) → transcribe → review → render with the locked theme → encode → package →
Dropbox delivery, with **no YouTube, no Google Drive**, and all outputs (4K / 720p /
with-vocals MP4 + CDG + TXT) downloadable from the portal via `job.file_urls`.
The encoder blocker (bug #8) took three iterations: the staging had to land in the
**orchestrator** path (`video_worker_orchestrator._run_encoding`, not the legacy
`_encode_via_gce`) and use the filename the running encoder VM's `custom` branch globs for
(`custom_instrumental.<ext>`, since the live VM boots the 2026-01-23 image whose `custom`
branch predates `*existing_instrumental*` / `*Instrumental User*`). The instrumental is
server-side-copied from `uploads/{job}/audio/existing_instrumental.*` →
`jobs/{job}/custom_instrumental.<ext>`.
## Gotchas / lessons
- The tenant pipeline had never run end-to-end, so every stage hid a latent bug. "Has a
real job of this shape ever completed in prod?" is a better readiness question than test
count.
- Theme asset paths must be **bare basenames** (consumer convention), not `gs://` URLs.
- AudioShake needs clean audio at offset 0; user-provided files vary — remux defensively.
- Public tenant config API redacts `dropbox_path`/`gdrive_folder_id`/`brand_prefix`; read
the stored GCS config for the real values.
@@ -0,0 +1,106 @@
# Match-Judge Improvements — Implementation Plan
**Date:** 2026-06-16
**Worktree:** `karaoke-gen-match-judge-improvements`
**Branch:** `feat/sess-20260616-0053-match-judge-improvements`
**Builds on:** match-judge v0.184.1 (PRs #836 + #838)
**Spec:** `docs/archive/2026-06-16-match-judge-improvements-prompt.md` (decisions by Andrew — settled)
Four items. Decisions are already made in the prompt; this doc records the concrete
shapes I'm committing to and the test plan. TDD throughout.
---
## Item 1 — Race fix: parallel tidy + hard gate
**Backend shape (decided: two-call `stage` contract).** Add `stage: "fast" | "full"`
to the endpoint + `judge_match`. Default `"full"` (backwards-compatible).
- `stage="fast"` (no tier needed): run catalog search + `classify_catalog_match` ONLY.
Never calls AI.
- confident catalog verdict (cosmetic/none) → return it (`needs_ai=False`).
- catalog undecided → return `MatchVerdict(none, confident=False, engine="catalog",
reason="needs ai", needs_ai=True)`.
- `stage="full"` (tier known): current pipeline + Item 4 (see below).
New field `needs_ai: bool = False` on `MatchVerdict` (+ `to_dict`, response model, TS type).
**Frontend two-phase coordination (AudioSourceStep):**
1. On mount (parallel with audio search): `matchJudge(artist, title, { stage: 'fast' })`.
Store the promise in a ref. If it resolves to a confident cosmetic verdict, apply the
silent tidy immediately (no re-search).
2. When the audio search resolves (tier known), one coordinating effect:
- `await` the fast promise.
- `needFull = fast == null || fast.needs_ai || (fastIsCatalogConfident && tier >= 3)`.
- if `needFull` → `matchJudge(artist, title, { stage: 'full', audioConfidenceTier: tier })`,
apply its verdict.
- settle the gate in a `finally` (always).
**Hard gate.** `gateReleased` state (starts false) → true when the judge settles.
Pick/select buttons (PickCard, ResultRow) and the fallback submit buttons are disabled
while `!gateReleased`. A subtle "Checking song details…" line shows when
`!gateReleased && !isSearching`. Safety timeout `JUDGE_GATE_TIMEOUT_MS = 12000` from when
the full call fires guarantees release even on a network hang (backend AI already caps at
12s). Gate never deadlocks: every path (disabled flag, fast/full failure, timeout) settles.
On a content re-search, keep the gate open (don't re-judge) — mirrors the existing
`judgeTriggered` semantics.
**Acceptance:** impossible to reach Step 3 with un-tidied metadata in normal flow; a slow
AI verdict never clobbers the selection; gate is imperceptible in cosmetic cases and bounded
(≤12s) otherwise.
## Item 2 — Two-way toggle for tidy/correction (frontend only)
`MatchNotice` becomes a clean two-way toggle. Add `correctionActive` state (default true).
- cosmetic applied: "Tidied to **X** · keep what I typed" → revert.
- cosmetic reverted: "Using what you typed: **Y** · use tidied version" → reapply.
- content applied: "Corrected to **X** — you typed “Y” · Undo" → revert.
- content reverted: "Using what you typed: **Y** · use the correction" → reapply.
Toggle is metadata-only (no re-search on toggle — matches old Undo + the "no restart on
cosmetic" rule). `appliedFrom` already holds the typed text; `verdict` holds canonical.
New i18n keys (translate all locales): `matchUsingTyped`, `matchUseTidied`,
`matchUseCorrection`.
## Item 3 — Title-screen preview perf (frontend only)
`TitleCardPreview.tsx` + `KaraokeBackgroundPreview.tsx`:
- Render canvas at **preview resolution** (960×540, dpr-aware, clamp dpr≤2) instead of
3840×2160. Keep coordinate constants in 4K space; apply `ctx.setTransform(scale,…)` so
drawing code is unchanged.
- Add **low-res** bg assets: `public/title-card-bg-preview.png`,
`public/karaoke-bg-preview.png` (downscaled from the 2.7 MB 4K originals). Previews use
these; the 4K originals stay for any real render path.
- **Preload** the preview bg(s) at Step 2 (export `preloadTitleCardBg()` /
`preloadKaraokeBg()`, call from AudioSourceStep mount) so they're warm by Step 4.
- **Spinner** "Loading title screen preview" overlay until the first draw completes
(`ready` state).
- Update `TitleCardPreview.test.tsx` mock (add `setTransform`/`scale`), add coverage for
the spinner + low-res bg src.
## Item 4 — Catalog-match trust: verify weak matches with AI (backend)
In `judge_match` (stage=full): when `classify_catalog_match` returns a confident verdict
BUT the audio tier is weak (`>= 3`), still call AI and let it override — catches a junk/
misspelled Spotify entry matching the user's exact typo (prod: `Queen / Bohemian Rapsody`
→ wrongly "already canonical"). AI overrides only when confident and `kind != none`;
otherwise keep the catalog verdict. Extra ~$0.0003/call cost only on weak-result cases.
## Testing
- **Backend unit** (`test_service.py`): fast-stage returns catalog verdict / needs_ai;
fast never calls AI; full-stage weak-tier catalog match → AI consulted → override;
full-stage strong-tier catalog match → no AI; AI-unconfident on weak tier → keep catalog.
- **Backend unit** (`test_classifier.py`): unchanged (still escalates on no match).
- **Backend route** (`test_match_judge_routes.py`): `stage` forwarded; `needs_ai` in response.
- **Frontend** (`AudioSourceStep.test.tsx`): fast call on mount; cosmetic applies from fast;
gate disables pick button until settled then enables; full call fired only when needed;
two-way toggle revert↔reapply.
- **Frontend** (`TitleCardPreview.test.tsx`): preview-res canvas, low-res bg, spinner.
- `make test` full suite green before `/shipit`.
## Out of scope / preserved
No Step-1 autocomplete; cosmetic must not restart search; deferred job creation; public
brand rule; audio-before-customize ordering. (Constraints from the 2026-06-15 doc.)
@@ -0,0 +1,67 @@
# Match-Judge Improvements — New-Session Prompt Doc
**Created:** 2026-06-16
**For:** a fresh session, started via `/startnomad gen match-judge improvements`
**Builds on:** the artist/title match-judge feature shipped in gen **v0.184.1** (PRs #836 + #838).
## Read first (context)
- Feature overview + gotchas: agent memory `project_match_judge.md` (and `[[project_match_judge]]`).
- Original design + history constraints: `docs/archive/2026-06-15-artist-title-matching-rework-plan.md`.
- **Honor the "Constraints from history" section of that plan** — no Step-1 autocomplete; cosmetic correction must not restart the audio search; deferred job-creation/search-session pattern; public-style brand rule; audio-before-customize ordering. Don't undo these.
### Where the code lives
- Backend: `backend/services/match_judge/` — `classifier.py` (deterministic + catalog), `ai.py` (Vertex `gemini-3.5-flash`), `service.py` (orchestration), `verdict.py` (`MatchVerdict`). Endpoint: `POST /api/catalog/match-judge` in `backend/api/routes/catalog.py`. Config in `backend/config.py` (`MATCH_JUDGE_ENABLED` / `MATCH_JUDGE_MODEL` / `MATCH_JUDGE_TIMEOUT_MS=12000`).
- Frontend: `frontend/components/job/steps/AudioSourceStep.tsx` — the judge effect, `applyCorrection`/`handleSuggestionAccept`/`handleUndoCorrection`, and the `MatchNotice` component. Client: `api.matchJudge` in `frontend/lib/api.ts`. i18n keys live in `frontend/messages/en.json` under `jobFlow` (`matchTidiedTo`, `matchKeepMine`, `matchCorrectedTo`, `matchUndo`, `matchDidYouMean`) — any new/changed strings must be translated to all 33 locales (`python scripts/translate.py --messages-dir ./messages --target all`).
### How it currently works (the starting point)
On Step 2, the judge effect fires **after** the audio search resolves (`isSearching === false`), passing `confidence.tier`. The verdict drives `MatchNotice`: cosmetic → silent apply + quiet "Tidied to X · keep what I typed" (no re-search); confident content → apply + "Corrected to X · Undo", re-search only if tier 3; ambiguous → ask-first "Did you mean?". `applyCorrection(newArtist, newTitle, reSearch)` writes to the parent via `onArtistTitleCorrection` (no-restart path) and, when `reSearch`, resets `searchTriggered`/results so the mount effect re-runs.
---
## Work items (with decisions already made)
### 1. Race: audio results can arrive before the tidy finishes
**Problem:** the judge runs *after* the audio search, so there's a window where results are shown but the tidy hasn't applied. If the user selects audio / advances fast, the un-tidied artist/title can be what's saved (job creation is deferred to Step 4, so it's usually caught, but not guaranteed). Worse: a `content`+reSearch verdict landing while the user is mid-selection can blow away results / a pick.
**Decision (Andrew):** **Tidy earlier (parallel) + a hard gate.**
- Run the **deterministic + catalog** tidy **in parallel with the audio search** (kick it off on mount; it doesn't need the tier). The **AI** layer still needs the tier, so it runs once the audio search resolves — but only when deterministic+catalog aren't confident.
- This likely means splitting the single `match-judge` call, OR adding a query param so the backend can do a fast catalog-only pass immediately and a full pass (with tier) after. Decide the cleanest shape — could be two calls (`/match-judge` cheap-first without tier, then a second with tier only if needed) or one call kicked off as soon as possible. Keep the backend contract clean.
- **Hard-gate selection:** disable "Use This Audio" (all audio pick buttons) with a subtle indicator (e.g. "Checking song details…") until **both** the audio search **and** the judge verdict have resolved + applied. The judge's 12s timeout must still unlock the gate (never strand the user). Because the tidy runs in parallel, the common cosmetic case adds ~no perceptible wait; only the rarer AI path holds the gate briefly.
- Gate releases when the verdict reaches a terminal state (cosmetic applied / content applied / ambiguous prompt shown / none / timeout). For **ambiguous**, release the gate (don't block indefinitely on an unsure result) but keep the "Did you mean?" prompt visible.
**Acceptance:** it is impossible to reach Step 3 with un-tidied metadata in the normal flow; a slow AI verdict never clobbers a selection; the gate is imperceptible for cosmetic cases and bounded (≤12s) otherwise.
### 2. Make "keep what I typed" reversible (two-way toggle)
**Decision (Andrew):** the tidy notice should let the user **see what it would revert to**, and **switch back** to the tidied version if they change their mind.
- Show both values. e.g. tidied state: *"Tidied to **Hard-Fi — I Shall Overcome** · keep what I typed"*. After clicking, reverted state: *"Using what you typed: **hard-fi - i shall overcome** · use tidied version"*, and "use tidied version" switches back. A clean two-way toggle; current value always clear.
- Same for the **content** correction ("Corrected to X · Undo") — Undo should be reversible back to the correction too.
- This is just frontend `MatchNotice` + state (`appliedFrom` already tracks the pre-correction text; add the inverse). New i18n keys as needed (translate all 33 locales).
### 3. Title-screen preview performance (the original "point D")
`frontend/components/job/TitleCardPreview.tsx` renders a **3840×2160 (4K) canvas** and loads a **4K** background PNG (`/title-card-bg.png`) — for what's shown as a small thumbnail. Slow, especially on mobile.
- Render the canvas at **display resolution** (e.g. ~960×540, or `devicePixelRatio`-aware), not 4K.
- Add a **low-res** background asset (downscale `public/title-card-bg.png`) and use it for the preview; keep the 4K for any real render path.
- **Preload** the background once the artist/title are locked at Step 2 (the preview currently lives on Step 4), so it's warm by the time the user arrives.
- Add a **"Loading title screen preview"** spinner while it renders.
- Note: private mode has a second canvas (`KaraokeBackgroundPreview.tsx`) — apply the same treatment. There's a `TitleCardPreview.test.tsx`; update it.
### 4. Catalog-match trust (the "second point" — yes, it's a real bug)
**Problem:** the classifier's exact catalog match can match a junk / misspelled Spotify entry (e.g. a karaoke/lyric upload titled with the user's exact typo), so it returns `none`/"already canonical" and **the AI judge never runs**. Observed in prod: `Queen / Bohemian Rapsody` → "already canonical" (wrong).
**Decision (Andrew):** **Verify weak matches with AI.** When the audio results were weak (**tier 3**), run the AI judge **even if the catalog "matched"**, and let the AI override the catalog verdict. The extra cost (~$0.0003/call) is only incurred on weak-result cases. Implement in `service.py` (don't let `classify_catalog_match` short-circuit when tier is weak) and/or `classifier.py`. Add unit tests covering: weak tier + junk exact-match → AI consulted → corrected; strong tier + exact-match → still short-circuits (no AI).
---
## Process
1. `/startnomad gen match-judge improvements`, read the context docs above.
2. Brainstorm/confirm the parallel-tidy backend shape (item 1) before coding — it's the trickiest. Consider visual mockups only if helpful; the decisions above are settled, so keep it light.
3. TDD: backend changes get unit/integration tests; frontend changes get Jest tests (mirror the existing `AudioSourceStep.test.tsx` / `TitleCardPreview.test.tsx` patterns). Update i18n for all 33 locales when strings change.
4. Run `make test` (full suite), then `/shipit` (CodeRabbit → version bump → PR with `@coderabbitai ignore` → merge → wait for deploy → verify prod). **Verify item 1 and item 4 live in prod** with real `/api/catalog/match-judge` calls and by clicking through Step 2 on localhost:3000 (dev server proxies to prod backend by default).
5. After shipping, trigger the daily prod E2E workflow: `gh workflow run e2e-daily.yml --ref main`.
## Notes / gotchas
- The shell/rtk wrapper mangles `&&`, `2>&1`, and reformats `gh --json -q` output — use `;`-separated commands and `rtk proxy gh …` for raw JSON.
- `gh pr merge --delete-branch` errors locally because `main` is checked out in the main clone worktree; the remote merge still succeeds — verify with `gh pr view <n> --json state`.
- CI dedupes test jobs on merge and goes straight to "Deploy - Backend (Cloud Run)"; the definitive deploy signal is the prod root version (`https://api.nomadkaraoke.com/`) flipping to the new value.
- Admin token for prod API tests: `gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1`, send as `Authorization: Bearer <token>`.
@@ -0,0 +1,83 @@
# Render status-poll pinning — fix for deploy-swap orphaning (job d3af33ae)
**Date:** 2026-06-16
**Worktree:** `karaoke-gen-encoding-job-not-found`
**Incident error:** `Encoding job <ID> lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`
## What happened (job d3af33ae, 2026-06-16 UTC)
| Time | Event |
|------|-------|
| 04:29:09 | `karaoke-backend@` starts **worker-a** (`34.57.78.246`) — render warmup |
| ~04:31:39 | Render submitted to **worker-a**; encoding begins |
| 04:33:01 | `github-actions-deployer@` starts **worker-b** (`34.10.189.118`) — deploy begins |
| **04:33:46.985** | Firestore `last_swap_at`: primary swapped worker-a → **worker-b** |
| 04:33:53 → 04:34:33 | Backend status polls fail 1/5 → 5/5: "Encoding job d3af33ae not found" |
| 04:34:33 | Render failed; deploy stops worker-a |
| 04:46:35 | User retried → re-rendered on worker-b → **success** |
The 4 polls that failed at 04:33:53–04:34:23 happened **while worker-a was still running and encoding**. The 404s came from worker-b (the just-swapped primary), which never received the job.
## Root cause
`EncodingService.get_job_status()` resolves the worker URL **fresh on every poll** via
`_get_worker_url()` → `config.active_url`. When a blue-green deploy flips `primary_vm` in
Firestore mid-render, in-flight status polls migrate from the worker that owns the job
(old primary) to the new primary, which 404s. A clean 404 is counted as a transient poll
failure; 5 in a row fails the render — even though the original worker finished the encode.
URL re-resolution is **correct for capacity fallback** (primary VM dead → start fallback →
re-route), but **wrong for a deploy swap** (old primary alive, still owns the job).
The drain logic added 2026-06-15 (`ci.yml` "Drain and stop old primary") prevents *stopping*
a busy VM, but the job is orphaned at the **poll layer** the instant the pointer swaps —
47s before the VM is stopped. The drain can't fix this.
## Fix: pin in-flight polls to the worker that accepted the job
Invariant: **once a job is accepted by a worker VM, all status polls for that job target
that same VM until terminal** — the poll follows the job, not the floating primary pointer.
### Changes (`backend/services/encoding_service.py`)
1. **`_request_with_retry(..., allow_failover: bool = True)`** — gate the warmup-on-failure
block and the post-warmup URL re-resolution on `allow_failover`. Default `True` keeps all
existing submit callers (and capacity fallback) unchanged.
2. **`get_job_status(job_id, worker_url: Optional[str] = None)`** — when `worker_url` is given,
poll `f"{worker_url}/status/{job_id}"` with `allow_failover=False` (a pinned poll must never
re-resolve to active_url nor spin up a fallback VM — a fresh VM can't have the job). When
omitted, behave exactly as today.
3. **`wait_for_completion(..., worker_url: Optional[str] = None)`** — thread `worker_url` into
`get_job_status`. Consecutive-failure tolerance unchanged (still rides out a brief restart of
the *pinned* worker). A pinned 404 is now the *true* "owning worker lost the job" signal.
4. **`encode_videos` / `render_video_on_gce` / `encode_preview_video`** — capture
`pinned_url = self._get_worker_url()` **after** submit returns, and pass it as `worker_url=`
to `wait_for_completion`. Capturing post-submit reflects a capacity-fallback re-route during
submit (warmup invalidates the cache, so `_get_worker_url()` returns the fallback URL) while
being *before* any later deploy swap.
### Why post-submit capture (not the submit return value)
A capacity-fallback during submit updates `active_override` + invalidates the URL cache, so the
*next* `_get_worker_url()` already returns the worker the job actually landed on. This avoids
threading the URL back through three `submit_*` return contracts.
## Tests (TDD — `backend/tests/test_encoding_service.py`)
- `get_job_status` targets the pinned URL over active_url, with `allow_failover=False`.
- `get_job_status` without a pin still uses active_url (regression).
- `wait_for_completion` threads `worker_url` into each poll.
- `_request_with_retry` does **not** warm up / re-resolve when `allow_failover=False`.
- **End-to-end:** `render_video_on_gce` keeps polling the submission worker even when
`active_url` has swapped to a worker that 404s — would fail before the fix, passes after.
- Update the 3 existing `wait_for_completion` tolerance mocks to accept `worker_url=None`.
## Scope notes / non-goals
- The single `get_job_status` call inside the `submit_*` 409-conflict handler stays unpinned
(rare two-request-same-job-during-swap edge); the main poll loop is pinned via the convenience
methods, which covers the join case.
- No change to the CI drain logic — it remains the correct guard for *stopping* a busy VM.
@@ -0,0 +1,175 @@
# Plan: Restore missing files in Dropbox track output folders
**Date:** 2026-06-17
**Branch:** `feat/sess-20260617-1501-dropbox-missing-files`
**Status:** Implemented (v0.186.0) — Parts A/B/C done + a bundled CLI ffmpeg-hang fix (see end).
## Problem
Track output folders uploaded to Dropbox (e.g. `NOMAD-1184 - Eddie Money - I'll Get By`)
are missing two file types that used to be present (last good folder ~Feb 2026):
1. **Screen videos** — the 5-second `.mov` clips generated from the title/end screen
images: `<artist> - <title> (Title).mov` and `<artist> - <title> (End).mov`.
The folder still has the `(Title).png`/`.jpg`/`(End).png` images, just not the `.mov`s.
2. **Original input audio** — the source file used for separation/transcription/with-vocals,
e.g. `<artist> - <title> (flacfetch).flac` or `<artist> - <title> (uploaded).mp3`.
## Root cause
The Dropbox upload (`VideoWorkerOrchestrator._upload_to_dropbox`,
`backend/workers/video_worker_orchestrator.py`) uploads **the entire `output_dir`** wholesale
via `dropbox.upload_folder(...)`. There is no curated file list — whatever is in `output_dir`
gets uploaded. So both files are missing simply because they are **no longer in `output_dir`**
by the time distribution runs. The pipeline migrated from a monolith (one working dir held
everything) to distributed GCE workers, narrowing what lands in `output_dir`:
### `.mov` screen videos — broke with PRs #647/#650 (2026-03-31)
- Old: `screens_worker` generated `(Title).mov`/`(End).mov` locally; `video_worker` pulled
them into `output_dir`.
- Now: to fit Cloud Run's 2 GiB cap (#640), `screens_worker` emits **PNG only**
(`intro_video_duration=0`), and `video_worker`/orchestrator download the **PNG**.
- The GCE encoder (`backend/services/gce_encoding/main.py`, `generate_mov_from_png`)
**still generates** `title.mov`/`end.mov` from the PNGs — but as throwaway intermediates in
a `screens/` temp dir with generic names. Only the `outputs/` dir is uploaded to GCS
`finals/`, and the orchestrator's `_download_gce_encoded_files` only maps back 5 named
finals (`lossless_4k`, `lossy_4k`, `mkv`, `720p`, `with_vocals`). The standalone `.mov`s
are never returned.
### Original input audio — never copied into `output_dir` in the distributed pipeline
- Audio is downloaded by `audio_worker` early and stored in GCS:
- Uploaded files → persisted to `jobs/{job_id}/input/{filename}` (because `uploads/` has a
7-day lifecycle; `jobs/` is permanent).
- URL/flacfetch jobs → `input_media_gcs_path` / `file_urls['input']`.
- The old monolith left this file in the working dir → it ended up in the Dropbox folder.
- The new orchestrator never copies it into `output_dir`.
## Decisions (from user, 2026-06-17)
- **Scope:** Forward fix for all future jobs **+ backfill original audio** for past jobs where
it still exists in GCS. **No `.mov` backfill** (can't regenerate without re-encoding).
- **Audio in Dropbox:** Include the full original audio file (it's the archival master), always.
## Fix design
Both fixes converge on "ensure the file is in `output_dir` before `_upload_to_dropbox`."
### Part A — Restore `.mov` screen videos (forward only)
Extend the existing GCE-finals mechanism so the standalone `.mov`s come back like any other final.
1. **GCE worker** (`backend/services/gce_encoding/main.py`, `run_encoding`):
After the title/end `.mov`s are generated (they already are, for concat), copy them into the
`outputs/` dir with proper names `{base_name} (Title).mov` / `{base_name} (End).mov` before
`output_files` is collected. They then upload to GCS `finals/` automatically via
`output_dir.glob("*")`.
2. **`EncodingOutput`** (`backend/services/encoding_interface.py`): add `title_mov_path`,
`end_mov_path`.
3. **`GCEEncodingBackend.encode`** (same file): in the filename→key mapping, match
`(title).mov` / `(end).mov` → new keys (`title_mov`, `end_mov`); populate the new
`EncodingOutput` fields.
4. **Orchestrator** (`_download_gce_encoded_files`): add `('title_mov_path', ...)`,
`('end_mov_path', ...)` to `file_mappings` so they download into `output_dir`. Failure to
download is non-fatal (consistent with existing per-file handling).
5. **Local encoding path** (`LocalEncodingService` / `LocalEncodingBackend`): verify during
implementation whether the local fallback already leaves the `.mov`s in `output_dir`; if not,
mirror the behavior. Production is GCE, so this is secondary.
### Part B — Restore original input audio (forward)
In the orchestrator's distribution stage, **before** `_upload_to_dropbox`, fetch the original
source audio from GCS into `output_dir` with the historical source-tagged name.
- New helper (e.g. `_stage_original_audio_for_upload`) that:
- Resolves the GCS source: `job.input_media_gcs_path` (uploads persisted to `jobs/`), else
`file_urls['input']`/`['input']['audio']`.
- Derives the source suffix from `job.audio_source_type`:
- `file_upload` → `(uploaded)`
- `audio_search` → `(flacfetch)`
- `youtube_url` → `(YouTube)`
- (matches the historical monolith convention: `{artist_title} (flacfetch)` etc.)
- Downloads to `output_dir/{base_name} ({suffix}){ext}`, preserving the real extension
(`.flac`/`.mp3`/`.webm`/...).
- Non-fatal on failure (warn, continue) — Dropbox is already best-effort.
### Part C — Backfill original audio for past jobs (audio only)
One-off script (`backend/scripts/` or `scripts/`) — dry-run by default:
- Query completed jobs since the cutoff (~Mar 2026) that have a `dropbox_link`/`brand_code`.
- For each: locate original audio in GCS (skip if gone). Locate the Dropbox folder via
`{dropbox_path}/{brand_code} - {artist} - {title}`. Upload the audio with the source-tagged
name **only if not already present**.
- Log a summary (restored / skipped-missing-audio / skipped-already-present / errors).
## Test plan
- **Unit:** `GCEEncodingBackend.encode` maps `.mov` filenames → new `EncodingOutput` fields;
source-suffix derivation for each `audio_source_type`; helper builds correct GCS source path
and output filename per source type.
- **Orchestrator:** `_download_gce_encoded_files` downloads the two new `.mov` mappings;
`_stage_original_audio_for_upload` places the file in `output_dir` before upload (assert the
whole-folder upload then includes it). Mock storage/Dropbox.
- **GCE worker:** `run_encoding` copies `.mov`s into `outputs/` with proper names (assert
collected `output_files` includes them).
- **Manual:** run one real job end-to-end, confirm the Dropbox folder now contains
`(Title).mov`, `(End).mov`, and `(flacfetch).flac`/`(uploaded).mp3`. Backfill dry-run on a
small batch, then live on a couple of known folders.
## Files to touch
- `backend/services/gce_encoding/main.py` (A1)
- `backend/services/encoding_interface.py` (A2, A3)
- `backend/workers/video_worker_orchestrator.py` (A4, B)
- `backend/services/local_encoding_service.py` (A5, verify)
- new backfill script (C)
- tests under `backend/tests/`
## Bundled fix: ffmpeg interactive-prompt hang in `--finalise-only` (CLI)
Found while regenerating the missing `.mov`s locally. `karaoke_finalise.py` only added
`-y` to `ffmpeg_base_command` when `non_interactive=True`. In interactive mode, a
pre-existing output (e.g. a prior `(With Vocals).mp4`) made ffmpeg emit
`... already exists. Overwrite? [y/N]` to captured stderr and block on stdin until the
600s subprocess timeout — silently aborting finalisation at step 2/6 (only CDG/TXT zips
produced; no Final video files). The output's mtime never changed, proving no encode ran.
Fix (in `karaoke_gen/karaoke_finalise/karaoke_finalise.py`):
1. `-y` is now **unconditional** (re-runs overwrite intermediates idempotently).
2. All ffmpeg `subprocess.run` calls pass `stdin=subprocess.DEVNULL` (defense-in-depth so
ffmpeg can never block on a prompt — `execute_command` + both branches of
`execute_command_with_fallback`).
Tests: `tests/unit/test_karaoke_finalise_ffmpeg_prompt.py`; updated two existing tests that
asserted the old conditional-`-y` / no-stdin behaviour.
## Daily E2E verification (added per request)
So the daily GHA E2E catches this class of regression automatically:
- `audio_download_worker` now records the original audio in `file_urls['input']['audio']`
(URL/search jobs previously only set `input_media_gcs_path`), matching the upload path —
so original audio shows consistently in the admin files manifest.
- `_upload_results` (video_worker) registers `title_mov`/`end_mov` under `file_urls['finals']`
(uploaded to `jobs/{id}/finals/title_mov.mov` etc.), so the screen MOVs are queryable +
downloadable in the admin UI.
- `happy-path-real-user.spec.ts` (daily E2E Stage 2) gained **STEP 10.5**: after completion it
calls `GET /api/admin/jobs/{id}/files` and asserts the manifest contains
`finals/title_mov`, `finals/end_mov`, `input/audio`, and `finals/lossless_4k_mp4` — failing
loudly if any expected output is missing (vs. the old check that only opened one download).
Tests: `test_upload_results_screen_movs.py` (mov registration + skip-when-missing),
extended `test_audio_download_worker.py` (input/audio recorded).
## Implementation notes (as built)
- Part A files: `gce_encoding/main.py` (copy MOVs into `outputs/`), `encoding_interface.py`
(`title_mov_path`/`end_mov_path` + list→dict mapping), `video_worker_orchestrator.py`
(`OrchestratorResult.title_mov/end_mov` + download mappings).
- Part B: `backend/services/original_audio.py` (new helper), orchestrator
`_stage_original_audio_for_upload` + two `OrchestratorConfig` fields wired in
`create_orchestrator_config_from_job`. Staged only when a folder upload will occur.
- Part C: `backend/scripts/backfill_original_audio.py` (dry-run default; `--live`),
`DropboxService.file_exists`.
- Local encoding backend leaves `title_mov_path`/`end_mov_path` as None (production is GCE;
the local CLI/monolith already writes `.mov`s into the track dir itself).
## Risks / notes
- Dropbox storage grows (large FLACs re-included) — intended per decision.
- `.mov` regeneration on GCE adds a couple of small copies, negligible cost.
- Backfill depends on original audio still existing in GCS; older jobs may have none → skipped.
- Keep all new steps non-fatal so distribution never fails for an archival-file hiccup.
@@ -0,0 +1,96 @@
/**
* @jest-environment jsdom
*
* Tests that the API client attaches the X-Tenant-ID header on white-label tenant
* portals (sourced from window.__TENANT_CONFIG__) and omits it on the consumer build.
*
* Regression guard for the root-cause bug: the frontend never sent X-Tenant-ID, so the
* shared api.nomadkaraoke.com backend could not detect the tenant and every tenant-portal
* job/sign-in silently fell back to consumer behavior (0 tenant jobs ever ran in prod).
*/
import { api, getTenantId } from '@/lib/api'
function setEdgeTenant(id: string | null) {
if (id) {
;(window as any).__TENANT_CONFIG__ = {
tenant: { id, name: id, subdomain: `${id}.nomadkaraoke.com` },
is_default: false,
}
} else {
delete (window as any).__TENANT_CONFIG__
}
}
describe('getTenantId', () => {
afterEach(() => setEdgeTenant(null))
it('returns null when no tenant config is present (consumer build)', () => {
setEdgeTenant(null)
expect(getTenantId()).toBeNull()
})
it('returns the tenant id from window.__TENANT_CONFIG__', () => {
setEdgeTenant('vocalstar')
expect(getTenantId()).toBe('vocalstar')
})
it('returns null when the injected config has no tenant (default/consumer domain)', () => {
;(window as any).__TENANT_CONFIG__ = { tenant: null, is_default: true }
expect(getTenantId()).toBeNull()
})
})
describe('X-Tenant-ID header attachment', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(global as any).fetch = fetchMock
fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) })
})
afterEach(() => setEdgeTenant(null))
it('attaches X-Tenant-ID to authenticated requests (createJobWithUploadUrls) on a tenant portal', async () => {
setEdgeTenant('vocalstar')
window.localStorage.setItem('karaoke_access_token', 'tok-123')
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ job_id: 'j1', upload_urls: [] }),
})
await api.createJobWithUploadUrls('Adele', 'Hello', [], {
is_private: true,
existing_instrumental: true,
})
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['X-Tenant-ID']).toBe('vocalstar')
expect(init.headers['Authorization']).toBe('Bearer tok-123')
window.localStorage.removeItem('karaoke_access_token')
})
it('attaches X-Tenant-ID to the magic-link request on a tenant portal', async () => {
setEdgeTenant('singa')
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
await api.sendMagicLink('user@singa.com')
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/api\/users\/auth\/magic-link$/)
expect(init.headers['X-Tenant-ID']).toBe('singa')
})
it('does NOT attach X-Tenant-ID on the consumer build', async () => {
setEdgeTenant(null)
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
await api.sendMagicLink('user@example.com')
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['X-Tenant-ID']).toBeUndefined()
})
})
@@ -1,6 +1,8 @@
"use client"
import { useRef, useEffect, useCallback } from "react"
import { useRef, useEffect, useState, useCallback } from "react"
import { useTranslations } from "next-intl"
import { Loader2 } from "lucide-react"
interface KaraokeBackgroundPreviewProps {
backgroundUrl?: string // Object URL from File, or undefined for solid color
@@ -9,9 +11,25 @@ interface KaraokeBackgroundPreviewProps {
unsungColor?: string // Color for unsung lyrics
}
// 4K coordinate space (the sample lyrics are laid out in it); the canvas renders at
// the much smaller preview resolution below via a scale transform.
const CANVAS_W = 3840
const CANVAS_H = 2160
const PREVIEW_W = 960
const PREVIEW_H = 540
const MAX_DPR = 2
// Low-res background for the preview (the 4K asset stays for the real render path).
const KARAOKE_BG_SRC = "/karaoke-bg-preview.png"
/** Warm the karaoke background cache ahead of time (e.g. on Step 2). */
export function preloadKaraokeBg(): void {
if (typeof window === "undefined") return
const img = new Image()
img.src = KARAOKE_BG_SRC
}
// 4 sample lines to match real karaoke video rendering
const SAMPLE_LINES = [
"Don't say that you don't understand",
@@ -30,7 +48,9 @@ export function KaraokeBackgroundPreview({
sungColor,
unsungColor,
}: KaraokeBackgroundPreviewProps) {
const t = useTranslations("karaokeBackgroundPreview")
const canvasRef = useRef<HTMLCanvasElement>(null)
const [ready, setReady] = useState(false)
const effectiveSungColor = sungColor || DEFAULT_SUNG_COLOR
const effectiveUnsungColor = unsungColor || DEFAULT_UNSUNG_COLOR
@@ -38,11 +58,21 @@ export function KaraokeBackgroundPreview({
const draw = useCallback(async () => {
const canvas = canvasRef.current
if (!canvas) return
// Size the backing store to the preview resolution (dpr-aware, capped) and
// scale the 4K coordinate space down to it.
const dpr = Math.min((typeof window !== "undefined" && window.devicePixelRatio) || 1, MAX_DPR)
const cw = Math.round(PREVIEW_W * dpr)
const ch = Math.round(PREVIEW_H * dpr)
if (canvas.width !== cw) canvas.width = cw
if (canvas.height !== ch) canvas.height = ch
const ctx = canvas.getContext("2d")
if (!ctx) return
ctx.setTransform(cw / CANVAS_W, 0, 0, ch / CANVAS_H, 0, 0)
// Draw background: custom image > solid color > default Nomad theme image
const bgSrc = backgroundUrl || (backgroundColor ? null : "/karaoke-bg.png")
const bgSrc = backgroundUrl || (backgroundColor ? null : KARAOKE_BG_SRC)
if (bgSrc) {
try {
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
@@ -116,6 +146,8 @@ export function KaraokeBackgroundPreview({
ctx.fillText(line, centerX, y)
}
})
setReady(true)
}, [backgroundUrl, backgroundColor, effectiveSungColor, effectiveUnsungColor])
useEffect(() => {
@@ -123,15 +155,26 @@ export function KaraokeBackgroundPreview({
}, [draw])
return (
<canvas
ref={canvasRef}
width={CANVAS_W}
height={CANVAS_H}
className="w-full rounded-lg"
style={{
aspectRatio: "16/9",
border: "1px solid var(--card-border)",
}}
/>
<div className="relative w-full" style={{ aspectRatio: "16/9" }}>
<canvas
ref={canvasRef}
width={PREVIEW_W}
height={PREVIEW_H}
className="w-full h-full rounded-lg"
style={{
border: "1px solid var(--card-border)",
}}
/>
{!ready && (
<div
className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg"
style={{ backgroundColor: "var(--secondary)", color: "var(--text-muted)" }}
data-testid="karaoke-background-preview-loading"
>
<Loader2 className="w-5 h-5 animate-spin" />
<span className="text-xs">{t('loading')}</span>
</div>
)}
</div>
)
}
+61 -12
View File
@@ -1,7 +1,8 @@
"use client"
import { useRef, useEffect, useCallback } from "react"
import { useRef, useEffect, useState, useCallback } from "react"
import { useTranslations } from 'next-intl'
import { Loader2 } from "lucide-react"
interface TitleCardPreviewProps {
artist: string
@@ -19,9 +20,19 @@ interface TitleCardPreviewProps {
// - Title: white (#ffffff), uppercase, region 370,980,3100,350
// - Artist: golden yellow (#ffdf6b), uppercase, region 370,1400,3100,450
// Coordinate space the title-card layout is authored in (style_params.json is in
// 4K). All region/font constants below are in this space; the canvas renders at a
// much smaller preview resolution (see PREVIEW_*) via a scale transform, so a small
// thumbnail no longer allocates a 4K (3840×2160) backing store + 4K PNG.
const CANVAS_W = 3840
const CANVAS_H = 2160
// Actual canvas backing-store resolution for the preview (multiplied by the
// device pixel ratio, capped, at draw time). Plenty sharp for the thumbnail.
const PREVIEW_W = 960
const PREVIEW_H = 540
const MAX_DPR = 2
// Title region: x=370, y=980, w=3100, h=350
const TITLE_X = 370
const TITLE_Y = 980
@@ -37,6 +48,9 @@ const ARTIST_H = 450
const TITLE_COLOR = "#ffffff"
const ARTIST_COLOR = "#ffdf6b"
// Low-res background sized for the preview (the full 4K asset stays for the real
// render path). Cached at module scope so it loads once per session.
const TITLE_CARD_BG_SRC = "/title-card-bg-preview.png"
let bgImageCache: HTMLImageElement | null = null
function loadBgImage(): Promise<HTMLImageElement> {
@@ -48,10 +62,21 @@ function loadBgImage(): Promise<HTMLImageElement> {
resolve(img)
}
img.onerror = reject
img.src = "/title-card-bg.png"
img.src = TITLE_CARD_BG_SRC
})
}
/** Warm the title-card background cache ahead of time (e.g. on Step 2) so the
* Step 4 preview paints instantly. Safe to call repeatedly; failures are ignored. */
export function preloadTitleCardBg(): void {
void loadBgImage().catch(() => {})
}
/** Test-only: clear the module-level bg cache so each test starts from a cold load. */
export function __resetTitleCardBgCacheForTest(): void {
bgImageCache = null
}
function fitText(
ctx: CanvasRenderingContext2D,
text: string,
@@ -126,6 +151,7 @@ function drawTextBlock(
export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroundColor, titleColor, artistColor }: TitleCardPreviewProps) {
const t = useTranslations('titleCardPreview')
const canvasRef = useRef<HTMLCanvasElement>(null)
const [ready, setReady] = useState(false)
const effectiveTitleColor = titleColor || TITLE_COLOR
const effectiveArtistColor = artistColor || ARTIST_COLOR
@@ -133,8 +159,18 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
const draw = useCallback(async () => {
const canvas = canvasRef.current
if (!canvas) return
// Size the backing store to the preview resolution (dpr-aware, capped) and
// scale the 4K coordinate space down to it, so we never allocate a 4K canvas.
const dpr = Math.min((typeof window !== "undefined" && window.devicePixelRatio) || 1, MAX_DPR)
const cw = Math.round(PREVIEW_W * dpr)
const ch = Math.round(PREVIEW_H * dpr)
if (canvas.width !== cw) canvas.width = cw
if (canvas.height !== ch) canvas.height = ch
const ctx = canvas.getContext("2d")
if (!ctx) return
ctx.setTransform(cw / CANVAS_W, 0, 0, ch / CANVAS_H, 0, 0)
// Draw background: custom image > solid color > default image
try {
@@ -194,6 +230,8 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
artist ? effectiveArtistColor : "rgba(255,223,107,0.25)",
fontFamily,
)
setReady(true)
}, [artist, title, customBackgroundUrl, backgroundColor, effectiveTitleColor, effectiveArtistColor, t])
useEffect(() => {
@@ -201,15 +239,26 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroun
}, [draw])
return (
<canvas
ref={canvasRef}
width={CANVAS_W}
height={CANVAS_H}
className="w-full rounded-lg"
style={{
aspectRatio: "16/9",
border: "1px solid var(--card-border)",
}}
/>
<div className="relative w-full" style={{ aspectRatio: "16/9" }}>
<canvas
ref={canvasRef}
width={PREVIEW_W}
height={PREVIEW_H}
className="w-full h-full rounded-lg"
style={{
border: "1px solid var(--card-border)",
}}
/>
{!ready && (
<div
className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg"
style={{ backgroundColor: "var(--secondary)", color: "var(--text-muted)" }}
data-testid="title-card-preview-loading"
>
<Loader2 className="w-5 h-5 animate-spin" />
<span className="text-xs">{t('loading')}</span>
</div>
)}
</div>
)
}
@@ -23,6 +23,7 @@ jest.mock("@/lib/api", () => ({
searchStandalone: jest.fn(),
searchCatalogTracks: jest.fn(),
checkCommunityVersions: jest.fn(),
matchJudge: jest.fn(),
createJobFromSearch: jest.fn(),
},
ApiError: class ApiError extends Error {
@@ -75,10 +76,46 @@ const defaultProps = {
onUrlReady: jest.fn(),
onFileReady: jest.fn(),
onBack: jest.fn(),
onAudioEditChange: jest.fn(),
noCredits: false,
}
function verdict(overrides: Partial<import("@/lib/api").MatchJudgeVerdict> = {}) {
return {
kind: "none" as const,
confident: true,
canonical_artist: "ABBA",
canonical_title: "Waterloo",
alternatives: [],
engine: "catalog" as const,
reason: "",
needs_ai: false,
...overrides,
}
}
/** Stage-aware matchJudge mock: the component fires a "fast" pass on mount and a
* "full" pass (with the tier) only when the fast pass is inconclusive / weak. */
function setJudgeVerdicts(opts: {
fast?: Partial<import("@/lib/api").MatchJudgeVerdict>
full?: Partial<import("@/lib/api").MatchJudgeVerdict>
}) {
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
const isFast = callOpts?.stage === "fast"
return Promise.resolve(verdict(isFast ? opts.fast : opts.full))
})
}
function setupMocks() {
// Reset confidence to the tier-1 default each test (mockReturnValue otherwise
// persists across tests because clearAllMocks only clears call history).
mockGetSearchConfidence.mockReturnValue({
tier: 1,
bestResult: { index: 0, title: "Waterloo", artist: "ABBA", provider: "YouTube", url: "https://yt.com/1" },
bestCategory: "LOSSLESS",
reason: "Perfect match",
warnings: [],
})
mockApi.searchStandalone.mockResolvedValue({
search_session_id: "sess-123",
results: [
@@ -92,6 +129,8 @@ function setupMocks() {
songs: [],
best_youtube_url: null,
})
// Default: catalog says "already canonical" on both passes (no change).
setJudgeVerdicts({ fast: {}, full: {} })
}
describe("AudioSourceStep", () => {
@@ -108,11 +147,63 @@ describe("AudioSourceStep", () => {
})
})
it("calls searchCatalogTracks on mount in parallel", async () => {
it("fires a fast catalog-only pass on mount (parallel with search)", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchCatalogTracks).toHaveBeenCalledWith("Waterloo", "ABBA", 5)
expect(mockApi.matchJudge).toHaveBeenCalledWith("ABBA", "Waterloo", { stage: "fast" })
})
})
it("fires a full pass with the tier when the fast pass is inconclusive", async () => {
setJudgeVerdicts({
fast: { kind: "none", confident: false, needs_ai: true, engine: "catalog" },
full: { kind: "none", confident: true },
})
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.matchJudge).toHaveBeenCalledWith(
"ABBA", "Waterloo", { stage: "full", audioConfidenceTier: 1 }
)
})
})
it("does NOT fire a full pass when the fast pass is confident and audio is strong", async () => {
// Default mocks: fast returns a confident catalog verdict, tier 1.
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.matchJudge).toHaveBeenCalledWith("ABBA", "Waterloo", { stage: "fast" })
})
// Give the coordinating effect a chance to (not) fire the full call.
await waitFor(() => {
expect(mockApi.matchJudge).toHaveBeenCalledTimes(1)
})
expect(mockApi.matchJudge).not.toHaveBeenCalledWith(
"ABBA", "Waterloo", expect.objectContaining({ stage: "full" })
)
})
it("fires a full pass to verify a catalog match when audio results are weak (tier 3)", async () => {
mockApi.searchStandalone.mockResolvedValue({
search_session_id: "sess-empty", results: [], results_count: 0,
})
mockGetSearchConfidence.mockReturnValue({
tier: 3, bestResult: null, bestCategory: null, reason: "", warnings: [],
})
setJudgeVerdicts({
fast: { kind: "none", confident: true, engine: "catalog" }, // catalog "matched"
full: { kind: "content", confident: true, canonical_title: "Waterloo (Fixed)", engine: "ai" },
})
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.matchJudge).toHaveBeenCalledWith(
"ABBA", "Waterloo", { stage: "full", audioConfidenceTier: 3 }
)
})
})
@@ -147,16 +238,119 @@ describe("AudioSourceStep", () => {
expect(screen.getByText("ABBA - Waterloo")).toBeInTheDocument()
})
it("renders SongSuggestionPanel when catalog returns results", async () => {
mockApi.searchCatalogTracks.mockResolvedValue([
{ artist_name: "ABBA", track_name: "Waterloo (Remastered)" },
])
it("auto-applies a cosmetic tidy from the fast pass and shows the tidy notice", async () => {
setJudgeVerdicts({
fast: {
kind: "cosmetic",
confident: true,
canonical_title: "Waterloo (Remastered)",
engine: "catalog",
},
})
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(screen.getByTestId("song-suggestion-panel")).toBeInTheDocument()
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("ABBA", "Waterloo (Remastered)")
})
expect(screen.getByTestId("match-tidy-notice")).toBeInTheDocument()
})
it("does not auto-apply an ambiguous match — shows an ask instead", async () => {
setJudgeVerdicts({
fast: { kind: "none", confident: false, needs_ai: true, engine: "catalog" },
full: {
kind: "ambiguous",
confident: false,
canonical_artist: "Lewis Capaldi",
canonical_title: "Bruises",
alternatives: [{ artist: "Fox Stevenson", title: "Bruises" }],
engine: "ai",
},
})
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(screen.getByTestId("match-didyoumean")).toBeInTheDocument()
})
expect(defaultProps.onArtistTitleCorrection).not.toHaveBeenCalled()
const user = userEvent.setup()
await user.click(screen.getByText("Lewis Capaldi — Bruises"))
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("Lewis Capaldi", "Bruises")
})
it("gates the pick button until the judge settles, then enables it", async () => {
// Fast pass is inconclusive; full pass resolves after a tick → gate releases.
let resolveFull: (v: import("@/lib/api").MatchJudgeVerdict) => void = () => {}
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
if (callOpts?.stage === "fast") {
return Promise.resolve(verdict({ kind: "none", confident: false, needs_ai: true }))
}
return new Promise<import("@/lib/api").MatchJudgeVerdict>((res) => { resolveFull = res })
})
render(<AudioSourceStep {...defaultProps} />)
// Pick button rendered but disabled while the full pass is in flight.
const pickButton = await screen.findByRole("button", { name: /Use This Audio/i })
expect(pickButton).toBeDisabled()
expect(screen.getByTestId("match-gate-checking")).toBeInTheDocument()
// Resolve the full pass → gate releases, button enables.
await act(async () => {
resolveFull(verdict({ kind: "none", confident: true }))
})
await waitFor(() => expect(pickButton).toBeEnabled())
expect(screen.queryByTestId("match-gate-checking")).not.toBeInTheDocument()
})
it("releases the gate via the safety timeout if the judge hangs", async () => {
jest.useFakeTimers()
try {
mockApi.matchJudge.mockImplementation((_a, _t, callOpts) => {
if (callOpts?.stage === "fast") {
return Promise.resolve(verdict({ kind: "none", confident: false, needs_ai: true }))
}
return new Promise(() => {}) // full pass never resolves
})
render(<AudioSourceStep {...defaultProps} />)
// Let the fast pass + coordinating effect run.
await act(async () => { await Promise.resolve() })
const pickButton = await screen.findByRole("button", { name: /Use This Audio/i })
expect(pickButton).toBeDisabled()
// Advance past the 12s safety timeout → gate releases.
await act(async () => { jest.advanceTimersByTime(12000) })
await waitFor(() => expect(pickButton).toBeEnabled())
} finally {
jest.useRealTimers()
}
})
it("toggles a cosmetic tidy back and forth (two-way)", async () => {
setJudgeVerdicts({
fast: { kind: "cosmetic", confident: true, canonical_title: "Waterloo (Remastered)", engine: "catalog" },
})
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(defaultProps.onArtistTitleCorrection).toHaveBeenCalledWith("ABBA", "Waterloo (Remastered)")
})
const user = userEvent.setup()
// Revert to what the user typed.
await user.click(screen.getByText("keep what I typed"))
expect(defaultProps.onArtistTitleCorrection).toHaveBeenLastCalledWith("ABBA", "Waterloo")
expect(screen.getByText(/Using what you typed/)).toBeInTheDocument()
// Switch back to the tidied version.
await user.click(screen.getByText("use tidied version"))
expect(defaultProps.onArtistTitleCorrection).toHaveBeenLastCalledWith("ABBA", "Waterloo (Remastered)")
})
it("renders CommunityVersionBanner when community data has results", async () => {
@@ -239,8 +433,8 @@ describe("AudioSourceStep", () => {
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
})
it("silently handles catalog search failure (does not show error)", async () => {
mockApi.searchCatalogTracks.mockRejectedValue(new Error("catalog down"))
it("silently handles matchJudge failure (does not show error)", async () => {
mockApi.matchJudge.mockRejectedValue(new Error("judge down"))
render(<AudioSourceStep {...defaultProps} />)
@@ -248,8 +442,8 @@ describe("AudioSourceStep", () => {
expect(mockApi.searchStandalone).toHaveBeenCalled()
})
// No error shown for catalog failure — it's a nice-to-have
expect(screen.queryByText("catalog down")).not.toBeInTheDocument()
// No error shown for judge failure — it's a nice-to-have
expect(screen.queryByText("judge down")).not.toBeInTheDocument()
})
it("silently handles community check failure", async () => {
@@ -264,16 +458,15 @@ describe("AudioSourceStep", () => {
expect(screen.queryByText("community down")).not.toBeInTheDocument()
})
it("does not show SongSuggestionPanel when catalog returns empty array", async () => {
mockApi.searchCatalogTracks.mockResolvedValue([])
it("shows no match notice for a 'none' verdict", async () => {
render(<AudioSourceStep {...defaultProps} />)
await waitFor(() => {
expect(mockApi.searchStandalone).toHaveBeenCalled()
expect(mockApi.matchJudge).toHaveBeenCalled()
})
expect(screen.queryByTestId("song-suggestion-panel")).not.toBeInTheDocument()
expect(screen.queryByTestId("match-tidy-notice")).not.toBeInTheDocument()
expect(screen.queryByTestId("match-didyoumean")).not.toBeInTheDocument()
})
it("does not show CommunityVersionBanner when has_community is false", async () => {
@@ -1,5 +1,5 @@
import { render, act } from "@testing-library/react"
import { TitleCardPreview } from "../TitleCardPreview"
import { render, act, screen } from "@testing-library/react"
import { TitleCardPreview, preloadTitleCardBg, __resetTitleCardBgCacheForTest } from "../TitleCardPreview"
// Module-level state shared with mock closures via reference
const state = {
@@ -32,6 +32,7 @@ function setupMocks() {
state.fontLoadResolve = null
HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
setTransform: jest.fn(),
drawImage: jest.fn(),
fillRect: jest.fn(),
fillText: jest.fn((text: string) => {
@@ -74,6 +75,7 @@ function setupMocks() {
beforeEach(() => {
setupMocks()
__resetTitleCardBgCacheForTest()
})
describe("TitleCardPreview", () => {
@@ -154,6 +156,7 @@ describe("TitleCardPreview", () => {
let _fillStyle = ""
let _font = ""
return {
setTransform: jest.fn(),
drawImage: jest.fn(),
fillRect: jest.fn(),
fillText: jest.fn((text: string) => {
@@ -187,6 +190,66 @@ describe("TitleCardPreview", () => {
expect(fillStyles).toContain("#00ff00")
})
it("renders the canvas at preview resolution, not 4K", async () => {
let result: ReturnType<typeof render>
await act(async () => {
result = render(<TitleCardPreview title="Test" artist="Artist" />)
await new Promise((r) => setTimeout(r, 100))
})
const canvasEl = result!.container.querySelector("canvas")
expect(canvasEl).not.toBeNull()
// dpr defaults to 1 in jsdom → 960×540 backing store (was 3840×2160).
expect(canvasEl!.width).toBe(960)
expect(canvasEl!.height).toBe(540)
})
it("loads the low-res preview background by default", async () => {
const loadedSrcs: string[] = []
global.Image = class MockImageDefault {
onload: (() => void) | null = null
onerror: (() => void) | null = null
_src = ""
complete = true
get src() { return this._src }
set src(v: string) {
this._src = v
loadedSrcs.push(v)
Promise.resolve().then(() => this.onload?.())
}
} as unknown as typeof Image
await act(async () => {
render(<TitleCardPreview title="Test" artist="Artist" />)
await new Promise((r) => setTimeout(r, 100))
})
expect(loadedSrcs).toContain("/title-card-bg-preview.png")
expect(loadedSrcs).not.toContain("/title-card-bg.png")
})
it("shows a loading spinner before the first draw completes", () => {
// Hold the font load open so draw() never reaches setReady(true).
state.fontCheckReturn = false
render(<TitleCardPreview title="Song" artist="Artist" />)
expect(screen.getByTestId("title-card-preview-loading")).toBeInTheDocument()
})
it("preloadTitleCardBg loads the low-res asset without throwing", () => {
const loadedSrcs: string[] = []
global.Image = class MockImagePreload {
onload: (() => void) | null = null
onerror: (() => void) | null = null
_src = ""
complete = false
get src() { return this._src }
set src(v: string) { this._src = v; loadedSrcs.push(v) }
} as unknown as typeof Image
expect(() => preloadTitleCardBg()).not.toThrow()
expect(loadedSrcs).toContain("/title-card-bg-preview.png")
})
it("loads custom background image when customBackgroundUrl is provided", async () => {
const loadedSrcs: string[] = []
global.Image = class MockImageCustom {
+311 -367
View File
@@ -2,8 +2,10 @@
import { useTranslations } from "next-intl"
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api"
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse, MatchJudgeVerdict } from "@/lib/api"
import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner"
import { preloadTitleCardBg } from "@/components/job/TitleCardPreview"
import { preloadKaraokeBg } from "@/components/job/KaraokeBackgroundPreview"
import {
ExtendedAudioSearchResult,
groupResults,
@@ -18,7 +20,7 @@ import {
} from "@/lib/audio-search-utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, Search, X, Scissors, Zap } from "lucide-react"
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info, X, Scissors, Zap } from "lucide-react"
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
interface AudioSourceStepProps {
@@ -47,6 +49,21 @@ type SearchStatus =
const MAX_SEARCH_ATTEMPTS = 3
const RETRY_DELAYS = [0, 2000, 4000] // ms delay before each attempt
// Audio tier at/above this is "weak" (poor / no results) — a hint the title may
// be a typo, which makes the AI judge worth consulting even on a catalog match.
const WEAK_TIER = 3
// Hard ceiling on how long the audio-selection gate stays closed waiting for the
// judge. The backend AI call already caps at ~12s; this is a belt-and-suspenders
// release so a network hang never strands the user. Bounds the gate to ≤12s.
const JUDGE_GATE_TIMEOUT_MS = 12000
/** True when a fast (catalog-only) pass produced a confident catalog verdict
* (a cosmetic tidy or an exact "already canonical" match) — i.e. no AI needed. */
function isCatalogConfident(v: MatchJudgeVerdict | null): boolean {
return !!v && !v.needs_ai && v.confident && (v.kind === 'cosmetic' || v.kind === 'none')
}
/** Returns true for transient errors that should be auto-retried */
function isRetryableError(err: unknown): boolean {
// Network errors (TypeError: Failed to fetch, connection refused, CORS)
@@ -126,6 +143,7 @@ export function AudioSourceStep({
noCredits,
onAudioEditChange,
}: AudioSourceStepProps) {
const tJobFlow = useTranslations('jobFlow')
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [searchStatus, setSearchStatus] = useState<SearchStatus>({ phase: 'searching', attempt: 1 })
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
@@ -138,19 +156,30 @@ export function AudioSourceStep({
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
const searchTriggered = useRef(false)
// Catalog song suggestions (parallel to audio search)
const [catalogResults, setCatalogResults] = useState<CatalogTrackResult[]>([])
const [catalogDismissed, setCatalogDismissed] = useState(false)
// Community version check (parallel to audio search)
const [communityData, setCommunityData] = useState<CommunityCheckResponse | null>(null)
const [communityDismissed, setCommunityDismissed] = useState(false)
// Fuzzy "Did you mean?" state
const [fuzzySuggestion, setFuzzySuggestion] = useState<CatalogTrackResult | null>(null)
const [fuzzyAlternatives, setFuzzyAlternatives] = useState<CatalogTrackResult[]>([])
const [fuzzyDismissed, setFuzzyDismissed] = useState(false)
const fuzzyTriggered = useRef(false)
// Artist/title match judge: formatting tidy + match-acceptance + did-you-mean.
// Two-phase: a fast catalog-only pass fires on mount (in parallel with the audio
// search) so the common cosmetic tidy is ready before results render; a full pass
// (with the confidence tier, may use AI) runs after the search resolves, only when
// the fast pass was inconclusive or a catalog match coincides with weak audio.
const [verdict, setVerdict] = useState<MatchJudgeVerdict | null>(null)
const [verdictDismissed, setVerdictDismissed] = useState(false)
// What we auto-applied, so the user can toggle back to exactly what they typed.
const [appliedFrom, setAppliedFrom] = useState<{ artist: string; title: string } | null>(null)
// Two-way toggle state: true = the canonical correction is applied, false = the
// user reverted to what they typed (they can switch back).
const [correctionActive, setCorrectionActive] = useState(true)
// The fast pass's promise, awaited by the full-pass effect once the tier is known.
const fastJudgeRef = useRef<Promise<MatchJudgeVerdict | null> | null>(null)
const fullJudgeTriggered = useRef(false)
// Hard gate: audio-selection buttons stay disabled until the judge settles, so a
// user can never advance with un-tidied metadata (and a slow verdict can't clobber
// a selection). Released on any terminal judge state or the safety timeout.
const [gateReleased, setGateReleased] = useState(false)
const [showBuyCreditsDialog, setShowBuyCreditsDialog] = useState(false)
@@ -204,17 +233,12 @@ export function AudioSourceStep({
}
}, [artist, title, onSearchCompleted])
// Auto-trigger audio search + catalog search in parallel on mount
// Auto-trigger audio search + community check in parallel on mount.
// The match judge runs in a separate effect once the search resolves (below).
useEffect(() => {
if (searchTriggered.current) return
searchTriggered.current = true
doSearch()
// Fire catalog search in parallel (non-blocking)
api.searchCatalogTracks(title, artist, 5)
.then((tracks) => setCatalogResults(tracks))
.catch(() => {
// Silently fail — catalog search is a nice-to-have
})
// Fire community version check in parallel (non-blocking)
api.checkCommunityVersions(artist, title)
.then((data) => setCommunityData(data))
@@ -223,66 +247,128 @@ export function AudioSourceStep({
})
}, [doSearch, artist, title])
// Warm the Step 4 preview backgrounds now (artist/title are locked here), so the
// title-card / karaoke previews paint instantly by the time the user arrives.
useEffect(() => {
preloadTitleCardBg()
preloadKaraokeBg()
}, [])
const confidence = useMemo(() => getSearchConfidence(results, title), [results, title])
const groupedResults = useMemo(() => groupResults(results), [results])
const otherResultsCount = results.length > 0 && confidence.bestResult ? results.length - 1 : 0
// Fuzzy "Did you mean?" — triggers when audio search is poor AND catalog didn't find a close title match
const catalogHasExactTitleMatch = useMemo(() =>
catalogResults.some((t) => t.track_name.toLowerCase() === title.toLowerCase()),
[catalogResults, title]
)
// Phase 1 — fast catalog-only pass, fired on mount in parallel with the audio
// search (no tier needed). A confident cosmetic tidy applies immediately so it's
// done before results render. The promise is awaited by phase 2.
useEffect(() => {
if (fuzzyTriggered.current) return
if (isSearching) return // Wait for audio search to complete
if (catalogHasExactTitleMatch) return // Catalog found the exact song — no typo
if (confidence.tier <= 2) return // Audio search found good results — no typo likely
fuzzyTriggered.current = true
// Try artist name as query first, fall back to title if that returns nothing
api.searchCatalogTracks(artist, undefined, 20)
.then((tracks) => {
const matches = findFuzzyMatches(title, tracks)
if (matches.length > 0) {
setFuzzySuggestion(matches[0])
setFuzzyAlternatives(matches.slice(1))
return
if (fastJudgeRef.current) return
fastJudgeRef.current = api.matchJudge(artist, title, { stage: 'fast' })
.then((v) => {
if (v.kind === 'cosmetic' && v.confident && !v.needs_ai) {
setVerdict(v)
applyCorrection(v.canonical_artist, v.canonical_title, false)
}
// Fallback: search by title (handles case where artist field has garbage like "fox stevenson bruises")
return api.searchCatalogTracks(title, undefined, 20).then((titleTracks) => {
const titleMatches = findFuzzyMatches(title, titleTracks, 0.6, true, artist)
if (titleMatches.length > 0) {
setFuzzySuggestion(titleMatches[0])
setFuzzyAlternatives(titleMatches.slice(1))
}
})
return v
})
.catch(() => {
// Silently fail
})
}, [isSearching, catalogResults, confidence.tier, artist, title])
.catch(() => null)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [artist, title])
function handleFuzzyAccept(track?: CatalogTrackResult) {
const chosen = track || fuzzySuggestion
if (!chosen) return
// Update parent's artist/title
onArtistTitleCorrection(chosen.artist_name, chosen.track_name)
// Reset and restart search with corrected name
setFuzzySuggestion(null)
setFuzzyAlternatives([])
setFuzzyDismissed(true)
setResults([])
setSearchStatus({ phase: 'searching', attempt: 1 })
setCatalogResults([])
setCatalogDismissed(false)
setCommunityData(null)
setCommunityDismissed(false)
setShowOtherOptions(false)
searchTriggered.current = false
fuzzyTriggered.current = false
// doSearch (and catalog/community searches) will re-fire via the useEffect
// when the parent re-renders us with corrected artist/title props, since
// searchTriggered.current is reset and doSearch is recreated with new props.
// Phase 2 — once the audio search resolves (so the tier is known): await the fast
// pass, run a full pass only when needed (fast inconclusive, or a catalog match
// landed on weak audio — item 4), then release the selection gate. Always settles.
useEffect(() => {
if (isSearching) return
if (fullJudgeTriggered.current) return
fullJudgeTriggered.current = true
let cancelled = false
const timer = setTimeout(() => {
if (!cancelled) setGateReleased(true)
}, JUDGE_GATE_TIMEOUT_MS)
const tier = confidence.tier
;(async () => {
const fast = await (fastJudgeRef.current ?? Promise.resolve(null))
const needFull = !fast || fast.needs_ai || (isCatalogConfident(fast) && tier >= WEAK_TIER)
if (needFull) {
try {
const full = await api.matchJudge(artist, title, { stage: 'full', audioConfidenceTier: tier })
if (!cancelled) applyFullVerdict(full, tier)
} catch {
// Silently fail — matching is a nice-to-have.
}
}
if (!cancelled) {
clearTimeout(timer)
setGateReleased(true)
}
})()
return () => {
cancelled = true
clearTimeout(timer)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isSearching])
// Apply a full-pass verdict (cosmetic tidy / confident content correction / ask).
function applyFullVerdict(v: MatchJudgeVerdict, tier: number) {
setVerdict(v)
if (v.kind === 'cosmetic' && v.confident) {
// Same song, formatting only — apply silently, never re-search.
applyCorrection(v.canonical_artist, v.canonical_title, false)
} else if (v.kind === 'content' && v.confident) {
// Real character change — apply, and re-search only if the typo'd search came
// back weak (tier 3) so we fetch better audio for the fix.
applyCorrection(v.canonical_artist, v.canonical_title, tier >= WEAK_TIER)
}
// ambiguous / unconfident content / none → render an ask (no auto-apply)
}
// Apply a corrected artist/title. reSearch=true re-runs the audio search with
// the corrected terms; the verdict notice stays visible across the re-search.
function applyCorrection(newArtist: string, newTitle: string, reSearch: boolean) {
if (newArtist === artist && newTitle === title) return
setAppliedFrom({ artist, title })
setCorrectionActive(true)
onArtistTitleCorrection(newArtist, newTitle)
if (reSearch) {
setResults([])
setSearchStatus({ phase: 'searching', attempt: 1 })
setCommunityData(null)
setCommunityDismissed(false)
setShowOtherOptions(false)
// Keep the gate open and don't re-judge the corrected terms. doSearch
// re-fires via the mount effect when the parent re-renders with the
// corrected artist/title props (searchTriggered is reset below).
searchTriggered.current = false
}
}
// User accepts an ambiguous "Did you mean?" suggestion (always re-search).
function handleSuggestionAccept(newArtist: string, newTitle: string) {
setVerdict({
kind: 'content', confident: true,
canonical_artist: newArtist, canonical_title: newTitle,
alternatives: [], engine: 'ai', reason: '', needs_ai: false,
})
applyCorrection(newArtist, newTitle, true)
}
// Two-way toggle. Revert restores exactly what the user typed; reapply switches
// back to the canonical correction. Toggling is metadata-only (no re-search).
function handleRevert() {
if (!appliedFrom) return
setCorrectionActive(false)
onArtistTitleCorrection(appliedFrom.artist, appliedFrom.title)
}
function handleReapply() {
if (!verdict) return
setCorrectionActive(true)
onArtistTitleCorrection(verdict.canonical_artist, verdict.canonical_title)
}
function handleSelect(index: number) {
@@ -428,20 +514,32 @@ export function AudioSourceStep({
</Button>
</div>
{/* Song name suggestions from catalog */}
{catalogResults.length > 0 && !catalogDismissed && (
<SongSuggestionPanel
results={catalogResults}
artist={artist}
title={title}
onSelect={(track) => {
onArtistTitleCorrection(track.artist_name, track.track_name)
setCatalogDismissed(true)
}}
onDismiss={() => setCatalogDismissed(true)}
{/* Artist/title formatting tidy + did-you-mean */}
{verdict && !verdictDismissed && (
<MatchNotice
verdict={verdict}
appliedFrom={appliedFrom}
correctionActive={correctionActive}
onAccept={handleSuggestionAccept}
onRevert={handleRevert}
onReapply={handleReapply}
onDismiss={() => setVerdictDismissed(true)}
/>
)}
{/* Selection gate indicator — while the judge confirms the song details, the
audio pick buttons stay disabled so we never advance with un-tidied metadata. */}
{!isSearching && !gateReleased && (
<div
className="flex items-center gap-2 text-xs"
style={{ color: 'var(--text-muted)' }}
data-testid="match-gate-checking"
>
<Loader2 className="w-3.5 h-3.5 animate-spin shrink-0" />
<span>{tJobFlow('matchChecking')}</span>
</div>
)}
{/* Community version banner */}
{communityData?.has_community && !communityDismissed && (
<CommunityVersionBanner
@@ -450,16 +548,6 @@ export function AudioSourceStep({
/>
)}
{/* "Did you mean?" fuzzy correction banner */}
{fuzzySuggestion && !fuzzyDismissed && (
<DidYouMeanBanner
suggestion={fuzzySuggestion}
alternatives={fuzzyAlternatives}
onAccept={handleFuzzyAccept}
onDismiss={() => setFuzzyDismissed(true)}
/>
)}
{/* Error display */}
{error && (
<div className="text-sm rounded p-3 text-red-400 bg-red-500/10">
@@ -501,6 +589,7 @@ export function AudioSourceStep({
searchTitle={title}
onSelect={handleSelect}
noCredits={noCredits}
locked={!gateReleased}
/>
)}
@@ -512,6 +601,7 @@ export function AudioSourceStep({
searchTitle={title}
onSelect={handleSelect}
noCredits={noCredits}
locked={!gateReleased}
/>
)}
@@ -529,6 +619,7 @@ export function AudioSourceStep({
uploadFile={uploadFile}
setUploadFile={setUploadFile}
noCredits={noCredits}
locked={!gateReleased}
onUrlSubmit={handleUrlSubmit}
onUploadSubmit={handleUploadSubmit}
/>
@@ -548,6 +639,7 @@ export function AudioSourceStep({
searchTitle={title}
onSelect={handleSelect}
noCredits={noCredits}
locked={!gateReleased}
/>
)}
@@ -568,6 +660,7 @@ export function AudioSourceStep({
uploadFile={uploadFile}
setUploadFile={setUploadFile}
noCredits={noCredits}
locked={!gateReleased}
onUrlSubmit={handleUrlSubmit}
onUploadSubmit={handleUploadSubmit}
/>
@@ -585,12 +678,14 @@ function PickCard({
searchTitle,
onSelect,
noCredits,
locked,
}: {
confidence: SearchConfidence
variant: "perfect" | "recommended"
searchTitle: string
onSelect: (index: number) => void
noCredits: boolean
locked?: boolean
}) {
const bestResult = confidence.bestResult!
const isPerfect = variant === "perfect"
@@ -688,7 +783,7 @@ function PickCard({
<Button
onClick={() => onSelect(bestResult.index)}
disabled={noCredits}
disabled={noCredits || locked}
className={`w-full text-white ${
isPerfect
? 'bg-green-600 hover:bg-green-500'
@@ -778,6 +873,7 @@ function OtherOptionsSection({
searchTitle,
onSelect,
noCredits,
locked,
}: {
confidence: SearchConfidence
groupedResults: ReturnType<typeof groupResults>
@@ -789,6 +885,7 @@ function OtherOptionsSection({
searchTitle: string
onSelect: (index: number) => void
noCredits: boolean
locked?: boolean
}) {
const isTier3 = confidence.tier === 3
@@ -808,6 +905,7 @@ function OtherOptionsSection({
searchTitle={searchTitle}
onSelect={onSelect}
noCredits={noCredits}
locked={locked}
defaultExpanded
alwaysShowMatchBadge
/>
@@ -844,6 +942,7 @@ function OtherOptionsSection({
searchTitle={searchTitle}
onSelect={onSelect}
noCredits={noCredits}
locked={locked}
/>
</div>
)}
@@ -860,6 +959,7 @@ function ResultCategories({
searchTitle,
onSelect,
noCredits,
locked,
defaultExpanded,
alwaysShowMatchBadge,
}: {
@@ -870,6 +970,7 @@ function ResultCategories({
searchTitle: string
onSelect: (index: number) => void
noCredits: boolean
locked?: boolean
defaultExpanded?: boolean
alwaysShowMatchBadge?: boolean
}) {
@@ -942,6 +1043,7 @@ function ResultCategories({
showMatchBadges={showMatchBadges}
onSelect={onSelect}
noCredits={noCredits}
locked={locked}
/>
))}
</div>
@@ -959,12 +1061,14 @@ function ResultRow({
showMatchBadges,
onSelect,
noCredits,
locked,
}: {
result: ExtendedAudioSearchResult
searchTitle: string
showMatchBadges: boolean
onSelect: (index: number) => void
noCredits: boolean
locked?: boolean
}) {
const mismatch = useMemo(() => checkFilenameMismatch(searchTitle, result), [searchTitle, result])
// Only show "Title match" when we actually verified a match (filename is non-empty)
@@ -1024,7 +1128,7 @@ function ResultRow({
<Button
size="sm"
onClick={() => onSelect(result.index)}
disabled={noCredits}
disabled={noCredits || locked}
className="h-7 px-3 text-xs shrink-0 bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
<Check className="w-3 h-3 mr-1" />
@@ -1034,191 +1138,6 @@ function ResultRow({
)
}
/** Song name suggestion panel — two modes: exact match confirmation vs correction suggestions */
function SongSuggestionPanel({
results,
artist,
title,
onSelect,
onDismiss,
}: {
results: CatalogTrackResult[]
artist: string
title: string
onSelect: (track: CatalogTrackResult) => void
onDismiss: () => void
}) {
const [showOthers, setShowOthers] = useState(false)
// Check if any result is a case-insensitive match for the user's input
const hasExactMatch = results.some(
(t) => t.artist_name.toLowerCase() === artist.toLowerCase() && t.track_name.toLowerCase() === title.toLowerCase()
)
// Results that differ from what the user typed (potential corrections)
const corrections = results.filter(
(t) => !(t.artist_name === artist && t.track_name === title)
)
// If the user already typed exactly right (case-sensitive), nothing to show
const hasExactCaseSensitiveMatch = results.some(
(t) => t.artist_name === artist && t.track_name === title
)
if (hasExactCaseSensitiveMatch && corrections.length === 0) {
// Perfect match, no alternatives — don't show the panel at all
return null
}
// Find the exact case-insensitive match (for casing correction)
const exactCaseInsensitiveMatch = hasExactMatch
? results.find(
(t) => t.artist_name.toLowerCase() === artist.toLowerCase() && t.track_name.toLowerCase() === title.toLowerCase()
)
: null
const hasCasingDifference = exactCaseInsensitiveMatch && (
exactCaseInsensitiveMatch.artist_name !== artist || exactCaseInsensitiveMatch.track_name !== title
)
// "Other" corrections excludes the exact case-insensitive match
const otherCorrections = corrections.filter(
(t) => !exactCaseInsensitiveMatch || t.artist_name !== exactCaseInsensitiveMatch.artist_name || t.track_name !== exactCaseInsensitiveMatch.track_name
)
// Mode 1: User's input matches a song (case-insensitive) — show confirmation with optional alternatives
if (hasExactMatch) {
return (
<div
className="border rounded-lg overflow-hidden border-green-500/30 bg-green-500/5"
data-testid="song-suggestion-panel"
>
<div className="px-3 py-2 flex items-center justify-between bg-green-500/10">
<div className="flex items-center gap-2">
<CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
<span className="text-xs font-semibold text-green-400">
Song found in our database
</span>
</div>
<button
onClick={onDismiss}
className="text-[10px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-3 h-3" />
Dismiss
</button>
</div>
<div className="px-3 py-2">
{hasCasingDifference && exactCaseInsensitiveMatch ? (
<div>
<p className="text-[10px] mb-1.5" style={{ color: 'var(--text-muted)' }}>
Use the official formatting?
</p>
<CatalogTrackList tracks={[exactCaseInsensitiveMatch]} onSelect={onSelect} />
</div>
) : (
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
Your artist and title matched a song in our database — looking good!
</p>
)}
{otherCorrections.length > 0 && (
<div className="mt-2">
<button
onClick={() => setShowOthers(!showOthers)}
className="flex items-center gap-1 text-[10px] hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
{showOthers ? (
<><ChevronUp className="w-3 h-3" /> Hide other matches</>
) : (
<><ChevronDown className="w-3 h-3" /> Show {otherCorrections.length} other match{otherCorrections.length !== 1 ? 'es' : ''}</>
)}
</button>
{showOthers && (
<div className="mt-1.5 space-y-1">
<CatalogTrackList tracks={otherCorrections} onSelect={onSelect} />
</div>
)}
</div>
)}
</div>
</div>
)
}
// Mode 2: No exact match — show corrections prominently
return (
<div
className="border rounded-lg overflow-hidden border-blue-500/30 bg-blue-500/5"
data-testid="song-suggestion-panel"
>
<div className="px-3 py-2 flex items-center justify-between bg-blue-500/10">
<div className="flex items-center gap-2">
<Search className="w-3.5 h-3.5 text-blue-400" />
<span className="text-xs font-semibold text-blue-400">
Use official artist/title formatting?
</span>
</div>
<button
onClick={onDismiss}
className="text-[10px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-3 h-3" />
Dismiss
</button>
</div>
<div className="px-3 py-2">
<p className="text-[10px] mb-2" style={{ color: 'var(--text-muted)' }}>
We found these in our song database. Click one to use the official artist/title formatting:
</p>
<CatalogTrackList tracks={corrections.length > 0 ? corrections : results} onSelect={onSelect} />
</div>
</div>
)
}
/** Reusable list of clickable catalog track rows */
function CatalogTrackList({
tracks,
onSelect,
}: {
tracks: CatalogTrackResult[]
onSelect: (track: CatalogTrackResult) => void
}) {
// Deduplicate by artist + track name (Spotify often returns the same song from different albums)
const uniqueTracks = tracks.filter((t, i, arr) =>
arr.findIndex((x) => x.artist_name === t.artist_name && x.track_name === t.track_name) === i
)
return (
<div className="space-y-1">
{uniqueTracks.map((track, i) => {
const duration = track.duration_ms
? `${Math.floor(track.duration_ms / 60000)}:${Math.floor((track.duration_ms % 60000) / 1000).toString().padStart(2, "0")}`
: null
return (
<button
key={track.track_id || `${track.artist_name}-${track.track_name}-${i}`}
onClick={() => onSelect(track)}
className="w-full text-left px-2.5 py-2 rounded-md text-xs flex items-center justify-between gap-2 transition-colors hover:bg-blue-500/10"
style={{ color: 'var(--text)' }}
>
<span className="min-w-0">
<span className="font-medium">{track.artist_name}</span>
<span style={{ color: 'var(--text-muted)' }}> — </span>
<span>{track.track_name}</span>
</span>
<span className="flex items-center gap-2 shrink-0">
{duration && (
<span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{duration}</span>
)}
<span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-500/15 text-blue-400 font-medium">
Use
</span>
</span>
</button>
)
})}
</div>
)
}
/** Compute similarity between two strings using longest common subsequence ratio */
export function stringSimilarity(a: string, b: string): number {
@@ -1274,93 +1193,6 @@ export function findFuzzyMatches(
.filter((t, i, arr) => arr.findIndex((x) => x.artist_name === t.artist_name && x.track_name === t.track_name) === i)
}
/** "Did you mean?" banner for typo correction */
function DidYouMeanBanner({
suggestion,
alternatives,
onAccept,
onDismiss,
}: {
suggestion: CatalogTrackResult
alternatives: CatalogTrackResult[]
onAccept: (track?: CatalogTrackResult) => void
onDismiss: () => void
}) {
const [showAlternatives, setShowAlternatives] = useState(false)
return (
<div
className="border rounded-lg overflow-hidden border-amber-500/40 bg-amber-500/5"
data-testid="did-you-mean-banner"
>
<div className="px-3 py-2 flex items-center justify-between bg-amber-500/10">
<div className="flex items-center gap-2">
<AlertTriangle className="w-3.5 h-3.5 text-amber-400" />
<span className="text-xs font-semibold text-amber-400">
Did you mean?
</span>
</div>
<button
onClick={onDismiss}
className="text-[10px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-3 h-3" />
No thanks
</button>
</div>
<div className="px-3 py-3">
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
We couldn&apos;t find great audio sources. Did you mean:
</p>
<button
onClick={() => onAccept()}
className="mt-2 w-full text-left px-3 py-2.5 rounded-md flex items-center justify-between gap-2 transition-colors border border-amber-500/30 hover:bg-amber-500/10"
>
<span className="text-sm" style={{ color: 'var(--text)' }}>
<span className="font-semibold">{suggestion.artist_name}</span>
<span style={{ color: 'var(--text-muted)' }}> — </span>
<span className="font-semibold">{suggestion.track_name}</span>
</span>
<span className="text-xs px-2 py-1 rounded bg-amber-500/15 text-amber-400 font-medium shrink-0">
Yes, search again
</span>
</button>
{alternatives.length > 0 && (
<div className="mt-2">
<button
onClick={() => setShowAlternatives(!showAlternatives)}
className="text-[11px] flex items-center gap-1 hover:opacity-80"
style={{ color: 'var(--text-muted)' }}
>
<ChevronDown className={`w-3 h-3 transition-transform ${showAlternatives ? 'rotate-180' : ''}`} />
{showAlternatives ? 'Hide' : 'Show'} {alternatives.length} other match{alternatives.length > 1 ? 'es' : ''}
</button>
{showAlternatives && (
<div className="mt-1.5 space-y-1">
{alternatives.slice(0, 5).map((alt, i) => (
<button
key={i}
onClick={() => onAccept(alt)}
className="w-full text-left px-3 py-2 rounded-md flex items-center justify-between gap-2 transition-colors border border-[var(--card-border)] hover:bg-amber-500/10 hover:border-amber-500/30"
>
<span className="text-xs" style={{ color: 'var(--text)' }}>
<span className="font-medium">{alt.artist_name}</span>
<span style={{ color: 'var(--text-muted)' }}> — </span>
<span className="font-medium">{alt.track_name}</span>
</span>
<span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400 shrink-0">
Search
</span>
</button>
))}
</div>
)}
</div>
)}
</div>
</div>
)
}
/** Contextual guidance when search returns no results */
function NoResultsSection() {
@@ -1396,6 +1228,7 @@ function FallbackSection({
uploadFile,
setUploadFile,
noCredits,
locked,
onUrlSubmit,
onUploadSubmit,
}: {
@@ -1408,6 +1241,7 @@ function FallbackSection({
uploadFile: File | null
setUploadFile: (file: File | null) => void
noCredits: boolean
locked?: boolean
onUrlSubmit: (e: React.FormEvent) => void
onUploadSubmit: (e: React.FormEvent) => void
}) {
@@ -1481,7 +1315,7 @@ function FallbackSection({
<Button
type="submit"
size="sm"
disabled={!youtubeUrl.trim() || noCredits}
disabled={!youtubeUrl.trim() || noCredits || locked}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
{t('useThisUrl')}
@@ -1533,7 +1367,7 @@ function FallbackSection({
<Button
type="submit"
size="sm"
disabled={!uploadFile || noCredits}
disabled={!uploadFile || noCredits || locked}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
Use This File
@@ -1543,3 +1377,113 @@ function FallbackSection({
</div>
)
}
/** Match-judge notice: a quiet two-way toggle for an auto-applied tidy/correction
* (switch between the canonical version and what you typed), or an ask-first
* "Did you mean?" prompt for ambiguous cases. */
function MatchNotice({
verdict,
appliedFrom,
correctionActive,
onAccept,
onRevert,
onReapply,
onDismiss,
}: {
verdict: MatchJudgeVerdict
appliedFrom: { artist: string; title: string } | null
correctionActive: boolean
onAccept: (artist: string, title: string) => void
onRevert: () => void
onReapply: () => void
onDismiss: () => void
}) {
const t = useTranslations('jobFlow')
const canonical = `${verdict.canonical_artist} — ${verdict.canonical_title}`
// Auto-applied cosmetic tidy or confident content correction → quiet two-way
// toggle. Active: shows the canonical value + a revert link. Reverted: shows what
// the user typed + a reapply link. The current value is always clear.
if (appliedFrom && (verdict.kind === 'cosmetic' || verdict.kind === 'content')) {
const typed = `${appliedFrom.artist} — ${appliedFrom.title}`
const isContent = verdict.kind === 'content'
let label: string
let action: string
let onToggle: () => void
if (correctionActive) {
label = isContent
? t('matchCorrectedTo', { value: canonical, typed })
: t('matchTidiedTo', { value: canonical })
action = isContent ? t('matchUndo') : t('matchKeepMine')
onToggle = onRevert
} else {
label = t('matchUsingTyped', { value: typed })
action = isContent ? t('matchUseCorrection') : t('matchUseTidied')
onToggle = onReapply
}
return (
<div
className="flex items-center gap-2 text-xs px-3 py-2 rounded-lg"
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text-muted)' }}
data-testid="match-tidy-notice"
data-correction-active={correctionActive}
>
<Check className="w-3.5 h-3.5 text-green-400 shrink-0" />
<span className="flex-1">{label}</span>
<button
type="button"
onClick={onToggle}
className="underline shrink-0"
style={{ color: 'var(--brand-pink)' }}
>
{action}
</button>
</div>
)
}
// Ambiguous (or unconfident content) → ask before changing anything.
if (verdict.kind === 'ambiguous' || verdict.kind === 'content') {
const options = [
{ artist: verdict.canonical_artist, title: verdict.canonical_title },
...verdict.alternatives,
].filter((o) => o.artist && o.title)
if (options.length === 0) return null
return (
<div
className="border rounded-lg p-3 border-amber-500/30 bg-amber-500/5"
data-testid="match-didyoumean"
>
<div className="flex items-center justify-between">
<span className="flex items-center gap-2 text-sm font-medium text-amber-400">
<Lightbulb className="w-4 h-4" />
{t('matchDidYouMean')}
</span>
<button
type="button"
onClick={onDismiss}
aria-label="Dismiss"
className="opacity-60 hover:opacity-100"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="mt-2 flex flex-col gap-1.5">
{options.map((o, i) => (
<button
key={`${o.artist}-${o.title}-${i}`}
type="button"
onClick={() => onAccept(o.artist, o.title)}
className="text-left text-sm px-2.5 py-1.5 rounded-md hover:bg-amber-500/10 transition-colors"
style={{ color: 'var(--text)' }}
>
{o.artist} — {o.title}
</button>
))}
</div>
</div>
)
}
return null
}
@@ -985,6 +985,52 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
console.log('STEP 10 COMPLETE: Downloads verified');
// =========================================================================
// STEP 10.5: Verify Output File Completeness
// =========================================================================
// Guards against regressions where files silently stop being produced/
// distributed (e.g. the screen .mov videos and the original input audio
// disappearing from the organised Dropbox folders). Asserts the job's file
// manifest contains every expected output, not just that one download works.
console.log('\n========================================');
console.log('STEP 10.5: Verify Output File Completeness');
console.log('========================================');
const manifestToken = process.env.E2E_ADMIN_TOKEN;
if (manifestToken && jobId) {
const filesResponse = await page.request.get(
`${API_URL}/api/admin/jobs/${jobId}/files`,
{ headers: { 'Authorization': `Bearer ${manifestToken}` } }
);
expect(filesResponse.ok()).toBe(true);
const manifest = await filesResponse.json();
const files: Array<{ category?: string; file_key?: string; name?: string }> =
manifest.files || [];
const keys = new Set(files.map((f) => `${f.category || ''}/${f.file_key || ''}`));
console.log(` Manifest has ${files.length} files:`);
for (const f of files) {
console.log(` - ${f.category}/${f.file_key}: ${f.name}`);
}
// The two regressions this guards against:
const required: Array<[string, string]> = [
['finals/title_mov', 'Title screen video (.mov)'],
['finals/end_mov', 'End screen video (.mov)'],
['input/audio', 'Original input audio'],
// Core deliverable sanity check
['finals/lossless_4k_mp4', 'Final lossless 4K video'],
];
const missing = required.filter(([key]) => !keys.has(key));
if (missing.length > 0) {
console.log(' MISSING expected output files:');
for (const [key, desc] of missing) console.log(` ✗ ${key} (${desc})`);
}
expect(missing, `Missing expected output files: ${missing.map(([k]) => k).join(', ')}`).toEqual([]);
console.log('STEP 10.5 COMPLETE: All expected output files present');
} else {
console.log(' Skipping - E2E_ADMIN_TOKEN not set or no job ID');
}
// =========================================================================
// STEP 11: Verify Distribution (if enabled)
// =========================================================================
+3
View File
@@ -76,6 +76,9 @@ function resetStore() {
error: null,
isInitialized: false,
})
// The store now mirrors resolved config onto window.__TENANT_CONFIG__ (so lib/api.ts
// can read it synchronously). Clear it between tests to keep them isolated.
delete (window as { __TENANT_CONFIG__?: unknown }).__TENANT_CONFIG__
}
describe("useTenant store", () => {
+79 -2
View File
@@ -55,10 +55,45 @@ function getLocaleFromPath(): string {
return 'en';
}
function getAuthHeaders(): HeadersInit {
const headers: HeadersInit = {
/**
* Resolve the current white-label tenant id, if any.
*
* On tenant portals the Cloudflare Pages edge function (frontend/functions/[[path]].ts)
* injects `window.__TENANT_CONFIG__` into the HTML before any app JS runs, and the
* tenant store (lib/tenant.ts) mirrors the same shape there in dev/preview. Reading it
* directly here keeps api.ts free of an import cycle with tenant.ts (which imports
* API_BASE_URL from this module).
*
* Returns null on the consumer build / consumer domain, so no tenant header is sent and
* existing consumer behavior is unchanged.
*/
export function getTenantId(): string | null {
if (typeof window === 'undefined') return null;
const injected = (window as { __TENANT_CONFIG__?: { tenant?: { id?: string } | null } }).__TENANT_CONFIG__;
const id = injected?.tenant?.id;
return typeof id === 'string' && id ? id : null;
}
/**
* Base headers attached to every API request: locale, and the X-Tenant-ID header when
* on a white-label tenant portal. The shared backend (api.nomadkaraoke.com) cannot infer
* the tenant from the Host (it's not the tenant subdomain) or from the prod-disabled
* `?tenant=` query param, so this header is the primary tenant-detection signal that lets
* the backend apply tenant config (locked theme, Dropbox path, no YouTube/GDrive).
*/
function getBaseHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Accept-Language': getLocaleFromPath(),
};
const tenantId = getTenantId();
if (tenantId) {
headers['X-Tenant-ID'] = tenantId;
}
return headers;
}
function getAuthHeaders(): HeadersInit {
const headers: Record<string, string> = getBaseHeaders();
const token = getAccessToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
@@ -473,6 +508,28 @@ export interface CommunityCheckResponse {
best_youtube_url: string | null;
}
export type MatchJudgeKind = 'cosmetic' | 'content' | 'ambiguous' | 'none';
export interface MatchJudgeVerdict {
kind: MatchJudgeKind;
confident: boolean;
canonical_artist: string;
canonical_title: string;
alternatives: { artist: string; title: string }[];
engine: 'deterministic' | 'catalog' | 'ai';
reason: string;
// Set by a "fast" (catalog-only) pass that couldn't decide — the client should
// follow up with a "full" call once the audio confidence tier is known.
needs_ai: boolean;
}
export type MatchJudgeStage = 'fast' | 'full';
export interface MatchJudgeOptions {
stage?: MatchJudgeStage;
audioConfidenceTier?: number;
}
export const api = {
/**
* List all jobs
@@ -1285,6 +1342,11 @@ export const api = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Carry tenant context so the backend validates the email domain against the
// tenant, embeds tenant_id in the magic-link token, and uses the tenant's
// sender email + portal URL. Without this, tenant sign-in silently falls back
// to the consumer (nomad) flow.
...getBaseHeaders(),
},
body: JSON.stringify(body),
});
@@ -1573,6 +1635,21 @@ export const api = {
return handleResponse(response);
},
async matchJudge(artist: string, title: string, opts?: MatchJudgeOptions): Promise<MatchJudgeVerdict> {
const body: Record<string, unknown> = { artist, title };
if (opts?.audioConfidenceTier != null) body.audio_confidence_tier = opts.audioConfidenceTier;
if (opts?.stage != null) body.stage = opts.stage;
const response = await fetch(`${API_BASE_URL}/api/catalog/match-judge`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
async changeVisibility(jobId: string, targetVisibility: 'public' | 'private'): Promise<ChangeVisibilityResponse> {
const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/change-visibility`, {
method: 'POST',
+19
View File
@@ -238,6 +238,11 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
isInitialized: true,
})
// Mirror to the edge-config global so synchronous, import-cycle-free consumers
// (e.g. getTenantId() in lib/api.ts) can read the tenant in dev/preview where the
// Cloudflare edge function does not inject __TENANT_CONFIG__.
mirrorTenantConfigToWindow(data)
// Apply tenant branding to CSS variables
if (data.tenant) {
applyTenantBranding(data.tenant.branding)
@@ -256,6 +261,7 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
setTenant: (tenant, isDefault) => {
set({ tenant, isDefault, isInitialized: true })
mirrorTenantConfigToWindow({ tenant, is_default: isDefault })
if (tenant) {
applyTenantBranding(tenant.branding)
}
@@ -348,6 +354,19 @@ function applyTenantBranding(branding: TenantBranding) {
}
}
/**
* Mirror the resolved tenant config onto `window.__TENANT_CONFIG__`.
*
* The Cloudflare edge function injects this global on tenant subdomains in production,
* but not in local dev or admin preview (where the tenant is resolved by fetch or
* setTenant). Mirroring it here gives lib/api.ts a single synchronous, import-cycle-free
* source of truth for attaching the X-Tenant-ID header in every environment.
*/
function mirrorTenantConfigToWindow(data: TenantConfigResponse) {
if (typeof window === "undefined") return
;(window as { __TENANT_CONFIG__?: TenantConfigResponse }).__TENANT_CONFIG__ = data
}
/**
* Hook to get tenant-aware API headers.
* Use this when making API calls that need tenant context.
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "لصق رابط",
"urlSupportedSitesHint": "يعمل مع YouTube و Facebook و SoundCloud و TikTok و Vimeo ومئات المواقع الأخرى.",
"urlSupportedSitesLink": "عرض جميع المواقع المدعومة",
"useThisUrl": "استخدام هذا الرابط"
"useThisUrl": "استخدام هذا الرابط",
"matchCorrectedTo": "تم التصحيح إلى {value} — لقد كتبت “{typed}”",
"matchDidYouMean": "هل تقصد؟",
"matchKeepMine": "الاحتفاظ بما كتبته",
"matchTidiedTo": "تم التنسيق إلى {value}",
"matchUndo": "تراجع",
"matchChecking": "جارٍ التحقق من تفاصيل الأغنية…",
"matchUseCorrection": "استخدام التصحيح",
"matchUseTidied": "استخدام النسخة المنقحة",
"matchUsingTyped": "استخدام ما كتبته: {value}"
},
"jobStatus": {
"settingUp": "جاري الإعداد",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "عنوان الأغنية",
"artist": "الفنان"
"artist": "الفنان",
"loading": "جارٍ تحميل معاينة شاشة العنوان"
},
"editTrack": {
"title": "تعديل المسار المكتمل",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "تكلفة تقديرية — يتم تأكيد التكلفة النهائية بعد التنزيل",
"reconcileTitle": "هذه الأغنية أطول من المتوقع",
"cancel": "إلغاء"
},
"karaokeBackgroundPreview": {
"loading": "جارٍ تحميل معاينة الخلفية"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Enganxa un enllaç",
"urlSupportedSitesHint": "Funciona amb YouTube, Facebook, SoundCloud, TikTok, Vimeo i centenars de llocs més.",
"urlSupportedSitesLink": "Consulta tots els llocs compatibles",
"useThisUrl": "Utilitza aquest URL"
"useThisUrl": "Utilitza aquest URL",
"matchCorrectedTo": "Corregit a {value} — has escrit “{typed}”",
"matchDidYouMean": "Volies dir?",
"matchKeepMine": "mantenir el que he escrit",
"matchTidiedTo": "Ajustat a {value}",
"matchUndo": "Desfer",
"matchChecking": "Comprovant els detalls de la cançó…",
"matchUseCorrection": "utilitza la correcció",
"matchUseTidied": "utilitza la versió polida",
"matchUsingTyped": "Utilitzant el que has escrit: {value}"
},
"jobStatus": {
"settingUp": "Configurant",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Títol de la cançó",
"artist": "Artista"
"artist": "Artista",
"loading": "Carregant la previsualització de la pantalla de títol"
},
"editTrack": {
"title": "Edita la pista completada",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Aproximat — el cost final es confirmarà després de la descàrrega",
"reconcileTitle": "Aquesta cançó és més llarga del que s'esperava",
"cancel": "Cancel·la"
},
"karaokeBackgroundPreview": {
"loading": "Carregant la previsualització del fons"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Vložit odkaz",
"urlSupportedSitesHint": "Funguje se službami YouTube, Facebook, SoundCloud, TikTok, Vimeo a stovkami dalších webů.",
"urlSupportedSitesLink": "Zobrazit všechny podporované weby",
"useThisUrl": "Použít tuto URL"
"useThisUrl": "Použít tuto URL",
"matchCorrectedTo": "Opraveno na {value} — zadal jsi „{typed}“",
"matchDidYouMean": "Měl jsi na mysli?",
"matchKeepMine": "ponechat můj text",
"matchTidiedTo": "Upraveno na {value}",
"matchUndo": "Zpět",
"matchChecking": "Kontrola detailů písně…",
"matchUseCorrection": "použít opravu",
"matchUseTidied": "použít upravenou verzi",
"matchUsingTyped": "Používám to, co jsi zadal: {value}"
},
"jobStatus": {
"settingUp": "Nastavování",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Název písničky",
"artist": "Interpret"
"artist": "Interpret",
"loading": "Načítání náhledu úvodní obrazovky"
},
"editTrack": {
"title": "Upravit dokončenou stopu",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Odhad — konečná cena se potvrdí po stažení",
"reconcileTitle": "Tato píseň je delší, než jsme čekali",
"cancel": "Zrušit"
},
"karaokeBackgroundPreview": {
"loading": "Načítání náhledu pozadí"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Indsæt et link",
"urlSupportedSitesHint": "Fungerer med YouTube, Facebook, SoundCloud, TikTok, Vimeo og hundredvis af andre sider.",
"urlSupportedSitesLink": "Se alle understøttede sider",
"useThisUrl": "Brug denne URL"
"useThisUrl": "Brug denne URL",
"matchCorrectedTo": "Rettet til {value} — du skrev “{typed}”",
"matchDidYouMean": "Mente du?",
"matchKeepMine": "behold det, jeg skrev",
"matchTidiedTo": "Finpudset til {value}",
"matchUndo": "Fortryd",
"matchChecking": "Tjekker sangdetaljer…",
"matchUseCorrection": "brug rettelsen",
"matchUseTidied": "brug den tilrettede version",
"matchUsingTyped": "Bruger det, du indtastede: {value}"
},
"jobStatus": {
"settingUp": "Sætter op",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Sangtitel",
"artist": "Kunstner"
"artist": "Kunstner",
"loading": "Indlæser forhåndsvisning af titelskærm"
},
"editTrack": {
"title": "Rediger fuldført nummer",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Anslået — endelig pris bekræftes efter download",
"reconcileTitle": "Denne sang er længere end forventet",
"cancel": "Annuller"
},
"karaokeBackgroundPreview": {
"loading": "Indlæser forhåndsvisning af baggrund"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Link einfügen",
"urlSupportedSitesHint": "Funktioniert mit YouTube, Facebook, SoundCloud, TikTok, Vimeo und Hunderten anderen Seiten.",
"urlSupportedSitesLink": "Alle unterstützten Seiten ansehen",
"useThisUrl": "Diese URL verwenden"
"useThisUrl": "Diese URL verwenden",
"matchCorrectedTo": "Korrigiert zu {value} – du hast „{typed}“ eingegeben",
"matchDidYouMean": "Meintest du?",
"matchKeepMine": "meine Eingabe behalten",
"matchTidiedTo": "Bereinigt zu {value}",
"matchUndo": "Rückgängig",
"matchChecking": "Songdetails werden überprüft…",
"matchUseCorrection": "Korrektur verwenden",
"matchUseTidied": "bereinigte Version verwenden",
"matchUsingTyped": "Verwende deine Eingabe: {value}"
},
"jobStatus": {
"settingUp": "Richte ein",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Songtitel",
"artist": "Künstler"
"artist": "Künstler",
"loading": "Titelbildschirm-Vorschau wird geladen"
},
"editTrack": {
"title": "Abgeschlossenen Track bearbeiten",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Geschätzt — endgültige Kosten werden nach dem Download bestätigt",
"reconcileTitle": "Dieser Song ist länger als erwartet",
"cancel": "Abbrechen"
},
"karaokeBackgroundPreview": {
"loading": "Hintergrundvorschau wird geladen"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Επικόλλησε έναν σύνδεσμο",
"urlSupportedSitesHint": "Λειτουργεί με YouTube, Facebook, SoundCloud, TikTok, Vimeo και εκατοντάδες άλλους ιστότοπους.",
"urlSupportedSitesLink": "Δες όλους τους υποστηριζόμενους ιστότοπους",
"useThisUrl": "Χρησιμοποίησε αυτό το URL"
"useThisUrl": "Χρησιμοποίησε αυτό το URL",
"matchCorrectedTo": "Διορθώθηκε σε {value} — πληκτρολόγησες “{typed}”",
"matchDidYouMean": "Μήπως εννοούσες;",
"matchKeepMine": "κράτα αυτό που πληκτρολόγησα",
"matchTidiedTo": "Διαμορφώθηκε σε {value}",
"matchUndo": "Αναίρεση",
"matchChecking": "Έλεγχος λεπτομερειών τραγουδιού…",
"matchUseCorrection": "χρησιμοποίησε τη διόρθωση",
"matchUseTidied": "χρησιμοποίησε την καθαρισμένη έκδοση",
"matchUsingTyped": "Χρησιμοποιείται αυτό που πληκτρολόγησες: {value}"
},
"jobStatus": {
"settingUp": "Ρύθμιση",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Τίτλος Τραγουδιού",
"artist": "Καλλιτέχνης"
"artist": "Καλλιτέχνης",
"loading": "Φόρτωση προεπισκόπησης οθόνης τίτλου"
},
"editTrack": {
"title": "Επεξεργασία Ολοκληρωμένου Κομματιού",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Εκτιμώμενο — το τελικό κόστος επιβεβαιώνεται μετά τη λήψη",
"reconcileTitle": "Αυτό το τραγούδι διαρκεί περισσότερο από το αναμενόμενο",
"cancel": "Ακύρωση"
},
"karaokeBackgroundPreview": {
"loading": "Φόρτωση προεπισκόπησης φόντου"
}
}
+14 -1
View File
@@ -470,6 +470,15 @@
"createAnother": "Create Another",
"noCreditsWarning": "You have no credits remaining. Buy credits to create new karaoke videos.",
"buyCredits": "Buy Credits",
"matchTidiedTo": "Tidied to {value}",
"matchKeepMine": "keep what I typed",
"matchCorrectedTo": "Corrected to {value} — you typed “{typed}”",
"matchUndo": "Undo",
"matchUsingTyped": "Using what you typed: {value}",
"matchUseTidied": "use tidied version",
"matchUseCorrection": "use the correction",
"matchChecking": "Checking song details…",
"matchDidYouMean": "Did you mean?",
"weFindBestAudio": "We find the best audio",
"uploadAFile": "upload a file",
"youtubeUrl": "YouTube URL",
@@ -683,7 +692,11 @@
},
"titleCardPreview": {
"songTitle": "Song Title",
"artist": "Artist"
"artist": "Artist",
"loading": "Loading title screen preview"
},
"karaokeBackgroundPreview": {
"loading": "Loading background preview"
},
"editTrack": {
"title": "Edit Completed Track",
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Pega un enlace",
"urlSupportedSitesHint": "Funciona con YouTube, Facebook, SoundCloud, TikTok, Vimeo y cientos de sitios más.",
"urlSupportedSitesLink": "Ver todos los sitios compatibles",
"useThisUrl": "Usar esta URL"
"useThisUrl": "Usar esta URL",
"matchCorrectedTo": "Corregido a {value} — escribiste “{typed}”",
"matchDidYouMean": "¿Quisiste decir?",
"matchKeepMine": "mantener lo que escribí",
"matchTidiedTo": "Ajustado a {value}",
"matchUndo": "Deshacer",
"matchChecking": "Revisando los detalles de la canción…",
"matchUseCorrection": "usar la corrección",
"matchUseTidied": "usar la versión arreglada",
"matchUsingTyped": "Usando lo que escribiste: {value}"
},
"jobStatus": {
"settingUp": "Configurando",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Título de la canción",
"artist": "Artista"
"artist": "Artista",
"loading": "Cargando vista previa de la pantalla de título"
},
"editTrack": {
"title": "Editar pista completada",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Estimado — el costo final se confirmará después de la descarga",
"reconcileTitle": "Esta canción es más larga de lo esperado",
"cancel": "Cancelar"
},
"karaokeBackgroundPreview": {
"loading": "Cargando vista previa del fondo"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Liitä linkki",
"urlSupportedSitesHint": "Toimii YouTuben, Facebookin, SoundCloudin, TikTokin, Vimeon ja satojen muiden sivustojen kanssa.",
"urlSupportedSitesLink": "Katso kaikki tuetut sivustot",
"useThisUrl": "Käytä tätä osoitetta"
"useThisUrl": "Käytä tätä osoitetta",
"matchCorrectedTo": "Korjattu muotoon {value} — kirjoitit ”{typed}”",
"matchDidYouMean": "Tarkoititko?",
"matchKeepMine": "säilytä kirjoittamani",
"matchTidiedTo": "Siistitty muotoon {value}",
"matchUndo": "Kumoa",
"matchChecking": "Tarkistetaan kappaleen tietoja…",
"matchUseCorrection": "käytä korjausta",
"matchUseTidied": "käytä siistittyä versiota",
"matchUsingTyped": "Käytetään kirjoittamaasi: {value}"
},
"jobStatus": {
"settingUp": "Asetetaan",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Kappaleen nimi",
"artist": "Esittäjä"
"artist": "Esittäjä",
"loading": "Ladataan otsikkonäytön esikatselua"
},
"editTrack": {
"title": "Muokkaa valmista raitaa",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Arvioitu — lopullinen hinta vahvistetaan latauksen jälkeen",
"reconcileTitle": "Tämä kappale on odotettua pidempi",
"cancel": "Peruuta"
},
"karaokeBackgroundPreview": {
"loading": "Ladataan taustan esikatselua"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Coller un lien",
"urlSupportedSitesHint": "Fonctionne avec YouTube, Facebook, SoundCloud, TikTok, Vimeo et des centaines d'autres sites.",
"urlSupportedSitesLink": "Voir tous les sites compatibles",
"useThisUrl": "Utiliser cette URL"
"useThisUrl": "Utiliser cette URL",
"matchCorrectedTo": "Corrigé en {value} — tu as tapé « {typed} »",
"matchDidYouMean": "Tu voulais dire ?",
"matchKeepMine": "garder ce que j'ai tapé",
"matchTidiedTo": "Ajusté en {value}",
"matchUndo": "Annuler",
"matchChecking": "Vérification des détails de la chanson…",
"matchUseCorrection": "utiliser la correction",
"matchUseTidied": "utiliser la version nettoyée",
"matchUsingTyped": "Utilisation de ce que tu as tapé : {value}"
},
"jobStatus": {
"settingUp": "Configuration",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Titre de la chanson",
"artist": "Artiste"
"artist": "Artiste",
"loading": "Chargement de l'aperçu de l'écran titre"
},
"editTrack": {
"title": "Modifier la piste terminée",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Estimé — coût final confirmé après le téléchargement",
"reconcileTitle": "Cette chanson est plus longue que prévu",
"cancel": "Annuler"
},
"karaokeBackgroundPreview": {
"loading": "Chargement de l'aperçu de l'arrière-plan"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "הדבקת קישור",
"urlSupportedSitesHint": "עובד עם YouTube, Facebook, SoundCloud, TikTok, Vimeo ומאות אתרים נוספים.",
"urlSupportedSitesLink": "לצפייה בכל האתרים הנתמכים",
"useThisUrl": "שימוש בכתובת זו"
"useThisUrl": "שימוש בכתובת זו",
"matchCorrectedTo": "תוקן ל-{value} — הקלדת “{typed}”",
"matchDidYouMean": "האם התכוונת?",
"matchKeepMine": "להשאיר את מה שהקלדתי",
"matchTidiedTo": "סודר ל-{value}",
"matchUndo": "ביטול",
"matchChecking": "בודקים את פרטי השיר…",
"matchUseCorrection": "להשתמש בתיקון",
"matchUseTidied": "להשתמש בגרסה המסודרת",
"matchUsingTyped": "משתמשים במה שהקלדת: {value}"
},
"jobStatus": {
"settingUp": "מגדיר",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "שם השיר",
"artist": "אמן"
"artist": "אמן",
"loading": "טעינת תצוגה מקדימה של מסך הכותרת"
},
"editTrack": {
"title": "ערוך רצועה שהושלמה",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "משוער — העלות הסופית תאושר לאחר ההורדה",
"reconcileTitle": "השיר הזה ארוך מהצפוי",
"cancel": "ביטול"
},
"karaokeBackgroundPreview": {
"loading": "טעינת תצוגה מקדימה של הרקע"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "एक लिंक पेस्ट करो",
"urlSupportedSitesHint": "यह YouTube, Facebook, SoundCloud, TikTok, Vimeo और सैकड़ों अन्य साइटों के साथ काम करता है।",
"urlSupportedSitesLink": "सभी समर्थित साइटें देखो",
"useThisUrl": "इस URL का इस्तेमाल करो"
"useThisUrl": "इस URL का इस्तेमाल करो",
"matchCorrectedTo": "सही करके {value} कर दिया गया — तुमने “{typed}” टाइप किया था",
"matchDidYouMean": "क्या तुम्हारा मतलब यह था?",
"matchKeepMine": "जो मैंने टाइप किया है वही रखो",
"matchTidiedTo": "ठीक करके {value} कर दिया गया",
"matchUndo": "पूर्ववत करो",
"matchChecking": "गाने की जानकारी चेक की जा रही है…",
"matchUseCorrection": "सुधार का इस्तेमाल करो",
"matchUseTidied": "व्यवस्थित वर्शन का इस्तेमाल करो",
"matchUsingTyped": "जो तुमने टाइप किया है, उसका इस्तेमाल हो रहा है: {value}"
},
"jobStatus": {
"settingUp": "सेटअप हो रहा है",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "गाने का टाइटल",
"artist": "आर्टिस्ट"
"artist": "आर्टिस्ट",
"loading": "टाइटल स्क्रीन प्रीव्यू लोड हो रहा है"
},
"editTrack": {
"title": "पूरा हुआ ट्रैक एडिट करो",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "अनुमानित — डाउनलोड के बाद अंतिम लागत की पुष्टि की जाएगी",
"reconcileTitle": "यह गाना उम्मीद से लंबा है",
"cancel": "कैंसल"
},
"karaokeBackgroundPreview": {
"loading": "बैकग्राउंड प्रीव्यू लोड हो रहा है"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Zalijepi poveznicu",
"urlSupportedSitesHint": "Radi s platformama YouTube, Facebook, SoundCloud, TikTok, Vimeo i stotinama drugih stranica.",
"urlSupportedSitesLink": "Pogledaj sve podržane stranice",
"useThisUrl": "Upotrijebi ovaj URL"
"useThisUrl": "Upotrijebi ovaj URL",
"matchCorrectedTo": "Ispravljeno u {value} — tvoj unos: “{typed}”",
"matchDidYouMean": "Jesi li mislio/la?",
"matchKeepMine": "zadrži moj unos",
"matchTidiedTo": "Uređeno u {value}",
"matchUndo": "Poništi",
"matchChecking": "Provjera detalja pjesme…",
"matchUseCorrection": "koristi ispravak",
"matchUseTidied": "koristi uređenu verziju",
"matchUsingTyped": "Koristimo ono što si upisao: {value}"
},
"jobStatus": {
"settingUp": "Postavljanje",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Naslov pjesme",
"artist": "Izvođač"
"artist": "Izvođač",
"loading": "Učitavanje pregleda naslovnog zaslona"
},
"editTrack": {
"title": "Uredi završenu pjesmu",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Procijenjeno — konačna cijena potvrđuje se nakon preuzimanja",
"reconcileTitle": "Ova pjesma je duža od očekivanog",
"cancel": "Odustani"
},
"karaokeBackgroundPreview": {
"loading": "Učitavanje pregleda pozadine"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Illessz be egy linket",
"urlSupportedSitesHint": "Működik a YouTube, Facebook, SoundCloud, TikTok, Vimeo és több száz más oldallal.",
"urlSupportedSitesLink": "Nézd meg az összes támogatott oldalt",
"useThisUrl": "Használd ezt az URL-t"
"useThisUrl": "Használd ezt az URL-t",
"matchCorrectedTo": "Javítva erre: {value} — ezt írtad: „{typed}”",
"matchDidYouMean": "Erre gondoltál?",
"matchKeepMine": "maradjon, amit írtam",
"matchTidiedTo": "Rendezve erre: {value}",
"matchUndo": "Visszavonás",
"matchChecking": "A dal adatainak ellenőrzése…",
"matchUseCorrection": "javítás használata",
"matchUseTidied": "letisztított verzió használata",
"matchUsingTyped": "Az általad beírtak használata: {value}"
},
"jobStatus": {
"settingUp": "Beállítás",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Dal címe",
"artist": "Előadó"
"artist": "Előadó",
"loading": "Címképernyő előnézetének betöltése"
},
"editTrack": {
"title": "Befejezett dal szerkesztése",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Becsült — a végső költséget a letöltés után erősítjük meg",
"reconcileTitle": "Ez a dal hosszabb a vártnál",
"cancel": "Mégse"
},
"karaokeBackgroundPreview": {
"loading": "Háttér előnézetének betöltése"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Tempel tautan",
"urlSupportedSitesHint": "Berfungsi dengan YouTube, Facebook, SoundCloud, TikTok, Vimeo, dan ratusan situs lainnya.",
"urlSupportedSitesLink": "Lihat semua situs yang didukung",
"useThisUrl": "Gunakan URL Ini"
"useThisUrl": "Gunakan URL Ini",
"matchCorrectedTo": "Dikoreksi menjadi {value} — Anda mengetik “{typed}”",
"matchDidYouMean": "Maksud Anda?",
"matchKeepMine": "tetap gunakan yang saya ketik",
"matchTidiedTo": "Dirapikan menjadi {value}",
"matchUndo": "Urungkan",
"matchChecking": "Memeriksa detail lagu…",
"matchUseCorrection": "gunakan koreksi",
"matchUseTidied": "gunakan versi yang dirapikan",
"matchUsingTyped": "Menggunakan yang Anda ketik: {value}"
},
"jobStatus": {
"settingUp": "Menyiapkan",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Judul Lagu",
"artist": "Artis"
"artist": "Artis",
"loading": "Memuat pratinjau layar judul"
},
"editTrack": {
"title": "Edit Track yang Selesai",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Estimasi — biaya akhir dikonfirmasi setelah diunduh",
"reconcileTitle": "Lagu ini lebih panjang dari perkiraan",
"cancel": "Batal"
},
"karaokeBackgroundPreview": {
"loading": "Memuat pratinjau latar belakang"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Incolla un link",
"urlSupportedSitesHint": "Funziona con YouTube, Facebook, SoundCloud, TikTok, Vimeo e centinaia di altri siti.",
"urlSupportedSitesLink": "Vedi tutti i siti supportati",
"useThisUrl": "Usa questo URL"
"useThisUrl": "Usa questo URL",
"matchCorrectedTo": "Corretto in {value} — hai digitato “{typed}”",
"matchDidYouMean": "Intendevi dire?",
"matchKeepMine": "mantieni quello che ho digitato",
"matchTidiedTo": "Sistemato in {value}",
"matchUndo": "Annulla",
"matchChecking": "Controllo dei dettagli del brano…",
"matchUseCorrection": "usa la correzione",
"matchUseTidied": "usa la versione ripulita",
"matchUsingTyped": "Uso quello che hai digitato: {value}"
},
"jobStatus": {
"settingUp": "Configurazione",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Titolo della canzone",
"artist": "Artista"
"artist": "Artista",
"loading": "Caricamento dell'anteprima della schermata del titolo"
},
"editTrack": {
"title": "Modifica traccia completata",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Stimato — costo finale confermato dopo il download",
"reconcileTitle": "Questa canzone è più lunga del previsto",
"cancel": "Annulla"
},
"karaokeBackgroundPreview": {
"loading": "Caricamento dell'anteprima dello sfondo"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "リンクを貼り付ける",
"urlSupportedSitesHint": "YouTube、Facebook、SoundCloud、TikTok、Vimeoなど、数百ものサイトに対応しています。",
"urlSupportedSitesLink": "対応サイト一覧を見る",
"useThisUrl": "このURLを使用する"
"useThisUrl": "このURLを使用する",
"matchCorrectedTo": "{value} に修正しました — 入力内容: 「{typed}」",
"matchDidYouMean": "もしかして?",
"matchKeepMine": "入力した内容をそのまま使う",
"matchTidiedTo": "{value} に整えました",
"matchUndo": "元に戻す",
"matchChecking": "曲の詳細を確認しています…",
"matchUseCorrection": "修正を適用する",
"matchUseTidied": "整形版を使用する",
"matchUsingTyped": "入力された内容を使用します: {value}"
},
"jobStatus": {
"settingUp": "セットアップ中",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "曲名",
"artist": "アーティスト"
"artist": "アーティスト",
"loading": "タイトル画面のプレビューを読み込んでいます"
},
"editTrack": {
"title": "完了したトラックを編集",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "目安 — 最終的な料金はダウンロード後に確定します",
"reconcileTitle": "この曲は想定より長くなっています",
"cancel": "キャンセル"
},
"karaokeBackgroundPreview": {
"loading": "背景プレビューを読み込んでいます"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "링크 붙여넣기",
"urlSupportedSitesHint": "YouTube, Facebook, SoundCloud, TikTok, Vimeo 등 수백 개의 사이트에서 사용할 수 있습니다.",
"urlSupportedSitesLink": "지원되는 모든 사이트 보기",
"useThisUrl": "이 URL 사용하기"
"useThisUrl": "이 URL 사용하기",
"matchCorrectedTo": "{value}(으)로 수정되었습니다 — 입력하신 내용: “{typed}”",
"matchDidYouMean": "혹시 다음을 찾으셨나요?",
"matchKeepMine": "입력한 내용 유지",
"matchTidiedTo": "{value}(으)로 정리되었습니다",
"matchUndo": "실행 취소",
"matchChecking": "노래 세부 정보 확인 중…",
"matchUseCorrection": "수정본 사용하기",
"matchUseTidied": "정리된 버전 사용하기",
"matchUsingTyped": "입력한 내용 사용: {value}"
},
"jobStatus": {
"settingUp": "설정 중",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "노래 제목",
"artist": "아티스트"
"artist": "아티스트",
"loading": "타이틀 화면 미리보기 불러오는 중"
},
"editTrack": {
"title": "완료된 트랙 편집",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "예상 비용 — 최종 비용은 다운로드 후 확정됩니다",
"reconcileTitle": "노래 길이가 예상보다 깁니다",
"cancel": "취소"
},
"karaokeBackgroundPreview": {
"loading": "배경 미리보기 불러오는 중"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Tampal pautan",
"urlSupportedSitesHint": "Berfungsi dengan YouTube, Facebook, SoundCloud, TikTok, Vimeo dan beratus-ratus laman web lain.",
"urlSupportedSitesLink": "Lihat semua laman web yang disokong",
"useThisUrl": "Gunakan URL Ini"
"useThisUrl": "Gunakan URL Ini",
"matchCorrectedTo": "Dibetulkan kepada {value} — anda menaip “{typed}”",
"matchDidYouMean": "Maksud anda?",
"matchKeepMine": "kekalkan apa yang saya taip",
"matchTidiedTo": "Dikemaskan kepada {value}",
"matchUndo": "Buat asal",
"matchChecking": "Menyemak butiran lagu…",
"matchUseCorrection": "gunakan pembetulan",
"matchUseTidied": "gunakan versi yang dikemaskan",
"matchUsingTyped": "Menggunakan apa yang anda taip: {value}"
},
"jobStatus": {
"settingUp": "Menyediakan",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Tajuk Lagu",
"artist": "Artis"
"artist": "Artis",
"loading": "Memuatkan pratonton skrin tajuk"
},
"editTrack": {
"title": "Edit Trek Selesai",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Anggaran — kos akhir disahkan selepas muat turun",
"reconcileTitle": "Lagu ini lebih panjang daripada yang dijangkakan",
"cancel": "Batal"
},
"karaokeBackgroundPreview": {
"loading": "Memuatkan pratonton latar belakang"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Lim inn en lenke",
"urlSupportedSitesHint": "Fungerer med YouTube, Facebook, SoundCloud, TikTok, Vimeo og hundrevis av andre nettsteder.",
"urlSupportedSitesLink": "Se alle støttede nettsteder",
"useThisUrl": "Bruk denne URL-en"
"useThisUrl": "Bruk denne URL-en",
"matchCorrectedTo": "Rettet til {value} – du skrev «{typed}»",
"matchDidYouMean": "Mente du?",
"matchKeepMine": "behold det jeg skrev",
"matchTidiedTo": "Justert til {value}",
"matchUndo": "Angre",
"matchChecking": "Sjekker sangdetaljer…",
"matchUseCorrection": "bruk rettelsen",
"matchUseTidied": "bruk oppryddet versjon",
"matchUsingTyped": "Bruker det du skrev inn: {value}"
},
"jobStatus": {
"settingUp": "Setter opp",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Sangtittel",
"artist": "Artist"
"artist": "Artist",
"loading": "Laster inn forhåndsvisning av tittelskjerm"
},
"editTrack": {
"title": "Rediger fullført spor",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Estimert — endelig pris bekreftes etter nedlasting",
"reconcileTitle": "Denne sangen er lengre enn forventet",
"cancel": "Avbryt"
},
"karaokeBackgroundPreview": {
"loading": "Laster inn forhåndsvisning av bakgrunn"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Plak een link",
"urlSupportedSitesHint": "Werkt met YouTube, Facebook, SoundCloud, TikTok, Vimeo en honderden andere sites.",
"urlSupportedSitesLink": "Bekijk alle ondersteunde sites",
"useThisUrl": "Gebruik deze URL"
"useThisUrl": "Gebruik deze URL",
"matchCorrectedTo": "Gecorrigeerd naar {value} — je typte “{typed}”",
"matchDidYouMean": "Bedoelde je?",
"matchKeepMine": "behoud wat ik typte",
"matchTidiedTo": "Opgeschoond naar {value}",
"matchUndo": "Ongedaan maken",
"matchChecking": "Nummergegevens controleren…",
"matchUseCorrection": "gebruik de correctie",
"matchUseTidied": "gebruik opgeschoonde versie",
"matchUsingTyped": "We gebruiken wat je hebt getypt: {value}"
},
"jobStatus": {
"settingUp": "Instellen",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Titel van nummer",
"artist": "Artiest"
"artist": "Artiest",
"loading": "Voorbeeld van titelscherm laden"
},
"editTrack": {
"title": "Bewerk Voltooide Track",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Geschat — definitieve kosten worden na downloaden bevestigd",
"reconcileTitle": "Dit nummer is langer dan verwacht",
"cancel": "Annuleren"
},
"karaokeBackgroundPreview": {
"loading": "Achtergrondvoorbeeld laden"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Wklej link",
"urlSupportedSitesHint": "Działa z YouTube, Facebookiem, SoundCloud, TikTokiem, Vimeo i setkami innych stron.",
"urlSupportedSitesLink": "Zobacz wszystkie obsługiwane strony",
"useThisUrl": "Użyj tego adresu URL"
"useThisUrl": "Użyj tego adresu URL",
"matchCorrectedTo": "Poprawiono na {value} — Twój wpis: „{typed}”",
"matchDidYouMean": "Czy chodziło Ci o?",
"matchKeepMine": "zachowaj mój wpis",
"matchTidiedTo": "Uporządkowano: {value}",
"matchUndo": "Cofnij",
"matchChecking": "Sprawdzanie szczegółów utworu…",
"matchUseCorrection": "użyj poprawki",
"matchUseTidied": "użyj uporządkowanej wersji",
"matchUsingTyped": "Używam wpisanego tekstu: {value}"
},
"jobStatus": {
"settingUp": "Konfigurowanie",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Tytuł piosenki",
"artist": "Wykonawca"
"artist": "Wykonawca",
"loading": "Ładowanie podglądu ekranu tytułowego"
},
"editTrack": {
"title": "Edytuj ukończony utwór",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Szacunkowo — ostateczny koszt zostanie potwierdzony po pobraniu",
"reconcileTitle": "Ta piosenka jest dłuższa, niż oczekiwano",
"cancel": "Anuluj"
},
"karaokeBackgroundPreview": {
"loading": "Ładowanie podglądu tła"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Cole um link",
"urlSupportedSitesHint": "Funciona com YouTube, Facebook, SoundCloud, TikTok, Vimeo e centenas de outros sites.",
"urlSupportedSitesLink": "Ver todos os sites compatíveis",
"useThisUrl": "Usar esta URL"
"useThisUrl": "Usar esta URL",
"matchCorrectedTo": "Corrigido para {value} — você digitou “{typed}”",
"matchDidYouMean": "Você quis dizer?",
"matchKeepMine": "manter o que eu digitei",
"matchTidiedTo": "Ajustado para {value}",
"matchUndo": "Desfazer",
"matchChecking": "Verificando detalhes da música…",
"matchUseCorrection": "usar a correção",
"matchUseTidied": "usar a versão ajustada",
"matchUsingTyped": "Usando o que você digitou: {value}"
},
"jobStatus": {
"settingUp": "Configurando",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Título da Música",
"artist": "Artista"
"artist": "Artista",
"loading": "Carregando prévia da tela de título"
},
"editTrack": {
"title": "Editar Faixa Concluída",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Estimado — custo final confirmado após o download",
"reconcileTitle": "Esta música é mais longa do que o esperado",
"cancel": "Cancelar"
},
"karaokeBackgroundPreview": {
"loading": "Carregando prévia do plano de fundo"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Lipește un link",
"urlSupportedSitesHint": "Funcționează cu YouTube, Facebook, SoundCloud, TikTok, Vimeo și sute de alte site-uri.",
"urlSupportedSitesLink": "Vezi toate site-urile acceptate",
"useThisUrl": "Folosește acest URL"
"useThisUrl": "Folosește acest URL",
"matchCorrectedTo": "Corectat în {value} — ai scris „{typed}”",
"matchDidYouMean": "Ai vrut să spui?",
"matchKeepMine": "păstrează ce am scris",
"matchTidiedTo": "Ajustat în {value}",
"matchUndo": "Anulează",
"matchChecking": "Se verifică detaliile melodiei…",
"matchUseCorrection": "folosește corecția",
"matchUseTidied": "folosește versiunea curățată",
"matchUsingTyped": "Folosim ce ai tastat: {value}"
},
"jobStatus": {
"settingUp": "Se configurează",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Titlul melodiei",
"artist": "Artist"
"artist": "Artist",
"loading": "Se încarcă previzualizarea ecranului de titlu"
},
"editTrack": {
"title": "Editează piesa finalizată",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Estimat — costul final va fi confirmat după descărcare",
"reconcileTitle": "Această melodie este mai lungă decât era de așteptat",
"cancel": "Anulează"
},
"karaokeBackgroundPreview": {
"loading": "Se încarcă previzualizarea fundalului"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Вставить ссылку",
"urlSupportedSitesHint": "Работает с YouTube, Facebook, SoundCloud, TikTok, Vimeo и сотнями других сайтов.",
"urlSupportedSitesLink": "Посмотреть все поддерживаемые сайты",
"useThisUrl": "Использовать эту ссылку"
"useThisUrl": "Использовать эту ссылку",
"matchCorrectedTo": "Исправлено на {value} — твой текст: «{typed}»",
"matchDidYouMean": "Имелось в виду?",
"matchKeepMine": "оставить мой вариант",
"matchTidiedTo": "Отформатировано как {value}",
"matchUndo": "Отменить",
"matchChecking": "Проверка данных песни…",
"matchUseCorrection": "использовать исправление",
"matchUseTidied": "использовать отформатированную версию",
"matchUsingTyped": "Используем твой вариант: {value}"
},
"jobStatus": {
"settingUp": "Настройка",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Название песни",
"artist": "Исполнитель"
"artist": "Исполнитель",
"loading": "Загрузка предпросмотра титульного экрана"
},
"editTrack": {
"title": "Редактировать завершенный трек",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Ориентировочно — итоговая стоимость будет подтверждена после скачивания",
"reconcileTitle": "Эта песня длиннее, чем ожидалось",
"cancel": "Отмена"
},
"karaokeBackgroundPreview": {
"loading": "Загрузка предпросмотра фона"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Vlož odkaz",
"urlSupportedSitesHint": "Funguje s YouTube, Facebook, SoundCloud, TikTok, Vimeo a stovkami ďalších stránok.",
"urlSupportedSitesLink": "Pozri si všetky podporované stránky",
"useThisUrl": "Použi túto URL"
"useThisUrl": "Použi túto URL",
"matchCorrectedTo": "Opravené na {value} — tvoj text: „{typed}“",
"matchDidYouMean": "Mal si na mysli?",
"matchKeepMine": "ponechať môj text",
"matchTidiedTo": "Upravené na {value}",
"matchUndo": "Vrátiť späť",
"matchChecking": "Kontrolujú sa detaily skladby…",
"matchUseCorrection": "použiť opravu",
"matchUseTidied": "použiť upravenú verziu",
"matchUsingTyped": "Používam to, čo si zadal: {value}"
},
"jobStatus": {
"settingUp": "Nastavuje sa",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Názov piesne",
"artist": "Interpret"
"artist": "Interpret",
"loading": "Načítava sa náhľad úvodnej obrazovky"
},
"editTrack": {
"title": "Upraviť dokončenú skladbu",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Odhadované — konečná cena bude potvrdená po stiahnutí",
"reconcileTitle": "Táto pieseň je dlhšia, ako sa očakávalo",
"cancel": "Zrušiť"
},
"karaokeBackgroundPreview": {
"loading": "Načítava sa náhľad pozadia"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Klistra in en länk",
"urlSupportedSitesHint": "Fungerar med YouTube, Facebook, SoundCloud, TikTok, Vimeo och hundratals andra webbplatser.",
"urlSupportedSitesLink": "Se alla webbplatser som stöds",
"useThisUrl": "Använd den här URL:en"
"useThisUrl": "Använd den här URL:en",
"matchCorrectedTo": "Korrigerat till {value} — du skrev ”{typed}”",
"matchDidYouMean": "Menade du?",
"matchKeepMine": "behåll det jag skrev",
"matchTidiedTo": "Justerat till {value}",
"matchUndo": "Ångra",
"matchChecking": "Kontrollerar låtdetaljer…",
"matchUseCorrection": "använd korrigeringen",
"matchUseTidied": "använd rensad version",
"matchUsingTyped": "Använder det du skrev: {value}"
},
"jobStatus": {
"settingUp": "Ställer in",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Låttitel",
"artist": "Artist"
"artist": "Artist",
"loading": "Laddar förhandsgranskning av titelskärm"
},
"editTrack": {
"title": "Redigera slutfört spår",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Preliminärt — slutgiltig kostnad bekräftas efter nedladdning",
"reconcileTitle": "Den här låten är längre än förväntat",
"cancel": "Avbryt"
},
"karaokeBackgroundPreview": {
"loading": "Laddar förhandsgranskning av bakgrund"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "วางลิงก์",
"urlSupportedSitesHint": "รองรับการใช้งานกับ YouTube, Facebook, SoundCloud, TikTok, Vimeo และเว็บไซต์อื่นๆ อีกหลายร้อยแห่ง",
"urlSupportedSitesLink": "ดูเว็บไซต์ที่รองรับทั้งหมด",
"useThisUrl": "ใช้ URL นี้"
"useThisUrl": "ใช้ URL นี้",
"matchCorrectedTo": "แก้ไขเป็น {value} — คุณพิมพ์ว่า “{typed}”",
"matchDidYouMean": "คุณหมายถึงคำนี้ใช่ไหม?",
"matchKeepMine": "ใช้ข้อความที่ฉันพิมพ์",
"matchTidiedTo": "จัดรูปแบบเป็น {value}",
"matchUndo": "เลิกทำ",
"matchChecking": "กำลังตรวจสอบรายละเอียดเพลง…",
"matchUseCorrection": "ใช้ตามที่แก้ไข",
"matchUseTidied": "ใช้เวอร์ชันที่จัดระเบียบแล้ว",
"matchUsingTyped": "ใช้ข้อความที่คุณพิมพ์: {value}"
},
"jobStatus": {
"settingUp": "กำลังตั้งค่า",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "ชื่อเพลง",
"artist": "ศิลปิน"
"artist": "ศิลปิน",
"loading": "กำลังโหลดตัวอย่างหน้าจอไตเติ้ล"
},
"editTrack": {
"title": "แก้ไขแทร็กที่เสร็จสมบูรณ์แล้ว",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "โดยประมาณ — จะยืนยันค่าใช้จ่ายจริงหลังดาวน์โหลด",
"reconcileTitle": "เพลงนี้ยาวกว่าที่คาดไว้",
"cancel": "ยกเลิก"
},
"karaokeBackgroundPreview": {
"loading": "กำลังโหลดตัวอย่างพื้นหลัง"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Mag-paste ng link",
"urlSupportedSitesHint": "Gumagana sa YouTube, Facebook, SoundCloud, TikTok, Vimeo at daan-daang iba pang mga site.",
"urlSupportedSitesLink": "Tingnan ang lahat ng suportadong site",
"useThisUrl": "Gamitin ang URL na Ito"
"useThisUrl": "Gamitin ang URL na Ito",
"matchCorrectedTo": "Itinama sa {value} — ang tinype mo ay “{typed}”",
"matchDidYouMean": "Ibig mo bang sabihin?",
"matchKeepMine": "panatilihin ang tinype ko",
"matchTidiedTo": "Inayos sa {value}",
"matchUndo": "I-undo",
"matchChecking": "Sinusuri ang mga detalye ng kanta…",
"matchUseCorrection": "gamitin ang itinama",
"matchUseTidied": "gamitin ang inayos na bersyon",
"matchUsingTyped": "Ginagamit ang iyong nai-type: {value}"
},
"jobStatus": {
"settingUp": "Sine-set up",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Pamagat ng Kanta",
"artist": "Artist"
"artist": "Artist",
"loading": "Nilo-load ang preview ng title screen"
},
"editTrack": {
"title": "I-edit ang Nakumpletong Track",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Tantiya — kukumpirmahin ang pinal na halaga pagkatapos ma-download",
"reconcileTitle": "Mas mahaba ang kantang ito kaysa sa inaasahan",
"cancel": "Kanselahin"
},
"karaokeBackgroundPreview": {
"loading": "Nilo-load ang preview ng background"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Bir bağlantı yapıştır",
"urlSupportedSitesHint": "YouTube, Facebook, SoundCloud, TikTok, Vimeo ve yüzlerce başka siteyle çalışır.",
"urlSupportedSitesLink": "Desteklenen tüm siteleri gör",
"useThisUrl": "Bu URL'yi Kullan"
"useThisUrl": "Bu URL'yi Kullan",
"matchCorrectedTo": "{value} olarak düzeltildi — “{typed}” yazmıştın",
"matchDidYouMean": "Bunu mu demek istedin?",
"matchKeepMine": "yazdığım gibi kalsın",
"matchTidiedTo": "{value} olarak düzenlendi",
"matchUndo": "Geri al",
"matchChecking": "Şarkı detayları kontrol ediliyor…",
"matchUseCorrection": "düzeltmeyi kullan",
"matchUseTidied": "düzenlenmiş sürümü kullan",
"matchUsingTyped": "Yazdığın kullanılıyor: {value}"
},
"jobStatus": {
"settingUp": "Ayarlanıyor",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Şarkı Adı",
"artist": "Sanatçı"
"artist": "Sanatçı",
"loading": "Başlık ekranı önizlemesi yükleniyor"
},
"editTrack": {
"title": "Tamamlanan Parçayı Düzenle",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Tahmini — nihai maliyet indirmeden sonra kesinleşir",
"reconcileTitle": "Bu şarkı beklenenden daha uzun",
"cancel": "İptal"
},
"karaokeBackgroundPreview": {
"loading": "Arka plan önizlemesi yükleniyor"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Вставити посилання",
"urlSupportedSitesHint": "Працює з YouTube, Facebook, SoundCloud, TikTok, Vimeo та сотнями інших сайтів.",
"urlSupportedSitesLink": "Переглянути всі підтримувані сайти",
"useThisUrl": "Використати це посилання"
"useThisUrl": "Використати це посилання",
"matchCorrectedTo": "Виправлено на {value} — твій варіант: «{typed}»",
"matchDidYouMean": "Маєш на увазі?",
"matchKeepMine": "залишити мій варіант",
"matchTidiedTo": "Відформатовано як {value}",
"matchUndo": "Скасувати",
"matchChecking": "Перевіряємо деталі пісні…",
"matchUseCorrection": "використати виправлення",
"matchUseTidied": "використати впорядковану версію",
"matchUsingTyped": "Використовуємо введений тобою текст: {value}"
},
"jobStatus": {
"settingUp": "Налаштування",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Назва пісні",
"artist": "Виконавець"
"artist": "Виконавець",
"loading": "Завантаження попереднього перегляду титульного екрана"
},
"editTrack": {
"title": "Редагувати завершений трек",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Орієнтовно — остаточна вартість підтверджується після завантаження",
"reconcileTitle": "Ця пісня довша, ніж очікувалося",
"cancel": "Скасувати"
},
"karaokeBackgroundPreview": {
"loading": "Завантаження попереднього перегляду фону"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "Dán liên kết",
"urlSupportedSitesHint": "Hỗ trợ YouTube, Facebook, SoundCloud, TikTok, Vimeo và hàng trăm trang web khác.",
"urlSupportedSitesLink": "Xem tất cả các trang web được hỗ trợ",
"useThisUrl": "Sử dụng URL này"
"useThisUrl": "Sử dụng URL này",
"matchCorrectedTo": "Đã sửa thành {value} — bạn đã nhập “{typed}”",
"matchDidYouMean": "Có phải ý bạn là?",
"matchKeepMine": "giữ nguyên nội dung tôi đã nhập",
"matchTidiedTo": "Đã chỉnh gọn thành {value}",
"matchUndo": "Hoàn tác",
"matchChecking": "Đang kiểm tra chi tiết bài hát…",
"matchUseCorrection": "sử dụng bản sửa đổi",
"matchUseTidied": "sử dụng bản đã tinh chỉnh",
"matchUsingTyped": "Sử dụng nội dung bạn đã nhập: {value}"
},
"jobStatus": {
"settingUp": "Đang thiết lập",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "Tên bài hát",
"artist": "Nghệ sĩ"
"artist": "Nghệ sĩ",
"loading": "Đang tải bản xem trước màn hình tiêu đề"
},
"editTrack": {
"title": "Chỉnh sửa bài hát đã hoàn thành",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "Ước tính — chi phí cuối cùng sẽ được xác nhận sau khi tải xuống",
"reconcileTitle": "Bài hát này dài hơn dự kiến",
"cancel": "Hủy"
},
"karaokeBackgroundPreview": {
"loading": "Đang tải bản xem trước hình nền"
}
}
+15 -2
View File
@@ -533,7 +533,16 @@
"pasteUrlButton": "粘贴链接",
"urlSupportedSitesHint": "支持 YouTube、Facebook、SoundCloud、TikTok、Vimeo 以及数百个其他网站。",
"urlSupportedSitesLink": "查看所有支持的网站",
"useThisUrl": "使用此链接"
"useThisUrl": "使用此链接",
"matchCorrectedTo": "已更正为 {value} — 您输入的是“{typed}”",
"matchDidYouMean": "您是不是指?",
"matchKeepMine": "保留我的输入",
"matchTidiedTo": "已整理为 {value}",
"matchUndo": "撤销",
"matchChecking": "正在检查歌曲详情…",
"matchUseCorrection": "使用修正内容",
"matchUseTidied": "使用整理后的版本",
"matchUsingTyped": "使用您输入的内容:{value}"
},
"jobStatus": {
"settingUp": "设置中",
@@ -683,7 +692,8 @@
},
"titleCardPreview": {
"songTitle": "歌曲名称",
"artist": "歌手"
"artist": "歌手",
"loading": "正在加载标题画面预览"
},
"editTrack": {
"title": "编辑已完成的曲目",
@@ -1566,5 +1576,8 @@
"estimatedLabel": "预估 — 最终费用将在下载后确认",
"reconcileTitle": "这首歌比预期的要长",
"cancel": "取消"
},
"karaokeBackgroundPreview": {
"loading": "正在加载背景预览"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 537 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 551 KiB

@@ -50,6 +50,18 @@ def create_encoding_worker_vms(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
# NOTE: Hyperdisk provisioned IOPS/throughput are deliberately
# NOT set here. Specifying them forces a full VM *replacement*
# (the provider treats boot-disk init params as immutable), and
# recreating a primary depends on us-central1-c capacity — the
# exact shortage the fallback fleet exists to absorb. So the
# disks are pinned to the Hyperdisk Balanced free baseline
# (3000 IOPS / 140 MB/s) live via `gcloud compute disks update`
# instead — non-disruptive, and pulumi does not manage this
# attribute so there is no drift. They were over-provisioned at
# 3600 IOPS / 290 MB/s (~$8.70/disk/mo wasted). Re-apply the
# gcloud tune after any worker-image rebuild that recreates the
# disks. See docs/archive/2026-06-14-gcp-cost-reduction-plan.md.
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
@@ -127,6 +139,18 @@ def create_encoding_worker_fallback_vms(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
# NOTE: Hyperdisk provisioned IOPS/throughput are deliberately
# NOT set here. Specifying them forces a full VM *replacement*
# (the provider treats boot-disk init params as immutable), and
# recreating a primary depends on us-central1-c capacity — the
# exact shortage the fallback fleet exists to absorb. So the
# disks are pinned to the Hyperdisk Balanced free baseline
# (3000 IOPS / 140 MB/s) live via `gcloud compute disks update`
# instead — non-disruptive, and pulumi does not manage this
# attribute so there is no drift. They were over-provisioned at
# 3600 IOPS / 290 MB/s (~$8.70/disk/mo wasted). Re-apply the
# gcloud tune after any worker-image rebuild that recreates the
# disks. See docs/archive/2026-06-14-gcp-cost-reduction-plan.md.
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
@@ -1,11 +1,36 @@
"""Firestore export to GCS staging bucket."""
import logging
from google.cloud import firestore_admin_v1
from google.cloud import firestore_admin_v1, storage
logger = logging.getLogger(__name__)
def _clear_prior_exports(staging_bucket: str, keep_date: str) -> None:
"""Delete prior firestore/ exports in staging except the keep_date one.
The Firestore export runs nightly to provide a fresh daily local (GCS)
restore point, but is only uploaded to S3 weekly (to cut egress). On
non-weekly days the export is held back from S3 and left in staging, so
without this cleanup a week of exports would pile up and the weekly upload
would ship all of them at once — defeating the saving. Keeping only the
latest export means the weekly upload ships exactly one.
"""
keep_prefix = f"firestore/{keep_date}"
try:
client = storage.Client()
bucket = client.bucket(staging_bucket)
for blob in bucket.list_blobs(prefix="firestore/"):
if not blob.name.startswith(keep_prefix):
try:
blob.delete()
except Exception as e:
logger.warning(f"Failed to delete stale firestore export {blob.name}: {e}")
except Exception as e:
# Best-effort cleanup — the export already succeeded, so never fail on it.
logger.warning(f"Failed to list/clear prior firestore exports: {e}")
def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
"""Export all Firestore collections to GCS.
@@ -32,5 +57,8 @@ def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
result = operation.result(timeout=1800) # 30 min timeout
# Keep only this export in staging so the weekly S3 upload ships exactly one.
_clear_prior_exports(staging_bucket, date_str)
logger.info(f"Firestore export complete: {output_uri}")
return f"Exported to {output_uri} ({date_str})"
+16 -4
View File
@@ -2,14 +2,18 @@
Backup to AWS Cloud Function.
Nightly backup pipeline:
1. Firestore export to GCS staging
1. Firestore export to GCS staging (nightly; uploaded to S3 weekly on Sundays)
2. BigQuery export to GCS staging (weekly/monthly schedule)
3. GCS job files delta sync to staging
4. Secret Manager export (encrypted with sealed-box public key) to staging
5. Upload staging files to S3
5. Upload staging files to S3 (Firestore export held back except Sundays)
6. Discord alert
Triggered by Cloud Scheduler at 1:00 AM ET daily.
Firestore is the bulk of the cross-cloud egress. Exporting it nightly to GCS
keeps a 1-day local restore point, while uploading to S3 only weekly keeps a
1-week off-site RPO at ~1/7th the egress cost.
"""
import datetime
@@ -59,7 +63,13 @@ def backup_to_aws(request):
results = {}
errors = []
logger.info(f"Starting backup for {date_str}")
# The Firestore export runs nightly (daily local restore point in GCS) but
# is only pushed off-site to S3 weekly, on Sundays — matching the BigQuery
# weekly cadence. This is the bulk of the cross-cloud egress, so weekly
# off-site keeps a 1-week off-site RPO while a 1-day local RPO is retained.
firestore_to_s3_today = today.weekday() == 6 # Sunday
logger.info(f"Starting backup for {date_str} (firestore->S3: {firestore_to_s3_today})")
# Step 1: Firestore export (nightly)
try:
@@ -123,11 +133,13 @@ def backup_to_aws(request):
logger.error(f"Secrets export failed: {e}")
errors.append(f"Secrets: {e}")
# Step 5: Upload to S3
# Step 5: Upload to S3. On non-Sundays, hold the Firestore export back
# (it stays in GCS staging as a daily local backup); it ships to S3 weekly.
try:
results["s3_upload"] = upload_staging_to_s3(
staging_bucket=STAGING_BUCKET,
s3_bucket=S3_BUCKET,
exclude_prefixes=[] if firestore_to_s3_today else ["firestore/"],
)
except Exception as e:
logger.error(f"S3 upload failed: {e}")
@@ -21,12 +21,20 @@ def upload_staging_to_s3(
staging_bucket: str,
s3_bucket: str,
project: str = "nomadkaraoke",
exclude_prefixes: list | None = None,
) -> str:
"""Upload all objects in staging bucket to S3 using streaming.
Walks the staging bucket and uploads each object to the corresponding
S3 key path. Skips marker files (.*).
S3 key path. Skips marker files (.*) and any object whose name starts with
one of ``exclude_prefixes`` (used to hold the nightly Firestore export back
from S3 on non-weekly days — it stays in GCS staging as a daily local
restore point and is uploaded only on the weekly run).
Excluded objects are left in staging (not deleted), so they remain a local
backup until the GCS lifecycle policy or the next weekly upload removes them.
"""
exclude_prefixes = exclude_prefixes or []
aws_creds = get_aws_credentials(project)
s3_client = boto3.client(
"s3",
@@ -45,6 +53,9 @@ def upload_staging_to_s3(
if blob.name.startswith(".") or "/.last_sync" in blob.name:
continue
if any(blob.name.startswith(p) for p in exclude_prefixes):
continue
try:
with blob.open("rb") as gcs_file:
s3_client.upload_fileobj(
@@ -5,8 +5,9 @@ from unittest.mock import MagicMock, patch
class TestFirestoreExport(unittest.TestCase):
@patch("firestore_export.storage.Client")
@patch("firestore_export.firestore_admin_v1.FirestoreAdminClient")
def test_export_firestore_calls_api(self, mock_client_class):
def test_export_firestore_calls_api(self, mock_client_class, mock_storage):
from firestore_export import export_firestore
mock_client = MagicMock()
@@ -14,6 +15,7 @@ class TestFirestoreExport(unittest.TestCase):
mock_operation = MagicMock()
mock_operation.result.return_value = MagicMock()
mock_client.export_documents.return_value = mock_operation
mock_storage.return_value.bucket.return_value.list_blobs.return_value = []
result = export_firestore(
project="test-project",
@@ -27,8 +29,9 @@ class TestFirestoreExport(unittest.TestCase):
assert request["name"] == "projects/test-project/databases/(default)"
assert "gs://test-staging/firestore/2026-03-29" in request["output_uri_prefix"]
@patch("firestore_export.storage.Client")
@patch("firestore_export.firestore_admin_v1.FirestoreAdminClient")
def test_export_firestore_returns_summary(self, mock_client_class):
def test_export_firestore_returns_summary(self, mock_client_class, mock_storage):
from firestore_export import export_firestore
mock_client = MagicMock()
@@ -36,11 +39,44 @@ class TestFirestoreExport(unittest.TestCase):
mock_operation = MagicMock()
mock_operation.result.return_value = MagicMock()
mock_client.export_documents.return_value = mock_operation
mock_storage.return_value.bucket.return_value.list_blobs.return_value = []
result = export_firestore("proj", "bucket", "2026-03-29")
assert isinstance(result, str)
assert "2026-03-29" in result
class TestClearPriorExports(unittest.TestCase):
@patch("firestore_export.storage.Client")
def test_keeps_latest_deletes_others(self, mock_storage):
from firestore_export import _clear_prior_exports
def _blob(name):
b = MagicMock()
b.name = name
return b
today = _blob("firestore/2026-03-29/out.bin")
old1 = _blob("firestore/2026-03-22/out.bin")
old2 = _blob("firestore/2026-03-15/out.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [
today, old1, old2,
]
_clear_prior_exports("staging", "2026-03-29")
today.delete.assert_not_called()
old1.delete.assert_called_once()
old2.delete.assert_called_once()
@patch("firestore_export.storage.Client")
def test_cleanup_failure_is_swallowed(self, mock_storage):
from firestore_export import _clear_prior_exports
mock_storage.return_value.bucket.return_value.list_blobs.side_effect = RuntimeError("boom")
# Must not raise — cleanup is best-effort, the export already succeeded.
_clear_prior_exports("staging", "2026-03-29")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,52 @@
"""Tests for s3_upload module, focused on the exclude_prefixes behavior."""
import unittest
from unittest.mock import MagicMock, patch
def _blob(name):
b = MagicMock()
b.name = name
return b
class TestUploadStagingToS3(unittest.TestCase):
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_excluded_prefix_not_uploaded_or_deleted(self, mock_creds, mock_storage, mock_boto):
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
fs = _blob("firestore/2026-03-29/out.bin")
sec = _blob("secrets/2026-03-29.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [fs, sec]
upload_staging_to_s3("staging", "s3b", exclude_prefixes=["firestore/"])
# firestore held back: not uploaded, not deleted (stays as local backup)
fs.delete.assert_not_called()
# secrets uploaded then deleted
sec.delete.assert_called_once()
self.assertEqual(mock_boto.return_value.upload_fileobj.call_count, 1)
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_no_exclude_uploads_everything(self, mock_creds, mock_storage, mock_boto):
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
fs = _blob("firestore/2026-03-29/out.bin")
sec = _blob("secrets/2026-03-29.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [fs, sec]
upload_staging_to_s3("staging", "s3b")
self.assertEqual(mock_boto.return_value.upload_fileobj.call_count, 2)
fs.delete.assert_called_once()
sec.delete.assert_called_once()
if __name__ == "__main__":
unittest.main()
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more