Compare commits

...
36 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 eac3dac910 fix: recognize Turbopack chunk-load errors for post-deploy auto-reload (#879)
## Problem

Prod error-monitor alert:

```
Error: Failed to load chunk /_next/static/chunks/<ID>.js from module <NUM>
    at https://gen.nomadkaraoke.com/_next/static/chunks/turbopack-*.js
```

The gen frontend is a static export (`output: 'export'`) served from
GitHub Pages with hashed chunk filenames. On deploy, old chunk hashes
vanish, so a user with an already-loaded tab hits a **post-deploy
mismatch** when the app lazy-loads a stale chunk. The frontend is
designed to auto-recover from this via `hardReload()` in
`client-error-setup.ts` — but the recovery wasn't firing.

## Root cause

`isChunkLoadError()` in `frontend/lib/version-check.ts` only recognized
webpack/native-ESM phrasings (`ChunkLoadError`, `Loading chunk <id>
failed`, `Failed to fetch dynamically imported module`, `Importing a
module script failed`).

**Next.js 16 defaults to Turbopack**, whose browser runtime throws a
plain `Error` (name `"Error"`, *not* `ChunkLoadError`) with a different
message: `Failed to load chunk <path> from module <n>` (also `… as a
runtime dependency of chunk <id>` / `… from an HMR update`). Confirmed
by inspecting the built runtime
`out/_next/static/chunks/turbopack-*.js`.

None of the regexes matched → the auto-hard-reload never triggered (user
saw a broken page) **and** the error was reported to the monitor → this
alert.

## Fix

- Add `/Failed to load chunk/i` to `isChunkLoadError()`'s regex list,
documenting all three bundler families.
- Add the first tests for `isChunkLoadError` (webpack, Turbopack ×3
variants, native ESM, negatives).
- Bump `0.191.1` → `0.191.2`.

Left the crash-reporter's `isBenignError` untouched: a chunk error that
survives the 60s reload circuit-breaker *should* still be reported
(persistent = a real problem like missing CDN files, not mere
staleness).

## Notes

- Users who already saw the error recover with a manual reload — this
fix makes future post-deploy mismatches self-heal automatically.
- The error store aggregates by pattern and does not persist
`user_email`, so the affected visitor can't be identified (and this hit
was on the logged-out `/zh/` homepage anyway).

## Testing

- `npx jest __tests__/version-check.test.ts
__tests__/CrashReport.test.tsx` → 20/20 pass
- `npx eslint` on changed files → clean

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 12:01:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1578984f5b fix: filter benign ResizeObserver-loop noise from client error monitor (#878)
## Summary
The error monitor fired a 🔴 New Error Pattern alert for \`ResizeObserver
loop completed with undelivered notifications\` (on \`singa.\`, build
ad3c0bff). This is a **benign, spec-defined browser signal** — not a
crash. Chrome hides it from its own console; every page using
ResizeObserver (TimelineCanvas, FlyerPreview, VNC toolbar) emits it
occasionally. It reached the monitor because the global
\`window.onerror\` handler reports everything with no benign-noise
filter.

## Changes
- Extend the existing \`isBenignError\` filter in
\`frontend/lib/crash-reporter.ts\` (which already drops media
\`AbortError\`) to also skip both ResizeObserver-loop phrasings
(\`completed with undelivered notifications\` + legacy \`loop limit
exceeded\`).
- Add \`crash-reporter\` unit tests (benign detection + that a genuine
error still POSTs).

## Testing
- [x] \`npx jest lib/__tests__/crash-reporter.test.ts\` — 5/5 pass
- [x] Verified real errors (e.g. the \`currentTime\` TypeError) are NOT
suppressed

## Review
- [x] Local CodeRabbit review (1 minor finding — test fetch-mock leak —
fixed)
- [x] Version bumped 0.191.0 → 0.191.1

## Context
Unrelated to the karaoke \`currentTime\` fix shipped in #877. Also
confirmed the same-day E2E "Happy Path" alert was a landing-page
\`page.goto\` timeout flake (site healthy), re-running to confirm.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 17:04:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ad3c0bffc0 fix: harden 4 prod error paths (seek non-finite, auto-correct 429, download race + timeout) (#877)
## Summary
Investigated and fixed four production error patterns flagged by the
error monitor, each with tests.

## Changes
**Frontend — `TypeError: currentTime non-finite`** (`/en/app/jobs`
review UI)
- Guard lyrics-review/audio-editor seek sinks
(`AudioPlayer.seekAndPlay`/`handleSeek`, `AudioEditor.seekTo`) and the
`handlePlaySegment` dispatcher with `Number.isFinite`; harden
`TimelineEditor.handleTimelineClick` against a zero-width container.
Restores parity with instrumental-review, which already had these
guards.

**Backend — auto-correct Vertex `429 RESOURCE_EXHAUSTED` surfaced as
generic 502**
- Retry model calls with exponential backoff on transient
(rate-limit/overload) errors via `_is_transient_model_error`; surface a
distinct **retryable 429** instead of 502. Retry env knobs parsed
defensively (clamp + warn, never crash at import).

**Backend — `audio-download-job` `InvalidStateTransitionError:
downloading -> downloading`**
- Root cause: a manual `/retry` raced the Cloud Run auto-retry; the
losing run's post-download transition raised and the generic `except`
`fail_job`'d a job the winner had already advanced. Fix: idempotent
transition — re-read status first, treat an already-advanced job as
success, and use `raise_on_invalid=False` so a race never fails a live
job.

**Backend/infra — `audio-download-job` 600s task-timeout SIGKILL**
- Internal `wait_for_download` timeout equalled the Cloud Run task
timeout, so slow torrents were SIGKILLed before failing gracefully
(leaving the orphaned retry that fed the race above). New
`DOWNLOAD_WAIT_TIMEOUT_SECONDS=1080` kept strictly below the task
timeout, raised `600s → 1200s`. **Infra already applied to prod via
`pulumi up` (targeted); stack is clean.**

## Testing
- [x] Backend: 122 tests across touched suites pass (auto_correct incl.
10 retry/env, audio_download_worker incl. 3 race/timeout, review API,
proactive)
- [x] Frontend: full jest suite 1073/1073 pass (incl. new AudioPlayer
non-finite guard test); `tsc` clean for changed files
- [x] Infra: `pulumi preview` clean (273 unchanged) after applying
timeout + reconciling pre-existing divebar drift

## Review
- [x] Local CodeRabbit review completed (1 major finding — retry env
validation — fixed + tested)
- [x] Version bumped 0.190.5 → 0.191.0

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 17:40:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b8e67e6ba6 feat: emit + push original-vocals guide on NOMAD render (write-path) (#875)
## Summary

Makes the kjbox **"Original Vocals"** sing-along guide
**self-maintaining**. When karaoke-gen finalises a new public NOMAD
master, it now automatically emits an aligned original-vocals guide and
pushes it to GCS — no re-run of the kjbox retro-fit pipeline.

**Key insight:** at render time karaoke-gen already has the isolated
`mixed_vocals` stem (a byproduct of the karaoke instrumental) and knows
the exact intro offset (the job's style `intro_video_duration`). So the
guide is simply `silence[intro] + vocals`, capped to the master's
duration — **no correlation, no review, no alignment measurement**.

## Changes

- `backend/services/original_vocals_guide.py` (new): pure ffmpeg builder
(`adelay` + `-f flac`, atomic `.part` rename) + `probe_duration`.
Best-effort, never raises.
- `nomad_master_mirror`: `push_vocals_guide` +
`delete_vocals_guides_by_brand` (siblings of the 720p methods);
brand-recycle cleanup now clears guides too.
- `video_worker_orchestrator`: `_emit_original_vocals_guide` pulls the
`mixed_vocals` stem from `jobs/{id}/stems/vocals_clean.flac`, resolves
the **actual** intro duration (long-intro styles honoured; `0`
preserved), caps to the master, registers it in `output_files`.
- `gdrive_service`: pushes the guide beside the 720p master (same
Nomad-brand gating + best-effort/distribution-warning contract).
- `config`: `nomad_vocals_guide_gcs_prefix` (`files/Nomad
Karaoke/vocals-padded`).

## Behaviour

- **Public NOMAD only** (`is_nomad_public_brand`, skips `NOMADNP`).
Shares the `nomad_master_fast_sync_enabled` gate.
- **Inert** until the kjbox device pulls the new prefix into
`NOMAD-vocals-padded/` (separate kjbox PR) — guides just accumulate in
GCS. Existing 1,459 device guides untouched.
- Every step best-effort: a guide failure is a distribution warning,
never fatal.

## Testing

- Builder unit tests (synthetic tone+silence): offset, duration cap,
valid flac, best-effort `None` paths.
- Mirror push/delete + gating; gdrive + orchestrator wiring; intro=0 /
long-intro resolution.
- Full backend suite: **3711 passed** (excl. emulator). CodeRabbit: 1
finding (intro-0 truthiness) fixed.

Design spec:
`docs/superpowers/specs/2026-07-09-original-vocals-writepath-design.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:26:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6f86b3d901 test(e2e): rewrite tenant daily E2E as a faithful frontend journey (#873)
## Why

The daily tenant E2E (`scripts/e2e/tenant_e2e.py`) drove the whole flow
via **direct backend API calls**, bypassing the frontend. Two problems:
1. **Not representative** — it never exercised the tenant portal UI a
real operator uses.
2. **Intermittent stuck-render orphans** (Run #31 vocalstar, #32 singa)
— because it never loaded the lyrics-review page, it never fired
`encoding-worker/warmup`, so the encoder was cold when the render
started and the job orphaned in `rendering_video` (no recovery).
Root-caused this session; the fix is to make the test faithful, which
fires the warmup a real user fires.

## What

Replaces `tenant_e2e.py` with
**`frontend/e2e/production/tenant-happy-path.spec.ts`** — a Playwright
journey mirroring `happy-path-real-user.spec.ts`, run per-tenant via the
existing `e2e-tenant-daily.yml` matrix (vocalstar, singa; `max-parallel:
1`):

login (real magic-link UI) → submit track (tenant form + real audio
upload) → wait for transcription → **open review UI (fires warmup)** →
approve → wait for render → assert tenant distribution (Dropbox present,
no YouTube, downloads, `is_private`) → cleanup.

- **Tenant auth**: added `inbox.testmail.app` to both tenants'
`allowed_email_domains` (setup scripts + live GCS config via
`scripts/e2e/update_tenant_allowlist.py`) so the test signs in through
the real magic-link UI.
- **Test audio**: short 60s clips fetched from private GCS in CI
(`scripts/e2e/fetch_test_audio.sh`) — fast, reliable uploads and quick
renders.
- Workflow reworked to Node/Playwright; `tenant_e2e.py` deleted; version
`0.190.3 → 0.190.4`.

## Findings surfaced (validating the exercise)

- **Browser upload was CORS-blocked in Playwright** by the shared
config's global `x-playwright-test` header (it made the GCS signed-URL
PUT preflight request a header the bucket's CORS doesn't allow).
Verified the same PUT succeeds in a real browser — a **test-harness
artifact, not a product bug**. Worked around by stripping the header for
`storage.googleapis.com` requests. (Note: any prod E2E doing a browser
signed-URL upload is affected by this global header.)

## Verification

Both tenants run **green end-to-end against prod** locally (login →
submit → review → render → distribution; render completed without
orphaning). Reworked workflow dispatched on this branch to confirm CI
wiring (Node setup + private-audio fetch + secrets).

Test-only + CI + tenant-config change. No product code.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 02:33:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 f93d5f6923 fix(e2e): click 'Complete Sign-In' gate in magic-link auth tests (#872)
## Problem

The daily E2E (`e2e-daily.yml`) **Stage 1 (Credit Purchase) failed**
(Run #87), with **Stage 2 (Happy Path) skipped** only because its `if`
requires Stage 1 success.

Root cause: yesterday's `fix(auth): gate magic-link verify behind
explicit click` (#870). The `/auth/verify` page no longer auto-consumes
the token on mount — it now shows a **"Complete Sign-In"** confirm gate,
and the token is only spent when that button is clicked (protects the
link from email scanners).

The three magic-link E2E specs navigate to the link then *immediately*
wait for the post-sign-in text ("Successfully signed in!" / "Welcome to
Nomad Karaoke!"). That text now only appears **after** clicking the gate
→ 30s timeout → failure. All three were affected (Stage 2 has the same
bug; it just never ran).

## Fix

New shared helper `clickCompleteSignInGate(page)` in
`frontend/e2e/helpers/auth.ts`:
- waits for the gate button (`getByRole('button', { name: /complete
sign-?in/i })`)
- races it against the `/sign-in failed/i` UI so a genuinely dead link
throws a diagnostic error instead of a bare timeout
- clicks the gate

Called after `page.goto(magicLink)` in:
- `credit-purchase-real.spec.ts` (Stage 1)
- `happy-path-real-user.spec.ts` (Stage 2)
- `full-user-journey.spec.ts`

## Verification

- `playwright test --list` compiles all three specs; ESLint clean;
CodeRabbit 0 findings.
- **Live against prod v0.190.2:** minted a real magic-link token via
`POST /api/users/auth/magic-link`, drove it in an isolated browser →
gate **"Complete Sign-In"** renders → click → **"Welcome to Nomad
Karaoke!"** interstitial → **"Start Creating Karaoke"** → `/app`. Every
selector in the fix and downstream test logic confirmed.

Test-only change (+ version bump 0.190.2 → 0.190.3).

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 14:30:45 -04:00
Andrew Beveridge ☄️ d84a827be3 feat(auth): show already-used/expired message upfront on verify page (#871)
@coderabbitai ignore

Follow-up to #870. That PR added the "Complete Sign-In" gate so email
link-scanners can't burn a magic link before the user clicks. This PR
improves the case where the link is **genuinely already used or
expired**: instead of showing a "Complete Sign-In" button that only
fails when clicked, the verify page now shows the "link expired or
already used" message (with one-click resend) **upfront**.

### How it stays scanner-safe

The decision uses a **read-only** status probe that does **not** consume
the token:

- New `GET /api/users/auth/link-status` +
`UserService.get_magic_link_status()` return `valid` / `used` /
`expired` / `invalid` without mutating the doc (verified by a unit test
asserting `update`/`set` are never called).
- The verify page calls it on mount:
- `valid` → show the **Complete Sign-In** gate (token still spent only
on the explicit click).
- `used`/`expired`/`invalid` → show the failure UI + resend immediately.
- probe **errors** → fall back to the gate, so a transient
status-endpoint failure never blocks a user holding a valid link.

Because the probe is non-mutating, a scanner rendering the page still
can't burn a valid token — consumption remains gated behind the click,
exactly as in #870.

### Notes

- Reuses existing i18n strings (`pleaseWait`, `verifyingWait`,
`linkExpiredOrUsed`) — no new translation keys.
- The status endpoint is an unauthenticated read, same trust model as
`/auth/verify` (the 256-bit token is the only credential); it reveals
only valid/used/expired for a token the caller already holds.

### Testing

- **Backend (9):** service returns correct status for
valid/used/expired/missing/empty **and does not consume** a valid token;
endpoint returns the status and short-circuits empty tokens without
hitting Firestore.
- **Frontend (8):** valid → gate, no verify on mount; dead link →
failure UI upfront with no gate and no verify call; probe-error → gate
fallback; resend recovery intact.
- Full frontend suite green (1072); backend auth suite green (75); `tsc`
+ `eslint` clean; CodeRabbit local: 0 findings.
- Version `0.190.1 → 0.190.2`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-07-03 19:40:52 +00:00
Andrew Beveridge ☄️ 2b258cd8f0 fix(auth): gate magic-link verify behind explicit click to survive email scanners (#870)
@coderabbitai ignore

## Problem

Magic-link sign-in could fail with **"This link has already been used"**
even on a fresh link. Root cause: the verify page (`/auth/verify`)
auto-consumed the single-use token on mount via a `useEffect` — **no
user gesture** — against the state-mutating `GET
/api/users/auth/verify`. Anything that *renders the page and runs its
JS* (Gmail/Safe-Browsing link scanners, corporate security proxies)
therefore burned the token and created a throwaway session before the
real user could click.

### Evidence (user `valhalla.gansett@gmail.com`, 2026-07-03, UTC)

Two of his login links were consumed within ~60s of delivery by **Google
LLC** IPs (`2607:f8b0…`, Chrome/149 headless). Cloud Run logs show his
own click losing an 82ms race for token `_VBC4O…`:

| Time | Result | IP | Owner | Browser |
|------|--------|----|-------|---------|
| 00:56:00.176 | **200 (burned it)** | `2607:f8b0…::12` | Google LLC |
Chrome/149 |
| 00:56:00.223 | 401 already-used | `2607:f8b0…::7` | Google (2nd edge)
| Chrome/149 |
| 00:56:00.258 | 401 already-used | `173.245.209.177` | Jacob's VPN |
Chrome/148 |

He got in only via a third link the scanner happened not to prefetch.
Scope check: last 30d, only 2/115 login sessions were consumed from
Google IPs, all his — so it's his specific mail/security setup tripping
a latent design weakness, not a mass outage.

## Fix

The verify page now opens on a **"Complete Sign-In" confirm gate** and
spends the token only on an explicit click. Scanners render the page but
don't click, so the token survives for the real user (standard
magic-link mitigation).

- Mount-time effect is now side-effect-free (stores referral code,
remembers the token) and does **not** verify.
- Verification moved into a `handleConfirm` click handler with a
re-entrancy guard against double-clicks.
- New i18n strings (`confirmTitle`, `confirmBody`, `confirmButton`)
translated to all 33 locales.

Note: switching GET→POST alone would **not** help — a JS-executing
scanner runs the fetch regardless of method. The user-gesture gate is
the robust fix.

## Not in scope

The admin one-click login path (`/app?admin_token=…`) auto-verifies the
same way and has the same latent exposure, but it's admin-only and
low-volume. Flagged in `LESSONS-LEARNED.md` for a follow-up rather than
changing that flow's UX here.

## Testing

- New unit tests: verify page does **not** call `verifyMagicLink` on
mount; verifies only after the "Complete Sign-In" click. Existing
resend-recovery tests updated to click through the gate.
- Full frontend unit suite green (1070 tests); `tsc` + `eslint` clean;
CodeRabbit local review: 0 findings.
- Version bumped `0.190.0 → 0.190.1`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-07-03 13:49:37 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 0fc67d2838 feat: remove Nomad GCS master on delete/edit/private (Phase 2) (#869)
## Why

Phase 1 pushes new Nomad 720p masters to the GCS mirror (→ kjbox in
minutes). This adds the **delete side** so an edit or delete also
propagates: the *latest* cut wins on the box, and stale/renamed masters
don't linger. Per the agreed policy — **Nomad deletes OK; community
keep-forever**.

## What

- **`NomadMasterMirror.delete_masters_by_brand(brand_code)`** — deletes
every 720p master object matched by the unique `"{brand_code} - "`
prefix. Keying on `brand_code` (not a reconstructed title) **covers
renames for free**: every title a release was published under shares the
same `NOMAD-#### - ` prefix.
- **Hard safety guard:** refuses unless the brand is a full `NOMAD-####`
code (non-empty suffix), so a bare/empty prefix can never over-delete.
The `" - "` (space-dash-space) separator makes prefixes collision-proof
across brand lengths (`NOMAD-15` can't match `NOMAD-150…`).
- **`cleanup_nomad_masters(brand_code)`** — best-effort, Nomad-only,
never raises. Wired after the existing Drive/Dropbox output deletes at
the four flows that remove a job's public outputs: job delete/edit
cleanup, re-finalize/re-encode (so a rename drops the old cut; the
re-run's push re-adds the new), admin delete-outputs, and visibility
public→private.

Same-name re-edits already self-heal via Phase 1 (push overwrites; kjbox
rsync updates on size change). This handles **deletes and renames**.

## Testing
- 26 unit tests: prefix delete, rename coverage, the `NOMAD-####` safety
guard (refuses bare/empty/`NOMADNP`/other brands), non-fatal on error,
`cleanup_nomad_masters` delegation/no-op.
- Integration wiring test: admin delete-outputs endpoint calls
`cleanup_nomad_masters` with the job's `brand_code`.
- Local: mirror + gdrive + jobs-API + admin-delete + visibility suites
green.

## Review
Local `feature-dev:code-reviewer` — verified the over-deletion safety
(prefix collision-proofness, brand gating, IAM scope) is sound; added
the wiring test it recommended.

Phase 2 of the nomad-master fast-sync work. Pairs with the kjbox
true-mirror change (Phase 3) so deletes reconcile onto the device.
(Phases 1 & 4 already shipped: #866, #867.)

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 22:11:45 +00:00
Andrew Beveridge ☄️andClaude Fable 5 e97f249efd fix: parse-titles auto-chunks large batches into concurrent Gemini calls (v0.189.1) (#868)
## Summary
Fixes the last loose end from the download-naming handoff: a 100-item
`POST /api/parse-karaoke-titles` batch rode a **single** Gemini call
that exceeded the 20s `parse_titles_timeout_ms`, blanking the whole
batch — forcing kjbox's `refine_titles.py` to run `--batch-size 10`. The
service now auto-chunks internally, so clients can send up to
`parse_titles_max_items` (200) in one request.

## Changes
- `service.parse_titles` splits any batch into **concurrent** chunks of
`parse_titles_chunk_size` (new setting, default 10, env
`PARSE_TITLES_CHUNK_SIZE`) via `asyncio.gather` — no single Gemini call
can outgrow the timeout, and a 100-item batch costs ~1 round-trip of
latency, not 10.
- Graceful degrade is now **per chunk**: a failed/mis-sized chunk blanks
only its own items instead of the whole batch. Kill-switch, `max_items`
tail-blanking, and id-alignment unchanged.

## Testing (TDD — all watched fail first)
- 25 items → exactly 3 calls of 10/10/5, id-aligned results
- Middle-chunk failure blanks only items 10–19
- Concurrency proven with a 3-way barrier (sequential execution would
deadlock)
- Configured chunk size respected (4/4/2)
- Full backend suite: 3663 passed, 139 env skips

## Review
- [x] CodeRabbit CLI: 0 findings

## After deploy
kjbox `refine_titles.py` can drop the `--batch-size 10` workaround
(default batch works).

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:48:54 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 f42e7321d2 fix(divebar): make 'Refresh catalog' reliably sync just-published tracks (Phase 4) (#867)
## Why

Clicking "Refresh catalog" (or the nightly-equivalent on demand)
advertised "trigger the GCS file sync now", but a just-published track
was indexed (searchable) yet **not byte-synced to GCS** until the next
nightly run. Verified 2026-07-02: the refresh fired all 3 divebar
scheduler jobs **concurrently**, but the file-sync VM only copies files
already in the BigQuery index — and it finished (~3 min) before the slow
index rebuild added the new rows. So the sync raced ahead of the index
and missed the new files.

## What

**Chain-on-completion, gated to the refresh path:**
- The index function (`divebar_mirror`) now, on a successful build,
triggers the index-dependent jobs itself — the file-sync VM + xref
rebuild — via `scheduler_v1.run_job`. This fires at the index's **actual
completion** (which outlasts the caller's HTTP timeout), so ordering is
guaranteed.
- The chain only fires when the request sets `chain_downstream`. A new
**refresh-only** scheduler job (`divebar-mirror-refresh`) carries that
flag in its body; the `refresh` action force-runs it instead of
`divebar-mirror-daily`.
- **The nightly pipeline is 100% untouched** — `divebar-mirror-daily` (2
AM) omits the flag, so it does not chain, and the standalone nightly
`divebar-sync-vm-daily` (3 AM) + `divebar-xref-rebuild-daily` (6 AM) run
once as before. No double-run; the nightly sync's safety net is
preserved.

## Files
- `functions/divebar_mirror/main.py`: `_wants_downstream_chain` +
`_trigger_downstream_jobs`, gated call, `GCP_REGION`.
- `functions/divebar_mirror/requirements.txt`: `google-cloud-scheduler`.
- `modules/divebar_mirror.py`: `GCP_REGION` env + new
`divebar-mirror-refresh` scheduler job (flag body, parked cron, run via
forceRun).
- `functions/divebar_lookup/main.py`: `refresh` triggers only
`divebar-mirror-refresh`.
- `__main__.py`: grant the mirror SA the existing
`divebarSchedulerRunner` role.

## Review
Local `feature-dev:code-reviewer`. It flagged (confidence 82) that an
earlier unconditional-chain version would double-run the nightly
sync/xref — fixed via the refresh-only flag+job above so the nightly
path is untouched.

## Testing
- `divebar_mirror/test_main.py`: downstream-trigger job paths,
partial-failure isolation, flag parsing (chains on flag, NOT on
absent/false).
- `divebar_lookup/test_main.py`: regression guard that refresh triggers
only `divebar-mirror-refresh` (never sync/xref/mirror-daily).

## Deploy
Infra-only. **Already applied to prod** via `pulumi up` (mirror+lookup
functions redeployed, `divebar-mirror-refresh` job created, mirror-SA
scheduler-runner grant). Verified the deployed job POSTs
`{"chain_downstream": true}` to the mirror function.

Phase 4 of the nomad-master fast-sync work. (Phase 1 shipped in #866.)

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 17:17:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a9700b7897 feat: fast-sync Nomad 720p masters to Divebar GCS mirror (Phase 1) (#866)
## Why

New Nomad releases upload to Google Drive at finalize time, but the
**Drive→GCS byte-sync VM only runs nightly (3 AM ET)**, and kjbox
mirrors that GCS folder to `/opt/nomad/downloads/NOMAD-720p/` every 5
min. So a release made during the day sat up to **~24h** before it could
reach kjbox. The "within minutes" expectation only ever held for the
GCS→kjbox hop; the Drive→GCS hop was the daily bottleneck.

Full diagnosis + phased plan:
`docs/archive/2026-07-02-nomad-master-fast-sync-plan.md`.

## What (Phase 1 — the push)

At finalize, push the 720p master **straight to GCS**
(`gs://nomadkaraoke-divebar-files/files/Nomad
Karaoke/MP4-720p/{brand_code} - {name}.mp4`) — the exact object the
nightly VM would produce — so kjbox's existing 5-min timer delivers it
within minutes. No kjbox change needed.

- **`backend/services/nomad_master_mirror.py`** (new):
`NomadMasterMirror.push_720p/delete_720p` + `is_nomad_public_brand`
gate.
- **`gdrive_service.upload_to_public_share`**: guarded
`_fast_sync_nomad_master` after the 720p Drive upload.
- **Config**: `DIVEBAR_FILES_BUCKET`, `NOMAD_MASTER_GCS_PREFIX`,
`NOMAD_MASTER_FAST_SYNC_ENABLED` (kill switch).
- **Infra**: grant `karaoke-backend` SA `objectAdmin` on the divebar
bucket. **Already applied to prod** via targeted `pulumi up` (update
#760).

## Guarantees

- **Idempotent** with the nightly VM (identical object name+size → its
additive rsync skips it); the VM stays the backfill safety net.
- **Nomad-brand only** — excludes `NOMADNP` private tracks and all other
brands/tenants.
- **Best-effort / non-fatal** — a push failure never breaks the
pipeline; it is surfaced as a `distribution_warnings` entry (drives the
admin alert) so it can't silently rot into "nightly-only".

## Testing

- New unit tests (`test_nomad_master_mirror.py`): gate matrix, exact GCS
object name, non-fatal on error, delete/404.
- `upload_to_public_share` integration tests: Nomad push happens with
correct name; non-Nomad/NOMADNP skipped; mirror failure non-fatal +
warning surfaced.
- Local: affected suites green (mirror, gdrive, distribution,
video_worker orchestrator). Full suite runs in CI.

## Scope / follow-ups

This is **Phase 1 of 4**. Follow-ups (separate PRs): Phase 2 gen
delete/replace on Nomad edit/delete; Phase 3 kjbox true-mirror so
deletes/renames reconcile onto the box; Phase 4 fix the "Refresh
catalog" button to run the divebar jobs sequentially (currently races
index vs sync).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 16:43:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 aecd73cb97 feat(api): POST /api/parse-karaoke-titles — batch karaoke-filename parser (#864)
## Summary
New admin endpoint **`POST /api/parse-karaoke-titles`** that turns messy
karaoke filenames into canonical `{artist, title, confidence}` using the
Vertex Gemini stack (reuses the match-judge client pattern). This is
**PR-A of the kjbox download-naming Phase 2** initiative — kjbox will
call it to canonicalise downloaded-file names (esp. fixing artist/title
order, e.g. KaraFun-reversed).

## Contract
- Request: `{items:[{id, filename, channel?, source?}]}`
- Response: `{results:[{id, artist, title, confidence}]}` — one
id-aligned result per input.
- Auth: `require_admin` (`X-Admin-Token`).

## Behaviour
- Batched single Gemini call (JSON response schema, temperature 0,
`location="global"`, Vertex — no API keys).
- **Never 500s on a model error:** kill-switch (`PARSE_TITLES_ENABLED`)
off, any model failure, or a batch length-mismatch → blank results
(`confidence: 0.0`). Fails closed if settings can't load. kjbox degrades
to its deterministic guess when this is unavailable.
- New settings: `parse_titles_enabled` / `_model` (gemini-3.5-flash) /
`_timeout_ms` (20s) / `_max_items` (200).

## Testing
- `backend/tests/test_parse_titles.py` (11 assertions: prompt build,
id-alignment, garbage-response, kill-switch, degrade-on-error, happy
path) + `test_parse_titles_route.py` (admin gate + happy path). All
green locally.

## Design
`kjbox/docs/archive/2026-06-30-download-naming-normalization-design.md`
§4; plan `2026-07-01-download-naming-p2-plan.md` (PR-A).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 00:45:54 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d1d7c50ad2 fix(divebar): retry transient download failures so a sync run drains to 0 (#865)
## Summary

Follow-up to #863. Marking dead links fixed the percentage *math*, but
the real reason the GCS mirror sat just under 100% turned out to be
**transient download failures** — a handful of network/5xx blips
scattered across the ~50k-file worklist (observed draining 217 → 37 → 6
→ 1 across successive runs, `marked_dead=0` throughout). Each was left
`NULL` and only cleared on a later night's run, so the KJ status %
hovered at 99.9% and only rounded to 100%.

This makes a **single** sync run reliably drain its worklist to zero.

## Change
`download_and_upload` now retries **transient** failures (5xx / network
/ timeout) up to **3 attempts with exponential backoff (2s, 4s)**. A
**404/410** (file gone from Drive) stays permanent and is returned
immediately **without** retrying (still marked `missing:drive_404`
upstream). After exhausting retries a transient failure returns `(False,
0, False)` — row stays `NULL`, retried next run. No unnecessary sleep
after the final attempt.

Net effect: the mirror lands on a solid **100% "Fully synced" (green)**
on its own each run, rather than depending on rounding.

## Testing
- +3 cases: transient retried-then-succeeds; transient exhausts attempts
→ stays retryable `NULL`; 404 not retried (`call_count == 1`). Autouse
fixture no-ops `time.sleep` so the suite stays fast. **11/11 pass.**
- Reviewed by local `code-reviewer` agent (CodeRabbit was rate-limited):
no issues ≥80 confidence; retry counting, backoff schedule, last-attempt
no-sleep, and 404-skip-retry all verified.

## Rollout
Deploys via the sync VM's `git pull origin main` on its next run (no
Pulumi, no restart).

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 00:29:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 2d186e8fb2 fix(divebar): mirror sync % reaches 100% (green) when fully caught up (#863)
## Summary

The KJ **Divebar Catalog Status** modal never reached a
fully-green/complete state — the GCS-mirror figure was pinned at **99.6%
synced** with a permanent "217 pending". Those 217 are Drive files that
now **404** (deleted/renamed since indexing); they sat at `gcs_path IS
NULL` forever, counted as "pending" *and* re-attempted every nightly
sync.

kjbox needs **no change** — its display already renders `>=95%` green
and `==100%` "Fully synced". The fix is entirely upstream in gen: make
"synced" mean *"everything that can be mirrored is"*.

## Changes

**`infrastructure/scripts/divebar_file_sync.py`**
- Classify download failures: a **404/410** (file gone from Drive) now
marks `gcs_path='missing:drive_404'` — a sentinel mirroring the existing
`skipped:too_large` — so it drops out of the `WHERE gcs_path IS NULL`
worklist (no more nightly re-attempts) and out of "pending".
**Transient** errors (5xx/network) still leave `gcs_path` NULL to retry.
- New **"unavailable"** tally in the run summary; progress-log cadence
and `get_sync_stats` updated to count only real `gs://` paths as synced.

**`infrastructure/functions/divebar_lookup/main.py`
(`_get_full_stats`)**
- `synced` = `COUNTIF(gcs_path LIKE 'gs://%')`; split out an
**`unavailable`** bucket (`missing:*`/`skipped:*`); `percent = synced /
(total - unavailable)`.
- A fully-caught-up mirror now reports **100%**. Payload also exposes
`unavailable`, `unavailable_gb`, `syncable_total` for transparent
display.

## Testing
- New `infrastructure/scripts/test_divebar_file_sync.py` (8 tests):
404/410-gone vs transient/5xx classification; each `sync_file` sentinel
path (dead-link, transient, success, too-large).
- +4 `_get_full_stats` percent cases in `divebar_lookup/test_main.py`
(100% when no pending; pending holds <100%; unavailable excluded from
denominator; zero-syncable guard). 23/23 pass.
- Stats SQL validated read-only against prod: `gcs_unavailable=1` today;
`percent → 100` once the sync marks the 217 dead links.
- CodeRabbit: 2 cycles → 0 findings.

## Rollout
- `divebar-lookup` deploys via `pulumi up` (run locally before merge).
- `divebar_file_sync.py` deploys via the sync VM's `git pull origin
main` on its next run; the first post-merge sync marks the 217 dead
links, after which the modal shows **100% "Fully synced" (green)**.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 23:47:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 107542ac39 fix(encoding): scope worker warmup/heartbeat to review-auth, not admin (#862)
## Summary

The lyrics-review page pre-warms the encoding VM on load (and heartbeats
while the reviewer edits) so it's booted by the time they preview a
render. Both endpoints — `POST /api/internal/encoding-worker/warmup` and
`/heartbeat` — required `require_admin` since they were introduced (Mar
25 2026, #595). So **every non-admin customer got a 403 and the JIT
pre-warm silently never fired**. Renders still completed (the encoding
flow's own `ensure_any_running()` boots the VM on demand), but customers
paid the full cold-boot latency the pre-warm was meant to hide. Reported
via 403s in the review-screen devtools console.

## Root cause

`require_admin` is an admin-only gate; the callers are ordinary
customers on a customer-facing page. Admin was the wrong altitude — the
rest of the review surface (`submitCorrections`, `handlers`,
annotations, audio-edit…) uses `require_review_auth`, which the review
page's token already satisfies.

## Fix

Re-scope both endpoints to `require_review_auth` with a `{job_id}` path
param:

- **Backend** (`encoding_worker.py`): `POST /warmup/{job_id}` and
`/heartbeat/{job_id}`, gated on `require_review_auth`. Warming the
shared VM now authorizes exactly like the review page's other calls, so
warmup/heartbeat succeed **precisely when** the review page works —
owners, admins (bypass), and `review_token` users included. Abuse
posture is unchanged: you can only warm the VM if you already have
review access to a real job.
- **Frontend** (`api.ts`, `LyricsAnalyzer.tsx`): thread `jobId` through
`warmupEncodingWorker`/`heartbeatEncodingWorker`, only fire in cloud
mode (`jobId` present — no cloud VM to warm in local mode).

## Changes

- `backend/api/routes/encoding_worker.py` — review-auth + `{job_id}`
path
- `frontend/lib/api.ts` — job-scoped URLs, `jobId` param + guard
- `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — pass `jobId`,
gate on it
- `backend/tests/test_encoding_worker_routes.py` — review-auth contract
+ regression guard that these routes are **not** admin-gated
- `docs/TROUBLESHOOTING.md` — note the auth change and 403 diagnosis
- `pyproject.toml` — 0.188.8 → 0.188.9

## Testing

- Backend: `test_encoding_worker_routes.py` (11) +
manager/persistence/system-status/retry (67 total) +
`test_api_routes.py` (17) — all green. New regression test asserts the
routes depend on `require_review_auth` and **never** `require_admin`,
plus 401-on-no-auth and 404-on-jobless-path.
- Frontend: `jest` lyrics-review + api (319) green; `tsc` clean on both
changed files.
- Prod verification to follow after deploy: open a review page as a
non-admin customer and confirm warmup/heartbeat return 200 (not 403).

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 22:25:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 8aa41e960c fix(lyrics-review): recompute segment times on Ctrl+click word delete (#861)
## Summary
- Ctrl+click "delete word" mode in the lyrics review Synchronizer
removed the word but left the **segment's** `start_time`/`end_time`
pointing at the deleted word — deleting the first word left the segment
starting too early; the last word left it ending too late.
- This diverged from the Edit-segment modal, which recomputes the
segment bounds on every word change. The two paths now behave
identically.

## Root cause
`deleteWord()` in
`frontend/lib/lyrics-review/utils/segmentOperations.ts` built the
updated segment with `{ ...segment, words, text }`, spreading the stale
`start_time`/`end_time` and never recomputing them from the remaining
words. The correct path (`EditModal.updateSegment`) filters the
remaining timed words and takes `Math.min`/`Math.max` (or `null` when
none remain). `LyricsAnalyzer.tsx:667` is the sole caller of
`deleteWord`.

## Changes
- `deleteWord` now recomputes `start_time`/`end_time` from the remaining
words (null when no timed words remain), mirroring
`EditModal.updateSegment`.
- Added 5 unit tests to `segmentOperations.test.ts`:
first/last/middle-word deletion, all-untimed remainder → null bounds,
and only-word deletion → whole segment removed.

## Testing
- [x] New `deleteWord` tests: red before fix, green after
- [x] Full `segmentOperations` suite: 11/11 pass
- [x] Full frontend jest suite: 82 suites / 1068 tests pass
- [x] `tsc --noEmit`: no new type errors in changed files

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

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 21:31:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 4fd9a85810 fix(custom-lyrics): don't 500 when a repair call returns an empty response (#860)
## Summary

Fixes the custom-lyrics **"NetworkError when attempting to fetch
resource"** failure (job `dc60ebf4`) and the recurring
**`custom_lyrics_repair_call_failed`** production alert (Count 2).

## Root cause
From prod logs, the flow for `dc60ebf4`:
1. Initial Gemini generation **succeeds** and validates (~2 min).
2. A **repair** iteration's response comes back with `response.text =
None` (safety block / MAX_TOKENS / empty candidate).
3. `_parse_lines(None)` → `TypeError: the JSON object must be str, bytes
or bytearray, not NoneType`.

That `TypeError`:
- was **re-raised by the repair loop** — throwing away the *successful
initial result*, and
- escaped as an **uncaught 500 with no CORS headers**, so the browser
(Firefox) showed an opaque `NetworkError` instead of any real message.

`api.nomadkaraoke.com` is direct Cloud Run (`server: Google Frontend`,
no Cloudflare, 1800s timeout), so this was **not** a proxy/latency
cutoff — the 500 itself was the failure.

## Fixes
- **`_call_gemini`**: treat `response.text = None` as a clean
`CustomLyricsServiceError(502)` with a diagnosable reason
(`prompt_block` / `finish_reason`). The endpoint already maps that to a
proper HTTP error **with CORS** — never a raw `TypeError`.
- **Repair loop**: a failed repair is best-effort → fall back to the
best candidate so far (new `StopReason.REPAIR_FAILED`) instead of
re-raising. The user gets their successful initial generation instead of
losing everything.
- **Log severity**: `custom_lyrics_repair_call_failed` downgraded from
`logger.exception` (ERROR) to `logger.warning` — now that it's
handled/non-fatal it shouldn't trip the error monitor; traceback
breadcrumb kept for diagnosing Gemini empties.

## Testing
- `test_repair_failure_falls_back_to_best` — initial succeeds, repair
raises → result is the initial lines, `stop_reason == REPAIR_FAILED`, no
exception.
- `test_empty_gemini_response_raises_clean_error` — `response.text=None`
→ `CustomLyricsServiceError(502)`, not `TypeError`.
- Full custom_lyrics suite green (60). CodeRabbit: 0 findings.

## Follow-up (not in this PR)
The initial Gemini call took ~2 min for this job — the end-to-end
latency (and the spinner UX during it) is a separate concern worth
optimizing (fewer repair iterations, faster model, or an async/polling
endpoint).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 18:38:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 37b405b9c6 fix: reject untimed lyrics before render + retry transient GDrive drops (#859)
## Summary

Triage + fix for a batch of Discord prod error alerts. Grouped into 3
root causes; fixed the two actionable ones.

### Group A — render/preview crash on untimed lyrics (PRIMARY,
job-breaking)
All the `unsupported format string passed to NoneType.__format__` and
`'<' not supported between instances of 'NoneType' and 'float'` alerts
were **one root cause**. Job `231806a4` ("Nelly Furtado - Maneater") had
Danish custom parody lyrics with **all 50 segments + 364 words
`start_time`/`end_time` = null** — the user pasted lyrics into the
Synchronizer's *Edit Lyrics* modal (which creates untimed segments as an
intermediate state) but never tap-synced, then triggered preview +
render. The output pipeline crashed cryptically at ~6 None-unsafe timing
sites instead of rejecting cleanly.

**Fix — fail loudly with an actionable message instead of crashing:**
- New shared gate `validate_segment_timing()` (`LyricsTimingError`) at
the top of `OutputGenerator.generate_outputs()` — covers preview + local
render + encoder.
- `render_video_worker` gates right after loading corrections,
**before** any expensive work or encoder dispatch — stops the
GCE-encoder crash *now*, without an encoder-wheel redeploy.
- Preview endpoint maps `LyricsTimingError` → **422** "synchronize
first" (was a cryptic 500).
- Defense-in-depth: `segment_resizer` debug logging is now None-safe (a
log line must never crash the pipeline).
- Frontend: block **Submit** when untimed words remain, pointing the
user to the synchronizer (`countUntimedWords` mirrors the backend gate).

### Group B — GDrive "brand_code search incomplete: N/3 subfolder(s)
failed"
Transient connection drops (`SSL: UNEXPECTED_EOF_WHILE_READING`, `Broken
pipe`) against idle Cloud Run containers. Wrapped the per-subfolder
Drive lookups in the existing retry-with-backoff + service-reset so
single drops self-heal.

### Group C — investigated, transient, no code change
- `request_audit_error` + "Exception in ASGI application" = one
Firestore *transaction-expiry* on
`/api/admin/rate-limits/blocklists/allowlisted-domains` (count 1,
admin-only).
- `Default STARTUP TCP probe failed … DEADLINE_EXCEEDED` = one slow cold
start that **succeeded on retry** at 12:10.

## Testing
- `test_timing_validation.py` (incl. all-null regression fixture
matching job 231806a4)
- None-safe resizer logging test
- GDrive transient-recovery + retry-exhaustion tests
- Frontend `countUntimedWords` Jest tests
- Re-ran output/, gdrive, render-worker, review-custom-lyrics,
generate_outputs-consumer suites — all green. CodeRabbit: 0 findings.

## Notes
- Frontend guard toast uses a plain string to match the existing
hardcoded toasts in `handleSubmitToServer` (no new i18n key → no locale
churn).
- Detail: `docs/archive/2026-07-01-render-untimed-lyrics-crash-plan.md`.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 16:54:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7655a2ea06 fix(divebar): repair nightly Drive→GCS sync scheduler (doubled URL + wrong token type) (#858)
## Summary

The `divebar-sync-vm-daily` Cloud Scheduler job — which starts the
`divebar-sync` GCE VM that copies community karaoke files **Drive → GCS
mirror** nightly — has never successfully started the VM. As a result
the byte sync silently stalled: the BigQuery index (`divebar_catalog`)
kept refreshing nightly, but **no new file bytes reached
`gs://nomadkaraoke-divebar-files`** since ~2026-05-16 (VM
`lastStartTimestamp` and newest GCS objects both 2026-05-16, ~6 weeks
stale).

Downstream impact: kjbox showed recent community/Nomad tracks as
"available from mirror" (index is fresh) but **fell back to YouTube on
download** because the bytes weren't in GCS. In the Nomad 720p folder
alone, 98 of 1,496 indexed releases (NOMAD-1406→1497) were missing from
GCS.

## Root cause — two bugs in the scheduler's `http_target`

1. **Doubled URL → HTTP 404 NOT_FOUND.** `instance.self_link` already
resolves to a full URL (`https://www.googleapis.com/compute/v1/...`);
the code prepended another compute host on top, producing
`.../compute/v1/https://www.googleapis.com/compute/v1/...`. Now the
`compute.instances.start` endpoint is built explicitly from
`PROJECT_ID`/`ZONE`/`name`.
2. **Wrong token type → HTTP 401 UNAUTHENTICATED** (masked by the 404
until #1 was fixed). `compute.googleapis.com` is a native Google API and
requires an **OAuth 2.0 access token** with `cloud-platform` scope, not
an OIDC identity token. Swapped `oidc_token` → `oauth_token`.

## Testing / deployment

Deployed to prod via **targeted** `pulumi up` (scheduler job resource
only — the other diffs in a full preview were non-reproducible
`FileArchive` re-hashes of unchanged function source, deliberately
excluded):

- Before: manual trigger → HTTP 404 (code 5), then HTTP 401 (code 2)
after the URL fix.
- After: manual trigger → **HTTP 200**, VM transitions to **RUNNING**,
startup script logs `=== Divebar file sync starting ===` and runs the
catch-up sync, then self-shuts-down.

No behavior change to any other resource; provider pin
(`pulumi-gcp==9.22.0`) held (269 unchanged).

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 16:06:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 eb711b32a8 fix(divebar): folder-brand-aware index parser + symmetric xref normalization (#857)
## Summary
- Rewrites the Divebar Drive→BigQuery **filename parser** to be
folder-brand-aware, fixing mis-split artists and brand-polluted titles
that prevented mirror files from surfacing in kjbox.
- Fixes a **normalization asymmetry** in the KN↔Divebar xref join (KN
side was only `LOWER(TRIM())` vs the db's fully-normalized columns) and
removes a buggy `brand_match` branch that produced wrong-song links.
- Switches both divebar Cloud Function modules to `pulumi.FileArchive`
so `pulumi up` actually redeploys changed code.

## Changes
- `divebar_mirror/filename_parser.py` — folder-brand-aware rewrite:
strip the brand token wherever it sits (disc-id prefix/suffix,
`(CODE)`/`CODE -` prefix, `[Brand]`/`(Brand)`/` - Brand` suffix, generic
karaoke tags), each strip gated on a folder-brand match so real song
text (`(Live)`, `(G)I-DLE`, bands like `UB40`/`311`/`ACDC`) survives.
Curated folder→KN-code map fills `brand_code`. En-dash separator +
leading-dash cleanup.
- `divebar_lookup/main.py` — new `_norm_sql(col)` routes **both** join
sides through one identical BigQuery expression replicating
`normalize_for_search`; `brand_match` branch removed (it matched
brand+artist with no title → Cartesian wrong-song links; 107,485/107,485
pairs were title mismatches in live data).
- `modules/divebar_mirror.py` + `modules/divebar_lookup.py` —
`FileArchive` + `BucketObject` with `generation` pinning (matches
`runner_manager`), so code changes redeploy.
- New `tests/unit/test_divebar_filename_parser.py` (48 cases) + 3
`_norm_sql` guard tests; version bump 0.188.3→0.188.4.

## Impact (validated read-only over all 50,046 live rows)
- null `brand_code`: 18,437 (37%) → **1,619 (3%)**
- Divebar files cross-referenced to a KN song: production **23,318** →
**33,449** on current data (+10,131 from the symmetry fix alone),
lifting toward ~38k after the parser re-index.

## Testing
- [x] 64 divebar unit tests pass locally (parser 48, index_builder 5,
divebar_lookup 11)
- [x] Offline validation harness over all 50k live rows (read-only
BigQuery); `_norm_sql` confirmed to reproduce `normalize_for_search`
exactly
- [ ] CI full suite

## Deploy / re-index (post-merge)
`pulumi up` redeploys both functions; then trigger scheduler
`divebar-mirror-daily` (re-parse → MERGE, preserves `gcs_path`) **then**
`divebar-xref-rebuild-daily`. Order matters. (`kn_data_sync` still uses
a static source object — future-edit redeploy trap, out of scope here.)

## Review
- [x] CodeRabbit CLI review completed locally (1 finding → fixed:
brand_match removal; cycle 2 clean)

@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-28 14:16:35 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ef65adedc7 feat: richer DRM-URL guidance + validate at 'Use this URL' (follow-up to #855) (#856)
## Summary

Follow-up to #855 (the Apple Music DRM-URL fix). Two improvements to how
we guide users who paste an undownloadable streaming link:

### 1. More downloader options + Google-search fallback
The DRM rejection now offers richer guidance:
- **Apple Music** → https://am-dl.pages.dev, https://aplmate.com
- **Spotify** → https://spotdown.org, https://spotmate.online
- **Everything else** (Tidal, Amazon Music, Deezer, Pandora) → a Google
search link for "`<platform> downloader`"

`_DRM_DOWNLOADER_SUGGESTIONS` now maps platform → list of URLs, and a
new `_drm_unsupported_detail()` helper picks `drmUrlUnsupportedWithLink`
(known tools) vs the new `drmUrlUnsupportedSearch` (web-search
fallback). `LinkifiedText` already renders multiple URLs as clickable
links, so no frontend change was needed for the message itself.

### 2. Validate at "Use this URL", not just final submit
Previously the guided flow collected the URL early but only surfaced the
DRM rejection at **final submit** — after the user walked the entire
flow. Now the "Use this URL" button calls a lightweight **`POST
/api/jobs/validate-url`** endpoint (reuses `_unsupported_url_platform` +
`_drm_unsupported_detail` — single source of truth, no duplicated
list/links/i18n), shows the guidance immediately with a "Checking…"
spinner, and blocks advancing. Fails open on network error since the
final submit still validates server-side.

## Review notes (CodeRabbit, local)
- Generalized Amazon Music host matching; `urlparse().hostname` for
robustness; locale-neutral comma join (not English "or").
- **Kept** the third-party downloader links by design — explicit product
decision (the third-party/link-rot risk is acknowledged;
`_DRM_DOWNLOADER_SUGGESTIONS` makes updates one-line).
- Disabled the URL input during validation to avoid a stale-result race.
- Skipped a suggested 400-handler in `validateJobUrl`: the endpoint
returns **200** with `{supported:false}`, not 400.

## Testing
- Backend: `TestUnsupportedDrmUrl`, `TestValidateJobUrlEndpoint` (+
existing) — `test_file_upload.py` 151 passed.
- Frontend: new `AudioSourceStep` interaction test (Apple Music URL
blocked at "Use this URL" with a clickable downloader link, no advance)
+ `LinkifiedText` tests — 32 passed; full job/ui suites green.

Details: `docs/archive/2026-06-27-apple-music-url-download-errors.md`

🤖 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-27 22:39:48 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 a213ec4d5d fix: reject DRM streaming URLs upfront + fix retry routing for failed URL downloads (#855)
## Summary

Investigated four simultaneous "New Error Pattern" alerts (Apple Music
`Unsupported URL` on `karaoke-backend`, plus `Failed to download audio
file` on `audio-separation-job` and `lyrics-transcription-job`). All
four were **one incident**: a user tried to make a karaoke track from an
Apple Music link (job `7f36304a`), submitted it twice, and clicked
**Retry** once. That exposed two real bugs, both fixed here.

### Bug A — DRM streaming URLs accepted, then fail deep with a cryptic
error
`_validate_url` had an allowlist but fell through to `return True` for
everything ("let yt-dlp try"). Apple Music / Spotify / Tidal / Amazon
Music / Deezer / Pandora are DRM-protected and can never download, so a
job got created and died at the download stage with an HTTP 500 +
"Unsupported URL".

**Fix:** new `_unsupported_url_platform()` helper + the
`create-from-url` endpoint now returns a friendly **400**
(`audioSearch.drmUrlUnsupported`, all 33 locales) before a job is
created. YouTube Music (`music.youtube.com`) is deliberately **not**
blocked — it's downloadable. Amazon Music matched generically
(`music.amazon.*`) to cover all country domains.

### Bug B — retrying a URL job that failed *before download* fires the
wrong workers
The retry "restart from beginning" branch was gated on
`job.input_media_gcs_path or job.url`. A URL job whose download never
succeeded still has `job.url` set but **no** audio in GCS, so Retry
jumped straight to the audio/lyrics workers → "Failed to download audio
file" → Cloud Run retried them (the ×6/×6 alert counts) → wasted GPU.
Latent for any URL-download failure, not just Apple Music.

**Fix:** the branch is now gated on `job.input_media_gcs_path` only. URL
jobs without downloaded audio fall through to the existing clean
**"resubmit"** 400 instead of firing doomed workers — matching the
endpoint's documented intent.

## Timeline (job `7f36304a`)

| Time (UTC) | Event |
|---|---|
| 20:23:02 | Job created from Apple Music URL |
| 20:23:07 | flacfetch → `Unsupported URL` → job failed, HTTP 500 |
| 20:23:31 | User clicks Retry → fires audio + lyrics workers (no audio
in GCS) |
| 20:24–20:28 | Workers fail repeatedly via Cloud Run retries → ×6/×6 |

## Testing

- `TestUnsupportedDrmUrl` — detection across all DRM platforms (+
subdomains, + Amazon country domains); YouTube/YouTube
Music/Vimeo/SoundCloud/generic/None not flagged.
- `TestRetryUrlJobWithoutDownload` — URL job without audio → 400
resubmit + **no** workers scheduled; URL job with audio in GCS →
restarts + workers scheduled.
- Full `test_file_upload.py` + `test_routes_jobs.py`: 217 passed (no
regressions).

Details: `docs/archive/2026-06-27-apple-music-url-download-errors.md`

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

@coderabbitai ignore

---

### Follow-up (same PR): actionable suggestion + clickable links

Rather than just "paste a YouTube link", the DRM rejection now suggests
**downloading the audio with a third-party tool, then uploading the
file**. For platforms with a verified downloader
(`_DRM_DOWNLOADER_SUGGESTIONS`) it links to it — **Apple Music →
https://am-dl.pages.dev** (`drmUrlUnsupportedWithLink`). URLs in
submit-error messages are now clickable via a new `LinkifiedText`
component (guided flow + URL-tab error). `LinkifiedText` has unit tests;
all backend tests still pass (218).

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 17:34:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b5e3f39d83 fix(bulk): detect community versions for overlong song titles (#854)
## Problem

In Bulk Mode (By album), ABBA's **"I Do, I Do, I Do, I Do, I Do"**
showed **no community versions** even though two exist on KaraokeNerds
(Nomad Karaoke + RUE ABBA Karaoke). Tracks with no detected community
version are **ticked by default**, so the user would have generated a
**duplicate of an existing community karaoke video**.

## Root cause

Not the commas, and not our title-matching — it's a limit in
**karaokenerds.com's own search**: it silently returns **zero results
once a query exceeds ~10 whitespace-separated terms** (verified against
the live site: 10 terms match, 11 return nothing, regardless of word
order).

`check_community_versions` searches `"{artist} {title}"`. For this track
that's 11 terms → 0 results → falsely reported as "no community
version".

| Query | Terms | Live result |
|---|---|---|
| `ABBA I Do I Do I Do I Do` | 9 | ✅ 2 songs |
| `I Do I Do I Do I Do I Do` (title alone) | 10 | ✅ 2 songs |
| `ABBA I Do, I Do, I Do, I Do, I Do` (what bulk sends) | 11 | ❌ 0 songs
|

## Fix

In `backend/services/karaokenerds_service.py`:
- Extracted `_search_songs(query)` and `_extract_community_songs(songs)`
helpers.
- When the combined `"{artist} {title}"` query **exceeds
`MAX_RELIABLE_QUERY_TERMS` (10)** *and* returns nothing, retry with
**title-only** (the highest-signal term), then keep only results whose
artist matches via `normalize_for_match` (reused from
`match_judge.classifier`) — guarding against same-titled songs by other
artists.
- **Gated on query length**, so short songs and genuine no-community
songs incur **zero extra requests** (KaraokeNerds rate-limiting matters
in bulk).

Verified through the real code path: the ABBA track now returns
`has_community: True` with both brands; short songs are unchanged.

**Known residual limit:** a title that *alone* exceeds 10 words still
chokes — inherent to KaraokeNerds' search, not handled here.

## Tests

4 regression tests (mock `_search_songs`): overlong→title-only fallback,
wrong-artist false-positive guard, short-query-no-fallback,
non-empty-skips-fallback. 48 passed across `test_karaokenerds_service`,
`test_bulk_album_lookup`, `test_bulk_search_worker`, `test_bulk_submit`,
`test_catalog_routes`, `test_match_judge_routes`. CodeRabbit: 0
findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 12:44:57 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 2ff5e4b49f feat(bulk): collapse editions to tracklist variants + clickable community versions (#852)
## Summary
Improves Bulk Mode's "By album" UX in two ways (live-MusicBrainz, no
mirror dependency):

**1. Edition selection → tracklist variants (A+C).** The release
dropdown was ~17 rows of the same album pressed in different countries.
Since the selection only feeds a list of track *names*, we now collapse
a release-group's editions into a few distinct **tracklist variants**
(Option 1: grouped by track count — zero extra MB calls, dodges the
egress rate-limiter) and show a single confident default — *"Using
Original · 1976 · 10 tracks"* — with a **Change** disclosure (hidden
entirely when there's one variant). **Track numbers** are now rendered.
Representative pressing is locale-biased (`next-intl` locale → country
preference), wiring the hook the future mirror upgrade will lean on.

**2. Community versions → vertical, clickable.** The wide inline
`Community version: A, B, C` is replaced by a vertical list, each row a
**clickable YouTube link** so the user can preview a version and decide
whether to remake it. We simply stopped discarding the `youtube_url` the
scraper already captured. Shared by album and text modes.

## Changes
- **Backend** — `musicbrainz_service.build_variants()` +
`country_prefs_for_locale()`; `karaokenerds_service` batch returns
`versions:[{brand,url}]` (back-compat `brands` kept); `bulk.py`
models/routes gain `variants`, `selected_variant_mbid`, per-track
`versions`, and a `locale` param.
- **Frontend** — new `CommunityVersions` component (replaces
`AvailabilityBadge`); `BulkAlbumMode` C-pattern picker + track numbers;
types updated.
- **i18n** — 6 new `bulk` keys translated to all 32 locales.
- **Docs** — `API.md` bulk endpoints updated.

## Testing
- Backend: new unit tests for variant grouping, locale prefs, versions
dedup, and route plumbing; full bulk/MB/KN/catalog suites green (62
passing across touched + regression files).
- Frontend: `community-versions.test.tsx` (link href/target/rel,
fallback, hidden states); `tsc` clean on all touched files.
- Post-deploy: API-level prod verification of
`/api/bulk/album/tracklist` (variants + versions present).

## Notes
- The larger mirror-backed upgrade (exact tracklist-signature grouping +
popularity ranking) is captured in
`docs/archive/2026-06-18-musicbrainz-mirror-and-album-ux-handoff.md`;
this PR is the cheap live-MB version.
- Design:
`docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md`.

🤖 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-22 18:44:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3b5fd07ba0 docs: archive PyPI 10GB storage-limit fix retrospective (#853)
## Summary

Archives a detailed retrospective of the 2026-06-22 PyPI 10 GB
storage-limit fix (shipped in #851), so future sessions can refer back
if it recurs.

Covers:
- **Symptom & diagnosis** — `poetry publish` 400ing at the 10 GB cap;
measured 10.711 GB / 444 releases
- **Root cause** — i18n's 33-locale static export bundled in wheel+sdist
since v0.172.1 (Apr 2026)
- **The two-part fix** — one-time web-UI deletion of 42 fat releases
(~4.35 GB freed) + wheel-only publish (104→54 MB/release)
- **How to bulk-delete PyPI releases** (no API; the
CSRF/`confirm_delete_version` web-UI technique) and the
Fastly-cached-JSON verification gotcha
- **Why `exclude` can't trim the sdist** while `out/` is git-tracked
- **Recurrence runbook**

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-22 22:34:49 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 bfa375639b ci: publish wheel-only to PyPI (fix 10 GB storage cap) (#851)
## Problem

Every `poetry publish` on merge to `main` was failing with:

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

The PyPI project had grown to **10.711 GB across 444 releases**, over
the 10 GB cap.

## Root cause

Since the i18n initiative (**v0.172.1, 2026-04-23**), `next build`
pre-renders the app into **33 locale directories** (~112 MB
uncompressed), and both the wheel **and** the sdist bundle this static
export. Per-release cost jumped from ~18 MB to ~104 MB (53.7 MB wheel +
50.2 MB sdist). 57 fat releases = >5.8 GB of the 10.7 GB total.

## Fix (this PR): publish wheel-only

The sdist is dead weight — we ship a universal `py3-none-any` wheel, pip
always installs from it, and nothing builds karaoke-gen from source (the
GCE encoding worker pulls the wheel from GCS, not PyPI).

- `poetry build --format wheel` in both the package-test and
package-publish jobs (no sdist built)
- drop `dist/*.tar.gz` from the GitHub release attachments
- bump `0.187.4 → 0.187.5`

**Per-release PyPI cost: 104 MB → 54 MB.** The wheel is unchanged — it
still bundles the frontend the CLI local-review server reads at runtime
(verified: built wheel contains all 3575 `out/` entries + entry points).

## Companion one-time cleanup (already done, not in this diff)

Deleted **42 old fat releases** (`0.172.1`–`0.182.2`, ~4.35 GB) via the
PyPI web UI, keeping the 15 most recent fat releases
(`0.183.0`–`0.187.2`) and all 387 small historical releases
(`≤0.171.x`). Project is now **~6.36 GB** (3.64 GB headroom). Nothing
internal pins old PyPI versions, so blast radius was zero.

## Testing

- `poetry build --format wheel` → `dist/` contains only the 53.7 MB
wheel (no tar.gz), wheel has all `out/` assets + 3 console entry points.
- `ci.yml` validated (parses, no remaining sdist/tar.gz dependencies).
- No application code changed; full suite runs in CI on this PR.
- The merge itself is the live verification that `poetry publish`
succeeds (publishes 0.187.5 wheel-only).

@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-22 18:16:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ec41ad5e5e feat: colorize word pills when a song has no reference lyrics (#850)
## Summary
- When a song has **no reference lyrics**, nothing classifies words as
anchor/gap/corrected, so every word pill rendered uncoloured — losing
the colour-scanning the review UI is built around (see attached
screenshot: every line plain grey).
- Adds a lowest-precedence **gap-orange** fallback for plain word pills,
gated on "no reference lyrics" (the same
`Object.keys(reference_lyrics).length === 0` signal `GuidancePanel` uses
for its "No reference lyrics found" panel).
- Works in **both Simple and Advanced** modes — threaded through the
single `wordPositions` render path both modes share.

## Changes
- `lib/lyrics-review/types.ts` — new `fallbackGapColor?: boolean` on
`WordProps`.
- `components/lyrics-review/shared/Word.tsx` — appends the fallback to
the end of the colour chain, so any real classification colour
(playing/AI/anchor/user-edited/corrected/gap) still wins.
- `components/lyrics-review/shared/HighlightedText.tsx` — new
`noReferenceFallback` prop, passed down as `fallbackGapColor` to both
`WordComponent` render paths.
- `components/lyrics-review/TranscriptionView.tsx` — computes
`hasReferenceLyrics` and passes
`noReferenceFallback={!hasReferenceLyrics}`.
- `components/lyrics-review/shared/__tests__/Word.test.tsx` — new
focused test (5 cases) verifying the orange appears only with the
fallback flag and never overrides a real classification colour.
- No new user-facing strings → no i18n changes.

## Testing
- [x] Frontend unit suite: 79 suites / 1049 tests pass (incl. new
`Word.test.tsx`)
- [x] Typecheck clean on all touched files
- [x] CodeRabbit CLI review: 0 findings

## Review
- [x] Local CodeRabbit review completed
- [x] No issues to address

@coderabbitai ignore

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

https://claude.ai/code/session_01E8pq3aMDRkcPdrsmd1PqHH

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 11:31:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 354f60b59d fix(lyrics-review): pad long-word duration pill in Simple mode (#849)
## Summary

Adds a little breathing room between a word and its long-word duration
pill in the Simple-mode lyrics review, so the amber `🕐 3.3s` badge isn't
squashed up against the word text.

## The bug

The duration badge uses `ml-auto` to hug the right edge in
Advanced/Timeline mode. But `ml-auto` only consumes free space — in
Simple mode the pill is content-sized, so `ml-auto` resolved to `0` and
the badge sat flush against the word. The badge's own `pl-1`/`px-1` only
pad *inside* the amber border, not between the word and the pill.

## The fix

Add `gap-1` (4px) to the outer flex container, applied only to long-word
pills (`hasDurationBadge`):

```diff
- hasDurationBadge ? 'inline-flex items-center' : 'inline-block',
+ hasDurationBadge ? 'inline-flex items-center gap-1' : 'inline-block',
```

- Plain words (no badge) are untouched — they use `inline-block`.
- Timeline/Advanced mode unaffected: `ml-auto` still hugs the badge to
the right edge; the gap is just a minimum.

## Before / After

Before: `now🕐3.3s` (badge flush against "now")
After: `now 🕐3.3s` (4px gap)

## Testing

- All 142 lyrics-review unit tests pass (17 suites).
- No snapshots reference this component, so the class change breaks
nothing.
- CodeRabbit: 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 19:44:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d5edaab7d2 feat(bulk): compact Single/Bulk toggle in card header (#848)
Moves the Single/Bulk switch from a full-width two-button tab (which
wasted vertical space for the ~majority who never bulk-submit) into a
subtle segmented control in the top-right of the Create Karaoke Video
card header. Content switches via state. Frontend-only.

🤖 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-18 18:07:55 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 7d21260438 fix(bulk): diagnose + harden MusicBrainz lookups failing in prod (#847)
Album-mode MusicBrainz lookups return 502 from Cloud Run (they work
locally + in unit tests). Prod logs show an empty exception message, so
this PR:

- Adds `%r` + `exc_info=True` to the 3 MB route handlers to capture the
real exception type + traceback in prod.
- Adds retry-with-backoff (3×) to `musicbrainz_service._get` for MB 503s
(rate-limiting) and transient transport/timeout errors — the most common
cloud-egress failure mode.

Text mode + the credit gate are already verified working in prod; album
lookup degrades gracefully to a 502 + frontend fallback. Once deployed,
the logs will reveal the true cause and we can apply the targeted fix
(e.g. route MB through flacfetch if it's a hard IP block).

Tests: 2 new retry unit tests (503→retry→success; exhaust→raise). Full
MB suite green.

🤖 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-18 17:14:16 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 4f411c4306 feat(lyrics-review): auto-apply corrections + timeline-in-text Advanced view (#846)
## Summary

Reworks the lyrics review UX now that AI auto-corrections are reliable,
and replaces the separate Timeline view with timing intelligence baked
into the lyrics themselves.

### Auto-correct display
- **Auto-apply on load** (= the old "Accept all") as the review
**baseline** — not an undoable edit — so no save/restore prompt appears
unless you make a genuine manual edit.
- Corrected words render **purple** with a grey struck-through "original
transcription" bubble above; words whose timing was **estimated** (a
word split into several, or inserted) get an **amber dashed underline**,
while clean 1:1 replacements stay solid.
- The standing suggestions row is gone — the toolbar button reads
**"Auto-corrected · N"** and opens a details panel on demand (per-item
**undo**, **Re-run**, **Revert all auto-corrections**).
- Guidance panel: purple/amber legend + a "play each corrected line and
re-check timing" tip. Tooltips say "auto-corrected by our system" (no
"AI").

### Timeline rework (replaces the Timeline view)
- Single **Simple / Advanced** toggle replaces both the Text/Timeline
toggle and the old Simple/Advanced badge; `DurationTimelineView`
deleted.
- Inline **>2s long-word** (badge inside the pill, right-aligned) and
**>2s inter-word gap** warnings, in both modes.
- **Advanced** mode stretches each word pill by its duration (flex) so a
segment fills the full width as a readable timeline; gap spacers are
**click-to-play** (hover shows a play icon).

### Session restore unification
- Removed the ad-hoc `window.confirm` localStorage path. The same
`SessionRestoreDialog` is now used everywhere — server-backed in cloud
mode, and a new **localStorage session store** when running karaoke-gen
locally.

### Other
- `crash-reporter`: never POST client errors from a localhost origin
(was tripping the prod error monitor during local dev).
- New `Word` provenance fields + apply-time stamping.

## Testing
- Frontend unit suite: **1034/1034 pass** (new tests for apply-time
stamping, the local session store, and the localhost-skip guard).
- `tsc --noEmit`: no new errors; ESLint: 0 errors.
- All **33 locales** translated and verified complete (1415 keys each).
- Iterated and verified live in a local frontend against the prod
backend across several real jobs (auto-apply, purple/bubbles/markers,
Advanced timeline, gap-click-to-play, clean fresh-load with no restore
prompt).
- Reviewed with CodeRabbit; findings addressed.

Design doc: `docs/archive/2026-06-18-autocorrect-applied-ux-design.md`

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 13:05:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 feca70674b feat: Bulk Mode — submit up to 100 karaoke jobs at once (album or text) (#845)
## Bulk Mode — submit up to 100 karaoke jobs at once

Adds a **Bulk Mode** tab to the job-submission flow so users can make
karaoke versions of a whole album (or a typed list) in one go.

### Two ways in
- **By album** — MusicBrainz artist → album → tracklist.
Live/remix/bonus tracks and songs that already have a community version
on KaraokeNerds start **unticked** (re-tick anything). Auto-picks the
canonical edition, with an edition switcher.
- **By text** — up to 100 artist/title rows, each with a
community-version availability badge.

### Auto + review-queue model
Batch settings (auto-pick lossless / public-private / skip audio edit /
skip customization) drive auto-completion. The server runs each audio
search and **auto-selects only a confident lossless ("tier 1") match**;
everything else is parked in the existing `AWAITING_AUDIO_SELECTION`
state and surfaced as a review queue (reusing the existing
`AudioSearchDialog`). A popular full-FLAC album with all toggles on =
zero further prompts; the tab can be closed (searches run as a Cloud Run
Job).

### Credits
Gated upfront: requires `credits >= number_of_songs` (1/song minimum)
before any job is created; admins bypass. Duration deltas for long
tracks are charged per-song during processing as today.

### Backend
- `POST /api/bulk/submit`, `GET /api/bulk/{batch_id}`, `GET
/api/bulk/album/{artists,albums,tracklist}`, `POST
/api/bulk/availability`
- `bulk_search_worker` Cloud Run Job (`infrastructure/`:
`bulk-search-job`) — search → tier-1 auto-select (with duration-delta
charge) or park; per-job crash isolation; idempotent on retry
(charge_pending guard prevents double-charge)
- New `musicbrainz_service` (release lookup + extras detection); reuses
existing `karaokenerds_service` scraper (batch helper) for availability
— **no karaoke-decide change** (it has the `is_community` flag matching
"community-created"; see design doc)
- `pick_auto_selection` ports the frontend tier-1 confidence rule to the
backend (parity test)

### Frontend
- `components/job/bulk/*` (album/text modes, batch settings, submit bar,
batch progress + review queue); api client + types; 33-locale i18n

### Testing
- 40 new backend tests (foundations, MusicBrainz, lookup routes, submit
credit gate, search worker auto/park + credit math, progress) + frontend
Jest for the default-selection and credit-gate helpers
- Safe production E2E smoke
(`frontend/e2e/production/bulk-mode.spec.ts`) — read-only lookups + gate
rejection, does not spawn real jobs
- Full backend suite green (3588 passed); frontend typechecks clean (no
new errors)

### Deploy notes
- **Requires `pulumi up`** to create the `bulk-search-job` Cloud Run Job
before submit works in prod.
- Design + plan: `docs/archive/2026-06-18-bulk-mode-design.md`,
`-plan.md`

Docs: `docs/API.md` § Bulk Mode, `docs/LESSONS-LEARNED.md`.

🤖 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-18 16:18:02 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 715c796bfb fix(dr): correct backup freshness monitor limit + scheduler deadline (weekly-S3 Firestore regressions) (#844)
## Summary

Fixes two DR-backup alerting regressions introduced by PR #823 (Jun-14
cost reduction), which switched the Firestore S3 upload from **nightly →
weekly (Sundays)** to cut cross-cloud egress. Both surfaced as Discord
alerts on 2026-06-17/18; backups themselves were never actually broken.

### 1. False "🚨 DR backup is stale" alert (fires every Tue–Sat)
The off-platform freshness monitor (`dr-backup-freshness.yml`) checks
the **S3** copy of `firestore/` against a **36h** limit — set back when
Firestore uploaded to S3 nightly. Since #823, Firestore ships to S3 only
weekly (like BigQuery, which correctly uses 192h), so the S3 copy is
>36h old from Tuesday onward **by design**.

Monitor run history confirms: 06-14 Sun ✅ → 06-15 Mon ✅ (~34h) → 06-16
Tue ❌ → 06-17 Wed ❌, repeating weekly.

**Fix:** Firestore limit `36h → 192h` (≈8 days), matching its actual
weekly off-site cadence. The nightly GCS-staging export (1-day local
restore point) is unaffected.

### 2. Spurious "Path already exists" FAILED backup report
Cloud Scheduler had no `attempt_deadline` (default **180s**), but the
Firestore export runs for minutes. Scheduler timed out the HTTP call and
retried (`retry_count=2`) while the original invocation kept running to
success; the retry then collided on the already-created
`firestore/<date>/` export path → `400 Path already exists`.

**Fix:** set `attempt_deadline="1800s"` (Cloud Scheduler max) and align
the Cloud **Function** `timeout_seconds` 3600 → 1800, so the function
can't outrun the scheduler's wait and reopen the same collision window
(per CodeRabbit).

Also refreshes `docs/DISASTER-RECOVERY.md`: Firestore off-site RPO is 7
days (S3) / 24h local (GCS), and the freshness-monitor section now
documents the per-prefix S3 cadence so this can't regress again.

## Changes
- `.github/workflows/dr-backup-freshness.yml` — Firestore freshness
limit 36h → 192h + explanatory comment
- `infrastructure/modules/backup.py` — scheduler
`attempt_deadline="1800s"`; function `timeout_seconds` 3600 → 1800
- `docs/DISASTER-RECOVERY.md` — RPO table + freshness-monitor cadence
docs

## Testing
- Backup function unit tests: 13 passed (no function code changed)
- YAML + embedded-Python + Pulumi module all validate/compile
- CodeRabbit: 0 findings (1 major fixed: function/scheduler timeout
mismatch)
- **`pulumi up` applied to prod** (clean diff: 2 updated, 265
unchanged). Verified live: scheduler `attemptDeadline=1800s`, function
`timeoutSeconds=1800`. Merging keeps IaC in sync (CI re-applies as
no-op).

Infra/CI + docs only; no application code (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-18 02:33:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 23ebee4657 fix(backfill): correct date filter, private-track path, and folder guard (#843)
## Summary
Follow-up to #842. Operational correctness fixes to
`backend/scripts/backfill_original_audio.py`, found while running the
original-audio backfill against production (**344 jobs restored, 0
errors**). As merged, the script silently did nothing and would have
mis-routed private tracks.

## Changes
- **Date filter:** `created_at` is stored as an ISO **string** in
Firestore, so the server-side `created_after`/`created_before` datetime
filters matched nothing ("Considering 0 jobs"). Now fetches completed
jobs (ordered desc) and filters the date window in Python; default fetch
limit raised to 5000 to bound the lookback.
- **Private-track path:** uses `get_effective_distribution_for_job()`
for the Dropbox path, so private (`NOMADNP`) tracks resolve to the
**NonPublished** path instead of the job's stored public `dropbox_path`
(was skipping 130+ private tracks as "folder missing").
- **Folder guard:** only uploads into a track folder that **already
exists** (new `skip-folder-missing`), so drifted brand/artist/title
naming can't create an orphan folder with a lone FLAC.
- **Env filter:** filters environment in Python (avoids needing a
3-field composite Firestore index); `--env` now defaults to none (test
jobs skip naturally — no brand/Dropbox folder).
- **Resilience:** per-job planning errors are counted, not fatal.

## Testing
- [x] 8 planner unit tests pass (`test_backfill_original_audio.py`),
incl. new `skip-folder-missing` case
- [x] Proven end-to-end in production: 344 original-audio files restored
to the correct public/private Dropbox folders, idempotent re-run
confirmed (already-present skipped, transient errors retried clean)

## Review
- [x] Validated by actually executing against prod; script-only change,
no runtime/service impact

@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 20:47:36 -04:00
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
243 changed files with 17708 additions and 1333 deletions

No files matched your search

+10 -3
View File
@@ -516,7 +516,10 @@ jobs:
virtualenvs-in-project: true
- name: Build package
run: poetry build
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
run: poetry build --format wheel
- name: Test package installation
run: |
@@ -831,7 +834,12 @@ jobs:
venv-package-${{ runner.os }}-py3.13-
- name: Build package
run: poetry build
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
# dead weight and pushed the project over PyPI's 10 GB storage cap.
# pip always installs from the wheel; nothing builds karaoke-gen from
# source (the GCE encoding worker pulls the wheel from GCS).
run: poetry build --format wheel
- name: Upload build artifacts
uses: actions/upload-artifact@v4
@@ -925,7 +933,6 @@ jobs:
prerelease: false
files: |
dist/*.whl
dist/*.tar.gz
deploy-frontend:
name: "Deploy - Frontend (Cloudflare Pages)"
+7 -1
View File
@@ -54,8 +54,14 @@ jobs:
BUCKET = os.environ["BUCKET"]
# (label, prefix, max_age_hours)
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
# sees the S3 (off-site) copy, so their limits must allow a full week
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
TARGETS = [
("Firestore", "firestore/", 36),
("Firestore", "firestore/", 192),
("GCS job files", "gcs/job-files/", 36),
("Encrypted secrets", "secrets/", 36),
("BigQuery weekly", "bigquery/daily-refresh/", 192),
+39 -11
View File
@@ -34,10 +34,12 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
- name: Setup Node.js
uses: actions/setup-node@v4
with:
python-version: '3.11'
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Authenticate to GCP
uses: google-github-actions/auth@v2
@@ -46,15 +48,38 @@ jobs:
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Install dependencies
run: pip install google-cloud-storage google-cloud-secret-manager
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Run tenant E2E
id: run_test
env:
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps chromium
- name: Fetch test audio (private GCS)
run: bash scripts/e2e/fetch_test_audio.sh frontend/e2e/fixtures
- name: Ensure testmail.app domain is allowlisted (rate limit)
run: |
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Run tenant E2E (frontend journey)
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TENANT_ID: ${{ matrix.tenant }}
TENANT_PORTAL_URL: https://${{ matrix.tenant }}.nomadkaraoke.com
run: |
echo "=== Tenant E2E (frontend): ${{ matrix.tenant }} ==="
npx playwright test tenant-happy-path.spec.ts \
--config=playwright.production.config.ts --project=chromium \
--reporter=list --timeout=2400000 2>&1 | tee e2e-output.log
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
@@ -63,7 +88,10 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
path: e2e-output.log
path: |
frontend/e2e-output.log
frontend/test-results/
frontend/playwright-report/
retention-days: 14
- name: Discord notification (failure)
+6
View File
@@ -1709,6 +1709,12 @@ async def delete_job_outputs(
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
results["gdrive"] = {"status": "error", "error": str(e)}
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too (prefix-keyed
# by brand_code, covers renames). Non-fatal, Nomad-only, no-op otherwise.
if brand_code:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
# Clean up GCS finals folder - prevents stale files from being picked up during re-encoding
try:
from backend.services.storage_service import StorageService
+476
View File
@@ -0,0 +1,476 @@
"""Bulk Mode API routes.
Lets a user submit up to 100 karaoke jobs at once, by text (artist/title rows)
or by album (MusicBrainz release lookup). Album tracklists and text rows are
enriched with KaraokeNerds community-version availability so the user can skip
tracks that already exist.
Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
(added in later phases).
"""
import logging
import uuid
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
from backend.api.dependencies import require_auth
from backend.services.auth_service import AuthResult
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/bulk", tags=["bulk"])
MAX_BULK_SONGS = 100
# --- Models -----------------------------------------------------------------
class BulkArtist(BaseModel):
mbid: Optional[str] = None
name: str
disambiguation: str = ""
type: Optional[str] = None
country: Optional[str] = None
class BulkAlbum(BaseModel):
release_group_mbid: str
title: str
primary_type: Optional[str] = None
secondary_types: list[str] = []
first_release_date: str = ""
is_studio: bool = True
class BulkEdition(BaseModel):
release_mbid: str
title: Optional[str] = None
status: Optional[str] = None
date: str = ""
country: Optional[str] = None
track_count: int = 0
class BulkEditionVariant(BaseModel):
"""A distinct tracklist variant (country pressings collapsed by track count)."""
representative_release_mbid: str
label: Literal["Original", "Reissue"] = "Original"
track_count: int = 0
year: str = ""
pressing_count: int = 0
delta_vs_original: int = 0
class CommunityVersion(BaseModel):
"""An existing community karaoke version the user can preview on YouTube."""
brand: str
url: str
class BulkTrack(BaseModel):
position: Optional[int] = None
title: str
recording_mbid: Optional[str] = None
length_ms: Optional[int] = None
is_extra: bool = False
extra_reason: str = ""
# Availability (filled from KaraokeNerds); available=True => already exists
available: bool = False
brands: list[str] = []
versions: list[CommunityVersion] = []
class BulkTracklistResponse(BaseModel):
release_mbid: Optional[str] = None
canonical_release_mbid: Optional[str] = None
selected_variant_mbid: Optional[str] = None
title: Optional[str] = None
date: str = ""
tracks: list[BulkTrack] = []
editions: list[BulkEdition] = []
variants: list[BulkEditionVariant] = []
class AvailabilityItem(BaseModel):
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
class AvailabilityRequest(BaseModel):
tracks: list[AvailabilityItem]
class AvailabilityResult(BaseModel):
artist: str
title: str
available: bool
brands: list[str] = []
brand_count: int = 0
versions: list[CommunityVersion] = []
class AvailabilityResponse(BaseModel):
results: list[AvailabilityResult]
# --- Album lookup routes ----------------------------------------------------
@router.get("/album/artists", response_model=list[BulkArtist])
async def album_artists(
request: Request,
q: str = Query(..., min_length=2, description="Artist name search"),
limit: int = Query(8, ge=1, le=25),
auth_result: AuthResult = Depends(require_auth),
):
"""Search MusicBrainz for artists (album-mode step 1)."""
from backend.services.musicbrainz_service import get_musicbrainz_service
try:
results = await get_musicbrainz_service().search_artists(q, limit=limit)
except Exception as e: # noqa: BLE001
logger.warning("MusicBrainz artist search failed: %r", e, exc_info=True)
raise HTTPException(status_code=502, detail="Artist lookup is temporarily unavailable")
return results
@router.get("/album/albums", response_model=list[BulkAlbum])
async def album_albums(
request: Request,
artist_mbid: str = Query(..., min_length=1),
auth_result: AuthResult = Depends(require_auth),
):
"""List an artist's albums (release-groups) for the album picker."""
from backend.services.musicbrainz_service import get_musicbrainz_service
try:
return await get_musicbrainz_service().get_albums(artist_mbid)
except Exception as e: # noqa: BLE001
logger.warning("MusicBrainz album list failed: %r", e, exc_info=True)
raise HTTPException(status_code=502, detail="Album lookup is temporarily unavailable")
@router.get("/album/tracklist", response_model=BulkTracklistResponse)
async def album_tracklist(
request: Request,
artist: str = Query(..., min_length=1, description="Artist name for availability checks"),
release_group_mbid: Optional[str] = Query(None),
release_mbid: Optional[str] = Query(None, description="Specific edition to load"),
locale: Optional[str] = Query(None, description="UI locale → biases representative-pressing choice"),
auth_result: AuthResult = Depends(require_auth),
):
"""Resolve an album's canonical tracklist (or a specific edition) and enrich
each track with KaraokeNerds community-version availability.
Response shape note: ``variants`` is only populated on the ``release_group_mbid``
path (the initial album load). When loading a specific edition via
``release_mbid`` it is intentionally ``[]`` — the client already holds the
variant list from the initial load and only needs the chosen edition's tracks.
"""
from backend.services.musicbrainz_service import (
get_musicbrainz_service,
country_prefs_for_locale,
)
from backend.services.karaokenerds_service import check_community_versions_batch
if not release_group_mbid and not release_mbid:
raise HTTPException(status_code=422, detail="release_group_mbid or release_mbid required")
mb = get_musicbrainz_service()
try:
if release_mbid:
# Loading a specific variant — variants already known to the client.
tracklist = await mb.get_release_tracklist(release_mbid)
tracklist.setdefault("editions", [])
tracklist.setdefault("canonical_release_mbid", release_mbid)
tracklist.setdefault("variants", [])
tracklist.setdefault("selected_variant_mbid", release_mbid)
else:
tracklist = await mb.get_album_tracklist(
release_group_mbid, preferred_countries=country_prefs_for_locale(locale)
)
except Exception as e: # noqa: BLE001
logger.warning("MusicBrainz tracklist failed: %r", e, exc_info=True)
raise HTTPException(status_code=502, detail="Tracklist lookup is temporarily unavailable")
tracks = tracklist.get("tracks", [])
# Availability enrichment — never fatal.
try:
avail = await check_community_versions_batch(
[{"artist": artist, "title": t["title"]} for t in tracks]
)
for t, a in zip(tracks, avail):
t["available"] = a["available"]
t["brands"] = a["brands"]
t["versions"] = a.get("versions", [])
except Exception as e: # noqa: BLE001
logger.warning("Availability enrichment failed (non-fatal): %s", e)
return BulkTracklistResponse(
release_mbid=tracklist.get("release_mbid"),
canonical_release_mbid=tracklist.get("canonical_release_mbid"),
selected_variant_mbid=tracklist.get("selected_variant_mbid"),
title=tracklist.get("title"),
date=tracklist.get("date", ""),
tracks=[BulkTrack(**t) for t in tracks],
editions=[BulkEdition(**e) for e in tracklist.get("editions", [])],
variants=[BulkEditionVariant(**v) for v in tracklist.get("variants", [])],
)
@router.post("/availability", response_model=AvailabilityResponse)
async def bulk_availability(
request: Request,
body: AvailabilityRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""Batch KaraokeNerds availability check for text-mode rows."""
from backend.services.karaokenerds_service import check_community_versions_batch
if len(body.tracks) > MAX_BULK_SONGS:
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} tracks per request")
results = await check_community_versions_batch(
[{"artist": t.artist, "title": t.title} for t in body.tracks]
)
return AvailabilityResponse(results=[AvailabilityResult(**r) for r in results])
# --- Submission -------------------------------------------------------------
class BulkSong(BaseModel):
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
display_artist: Optional[str] = None
display_title: Optional[str] = None
class BulkSettings(BaseModel):
auto_select_if_lossless: bool = True
is_private: bool = False
skip_audio_edit: bool = True
skip_customization: bool = True
class BulkSubmitRequest(BaseModel):
songs: list[BulkSong]
settings: BulkSettings = Field(default_factory=BulkSettings)
class BulkSubmitResponse(BaseModel):
batch_id: str
job_ids: list[str]
total: int
@router.post("/submit", response_model=BulkSubmitResponse)
async def bulk_submit(
request: Request,
body: BulkSubmitRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""Create one job per song, gate on credits upfront, and dispatch the batch
search worker. Jobs start parked (auto_download=False) and the worker either
auto-selects a confident lossless match or leaves them awaiting selection."""
from backend.config import get_settings
from backend.exceptions import InsufficientCreditsError
from backend.models.job import JobCreate
from backend.services.job_manager import JobManager
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
from backend.services.theme_service import get_theme_service
from backend.services.worker_service import get_worker_service
n = len(body.songs)
if n == 0:
raise HTTPException(status_code=422, detail="At least one song is required")
if n > MAX_BULK_SONGS:
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} songs per batch")
user_email = auth_result.user_email
is_admin = bool(auth_result.is_admin)
# Upfront credit gate (1 credit/song minimum). Admins bypass.
if not is_admin and user_email:
from backend.services.user_service import get_user_service
available = get_user_service().check_credits(user_email)
if available < n:
raise HTTPException(
status_code=402,
detail={
"error": "insufficient_credits",
"message": "You don't have enough credits for this batch.",
"credits_available": available,
"credits_required": n,
},
)
settings = get_settings()
theme_service = get_theme_service()
theme_id = theme_service.get_default_theme_id()
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
batch_id = uuid.uuid4().hex[:12]
bulk_settings = body.settings.model_dump()
job_manager = JobManager()
job_ids: list[str] = []
for song in body.songs:
display_artist = (song.display_artist or song.artist).strip()
display_title = (song.display_title or song.title).strip()
request_metadata = {
"created_from": "bulk",
"batch_id": batch_id,
"user_email": user_email,
}
job_create = JobCreate(
artist=display_artist,
title=display_title,
theme_id=theme_id,
enable_cdg=resolved_cdg,
enable_txt=resolved_txt,
user_email=user_email,
audio_search_artist=song.artist.strip(),
audio_search_title=song.title.strip(),
auto_download=False,
is_private=body.settings.is_private,
brand_prefix=settings.default_brand_prefix,
enable_youtube_upload=settings.default_enable_youtube_upload,
youtube_description=settings.default_youtube_description,
discord_webhook_url=settings.default_discord_webhook_url,
dropbox_path=settings.default_dropbox_path,
gdrive_folder_id=settings.default_gdrive_folder_id,
request_metadata=request_metadata,
)
try:
job = job_manager.create_job(job_create, is_admin=is_admin)
except InsufficientCreditsError:
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
# already-created jobs are valid and will proceed.
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
break
job_manager.update_job(
job.job_id,
{
"state_data.batch_id": batch_id,
"state_data.bulk_settings": bulk_settings,
"state_data.bulk_pending_search": True,
},
)
job_ids.append(job.job_id)
if not job_ids:
raise HTTPException(status_code=402, detail="No jobs could be created")
# Dispatch the batch search worker. Retry once on transient failure. If it
# still fails the jobs exist (and are charged) but won't process, so surface
# an explicit error with the batch_id — and tell the user NOT to resubmit
# (that would create+charge a second batch); the batch can be re-dispatched.
worker_service = get_worker_service()
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
if not triggered:
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
if not triggered:
logger.critical(
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
batch_id, len(job_ids),
)
raise HTTPException(
status_code=503,
detail={
"error": "dispatch_failed",
"message": "Your batch was created but processing couldn't start. "
"Please don't resubmit — contact support with this batch ID and we'll start it.",
"batch_id": batch_id,
"job_ids": job_ids,
},
)
logger.info("[batch:%s] created %d jobs, dispatched bulk-search worker", batch_id, len(job_ids))
return BulkSubmitResponse(batch_id=batch_id, job_ids=job_ids, total=len(job_ids))
# --- Progress ---------------------------------------------------------------
class BulkJobStatus(BaseModel):
job_id: str
artist: str
title: str
status: str
auto_selected: bool = False
class BulkBatchResponse(BaseModel):
batch_id: str
total: int
counts: dict
jobs: list[BulkJobStatus]
# Status -> progress bucket for the batch summary.
_AWAITING = "awaiting_audio_selection"
_TERMINAL_OK = "complete"
_TERMINAL_FAIL = "failed"
_SEARCHING = {"pending", "searching_audio"}
def _bucket(status: str, pending_search: bool) -> str:
if pending_search or status in _SEARCHING:
return "searching"
if status == _AWAITING:
return "awaiting_selection"
if status == _TERMINAL_OK:
return "complete"
if status == _TERMINAL_FAIL:
return "failed"
return "processing"
@router.get("/{batch_id}", response_model=BulkBatchResponse)
async def bulk_batch(
request: Request,
batch_id: str,
auth_result: AuthResult = Depends(require_auth),
):
"""Progress summary for a batch: counts by bucket + per-job status."""
from backend.services.job_manager import JobManager
job_manager = JobManager()
jobs = job_manager.list_jobs_by_batch_id(batch_id)
if not bool(auth_result.is_admin):
email = (auth_result.user_email or "").lower()
jobs = [j for j in jobs if (j.user_email or "").lower() == email]
if not jobs:
raise HTTPException(status_code=404, detail="Batch not found")
counts = {"searching": 0, "awaiting_selection": 0, "processing": 0, "complete": 0, "failed": 0}
job_statuses: list[BulkJobStatus] = []
for j in jobs:
status = j.status.value if hasattr(j.status, "value") else str(j.status)
sd = j.state_data or {}
bucket = _bucket(status, bool(sd.get("bulk_pending_search")))
counts[bucket] += 1
job_statuses.append(
BulkJobStatus(
job_id=j.job_id,
artist=j.audio_search_artist or j.artist or "",
title=j.audio_search_title or j.title or "",
status=status,
auto_selected=bool(sd.get("bulk_auto_selected")),
)
)
return BulkBatchResponse(
batch_id=batch_id, total=len(jobs), counts=counts, jobs=job_statuses
)
+27 -9
View File
@@ -2,13 +2,21 @@
Encoding worker lifecycle endpoints.
Provides warmup and heartbeat endpoints for the blue-green
encoding worker VMs. Called by the frontend to ensure the
primary VM is running before encoding requests.
encoding worker VMs. Called by the lyrics-review frontend to ensure the
primary VM is running before the reviewer previews a render.
Auth: these are gated on ``require_review_auth`` (review access to a specific
job), NOT ``require_admin``. The callers are ordinary customers on the
lyrics-review page — gating on admin makes every non-admin caller 403, which
silently defeats the JIT pre-warm. Scoping to the job being reviewed keeps the
abuse posture identical to the rest of the review surface: you can only warm
the shared encoding VM if you already have review access to a real job.
"""
import logging
from typing import Tuple
from fastapi import APIRouter, Depends
from backend.api.dependencies import require_admin
from backend.api.dependencies import require_review_auth
from backend.services.encoding_worker_manager import EncodingWorkerManager
from backend.services.encoding_errors import EncodingWorkerStartError
@@ -36,12 +44,17 @@ def get_worker_manager():
return _manager
@router.post("/warmup")
@router.post("/warmup/{job_id}")
async def warmup_encoding_worker(
_admin=Depends(require_admin),
job_id: str,
_auth: Tuple[str, str] = Depends(require_review_auth),
manager=Depends(get_worker_manager),
):
"""Start the primary encoding worker VM if it's stopped."""
"""Start the primary encoding worker VM if it's stopped.
Called on lyrics-review page load so the VM is warm by the time the
reviewer previews a render. ``job_id`` scopes auth to the job under review.
"""
try:
result = manager.ensure_primary_running()
if result["started"]:
@@ -64,12 +77,17 @@ async def warmup_encoding_worker(
return {"started": False, "error": str(e)}
@router.post("/heartbeat")
@router.post("/heartbeat/{job_id}")
async def heartbeat_encoding_worker(
_admin=Depends(require_admin),
job_id: str,
_auth: Tuple[str, str] = Depends(require_review_auth),
manager=Depends(get_worker_manager),
):
"""Update activity timestamp to prevent idle shutdown."""
"""Update activity timestamp to prevent idle shutdown.
Called periodically while the reviewer works. ``job_id`` scopes auth to the
job under review.
"""
try:
manager.update_activity()
return {"status": "ok"}
+141 -1
View File
@@ -1581,11 +1581,140 @@ def _validate_url(url: Optional[str]) -> bool:
for supported in supported_domains:
if domain == supported or domain.endswith('.' + supported):
return True
# For other URLs, let yt-dlp try (it supports many more sites)
return True
# Streaming services whose catalogue is DRM-protected and therefore cannot be
# downloaded by yt-dlp / flacfetch. Submitting one of these only creates a job
# that fails deep in the download stage with a cryptic "Unsupported URL" error
# (and lets the user trigger a futile retry), so we reject them at submission
# time with a clear, actionable message. Maps host -> friendly platform name;
# matching is suffix-based, so e.g. "spotify.com" also covers open./play.
_UNSUPPORTED_DRM_HOSTS = {
'music.apple.com': 'Apple Music',
'itunes.apple.com': 'Apple Music',
'spotify.com': 'Spotify',
'tidal.com': 'Tidal',
'deezer.com': 'Deezer',
'pandora.com': 'Pandora',
}
# Third-party tools that can download audio from a DRM platform, which the user
# can then upload to us. Listed where we know of working options; platforms
# without an entry fall back to a web-search link for "<platform> downloader".
_DRM_DOWNLOADER_SUGGESTIONS = {
'Apple Music': ['https://am-dl.pages.dev', 'https://aplmate.com'],
'Spotify': ['https://spotdown.org', 'https://spotmate.online'],
}
def _drm_unsupported_detail(locale: str, platform: str) -> str:
"""
Build the user-facing 400 message for a rejected DRM streaming URL.
Platforms with known downloader tools get a "download from {tools}, then
upload" message linking each tool; everything else gets a "search the web
for a '<platform> downloader'" message linking a Google search. Either way
the goal is to guide the user to obtain the audio and upload it themselves.
"""
downloaders = _DRM_DOWNLOADER_SUGGESTIONS.get(platform)
if downloaders:
# Join with commas (locale-neutral) rather than an English "or"; the
# message wording frames them as options and LinkifiedText makes each
# URL clickable in the frontend.
return t(
locale, "audioSearch.drmUrlUnsupportedWithLink",
platform=platform, downloader=", ".join(downloaders),
)
from urllib.parse import quote_plus
search_url = "https://www.google.com/search?q=" + quote_plus(f"{platform} downloader")
return t(
locale, "audioSearch.drmUrlUnsupportedSearch",
platform=platform, searchUrl=search_url,
)
def _unsupported_url_platform(url: Optional[str]) -> Optional[str]:
"""
Return a friendly platform name if the URL belongs to a known DRM-protected
streaming service that cannot be downloaded, else None.
These links (Apple Music, Spotify, Tidal, Amazon Music, Deezer, Pandora) are
rejected at submission time instead of being allowed to create a job that
always fails deep in the download stage. Note: YouTube Music
(music.youtube.com) is downloadable and is deliberately NOT included.
"""
if not url or not isinstance(url, str):
return None
from urllib.parse import urlparse
try:
# .hostname is already lowercased and strips userinfo, port, and IPv6
# brackets, so it's safer than parsing .netloc by hand.
domain = (urlparse(url).hostname or "").lower()
except (ValueError, TypeError):
return None
if not domain:
return None
# Normalise leading www.
if domain.startswith('www.'):
domain = domain[4:]
for host, platform in _UNSUPPORTED_DRM_HOSTS.items():
if domain == host or domain.endswith('.' + host):
return platform
# Amazon Music spans many country domains (music.amazon.com, .co.uk, .co.jp,
# .fr, .de, ...), so match the music.amazon.* prefix generically.
if domain == 'music.amazon' or domain.startswith('music.amazon.'):
return 'Amazon Music'
return None
class ValidateUrlRequest(BaseModel):
"""Request to pre-validate a URL before submitting a job."""
url: str = Field(..., description="The URL the user intends to submit")
class ValidateUrlResponse(BaseModel):
"""Whether a URL can be used for a job, with a friendly reason if not."""
supported: bool
detail: Optional[str] = None
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
async def validate_job_url(
request: Request,
body: ValidateUrlRequest,
auth_result: AuthResult = Depends(require_auth),
) -> ValidateUrlResponse:
"""
Lightweight pre-flight check for a job URL, used by the guided submission
flow so unsupported links are caught at the "Use this URL" step instead of
only at final submit. Mirrors the URL validation in create_job_from_url.
"""
locale = get_locale_from_request(request)
platform = _unsupported_url_platform(body.url)
if platform:
return ValidateUrlResponse(
supported=False, detail=_drm_unsupported_detail(locale, platform)
)
if not _validate_url(body.url):
return ValidateUrlResponse(
supported=False,
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL.",
)
return ValidateUrlResponse(supported=True)
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
async def create_job_from_url(
request: Request,
@@ -1619,6 +1748,17 @@ async def create_job_from_url(
)
try:
# Reject DRM-protected streaming links upfront (Apple Music, Spotify,
# Tidal, etc.). These can never be downloaded, so creating a job would
# only fail deep in the pipeline with a cryptic error and tempt the user
# into a futile retry storm.
unsupported_platform = _unsupported_url_platform(body.url)
if unsupported_platform:
raise HTTPException(
status_code=400,
detail=_drm_unsupported_detail(locale, unsupported_platform),
)
# Validate URL
if not _validate_url(body.url):
raise HTTPException(
+27 -3
View File
@@ -396,6 +396,11 @@ async def edit_completed_track(
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
# Also remove the Nomad 720p master from the GCS fast-sync mirror
# (prefix-keyed by brand_code, so it covers renames). Non-fatal,
# Nomad-brand only, no-op otherwise.
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
else:
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
except Exception as e:
@@ -576,6 +581,8 @@ _SUMMARY_STATE_DATA_KEYS = {
'pending_additional_credits',
'duration_actual_seconds',
'duration_confirm_reason',
'batch_id',
'bulk_auto_selected',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
@@ -1980,9 +1987,18 @@ async def retry_job(
"retry_stage": "screens_generation"
}
# If we have input audio (uploaded or from URL), restart from beginning
elif job.input_media_gcs_path or job.url:
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
# If the input audio is already in GCS (an uploaded file, or a URL whose
# download succeeded), restart from beginning — the audio/lyrics workers
# re-fetch it from GCS.
#
# A URL job whose download never succeeded has only `job.url` and NO
# audio in GCS, so it must NOT take this branch: triggering the workers
# would just fail with "Failed to download audio file" and Cloud Run
# would retry them repeatedly (see job 7f36304a — an Apple Music link).
# Such jobs fall through to the "resubmit" refusal below, since there is
# no worker that re-downloads a generic URL.
elif job.input_media_gcs_path:
logger.info(f"Job {job_id}: Has input audio in GCS, restarting from beginning")
# Clear error state and any partial progress
job_manager.update_job(job_id, {
@@ -2271,6 +2287,14 @@ async def cleanup_distribution(
"status": "skipped",
"reason": "no files found to delete",
}
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too, so a
# re-finalise (incl. artist/title rename) doesn't leave the old cut on
# kjbox. Prefix-keyed by brand_code (covers renames); the subsequent
# re-run's push re-adds the new master. Non-fatal, Nomad-only.
if brand_code:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
else:
results["gdrive"] = {
"status": "failed",
+52
View File
@@ -0,0 +1,52 @@
"""POST /api/parse-karaoke-titles — batch karaoke-filename → artist/title.
Internal admin endpoint used by kjbox to canonicalise downloaded-file names.
Reuses the Vertex Gemini parser; never blocks the caller (kjbox degrades to a
deterministic guess when this is unavailable).
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult
from backend.services.parse_titles import parse_titles
logger = logging.getLogger(__name__)
router = APIRouter(tags=["parse-titles"])
class ParseItem(BaseModel):
id: str
filename: str
channel: Optional[str] = None
source: Optional[str] = None
class ParseRequest(BaseModel):
items: list[ParseItem]
class ParseResult(BaseModel):
id: str
artist: str
title: str
confidence: float
class ParseResponse(BaseModel):
results: list[ParseResult]
@router.post("/parse-karaoke-titles", response_model=ParseResponse)
async def parse_karaoke_titles(
body: ParseRequest,
auth_result: AuthResult = Depends(require_admin),
):
items = [i.model_dump() for i in body.items]
results = await parse_titles(items)
logger.info("parse-karaoke-titles: %d items", len(items))
return {"results": results}
+8
View File
@@ -185,6 +185,7 @@ def _synthesized_segments(target_lines: list[str]) -> list[dict]:
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.output.timing_validation import LyricsTimingError
# Import from the unified style loader
from karaoke_gen.style_loader import load_styles_from_gcs
@@ -1226,6 +1227,13 @@ async def generate_preview_video(
return {"status": "success", "preview_hash": preview_hash}
except LyricsTimingError as timing_err:
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
# user-fixable input problem, not a server fault. Return 422 with an
# actionable message instead of a cryptic 500.
logger.warning(f"Job {job_id}: Preview blocked — lyrics not synchronized: {timing_err}")
span.set_attribute("error", "lyrics_not_synchronized")
raise HTTPException(status_code=422, detail=str(timing_err)) from timing_err
except Exception as e:
logger.error(f"Job {job_id}: Failed to generate preview video: {e}", exc_info=True)
span.set_attribute("error", str(e))
+26
View File
@@ -481,6 +481,32 @@ async def verify_magic_link(
)
class MagicLinkStatusResponse(BaseModel):
status: str # "valid" | "used" | "expired" | "invalid"
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
async def magic_link_status(
token: str,
user_service: UserService = Depends(get_user_service),
):
"""
Read-only status of a magic link — does NOT consume it.
The verify page calls this on load so it can show the correct UI upfront:
the "Complete Sign-In" gate for a valid link, or an "already used / expired"
message for a dead one — without making the user click only to then fail.
This endpoint is intentionally non-mutating so that an email link-scanner
which renders the verify page (and triggers this read) cannot burn a still-
valid token before the real user clicks. Token consumption happens only in
the separate GET /auth/verify, which requires an explicit user click.
"""
if not token or not token.strip():
return MagicLinkStatusResponse(status="invalid")
return MagicLinkStatusResponse(status=user_service.get_magic_link_status(token))
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
async def resend_magic_link_from_token(
request: ResendFromTokenRequest,
+24
View File
@@ -20,6 +20,17 @@ class Settings(BaseSettings):
gcs_temp_bucket: str = os.getenv("GCS_TEMP_BUCKET", "karaoke-gen-temp")
gcs_output_bucket: str = os.getenv("GCS_OUTPUT_BUCKET", "karaoke-gen-outputs")
firestore_collection: str = os.getenv("FIRESTORE_COLLECTION", "jobs")
# Nomad master fast-sync: push freshly-published Nomad 720p masters straight to the
# Divebar GCS mirror so kjbox (which mirrors that folder every 5 min) picks them up
# within minutes instead of waiting for the nightly Drive->GCS VM. Nomad-brand only.
divebar_files_bucket: str = os.getenv("DIVEBAR_FILES_BUCKET", "nomadkaraoke-divebar-files")
nomad_master_gcs_prefix: str = os.getenv("NOMAD_MASTER_GCS_PREFIX", "files/Nomad Karaoke/MP4-720p")
nomad_master_fast_sync_enabled: bool = os.getenv("NOMAD_MASTER_FAST_SYNC_ENABLED", "true").lower() == "true"
# Original-vocals guide: a padded isolated-vocals file (silence[intro] + vocals) pushed to
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
# Audio Separator API (for GPU processing)
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
@@ -117,6 +128,19 @@ class Settings(BaseSettings):
# 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"))
# Batch karaoke-filename parser (kjbox download-naming). Reuses the Vertex
# Gemini stack. Larger timeout than match_judge because it batches ~200 items.
parse_titles_enabled: bool = os.getenv("PARSE_TITLES_ENABLED", "true").lower() in (
"1", "true", "yes",
)
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.5-flash")
parse_titles_timeout_ms: int = int(os.getenv("PARSE_TITLES_TIMEOUT_MS", "20000"))
parse_titles_max_items: int = int(os.getenv("PARSE_TITLES_MAX_ITEMS", "200"))
# Items per Gemini call: large client batches are split into concurrent
# chunks of this size so one call never outgrows parse_titles_timeout_ms
# (a 100-item single call did, blanking the whole batch).
parse_titles_chunk_size: int = int(os.getenv("PARSE_TITLES_CHUNK_SIZE", "10"))
# 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)
+3 -1
View File
@@ -10,7 +10,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
from backend.services.spacy_preloader import preload_spacy_model
@@ -187,6 +187,8 @@ app.include_router(admin.router, prefix="/api") # Admin dashboard and managemen
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
app.include_router(push.router, prefix="/api") # Push notification subscription management
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename parser
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
+1
View File
@@ -0,0 +1 @@
"""Operational and maintenance scripts for the karaoke-gen backend."""
+199
View File
@@ -0,0 +1,199 @@
#!/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-folder-missing"`` — the track's Dropbox folder doesn't exist (detail=folder)
- ``"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
from backend.services.job_defaults_service import get_effective_distribution_for_job
state = getattr(job, "state_data", None) or {}
brand_code = state.get("brand_code")
# Use the EFFECTIVE dropbox path — private (NOMADNP) tracks upload to the
# NonPublished path, not the job's stored (public) dropbox_path. This mirrors
# what the orchestrator does at distribution time.
dropbox_path = get_effective_distribution_for_job(job).dropbox_path
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}"
# Only backfill into a track folder that already exists — never create a new
# folder (guards against drifted brand/artist/title naming producing an orphan).
if not dropbox.file_exists(folder):
return ("skip-folder-missing", folder)
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
# NOTE: created_at is stored as an ISO string in Firestore, so server-side
# created_after/created_before datetime filters match nothing. We fetch the most
# recent completed jobs (ordered by created_at desc) and filter dates in Python.
# `limit` therefore bounds how far back we look — set it high enough to cover the
# window since `since`.
jobs = jm.list_jobs(status=JobStatus.COMPLETE, limit=limit)
def _created(j):
c = getattr(j, "created_at", None)
if c is None:
return None
return c.replace(tzinfo=None) if getattr(c, "tzinfo", None) else c
since_naive = since.replace(tzinfo=None)
until_naive = until.replace(tzinfo=None) if until else None
def _in_window(j):
c = _created(j)
if c is None:
return False
if c < since_naive:
return False
if until_naive and c >= until_naive:
return False
return True
jobs = [j for j in jobs if _in_window(j)]
if environment:
def _env(j):
rm = getattr(j, "request_metadata", None)
if rm is None:
return None
return rm.get("environment") if isinstance(rm, dict) else getattr(rm, "environment", None)
jobs = [j for j in jobs if _env(j) == environment]
logger.info(
"Considering %d completed jobs since %s (env=%s, fetch limit=%d)",
len(jobs), since.date(), environment or "all", limit,
)
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=5000,
help="Max completed jobs to fetch (most-recent first). Bounds how far "
"back the date window can reach.")
parser.add_argument("--env", default=None, dest="environment",
help="Filter to a request environment (e.g. production). Default: all "
"(test jobs are skipped anyway — no brand code / Dropbox folder).")
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()
+147 -1
View File
@@ -18,7 +18,8 @@ downloads since Cloud Run doesn't support BitTorrent peer connections.
import asyncio
import logging
import os
from typing import List, Optional
import re
from typing import Any, Dict, List, Optional
import nest_asyncio
@@ -47,6 +48,151 @@ AudioSearchError = AudioFetcherError
AudioDownloadResult = AudioFetchResult
# ---------------------------------------------------------------------------
# Bulk Mode: tier-1 auto-selection.
#
# This is a faithful port of the frontend confidence-tier logic in
# frontend/lib/audio-search-utils.ts (categorizeResult / getBestResult /
# checkFilenameMismatch / getSearchConfidence). It operates on the dicts
# produced by AudioSearchResult.to_dict() (keys: is_lossless, quality_data,
# seeders, provider, release_type, target_file, title, index).
#
# MAINTENANCE SEAM: if the frontend tier rule changes, update both. The
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
# ---------------------------------------------------------------------------
_BEST_RESULT_PRIORITY = [
"BEST CHOICE",
"STUDIO ALBUMS",
"HI-RES 24-BIT",
"SINGLES",
"COMPILATIONS",
"SPOTIFY",
"YOUTUBE",
"OTHER",
]
def _categorize_result(result: Dict[str, Any]) -> str:
"""Port of categorizeResult() from audio-search-utils.ts."""
is_lossless = result.get("is_lossless") is True
quality_data = result.get("quality_data") or {}
is_24bit = quality_data.get("bit_depth") == 24
seeders = result.get("seeders") or 0
provider = (result.get("provider") or "").lower()
release_type = (result.get("release_type") or "").lower()
media = (quality_data.get("media") or "").lower()
if provider == "spotify":
return "SPOTIFY"
if provider == "youtube" or not is_lossless:
return "YOUTUBE"
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
if is_lossless and media == "vinyl":
return "VINYL RIPS"
if is_lossless and seeders >= 50:
return "BEST CHOICE"
if is_lossless and is_24bit:
return "HI-RES 24-BIT"
if is_lossless and (
release_type == "live album" or release_type == "bootleg" or "live" in release_type
):
return "LIVE VERSIONS"
if is_lossless and release_type in ("compilation", "soundtrack", "anthology"):
return "COMPILATIONS"
if is_lossless and release_type in ("single", "ep"):
return "SINGLES"
if is_lossless and (release_type == "album" or not release_type):
return "STUDIO ALBUMS"
return "OTHER"
def _get_best_result(results: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
"""Port of getBestResult() — highest-priority category, skipping vinyl."""
if not results:
return None
best: Optional[Dict[str, Any]] = None
best_priority = float("inf")
for result in results:
category = _categorize_result(result)
if category == "VINYL RIPS":
continue
try:
priority = _BEST_RESULT_PRIORITY.index(category)
except ValueError:
priority = float("inf")
if priority < best_priority:
best = result
best_priority = priority
elif priority == best_priority and best is not None:
if (result.get("seeders") or 0) > (best.get("seeders") or 0):
best = result
return best if best is not None else results[0]
def _check_filename_mismatch(search_title: str, result: Dict[str, Any]) -> bool:
"""Port of checkFilenameMismatch() — True if the file is clearly another track."""
if len(search_title) < 3:
return False
target_file = result.get("target_file")
if target_file:
raw_filename = target_file.split("/")[-1] or target_file
without_ext = re.sub(r"\.[^.]+$", "", raw_filename)
filename = re.sub(r"^\d{1,3}\s*[-.\s]\s*", "", without_ext)
elif result.get("title"):
filename = result["title"]
else:
return False
def normalize(s: str) -> str:
s = s.lower()
s = re.sub(r"[_\-.]+", " ", s)
s = re.sub(r"[^a-z0-9\s]", "", s)
s = re.sub(r"\s+", " ", s)
return s.strip()
norm_title = normalize(search_title)
norm_file = normalize(filename)
if not norm_file or not norm_title:
return False
# Stricter than the frontend's substring check (intentional — for the bulk
# AUTO-select path we'd rather park an uncertain match than auto-pick the
# wrong track). A match requires every title word to appear as a whole word
# in the filename, so "One" no longer matches "Someone".
title_tokens = [t for t in norm_title.split() if t]
file_tokens = set(norm_file.split())
if not title_tokens:
return False
matches = all(tok in file_tokens for tok in title_tokens)
return not matches
def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -> Optional[int]:
"""Return the index to auto-select, or None if no confident lossless pick.
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
must match ``search_title`` (the song the user searched for). Otherwise we
defer to human selection.
"""
if not results:
return None
# Require a usable title before auto-selecting: a blank/too-short title can't
# be verified against the filename, so defer to human selection.
if len((search_title or "").strip()) < 3:
return None
best = _get_best_result(results)
if best is None:
return None
if _categorize_result(best) != "BEST CHOICE":
return None
if _check_filename_mismatch(search_title, best):
return None
return best.get("index")
class AudioSearchService:
"""
Service for searching and downloading audio files.
+103 -7
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
import logging
import os
import time
import uuid
from dataclasses import asdict, dataclass, field
@@ -35,9 +36,63 @@ VALID_CATEGORIES = {
class AutoCorrectServiceError(Exception):
def __init__(self, message: str, *, status_code: int = 400) -> None:
def __init__(
self, message: str, *, status_code: int = 400, retryable: bool = False
) -> None:
super().__init__(message)
self.status_code = status_code
# True for transient provider conditions (rate limits, overload) the
# caller may safely retry; drives backoff in _call_model.
self.retryable = retryable
# Retry knobs for a single model call. Vertex 429 RESOURCE_EXHAUSTED is a
# recurring, transient condition; a short app-level backoff lets quota recover
# where the SDK's fast internal retry cannot. Kept small so a request never
# stalls the review UI for long. Parsed defensively: a malformed env override
# clamps to a safe value with a warning rather than crashing the backend at
# import or breaking the retry loop.
def _env_number(name: str, default: float, *, minimum: float, is_int: bool) -> float:
raw = os.environ.get(name)
if raw is None:
return default
try:
val: float = int(raw) if is_int else float(raw)
except ValueError:
logger.warning("invalid %s=%r; using default %s", name, raw, default)
return default
import math as _math
if not _math.isfinite(val) or val < minimum:
logger.warning(
"%s=%s out of range (min %s); clamping to %s", name, val, minimum, minimum
)
return minimum
return val
_MODEL_CALL_MAX_ATTEMPTS = int(
_env_number("AUTO_CORRECT_MODEL_MAX_ATTEMPTS", 3, minimum=1, is_int=True)
)
_MODEL_CALL_BACKOFF_SECONDS = float(
_env_number("AUTO_CORRECT_MODEL_BACKOFF_SECONDS", 2.0, minimum=0.0, is_int=False)
)
def _is_transient_model_error(exc: BaseException) -> bool:
"""True when a provider exception is a retryable rate-limit/overload.
Matches both structured status codes (google-genai ClientError/ServerError
expose ``code``; Anthropic errors expose ``status_code``) and, as a
fallback, the textual markers Vertex/Anthropic use — so detection survives
SDK exception-class churn.
"""
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
if isinstance(code, int) and code in {429, 500, 502, 503, 529}:
return True
text = str(exc).upper()
markers = ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "OVERLOADED", "429", "503", "529")
return any(m in text for m in markers)
@dataclass
@@ -388,10 +443,33 @@ class AutoCorrectService:
def _call_model(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
if model.startswith("claude"):
return self._call_anthropic(model, system_prompt, user_prompt, job_id=job_id)
return self._call_gemini(model, system_prompt, user_prompt, job_id=job_id)
"""Return (parsed_json, token_usage). Usage is None if unreadable.
Transient provider errors (rate limits / overload, flagged
``retryable``) are retried with exponential backoff. Permanent errors
(misconfig, malformed output) fail fast.
"""
for attempt in range(1, _MODEL_CALL_MAX_ATTEMPTS + 1):
try:
if model.startswith("claude"):
return self._call_anthropic(
model, system_prompt, user_prompt, job_id=job_id
)
return self._call_gemini(
model, system_prompt, user_prompt, job_id=job_id
)
except AutoCorrectServiceError as exc:
if not exc.retryable or attempt == _MODEL_CALL_MAX_ATTEMPTS:
raise
backoff = _MODEL_CALL_BACKOFF_SECONDS * (2 ** (attempt - 1))
logger.warning(
"auto-correct model call transient failure job=%s model=%s "
"attempt=%d/%d; retrying in %.1fs (%s)",
job_id, model, attempt, _MODEL_CALL_MAX_ATTEMPTS, backoff, exc,
)
time.sleep(backoff)
# Unreachable: the loop either returns or raises on the final attempt.
raise AssertionError("retry loop exited without returning or raising")
@staticmethod
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
@@ -440,8 +518,6 @@ class AutoCorrectService:
def _call_anthropic(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
import os
import anthropic
if not os.environ.get("ANTHROPIC_API_KEY"):
@@ -478,6 +554,16 @@ class AutoCorrectService:
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
)
except Exception as exc:
if _is_transient_model_error(exc):
logger.warning(
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
job_id, model, exc,
)
raise AutoCorrectServiceError(
"AI model is temporarily rate-limited",
status_code=429,
retryable=True,
) from exc
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
raise AutoCorrectServiceError(
"AI model call failed", status_code=502
@@ -520,6 +606,16 @@ class AutoCorrectService:
),
)
except Exception as exc: # surface as 502, never a stuck job
if _is_transient_model_error(exc):
logger.warning(
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
job_id, model, exc,
)
raise AutoCorrectServiceError(
"AI model is temporarily rate-limited",
status_code=429,
retryable=True,
) from exc
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
raise AutoCorrectServiceError(
"AI model call failed", status_code=502
+3
View File
@@ -15,6 +15,9 @@ class StopReason(str, Enum):
MAX_ITERS_REACHED = "max_iters_reached"
LINE_COUNT_MISMATCH = "line_count_mismatch"
VERBATIM_SKIP = "verbatim_skip"
# A repair iteration failed (e.g. the model returned an empty/blocked
# response); we keep the best result found so far instead of failing.
REPAIR_FAILED = "repair_failed"
@dataclass
+45 -3
View File
@@ -247,11 +247,20 @@ class CustomLyricsService:
settings=settings,
)
except Exception:
logger.exception(
# Repair is a best-effort *improvement* step. If a repair call
# fails (e.g. the model returned an empty/blocked response, or a
# transient Vertex error), we must NOT throw away the successful
# initial result — that turned a working generation into a 500 and
# a browser "NetworkError". Keep the best candidate found so far.
# WARNING (not exception/ERROR): this is now a handled, non-fatal
# degradation, so it should not trip the production error monitor.
logger.warning(
"custom_lyrics_repair_call_failed",
exc_info=True,
extra={"job_id": job_id, "iteration": iter_num, "stage": "repair"},
)
raise
stop_reason = StopReason.REPAIR_FAILED
break
validations = self._validate_with_length_handling(
candidate_lines, target_lines, target_segments,
tolerance=params.tolerance, fixed=settings.fixed_line_count,
@@ -564,7 +573,40 @@ class CustomLyricsService:
},
),
)
return self._parse_lines(response.text)
# The model can return no text (safety block, MAX_TOKENS with no content,
# empty candidate). `response.text` is then None and json.loads(None) would
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
# reports a confusing "NetworkError". Surface a clean, diagnosable error.
text = response.text
if text is None:
raise CustomLyricsServiceError(
f"The AI returned an empty response ({self._describe_empty_response(response)}). "
f"Please try again.",
status_code=502,
)
return self._parse_lines(text)
@staticmethod
def _describe_empty_response(response: Any) -> str:
"""Best-effort reason for an empty model response, for logs and messages."""
parts: list[str] = []
try:
block_reason = getattr(getattr(response, "prompt_feedback", None), "block_reason", None)
if block_reason:
parts.append(f"prompt_block={getattr(block_reason, 'name', block_reason)}")
except Exception: # pragma: no cover - defensive
pass
try:
candidates = getattr(response, "candidates", None) or []
if candidates:
finish = getattr(candidates[0], "finish_reason", None)
if finish is not None:
parts.append(f"finish_reason={getattr(finish, 'name', finish)}")
else:
parts.append("no_candidates")
except Exception: # pragma: no cover - defensive
pass
return ", ".join(parts) if parts else "unknown"
@staticmethod
def _parse_lines(text: str) -> list[str]:
+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
+19 -1
View File
@@ -177,7 +177,23 @@ class FirestoreService:
except Exception as e:
logger.error(f"Error listing jobs: {e}")
raise
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
"""List all jobs belonging to a Bulk Mode batch (state_data.batch_id == batch_id).
Single-field equality, so no composite index is required.
"""
try:
query = (
self.db.collection(self.collection)
.where(filter=FieldFilter('state_data.batch_id', '==', batch_id))
.limit(limit)
)
return [Job(**doc.to_dict()) for doc in query.stream()]
except Exception as e:
logger.error(f"Error listing jobs for batch {batch_id}: {e}")
raise
# Fields needed by the dashboard summary view
SUMMARY_FIELD_PATHS = [
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
@@ -194,6 +210,8 @@ class FirestoreService:
'state_data.pending_additional_credits',
'state_data.duration_actual_seconds',
'state_data.duration_confirm_reason',
'state_data.batch_id',
'state_data.bulk_auto_selected',
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
'processing_metadata',
]
+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
+158 -36
View File
@@ -266,6 +266,7 @@ class GoogleDriveService:
brand_code: str,
base_name: str,
output_files: dict,
warnings: Optional[list] = None,
) -> Dict[str, str]:
"""
Upload final files to public share folder structure.
@@ -322,6 +323,30 @@ class GoogleDriveService:
uploaded_files["mp4_720p"] = file_id
logger.info(f"Uploaded 720p MP4 to MP4-720p/ folder")
# Fast-sync the 720p master straight to the Divebar GCS mirror so kjbox
# (which mirrors that folder every 5 min) picks it up within minutes,
# instead of waiting for the nightly Drive->GCS VM. Nomad-brand only,
# best-effort, never fatal to the Drive upload. A failure is surfaced as
# a distribution warning (drives the admin alert) so this can't silently
# rot into "nightly VM only" — the nightly VM stays the backfill net.
fast_sync_warning = self._fast_sync_nomad_master(
brand_code, mp4_720p_path, f"{filename_base}.mp4"
)
if fast_sync_warning and warnings is not None:
warnings.append(fast_sync_warning)
# Push the padded original-vocals guide (silence[intro] + mixed_vocals) to the
# vocals prefix in the same Divebar mirror, so kjbox can layer it under the master
# at the "Original Vocals" slider. Same Nomad-brand gating + best-effort contract
# as the 720p push; the guide was pre-built by the orchestrator when available.
guide_path = output_files.get("original_vocals_guide")
if guide_path and os.path.exists(guide_path):
guide_warning = self._fast_sync_vocals_guide(
brand_code, guide_path, f"{filename_base}.flac"
)
if guide_warning and warnings is not None:
warnings.append(guide_warning)
# Upload CDG ZIP to CDG/
cdg_zip_path = output_files.get("final_karaoke_cdg_zip")
if cdg_zip_path and os.path.exists(cdg_zip_path):
@@ -337,6 +362,74 @@ class GoogleDriveService:
logger.info(f"Public share upload complete: {len(uploaded_files)} files uploaded")
return uploaded_files
def _fast_sync_nomad_master(
self, brand_code: str, local_720p_path: str, filename: str
) -> Optional[str]:
"""Best-effort push of a freshly-published Nomad 720p master to the Divebar
GCS mirror so kjbox picks it up within minutes (vs the nightly VM).
No-op unless the fast-sync is enabled and this is a public Nomad release
(``NOMAD-####``, excluding ``NOMADNP`` private tracks). Never raises — the
Drive upload has already succeeded and the nightly VM is the backfill net.
Returns a human-readable warning string on failure (so the caller can surface
it via ``distribution_warnings`` / the admin alert), or ``None`` on
success or when skipped.
"""
try:
from backend.config import settings
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
if not settings.nomad_master_fast_sync_enabled:
return None
if not is_nomad_public_brand(brand_code):
return None
if NomadMasterMirror().push_720p(local_720p_path, filename):
return None
return (
f"Nomad master fast-sync to the GCS mirror failed for {filename} "
f"(the nightly Drive->GCS VM will backfill it)"
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning(f"Nomad master fast-sync skipped (unexpected error): {e}")
return f"Nomad master fast-sync errored for {filename}: {e}"
def _fast_sync_vocals_guide(
self, brand_code: str, local_path: str, filename: str
) -> Optional[str]:
"""Best-effort push of a freshly-built original-vocals guide to the Divebar GCS
mirror's vocals prefix so kjbox can pull it into ``NOMAD-vocals-padded/``.
No-op unless the fast-sync is enabled and this is a public Nomad release
(``NOMAD-####``, excluding ``NOMADNP``). Never raises — nothing downstream
depends on the guide. Returns a human-readable warning on failure (surfaced via
``distribution_warnings`` / the admin alert), or ``None`` on success or skip.
"""
try:
from backend.config import settings
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
if not settings.nomad_master_fast_sync_enabled:
return None
if not is_nomad_public_brand(brand_code):
return None
if NomadMasterMirror().push_vocals_guide(local_path, filename):
return None
return (
f"Original-vocals guide sync to the GCS mirror failed for {filename}"
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning(f"Original-vocals guide sync skipped (unexpected error): {e}")
return f"Original-vocals guide sync errored for {filename}: {e}"
def delete_file(self, file_id: str) -> bool:
"""
Delete a file from Google Drive.
@@ -387,6 +480,69 @@ class GoogleDriveService:
results[file_id] = self.delete_file(file_id)
return results
def _search_subfolder_for_brand(
self, root_folder_id: str, subfolder: str, brand_code: str
) -> list[str]:
"""Return file IDs in ``subfolder`` whose name starts with ``{brand_code} - ``.
Read-only Drive lookups, wrapped in retry-with-backoff so transient
connection drops (SSL EOF / BrokenPipe against idle Cloud Run containers)
self-heal instead of surfacing as "GDrive brand_code search incomplete".
Non-transient errors reraise immediately for the caller to record.
"""
def _do_search() -> list[str]:
ids: list[str] = []
# Find the subfolder
escaped_subfolder = subfolder.replace("'", "\\'")
query = (
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(
q=query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
return ids
subfolder_id = results["files"][0]["id"]
# Search for files whose name starts with the brand code
# Use contains for efficiency, then filter by exact prefix
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
f"and trashed=false"
)
file_results = self.service.files().list(
q=file_query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
ids.append(f["id"])
logger.info(
f"Found GDrive file to clean up in {subfolder}/: "
f"{f['name']} ({f['id']})"
)
return ids
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
return _do_search()
return [] # pragma: no cover - Retrying always returns or raises
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
"""
Search for files in public share subfolders matching a brand code prefix.
@@ -411,43 +567,9 @@ class GoogleDriveService:
for subfolder in subfolders:
try:
# Find the subfolder
escaped_subfolder = subfolder.replace("'", "\\'")
query = (
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
found_ids.extend(
self._search_subfolder_for_brand(root_folder_id, subfolder, brand_code)
)
results = self.service.files().list(
q=query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
continue
subfolder_id = results["files"][0]["id"]
# Search for files whose name starts with the brand code
# Use contains for efficiency, then filter by exact prefix
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
f"and trashed=false"
)
file_results = self.service.files().list(
q=file_query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
found_ids.append(f["id"])
logger.info(
f"Found GDrive file to clean up in {subfolder}/: "
f"{f['name']} ({f['id']})"
)
except Exception as e:
logger.error(
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
+4
View File
@@ -189,6 +189,10 @@ class JobManager:
def update_job(self, job_id: str, updates: Dict[str, Any]) -> None:
"""Update job with arbitrary fields."""
self.firestore.update_job(job_id, updates)
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
"""List all jobs in a Bulk Mode batch (state_data.batch_id == batch_id)."""
return self.firestore.list_jobs_by_batch_id(batch_id, limit=limit)
def list_jobs(
self,
+122 -28
View File
@@ -5,6 +5,7 @@ Scrapes karaokenerds.com to check if a song already has community-approved
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
"""
import asyncio
import logging
import re
import time
@@ -14,12 +15,22 @@ from urllib.parse import urlencode
import httpx
from bs4 import BeautifulSoup
from backend.services.match_judge.classifier import normalize_for_match
logger = logging.getLogger(__name__)
SEARCH_URL = "https://karaokenerds.com/Search"
REQUEST_TIMEOUT = 8
USER_AGENT = "NomadKaraokeGen/1.0"
# karaokenerds.com's search silently returns zero results once a query exceeds
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
# artist blow past this, so the song is falsely reported as having no community
# version. When that happens we retry with the title alone (the highest-signal
# term) and keep only results whose artist matches.
MAX_RELIABLE_QUERY_TERMS = 10
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
_cache: dict[str, tuple[float, Any]] = {}
CACHE_TTL_SECONDS = 3600 # 1 hour
@@ -145,6 +156,45 @@ def parse_results(html: str) -> list[dict]:
return songs
async def _search_songs(query: str) -> list[dict] | None:
"""Run a single karaokenerds search and parse the results.
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
caller can distinguish "search errored" from "search returned nothing").
"""
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
url = f"{SEARCH_URL}?{params}"
try:
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
resp = await client.get(
url,
headers={"User-Agent": USER_AGENT},
follow_redirects=True,
)
resp.raise_for_status()
except Exception as e:
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
return None
return parse_results(resp.text)
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
community_songs: list[dict] = []
best_youtube_url: str | None = None
for song in songs:
community_tracks = [t for t in song["tracks"] if t["is_community"]]
if community_tracks:
community_songs.append({
"title": song["title"],
"artist": song["artist"],
"community_tracks": community_tracks,
})
if best_youtube_url is None:
best_youtube_url = community_tracks[0]["youtube_url"]
return community_songs, best_youtube_url
async def check_community_versions(artist: str, title: str) -> dict:
"""
Check if a song has community-approved karaoke versions on karaokenerds.
@@ -160,39 +210,32 @@ async def check_community_versions(artist: str, title: str) -> dict:
if cached is not None:
return cached
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
url = f"{SEARCH_URL}?{params}"
try:
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
resp = await client.get(
url,
headers={"User-Agent": USER_AGENT},
follow_redirects=True,
)
resp.raise_for_status()
except Exception as e:
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
songs = await _search_songs(query)
if songs is None:
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
# site, matching prior behaviour.
result = {"has_community": False, "songs": [], "best_youtube_url": None}
_cache_set(cache_key, result)
return result
songs = parse_results(resp.text)
# karaokenerds chokes on overlong queries and returns nothing. If the
# combined "artist title" query was too long AND came back empty, retry with
# the title alone, then keep only results whose artist matches (title-only is
# broader, so this guards against same-titled songs by other artists).
if (
not songs
and title.strip()
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
):
fallback = await _search_songs(title)
if fallback:
key_artist = normalize_for_match(artist)
songs = [
s for s in fallback
if normalize_for_match(s.get("artist") or "") == key_artist
]
# Filter to only songs that have community tracks with YouTube URLs
community_songs = []
best_youtube_url = None
for song in songs:
community_tracks = [t for t in song["tracks"] if t["is_community"]]
if community_tracks:
community_songs.append({
"title": song["title"],
"artist": song["artist"],
"community_tracks": community_tracks,
})
if best_youtube_url is None:
best_youtube_url = community_tracks[0]["youtube_url"]
community_songs, best_youtube_url = _extract_community_songs(songs)
result = {
"has_community": len(community_songs) > 0,
@@ -201,3 +244,54 @@ async def check_community_versions(artist: str, title: str) -> dict:
}
_cache_set(cache_key, result)
return result
async def check_community_versions_batch(
songs: list[dict], concurrency: int = 5
) -> list[dict]:
"""Check community-version availability for many songs (Bulk Mode).
``songs`` is a list of ``{"artist": str, "title": str}``. Returns a list in the
same order, each ``{"artist", "title", "available": bool, "brands": [str],
"brand_count": int, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
uses to render clickable links; ``brands``/``brand_count`` are retained for
back-compat. Bounded concurrency keeps us polite to karaokenerds.com; per-song
results reuse the existing 1h cache. A failed lookup degrades to
``available=False`` (the track simply stays selectable) — never raises.
"""
sem = asyncio.Semaphore(max(1, concurrency))
async def _one(song: dict) -> dict:
artist = (song.get("artist") or "").strip()
title = (song.get("title") or "").strip()
if not artist or not title:
return {"artist": artist, "title": title, "available": False,
"brands": [], "brand_count": 0, "versions": []}
async with sem:
res = await check_community_versions(artist, title)
versions: list[dict] = []
versioned_brands: set[str] = set()
brands: list[str] = []
for matched in res.get("songs", []):
for track in matched.get("community_tracks", []):
name = track.get("brand_name")
if not name:
continue
if name not in brands:
brands.append(name)
# A clickable version needs a URL; brand still counts as "exists" without one.
url = track.get("youtube_url")
if url and name not in versioned_brands:
versioned_brands.add(name)
versions.append({"brand": name, "url": url})
return {
"artist": artist,
"title": title,
"available": bool(res.get("has_community")),
"brands": brands,
"brand_count": len(brands),
"versions": versions,
}
return await asyncio.gather(*[_one(s) for s in songs])
+391
View File
@@ -0,0 +1,391 @@
"""MusicBrainz lookup service for Bulk Mode album/release lookup.
Provides artist search, album (release-group) listing, canonical-release
selection, and tracklist retrieval with "extra track" detection (live /
remix / bonus / demo / acoustic / instrumental).
MusicBrainz asks for a descriptive User-Agent and ~1 request/second. We add a
small process-wide throttle and a short in-memory TTL cache because album
lookups are interactive and low-volume.
API shapes (captured from the live API, 2026-06):
- GET /ws/2/artist?query=&fmt=json -> {artists: [{id,name,disambiguation,type,score,country}]}
- GET /ws/2/release-group?artist=&type=album&fmt=json
-> {release-groups: [{id,title,primary-type,secondary-types:[str],first-release-date}]}
- GET /ws/2/release?release-group=&inc=media&fmt=json
-> {releases: [{id,title,status,date,country,packaging,disambiguation,media:[{track-count}]}]}
- GET /ws/2/release/{id}?inc=recordings&fmt=json
-> {id,title,status,date,country,media:[{format,track-count,
tracks:[{position,title,length,recording:{id,title,disambiguation,length}}]}]}
"""
from __future__ import annotations
import asyncio
import logging
import re
import time
from collections import Counter
from typing import Any, Dict, List, Optional
from urllib.parse import urlencode
import httpx
logger = logging.getLogger(__name__)
MB_BASE = "https://musicbrainz.org/ws/2"
USER_AGENT = "NomadKaraoke/1.0 (contact@nomadkaraoke.com)"
_MIN_INTERVAL_S = 1.0 # MusicBrainz politeness: ~1 req/s
_CACHE_TTL_S = 600 # 10 min — album metadata is effectively static
_REQUEST_TIMEOUT_S = 15.0
_MAX_RETRIES = 3 # MusicBrainz 503s / transient transport errors are common from cloud egress
_RETRY_BACKOFF_S = 0.5
# Country preference for canonical-release tie-breaks (worldwide / Europe / US / UK).
_PREFERRED_COUNTRIES = ["XW", "XE", "US", "GB"]
# Locale → ordered country preference for picking which pressing backs a variant.
# Biases the representative release toward the user's likely region; falls back to
# the worldwide default for anything unmapped. Keyed by the language part of the
# locale (region suffix is ignored, e.g. "en-US" → "en").
_LOCALE_COUNTRY_PREFS: Dict[str, List[str]] = {
"en": ["GB", "US", "AU", "CA", "IE", "NZ"],
"es": ["ES", "MX", "AR"],
"fr": ["FR", "CA", "BE"],
"de": ["DE", "AT", "CH"],
"it": ["IT"],
"pt": ["PT", "BR"],
"nl": ["NL", "BE"],
"sv": ["SE"],
"ja": ["JP"],
"ko": ["KR"],
"zh": ["CN", "TW", "HK"],
}
def country_prefs_for_locale(locale: Optional[str]) -> List[str]:
"""Map a next-intl locale to an ordered country preference list.
Returns a copy of the worldwide default (``_PREFERRED_COUNTRIES``) for an
empty/unknown locale so callers can mutate freely.
"""
if not locale:
return list(_PREFERRED_COUNTRIES)
base = re.split(r"[-_]", locale)[0].lower()
return list(_LOCALE_COUNTRY_PREFS.get(base, _PREFERRED_COUNTRIES))
# "Extra" track qualifier keywords. Matched only inside (), [], or after " - "
# so we don't misfire on legitimate titles that happen to contain a word.
_EXTRA_KEYWORDS = [
"live",
"remix",
"remixed",
"bonus",
"demo",
"acoustic",
"instrumental",
"rehearsal",
"alternate",
"alternative",
"radio edit",
"single edit",
"extended",
"re-recorded",
"rerecorded",
"session",
"outtake",
]
_EXTRA_KEYWORDS_RE = "|".join(re.escape(k) for k in _EXTRA_KEYWORDS)
# A qualifier segment: (...keyword...), [...keyword...], or " - ...keyword..."
_QUALIFIER_RE = re.compile(
r"(?:[\(\[][^\)\]]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b[^\)\]]*[\)\]])"
r"|(?:\s[-–]\s[^\(\[]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b)",
re.IGNORECASE,
)
def classify_extra(title: str, disambiguation: str = "") -> tuple[bool, str]:
"""Return (is_extra, reason). Conservative: only flags clear qualifiers."""
disamb = (disambiguation or "").strip().lower()
if disamb:
for kw in _EXTRA_KEYWORDS:
if re.search(r"\b" + re.escape(kw) + r"\b", disamb):
return True, disamb
m = _QUALIFIER_RE.search(title or "")
if m:
return True, m.group(0).strip(" -–()[]")
return False, ""
class MusicBrainzService:
"""Thin async client around the MusicBrainz web service."""
def __init__(self) -> None:
self._last_request_at = 0.0
self._throttle_lock = asyncio.Lock()
self._cache: Dict[str, tuple[float, Any]] = {}
# -- HTTP plumbing -----------------------------------------------------
async def _throttle(self) -> None:
# Non-blocking: yields to the event loop instead of stalling it.
async with self._throttle_lock:
now = time.monotonic()
wait = self._last_request_at + _MIN_INTERVAL_S - now
if wait > 0:
await asyncio.sleep(wait)
self._last_request_at = time.monotonic()
async def _get(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
cache_key = path + "?" + urlencode(sorted(params.items()))
cached = self._cache.get(cache_key)
if cached and (time.monotonic() - cached[0]) < _CACHE_TTL_S:
return cached[1]
params = {**params, "fmt": "json"}
last_exc: Optional[Exception] = None
for attempt in range(_MAX_RETRIES):
await self._throttle()
try:
async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT_S) as client:
resp = await client.get(
f"{MB_BASE}/{path}", params=params, headers={"User-Agent": USER_AGENT}
)
# MusicBrainz returns 503 when rate-limited/throttled — retry those.
if resp.status_code == 503 and attempt < _MAX_RETRIES - 1:
last_exc = httpx.HTTPStatusError(
"503 from MusicBrainz", request=resp.request, response=resp
)
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
continue
resp.raise_for_status()
data = resp.json()
self._cache[cache_key] = (time.monotonic(), data)
return data
except (httpx.TransportError, httpx.TimeoutException) as e:
# Connection/timeout errors — retry with backoff.
last_exc = e
logger.warning("MusicBrainz %s attempt %d/%d failed: %r", path, attempt + 1, _MAX_RETRIES, e)
if attempt < _MAX_RETRIES - 1:
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
# Exhausted retries.
raise last_exc if last_exc else RuntimeError(f"MusicBrainz request failed: {path}")
# -- Public API --------------------------------------------------------
async def search_artists(self, name: str, limit: int = 8) -> List[Dict[str, Any]]:
"""Search artists by name."""
if not name or not name.strip():
return []
data = await self._get("artist", {"query": name.strip(), "limit": limit})
out = []
for a in data.get("artists", []):
out.append(
{
"mbid": a.get("id"),
"name": a.get("name"),
"disambiguation": a.get("disambiguation") or "",
"type": a.get("type"),
"country": a.get("country"),
"score": a.get("score"),
}
)
return out
async def get_albums(self, artist_mbid: str, limit: int = 100) -> List[Dict[str, Any]]:
"""List an artist's albums (release-groups), studio albums first, then by date."""
data = await self._get(
"release-group",
{"artist": artist_mbid, "type": "album|ep", "limit": limit},
)
groups = []
for rg in data.get("release-groups", []):
secondary = rg.get("secondary-types") or []
groups.append(
{
"release_group_mbid": rg.get("id"),
"title": rg.get("title"),
"primary_type": rg.get("primary-type"),
"secondary_types": secondary,
"first_release_date": rg.get("first-release-date") or "",
"is_studio": len(secondary) == 0,
}
)
# Studio albums first, then earliest release date.
groups.sort(key=lambda g: (not g["is_studio"], g["first_release_date"] or "9999"))
return groups
@staticmethod
def _total_tracks(release: Dict[str, Any]) -> int:
return sum((m.get("track-count") or 0) for m in (release.get("media") or []))
async def _list_editions(self, release_group_mbid: str) -> List[Dict[str, Any]]:
data = await self._get(
"release",
{"release-group": release_group_mbid, "inc": "media", "limit": 100},
)
editions = []
for r in data.get("releases", []):
editions.append(
{
"release_mbid": r.get("id"),
"title": r.get("title"),
"status": r.get("status"),
"date": r.get("date") or "",
"country": r.get("country"),
"packaging": r.get("packaging"),
"disambiguation": r.get("disambiguation") or "",
"track_count": self._total_tracks(r),
}
)
return editions
@staticmethod
def pick_canonical_edition(
editions: List[Dict[str, Any]],
preferred_countries: Optional[List[str]] = None,
) -> Optional[Dict[str, Any]]:
"""Pick the standard edition: official, modal track count, earliest, preferred country.
Choosing the most common track count avoids deluxe/remaster editions that
tack bonus tracks on the end. ``preferred_countries`` overrides the default
worldwide-first tie-break (used for locale-aware selection).
"""
if not editions:
return None
prefs = preferred_countries or _PREFERRED_COUNTRIES
official = [e for e in editions if e.get("status") == "Official"] or editions
with_tracks = [e for e in official if e.get("track_count", 0) > 0] or official
counts = Counter(e["track_count"] for e in with_tracks if e.get("track_count", 0) > 0)
if counts:
standard = counts.most_common(1)[0][0]
candidates = [e for e in with_tracks if e["track_count"] == standard]
else:
candidates = with_tracks
def country_rank(e: Dict[str, Any]) -> int:
c = e.get("country")
return prefs.index(c) if c in prefs else len(prefs)
candidates.sort(key=lambda e: (e.get("date") or "9999", country_rank(e)))
return candidates[0]
@staticmethod
def build_variants(
editions: List[Dict[str, Any]],
preferred_countries: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Collapse a release-group's editions into distinct tracklist *variants*.
Country pressings are irrelevant for karaoke (we only need the track names),
so editions are grouped by ``track_count`` — within one release-group, same
count ≈ same songs. Each variant exposes a representative release (earliest +
preferred-country), the earliest year, how many pressings collapsed in, and a
label/delta relative to the "Original" (earliest) variant. Editions without a
track count are dropped. See
``docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md``.
"""
if not editions:
return []
official = [e for e in editions if e.get("status") == "Official"] or editions
with_tracks = [e for e in official if (e.get("track_count") or 0) > 0]
if not with_tracks:
return []
groups: Dict[int, List[Dict[str, Any]]] = {}
for e in with_tracks:
groups.setdefault(e["track_count"], []).append(e)
variants: List[Dict[str, Any]] = []
for track_count, group in groups.items():
rep = MusicBrainzService.pick_canonical_edition(group, preferred_countries)
earliest = min((e.get("date") or "9999") for e in group)
year = earliest[:4] if earliest and earliest != "9999" else ""
variants.append(
{
"representative_release_mbid": rep["release_mbid"],
"track_count": track_count,
"year": year,
"pressing_count": len(group),
"_earliest": earliest,
}
)
# Original = earliest release, then most pressings, then fewest tracks.
variants.sort(key=lambda v: (v["_earliest"], -v["pressing_count"], v["track_count"]))
original = variants[0]
original_tc = original["track_count"]
for v in variants:
v["delta_vs_original"] = v["track_count"] - original_tc
v["label"] = "Original" if v is original else "Reissue"
del v["_earliest"]
# Display order: Original first, then by year ascending, then track count.
variants.sort(key=lambda v: (v["label"] != "Original", v["year"] or "9999", v["track_count"]))
return variants
async def get_release_tracklist(self, release_mbid: str) -> Dict[str, Any]:
"""Fetch a release's tracklist with per-track extra detection."""
data = await self._get(f"release/{release_mbid}", {"inc": "recordings"})
tracks: List[Dict[str, Any]] = []
for medium in data.get("media") or []:
for t in medium.get("tracks") or []:
rec = t.get("recording") or {}
title = t.get("title") or rec.get("title") or ""
disamb = rec.get("disambiguation") or ""
is_extra, reason = classify_extra(title, disamb)
length_ms = t.get("length") or rec.get("length")
tracks.append(
{
"position": t.get("position"),
"title": title,
"recording_mbid": rec.get("id"),
"disambiguation": disamb,
"length_ms": length_ms,
"is_extra": is_extra,
"extra_reason": reason,
}
)
return {
"release_mbid": data.get("id"),
"title": data.get("title"),
"date": data.get("date") or "",
"country": data.get("country"),
"tracks": tracks,
}
async def get_album_tracklist(
self,
release_group_mbid: str,
preferred_countries: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Resolve the canonical edition of an album and return its tracklist, the raw
editions, and the collapsed tracklist ``variants``. ``preferred_countries``
biases representative selection (locale-aware)."""
editions = await self._list_editions(release_group_mbid)
canonical = self.pick_canonical_edition(editions, preferred_countries)
variants = self.build_variants(editions, preferred_countries)
if not canonical:
return {
"release_mbid": None,
"title": None,
"tracks": [],
"editions": editions,
"variants": variants,
"selected_variant_mbid": None,
}
tracklist = await self.get_release_tracklist(canonical["release_mbid"])
tracklist["editions"] = editions
tracklist["canonical_release_mbid"] = canonical["release_mbid"]
tracklist["variants"] = variants
tracklist["selected_variant_mbid"] = canonical["release_mbid"]
return tracklist
_service: Optional[MusicBrainzService] = None
def get_musicbrainz_service() -> MusicBrainzService:
global _service
if _service is None:
_service = MusicBrainzService()
return _service
+186
View File
@@ -0,0 +1,186 @@
"""
Fast-path mirror of freshly-published Nomad masters into the Divebar GCS bucket.
New Nomad releases are uploaded to Google Drive at finalize time, but the Drive->GCS
byte-sync VM only runs nightly, so kjbox (which mirrors that GCS folder every 5 min)
would otherwise wait up to ~24h for a new master. This pushes the 720p master straight
to the exact GCS object the nightly VM would produce, so kjbox picks it up within minutes.
Idempotent with the nightly VM: identical object name + size means its additive
`gcloud storage rsync` sees the file already present and skips it.
Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding the
``NOMADNP`` private-track prefix). Every operation is best-effort / non-fatal: a failure
here must never break the distribution pipeline — the nightly VM remains the safety net.
"""
import logging
from typing import Optional
from google.cloud import storage
from google.cloud.exceptions import NotFound
from backend.config import settings
logger = logging.getLogger(__name__)
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
if not brand_code:
return False
prefix = brand_code.split("-", 1)[0].strip().upper()
return prefix == "NOMAD"
class NomadMasterMirror:
"""Push/remove Nomad 720p masters in the Divebar GCS bucket that kjbox mirrors."""
def __init__(self, client: Optional[storage.Client] = None):
self._client = client or storage.Client(project=settings.google_cloud_project)
self._bucket = self._client.bucket(settings.divebar_files_bucket)
def _blob_name(self, filename: str) -> str:
prefix = settings.nomad_master_gcs_prefix.strip("/")
return f"{prefix}/{filename}"
def _vocals_blob_name(self, filename: str) -> str:
prefix = settings.nomad_vocals_guide_gcs_prefix.strip("/")
return f"{prefix}/{filename}"
def push_720p(self, local_path: str, filename: str) -> bool:
"""Upload a 720p master to the divebar GCS mirror. Best-effort; returns success."""
blob_name = self._blob_name(filename)
try:
blob = self._bucket.blob(blob_name)
blob.upload_from_filename(local_path)
logger.info(
"Fast-synced Nomad master to gs://%s/%s",
settings.divebar_files_bucket,
blob_name,
)
return True
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Nomad master fast-sync push failed for %s: %s", blob_name, e)
return False
def delete_720p(self, filename: str) -> bool:
"""Delete a 720p master from the mirror. Best-effort; 404 == already gone."""
blob_name = self._blob_name(filename)
try:
self._bucket.blob(blob_name).delete()
logger.info(
"Removed Nomad master from gs://%s/%s",
settings.divebar_files_bucket,
blob_name,
)
return True
except NotFound:
logger.debug("Nomad master already absent in mirror: %s", blob_name)
return False
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Nomad master mirror delete failed for %s: %s", blob_name, e)
return False
def push_vocals_guide(self, local_path: str, filename: str) -> bool:
"""Upload a padded original-vocals guide to the divebar GCS mirror's vocals
prefix (which kjbox pulls into ``NOMAD-vocals-padded/``). Best-effort."""
blob_name = self._vocals_blob_name(filename)
try:
blob = self._bucket.blob(blob_name)
blob.upload_from_filename(local_path)
logger.info(
"Pushed original-vocals guide to gs://%s/%s",
settings.divebar_files_bucket,
blob_name,
)
return True
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Vocals-guide push failed for %s: %s", blob_name, e)
return False
def delete_vocals_guides_by_brand(self, brand_code: str) -> int:
"""Delete ALL original-vocals guide objects for a Nomad release, matched by the
unique ``{brand_code} - `` filename prefix (covers renames). Best-effort; returns
the count deleted. Refuses a non-Nomad / bare brand code (same guardrail as the
master prefix-delete) so a broad prefix can never wipe unrelated objects."""
if not is_nomad_public_brand(brand_code):
return 0
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
if not suffix.strip():
return 0
prefix = f"{settings.nomad_vocals_guide_gcs_prefix.strip('/')}/{brand_code} - "
deleted = 0
try:
for blob in self._bucket.list_blobs(prefix=prefix):
try:
blob.delete()
deleted += 1
except Exception as e: # noqa: BLE001
logger.warning("Failed to delete vocals-guide object %s: %s", blob.name, e)
if deleted:
logger.info(
"Removed %d original-vocals guide object(s) from gs://%s/%s*",
deleted, settings.divebar_files_bucket, prefix,
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Vocals-guide mirror prefix-delete failed for %s: %s", prefix, e)
return deleted
def delete_masters_by_brand(self, brand_code: str) -> int:
"""Delete ALL 720p master objects for a Nomad release, matched by the unique
``{brand_code} - `` filename prefix.
Keying on the brand_code prefix (rather than a reconstructed title) covers
renames for free: every artist/title variant a release was ever published
under shares the same ``NOMAD-#### - `` prefix. Best-effort; returns the count
deleted. Refuses to run for a non-Nomad / empty brand code so a broad prefix
can never match unrelated objects.
"""
if not is_nomad_public_brand(brand_code):
return 0
# Require a full ``NOMAD-####`` code (non-empty suffix after the hyphen) so the
# delete prefix is always specific to one release — never a bare ``NOMAD``.
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
if not suffix.strip():
return 0
prefix = f"{settings.nomad_master_gcs_prefix.strip('/')}/{brand_code} - "
deleted = 0
try:
for blob in self._bucket.list_blobs(prefix=prefix):
try:
blob.delete()
deleted += 1
except Exception as e: # noqa: BLE001
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
if deleted:
logger.info(
"Removed %d Nomad master object(s) from gs://%s/%s*",
deleted, settings.divebar_files_bucket, prefix,
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Nomad master mirror prefix-delete failed for %s: %s", prefix, e)
return deleted
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
brands or when fast-sync is disabled. Never raises — a cleanup failure must not
break job delete/edit flows (the object just lingers until overwritten). Call this
wherever the pipeline deletes a job's Drive/Dropbox outputs.
"""
try:
if not settings.nomad_master_fast_sync_enabled:
return 0
if not is_nomad_public_brand(brand_code):
return 0
mirror = NomadMasterMirror()
deleted = mirror.delete_masters_by_brand(brand_code)
# A recycled brand must not keep serving its old original-vocals guide, so remove
# the GCS guide(s) too. (Note: with the device's additive-only vocals sync this
# won't auto-remove an already-downloaded device copy — a documented limitation.)
mirror.delete_vocals_guides_by_brand(brand_code)
return deleted
except Exception as e: # noqa: BLE001 - never fatal to the caller
logger.warning("Nomad master mirror cleanup skipped: %s", e)
return 0
+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}"
+106
View File
@@ -0,0 +1,106 @@
"""Build the padded original-vocals guide that feeds kjbox's "Original Vocals" slider.
At render time karaoke-gen already has the isolated ``mixed_vocals`` stem (a byproduct
of making the karaoke instrumental) and knows the exact intro offset (the master is
``[silent title-card intro] + song + [tail]`` and the intro length is the job's style
``intro_video_duration``). So the guide is simply ``silence[intro] + vocals``, capped to
the master's duration — no cross-correlation, no human review, no alignment measurement.
This is byte-compatible with what the kjbox retro-fit ``pad_vocals.sh`` produced.
Every function here is best-effort: it returns ``None`` / ``0`` on any failure and never
raises, so a guide problem can never break the distribution pipeline.
"""
import logging
import os
import subprocess
from typing import Optional
logger = logging.getLogger(__name__)
def probe_duration(path: str, ffprobe_path: str = "ffprobe") -> Optional[float]:
"""Return a media file's duration in seconds, or ``None`` if it can't be measured."""
try:
if not path or not os.path.isfile(path):
return None
result = subprocess.run(
[
ffprobe_path, "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path,
],
capture_output=True, text=True, timeout=60,
)
if result.returncode != 0:
return None
return float(result.stdout.strip())
except Exception as e: # noqa: BLE001 - never fatal
logger.warning("Could not probe duration for %s: %s", path, e)
return None
def build_original_vocals_guide(
mixed_vocals_path: str,
intro_seconds: float,
dest_path: str,
master_duration: Optional[float] = None,
ffmpeg_path: str = "ffmpeg",
) -> Optional[str]:
"""Emit ``silence[intro] + mixed_vocals`` as a FLAC guide aligned to the master.
Args:
mixed_vocals_path: The isolated vocals stem (all vocals: lead + backing).
intro_seconds: The master's silent title-card length (job's ``intro_video_duration``).
dest_path: Where to write the guide (``.flac``).
master_duration: If given, the output is capped to this length (``-t``) so the
guide can never bleed past the master. Omit to leave the vocals' own length.
ffmpeg_path: ffmpeg binary.
Returns:
``dest_path`` on success, else ``None`` (missing input / ffmpeg failure). Never raises.
"""
try:
if not mixed_vocals_path or not os.path.isfile(mixed_vocals_path):
logger.warning("Vocals guide: missing mixed-vocals stem %s", mixed_vocals_path)
return None
if intro_seconds is None or intro_seconds < 0:
logger.warning("Vocals guide: invalid intro_seconds %r", intro_seconds)
return None
delay_ms = int(round(float(intro_seconds) * 1000))
os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True)
tmp_path = dest_path + ".part"
cmd = [
ffmpeg_path, "-y", "-hide_banner", "-nostats", "-loglevel", "error",
"-i", mixed_vocals_path,
"-af", f"adelay={delay_ms}:all=1",
]
if master_duration and master_duration > 0:
cmd += ["-t", f"{float(master_duration):.3f}"]
# ``-f flac`` is mandatory: the ``.part`` extension would otherwise make the
# muxer guess the container from the extension and fail.
cmd += ["-c:a", "flac", "-f", "flac", tmp_path]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if result.returncode != 0 or not os.path.isfile(tmp_path):
logger.warning(
"Vocals guide: ffmpeg failed (rc=%s) for %s: %s",
result.returncode, mixed_vocals_path, (result.stderr or "")[-200:].strip(),
)
_quiet_remove(tmp_path)
return None
os.replace(tmp_path, dest_path)
logger.info("Built original-vocals guide: %s", dest_path)
return dest_path
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Vocals guide build failed for %s: %s", mixed_vocals_path, e)
_quiet_remove(dest_path + ".part")
return None
def _quiet_remove(path: str) -> None:
try:
os.remove(path)
except OSError:
pass
@@ -0,0 +1,2 @@
"""Batch karaoke-filename → {artist, title, confidence} parser (Vertex Gemini)."""
from backend.services.parse_titles.service import parse_titles # noqa: F401
+148
View File
@@ -0,0 +1,148 @@
"""Vertex-Gemini layer for batch karaoke-filename parsing.
Turns messy karaoke *filenames* (YouTube titles, community/producer naming,
KaraFun-reversed order) into canonical {artist, title, confidence}. Distinct
from match_judge (which judges an already-split artist/title). The model call
is injectable for tests.
"""
from __future__ import annotations
import asyncio
import copy
import json
import logging
from typing import Awaitable, Callable, Optional
logger = logging.getLogger(__name__)
Generate = Callable[[str, str, str], Awaitable[dict]]
_SYSTEM_PROMPT = (
"You extract canonical song metadata from karaoke video/file names for a "
"karaoke library. Each item has an id and a filename (sometimes a channel or "
"source). Filenames are noisy: they carry karaoke markers ('(Karaoke Version)', "
"'KARAOKE', '[karaoke]', 'Instrumental', producer/brand tags), YouTube ids or "
"channel names, and inconsistent separators. Crucially the artist/title ORDER "
"is inconsistent — most are 'Artist - Title' but some sources (e.g. KaraFun) are "
"'Title - Artist'. Use your knowledge of real songs to put artist and title in "
"the correct fields.\n"
"Return JSON: {\"results\": [{\"id\", \"artist\", \"title\", \"confidence\"}]}. "
"Return exactly one result per input id, echoing the id verbatim.\n"
"artist/title: official formatting, karaoke noise removed, no brand codes or "
"YouTube ids. If you cannot identify one field, return it as an empty string.\n"
"confidence: 0.0-1.0 — your certainty the artist/title (and their order) are "
"correct. Be honest; low confidence for ambiguous or unknown songs. Never invent "
"a song; if unsure, return best-effort split with low confidence."
)
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "string"},
"artist": {"type": "string"},
"title": {"type": "string"},
"confidence": {"type": "number"},
},
"required": ["id"],
},
}
},
"required": ["results"],
}
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "parse_titles_model", "gemini-3.5-flash")
except Exception: # pragma: no cover - config guard
return "gemini-3.5-flash"
def build_prompts(items: list[dict]) -> tuple[str, str]:
lines = ["Parse these karaoke filenames:"]
for it in items:
parts = [f'id={it.get("id")!r}', f'filename={it.get("filename", "")!r}']
if it.get("channel"):
parts.append(f'channel={it["channel"]!r}')
if it.get("source"):
parts.append(f'source={it["source"]!r}')
lines.append("- " + " ".join(parts))
return _SYSTEM_PROMPT, "\n".join(lines)
def _clean(v) -> str:
return (v or "").strip() if isinstance(v, str) else ""
def _conf(v) -> float:
try:
f = float(v)
except (TypeError, ValueError):
return 0.0
return max(0.0, min(1.0, f))
def parse_map_from_response(data: object, items: list[dict]) -> list[dict]:
"""Return one id-aligned result per input, filling any misses with blanks."""
by_id: dict[str, dict] = {}
if isinstance(data, dict):
for r in data.get("results") or []:
if isinstance(r, dict) and r.get("id") is not None:
by_id[str(r["id"])] = r
out = []
for it in items:
rid = str(it.get("id"))
r = by_id.get(rid, {})
out.append({
"id": rid,
"artist": _clean(r.get("artist")),
"title": _clean(r.get("title")),
"confidence": _conf(r.get("confidence")),
})
return out
async def ai_parse(
items: list[dict], *, model: Optional[str] = None,
generate: Optional[Generate] = None,
) -> list[dict]:
gen = generate or _default_generate
system, user = build_prompts(items)
data = await gen(model or _model(), system, user)
return parse_map_from_response(data, items)
async def _default_generate(model: str, system: str, user: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system, user)
def _blocking_generate(model: str, system: str, user: str) -> dict:
from google import genai
from google.genai import types
from backend.config import settings
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
response = client.models.generate_content(
model=model,
contents=[user],
config=types.GenerateContentConfig(
system_instruction=system,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
),
)
return json.loads(response.text)
+68
View File
@@ -0,0 +1,68 @@
"""Batch orchestration + graceful degrade for karaoke-filename parsing."""
from __future__ import annotations
import asyncio
import logging
from backend.services.parse_titles import ai
logger = logging.getLogger(__name__)
def _blanks(items: list[dict]) -> list[dict]:
return [
{"id": str(it.get("id")), "artist": "", "title": "", "confidence": 0.0}
for it in items
]
async def parse_titles(
items: list[dict], *, model=None, generate=None
) -> list[dict]:
"""Parse a batch of filenames → id-aligned {id, artist, title, confidence}.
Large batches are split into concurrent chunks of parse_titles_chunk_size
so a single Gemini call never outgrows parse_titles_timeout_ms (a 100-item
single call did, and the timeout blanked the whole batch).
Never raises: a disabled kill-switch or any model failure yields blank
results — per chunk, so one bad chunk doesn't blank its neighbours — and
the (kjbox) caller keeps its deterministic guess.
"""
if not items:
return []
try:
from backend.config import settings
enabled = getattr(settings, "parse_titles_enabled", True)
max_items = int(getattr(settings, "parse_titles_max_items", 200))
chunk_size = max(1, int(getattr(settings, "parse_titles_chunk_size", 10)))
except Exception: # pragma: no cover
# Fail closed: if config can't load, don't reach for the external AI.
logger.warning("parse_titles settings unavailable; disabling parser")
enabled, max_items, chunk_size = False, 200, 10
if not enabled:
return _blanks(items)
head, tail = items[:max_items], items[max_items:]
chunks = [head[i:i + chunk_size] for i in range(0, len(head), chunk_size)]
parsed = await asyncio.gather(
*(_parse_chunk(chunk, model=model, generate=generate) for chunk in chunks)
)
return [r for chunk_results in parsed for r in chunk_results] + _blanks(tail)
async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
"""One Gemini call; any failure degrades to blanks for this chunk only."""
try:
results = await ai.ai_parse(chunk, model=model, generate=generate)
except Exception as exc:
logger.warning(
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
return _blanks(chunk)
# ai_parse is id-aligned by construction; guard the contract defensively so a
# future refactor can't silently return a mis-aligned/short batch.
if len(results) != len(chunk):
logger.warning(
"parse_titles chunk length mismatch; blanks for %d items", len(chunk))
return _blanks(chunk)
return results
+30
View File
@@ -373,6 +373,36 @@ class UserService:
logger.exception("Error verifying magic link")
return False, None, "An error occurred during verification"
def get_magic_link_status(self, token: str) -> str:
"""
Read-only check of a magic link's status WITHOUT consuming it.
Used by the verify page on load to decide whether to show the
"Complete Sign-In" gate (valid) or a dead-link message (used/expired).
Crucially this must never mutate the token: an email link-scanner that
renders the verify page triggers this read, but must not burn a still-
valid link before the real user clicks.
Returns one of: "valid", "used", "expired", "invalid".
"""
try:
if not token or not token.strip():
return "invalid"
doc = self.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
if not doc.exists:
return "invalid"
magic_link = MagicLinkToken(**doc.to_dict())
if magic_link.used:
return "used"
if datetime.utcnow() > magic_link.expires_at:
return "expired"
return "valid"
except Exception:
logger.exception("Error checking magic link status")
return "invalid"
def grant_welcome_credits_if_eligible(
self,
email: str,
@@ -269,6 +269,12 @@ class VisibilityChangeService:
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to delete Google Drive files: {e}")
# A track going private should also leave the public Nomad GCS fast-sync mirror
# (and thus kjbox). Prefix-keyed by brand_code, non-fatal, Nomad-only.
if brand_code:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
# Delete GCS finals if requested
if not keep_gcs_finals:
try:
+41
View File
@@ -379,6 +379,47 @@ class WorkerService:
worker_module="audio_download_worker",
)
async def trigger_bulk_search_worker(self, batch_id: str) -> bool:
"""Trigger the Bulk Mode search worker for a whole batch as a Cloud Run Job.
The worker processes every job stamped with ``batch_id``: it runs each
audio search, auto-selects confident lossless matches, and parks the rest
in AWAITING_AUDIO_SELECTION. Uses a Cloud Run Job (not BackgroundTasks) so
the batch survives API instance scale-down and the user can close the tab.
"""
try:
from google.cloud import run_v2
project = self.settings.google_cloud_project
if not project:
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger bulk search job")
return False
location = self.settings.gcp_region
job_name = f"projects/{project}/locations/{location}/jobs/bulk-search-job"
client = run_v2.JobsClient()
request = run_v2.RunJobRequest(
name=job_name,
overrides=run_v2.RunJobRequest.Overrides(
container_overrides=[
run_v2.RunJobRequest.Overrides.ContainerOverride(
args=[
"python", "-m", "backend.workers.bulk_search_worker",
"--batch-id", batch_id,
],
)
]
),
)
operation = client.run_job(request=request)
logger.info(f"[batch:{batch_id}] Started Cloud Run Job bulk-search-job: {operation.metadata}")
return True
except Exception as e:
logger.error(
f"[batch:{batch_id}] Failed to trigger bulk-search-job: {e}", exc_info=True
)
return False
async def trigger_audio_worker(self, job_id: str) -> bool:
"""
Trigger audio separation worker.
@@ -0,0 +1,129 @@
"""Tests for model-call retry/backoff on transient Vertex/Anthropic errors.
A Vertex 429 RESOURCE_EXHAUSTED is a recurring, transient condition (other
call sites like parse_titles degrade gracefully). Auto-correct should retry
with backoff and only surface a distinct, retryable 429 to the caller when
the rate limit persists — never a generic 502 that reads as a hard failure.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
_env_number,
_is_transient_model_error,
)
class _FakeClientError(Exception):
"""Mimics google.genai.errors.ClientError (has a numeric ``code``)."""
def __init__(self, code: int, message: str) -> None:
super().__init__(message)
self.code = code
def _service() -> AutoCorrectService:
return AutoCorrectService()
def test_is_transient_detects_429_resource_exhausted() -> None:
exc = _FakeClientError(429, "429 RESOURCE_EXHAUSTED. Resource exhausted.")
assert _is_transient_model_error(exc) is True
def test_is_transient_detects_503_and_overloaded() -> None:
assert _is_transient_model_error(_FakeClientError(503, "UNAVAILABLE")) is True
assert _is_transient_model_error(Exception("529 overloaded_error")) is True
def test_is_transient_ignores_permanent_client_errors() -> None:
assert _is_transient_model_error(_FakeClientError(400, "INVALID_ARGUMENT")) is False
assert _is_transient_model_error(ValueError("bad schema")) is False
def test_env_number_uses_default_when_unset(monkeypatch) -> None:
monkeypatch.delenv("AC_TEST_KNOB", raising=False)
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 3
def test_env_number_clamps_below_minimum(monkeypatch) -> None:
monkeypatch.setenv("AC_TEST_KNOB", "0")
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 1
def test_env_number_falls_back_on_garbage(monkeypatch) -> None:
monkeypatch.setenv("AC_TEST_KNOB", "not-a-number")
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 2.0
def test_env_number_rejects_non_finite(monkeypatch) -> None:
monkeypatch.setenv("AC_TEST_KNOB", "inf")
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 0.0
def test_retryable_call_retries_then_succeeds() -> None:
"""A transient failure is retried; a later success is returned."""
service = _service()
attempts = {"n": 0}
def flaky(model, system_prompt, user_prompt, *, job_id):
attempts["n"] += 1
if attempts["n"] < 3:
raise AutoCorrectServiceError(
"AI model is rate-limited", status_code=429, retryable=True
)
return {"suggestions": []}, None
with patch.object(service, "_call_gemini", side_effect=flaky), \
patch.object(service, "_call_anthropic", side_effect=flaky), \
patch("backend.services.auto_correct.service.time.sleep") as sleep:
raw, usage = service._call_model(
"gemini-3.1-pro-preview", "sys", "user", job_id="job-1"
)
assert raw == {"suggestions": []}
assert attempts["n"] == 3
assert sleep.call_count == 2 # slept before each retry
def test_retryable_call_exhausts_and_raises_429() -> None:
"""Persistent rate-limit surfaces a retryable 429, not a generic 502."""
service = _service()
def always_rate_limited(model, system_prompt, user_prompt, *, job_id):
raise AutoCorrectServiceError(
"AI model is rate-limited", status_code=429, retryable=True
)
with patch.object(service, "_call_gemini", side_effect=always_rate_limited), \
patch("backend.services.auto_correct.service.time.sleep"), \
patch("backend.services.auto_correct.service._MODEL_CALL_MAX_ATTEMPTS", 3):
with pytest.raises(AutoCorrectServiceError) as ei:
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
assert ei.value.status_code == 429
assert ei.value.retryable is True
def test_non_retryable_error_fails_fast_without_sleeping() -> None:
"""A permanent error (e.g. bad output) is not retried."""
service = _service()
calls = {"n": 0}
def bad_output(model, system_prompt, user_prompt, *, job_id):
calls["n"] += 1
raise AutoCorrectServiceError("AI returned non-JSON output", status_code=502)
with patch.object(service, "_call_gemini", side_effect=bad_output), \
patch("backend.services.auto_correct.service.time.sleep") as sleep:
with pytest.raises(AutoCorrectServiceError) as ei:
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
assert calls["n"] == 1
assert ei.value.status_code == 502
sleep.assert_not_called()
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch
import pytest
from backend.services.custom_lyrics.result import StopReason
from backend.services.custom_lyrics.service import CustomLyricsService
from backend.services.custom_lyrics.service import CustomLyricsService, CustomLyricsServiceError
from backend.services.custom_lyrics.settings import GenerationSettings, StrictnessLevel
@@ -97,6 +97,67 @@ def test_repairs_one_line(service: CustomLyricsService) -> None:
assert result.stop_reason is StopReason.SUCCESS
def test_repair_failure_falls_back_to_best(service: CustomLyricsService) -> None:
"""A failed repair call must keep the successful initial result, not 500.
Regression for job dc60ebf4: the initial generation succeeded but the repair
Gemini call returned response.text=None -> json.loads(None) TypeError ->
uncaught 500 (no CORS headers) -> browser "NetworkError". The whole good
generation was thrown away by a best-effort improvement step.
"""
target_segments = [_segment(0.0, 1.0, "aa"), _segment(1.0, 2.0, "bb")]
target_lines = ["aa", "bb"]
calls = {"n": 0}
def _fake_call(*args, **kwargs):
calls["n"] += 1
if calls["n"] == 1:
return ["xx yy zz qq", "yy"] # initial: 1 violation → triggers a repair
raise RuntimeError("Gemini returned an empty response") # repair blows up
with patch.object(CustomLyricsService, "_call_gemini", side_effect=_fake_call):
result = service.generate(
job_id="j1",
target_lines=target_lines,
target_segments=target_segments,
artist=None, title=None, custom_text="c",
file_bytes=None, file_mime=None, file_name=None,
notes=None,
settings=GenerationSettings(strictness=StrictnessLevel.BALANCED),
)
assert result.stop_reason is StopReason.REPAIR_FAILED
assert result.lines == ["xx yy zz qq", "yy"] # fell back to the initial (best)
assert calls["n"] == 2 # initial + exactly one failed repair, then stop
def test_empty_gemini_response_raises_clean_error(service: CustomLyricsService) -> None:
"""response.text=None -> CustomLyricsServiceError(502), never a raw TypeError.
The endpoint maps CustomLyricsServiceError to a proper HTTP error (with CORS);
a raw TypeError escapes to a 500 with no CORS headers, which the browser shows
as an opaque "NetworkError".
"""
fake_response = MagicMock()
fake_response.text = None
fake_response.candidates = []
fake_response.prompt_feedback = None
fake_client = MagicMock()
fake_client.models.generate_content.return_value = fake_response
with patch("backend.services.custom_lyrics.service.genai.Client", return_value=fake_client):
with pytest.raises(CustomLyricsServiceError) as exc:
service._call_gemini(
system_prompt="s",
user_prompt="u",
pdf_bytes=None,
settings=GenerationSettings(),
)
assert exc.value.status_code == 502
assert "empty response" in str(exc.value).lower()
def test_plateau_detection(service: CustomLyricsService) -> None:
target_segments = [_segment(0.0, 1.0, "aa")]
target_lines = ["aa"]
@@ -108,6 +108,24 @@ class TestDeleteOutputsSuccess:
assert data["job_id"] == "test-job-123"
assert "outputs_deleted_at" in data
def test_delete_outputs_removes_nomad_gcs_master(self, client, mock_complete_job):
"""Deleting a NOMAD job's outputs must also remove its 720p master from the
GCS fast-sync mirror (wiring guard for the delete side)."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
patch('backend.services.nomad_master_mirror.cleanup_nomad_masters') as mock_cleanup:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_complete_job # brand_code = "NOMAD-1234"
mock_jm_class.return_value = mock_jm
mock_db = Mock()
mock_db.collection.return_value.document.return_value = Mock()
mock_user_service.return_value.db = mock_db
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
assert response.status_code == 200
mock_cleanup.assert_called_once_with("NOMAD-1234")
def test_delete_outputs_clears_state_data_keys(self, client, mock_complete_job):
"""Test that output-related state_data keys are listed as cleared."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
+113
View File
@@ -14,10 +14,41 @@ from backend.workers.audio_download_worker import (
process_audio_download,
_extract_gcs_path,
_download_audio,
DOWNLOAD_WAIT_TIMEOUT_SECONDS,
)
from backend.services.audio_search_service import DownloadError
def _cloud_run_task_timeout_seconds() -> int:
"""Parse the audio-download-job task timeout from the Pulumi module."""
import pathlib
import re
src = (
pathlib.Path(__file__).resolve().parents[2]
/ "infrastructure" / "modules" / "cloud_run.py"
).read_text()
# The audio-download job block sets timeout="NNNNs" right before max_retries.
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,\s*\n\s*vpc_access=', src)
assert m, "could not locate audio-download-job timeout in cloud_run.py"
return int(m.group(1))
def test_download_wait_timeout_below_cloud_run_task_timeout():
"""The in-worker download wait MUST expire before Cloud Run SIGKILLs the task.
If they are equal (the old 600s/600s), the SIGKILL bypasses graceful
failure handling and leaves an in-flight auto-retry racing manual retries
(job 1cd29294). Keep meaningful headroom for the final upload + transition.
"""
task_timeout = _cloud_run_task_timeout_seconds()
assert DOWNLOAD_WAIT_TIMEOUT_SECONDS < task_timeout, (
f"download wait {DOWNLOAD_WAIT_TIMEOUT_SECONDS}s must be < Cloud Run "
f"task timeout {task_timeout}s"
)
assert task_timeout - DOWNLOAD_WAIT_TIMEOUT_SECONDS >= 60
def _make_job(
job_id: str = "test-job-123",
status=JobStatus.DOWNLOADING_AUDIO,
@@ -124,6 +155,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")
@@ -190,6 +226,83 @@ class TestProcessAudioDownload:
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_concurrent_run_completing_mid_download_is_idempotent(self):
"""A second run finishing while we download must not fail the job.
Regression for job 1cd29294: a manual /retry raced this task's Cloud
Run auto-retry. The loser downloaded, then tried DOWNLOADING ->
DOWNLOADING, which raised InvalidStateTransitionError, and the generic
except marked a job the winner had already advanced as FAILED. The
loser must instead detect the advance and return success without
transitioning, failing, or re-triggering downstream workers.
"""
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
# By the time our download finishes, a concurrent run advanced the job.
advanced_job = _make_job(status=JobStatus.DOWNLOADING)
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
mock_jm = MagicMock()
# Entry sees DOWNLOADING_AUDIO; the pre-transition re-read sees the
# concurrent run's advance to DOWNLOADING.
mock_jm.get_job.side_effect = [entry_job, advanced_job]
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
mock_dl.assert_awaited_once() # we did download before detecting the race
mock_jm.transition_to_state.assert_not_called()
mock_jm.fail_job.assert_not_called()
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_invalid_transition_at_commit_treated_as_success_if_advanced(self):
"""A race that slips past the guard still must not fail the job.
If the job advances between the pre-transition re-read and the
transition itself, transition_to_state returns False (raise_on_invalid
is off); we re-read, see the advance, and return success.
"""
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
mock_jm = MagicMock()
# Entry + pre-transition guard both see DOWNLOADING_AUDIO (guard
# passes); the transition fails; the post-failure re-read sees the
# concurrent advance.
mock_jm.get_job.side_effect = [
entry_job,
_make_job(status=JobStatus.DOWNLOADING_AUDIO),
_make_job(status=JobStatus.DOWNLOADING),
]
mock_jm.transition_to_state.return_value = False
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
mock_jm.fail_job.assert_not_called()
mock_ws.trigger_audio_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_uses_state_data_selection_when_available(self):
"""Should prefer state_data search results over job-level params."""
@@ -0,0 +1,93 @@
"""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, folder_exists=True, file_present=False):
storage = MagicMock()
storage.file_exists.return_value = gcs_exists
dropbox = MagicMock()
# plan_job_backfill calls dropbox.file_exists for the folder first, then the file.
calls = {"n": 0}
def _fe(_path):
calls["n"] += 1
return folder_exists if calls["n"] == 1 else file_present
dropbox.file_exists.side_effect = _fe
return storage, dropbox
class TestPlanJobBackfill:
def test_upload_when_audio_present_and_not_yet_uploaded(self):
storage, dropbox = _services(gcs_exists=True, folder_exists=True, file_present=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, folder_exists=True, file_present=True)
action, _ = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
assert action == "skip-already-present"
def test_skip_when_track_folder_missing(self):
storage, dropbox = _services(gcs_exists=True, folder_exists=False)
action, detail = plan_job_backfill(_job(), storage=storage, dropbox=dropbox)
assert action == "skip-folder-missing"
assert detail.endswith("NOMAD-1184 - Eddie Money - I'll Get By")
def test_sanitizes_artist_title_for_paths(self):
storage, dropbox = _services(gcs_exists=True, folder_exists=True, file_present=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
+173
View File
@@ -0,0 +1,173 @@
"""Tests for Bulk Mode album lookup + availability routes and the batch helper."""
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_auth, AuthResult, UserType
def _auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=999,
message="ok",
user_email="t@example.com",
is_admin=False,
)
@pytest.fixture
def client(monkeypatch):
app.dependency_overrides[require_auth] = _auth
yield TestClient(app)
app.dependency_overrides.clear()
class TestBatchHelper:
@pytest.mark.asyncio
async def test_batch_maps_community_results(self, monkeypatch):
from backend.services import karaokenerds_service as kn
async def fake_single(artist, title):
if title == "One More Time":
return {
"has_community": True,
"songs": [{"community_tracks": [{"brand_name": "KV"}, {"brand_name": "KaraFun"}]}],
"best_youtube_url": None,
}
return {"has_community": False, "songs": [], "best_youtube_url": None}
monkeypatch.setattr(kn, "check_community_versions", fake_single)
out = await kn.check_community_versions_batch(
[{"artist": "Daft Punk", "title": "One More Time"},
{"artist": "Daft Punk", "title": "Aerodynamic"}]
)
assert out[0]["available"] is True
assert out[0]["brands"] == ["KV", "KaraFun"]
assert out[1]["available"] is False
assert out[1]["brand_count"] == 0
class TestAvailabilityRoute:
def test_availability_endpoint(self, client, monkeypatch):
from backend.services import karaokenerds_service as kn
async def fake_batch(songs, concurrency=5):
return [{"artist": s["artist"], "title": s["title"], "available": True,
"brands": ["KV"], "brand_count": 1} for s in songs]
monkeypatch.setattr(kn, "check_community_versions_batch", fake_batch)
resp = client.post("/api/bulk/availability", json={"tracks": [{"artist": "A", "title": "B"}]})
assert resp.status_code == 200
assert resp.json()["results"][0]["available"] is True
def test_availability_rejects_over_limit(self, client):
tracks = [{"artist": f"A{i}", "title": f"T{i}"} for i in range(101)]
resp = client.post("/api/bulk/availability", json={"tracks": tracks})
assert resp.status_code == 422
class TestAlbumTracklistRoute:
def test_tracklist_merges_availability(self, client, monkeypatch):
from backend.services import musicbrainz_service as mbs
from backend.services import karaokenerds_service as kn
class FakeMB:
async def get_album_tracklist(self, rg, preferred_countries=None):
return {
"release_mbid": "rel1",
"canonical_release_mbid": "rel1",
"title": "Discovery",
"date": "2001",
"tracks": [
{"position": 1, "title": "One More Time", "recording_mbid": "r1",
"length_ms": 320840, "is_extra": False, "extra_reason": ""},
{"position": 2, "title": "Aerodynamic (Live)", "recording_mbid": "r2",
"length_ms": 210000, "is_extra": True, "extra_reason": "live"},
],
"editions": [{"release_mbid": "rel1", "title": "Discovery", "status": "Official",
"date": "2001", "country": "XE", "track_count": 2}],
}
async def fake_batch(songs, concurrency=5):
return [{"artist": s["artist"], "title": s["title"],
"available": s["title"] == "One More Time",
"brands": ["KV"] if s["title"] == "One More Time" else [],
"brand_count": 1 if s["title"] == "One More Time" else 0} for s in songs]
monkeypatch.setattr(mbs, "get_musicbrainz_service", lambda: FakeMB())
monkeypatch.setattr(kn, "check_community_versions_batch", fake_batch)
resp = client.get("/api/bulk/album/tracklist", params={"artist": "Daft Punk", "release_group_mbid": "rg1"})
assert resp.status_code == 200
data = resp.json()
assert data["canonical_release_mbid"] == "rel1"
assert data["tracks"][0]["available"] is True
assert data["tracks"][0]["brands"] == ["KV"]
assert data["tracks"][1]["is_extra"] is True
assert data["tracks"][1]["available"] is False
def test_tracklist_requires_an_id(self, client):
resp = client.get("/api/bulk/album/tracklist", params={"artist": "X"})
assert resp.status_code == 422
class TestVariantsAndVersions:
def test_tracklist_returns_variants_versions_and_passes_locale(self, client, monkeypatch):
from backend.services import musicbrainz_service as mbs
from backend.services import karaokenerds_service as kn
captured = {}
class FakeMB:
async def get_album_tracklist(self, rg, preferred_countries=None):
captured["prefs"] = preferred_countries
return {
"release_mbid": "rel1", "canonical_release_mbid": "rel1",
"selected_variant_mbid": "rel1", "title": "Arrival", "date": "1976",
"tracks": [{"position": 1, "title": "Dancing Queen", "recording_mbid": "r1",
"length_ms": 230000, "is_extra": False, "extra_reason": ""}],
"editions": [],
"variants": [
{"representative_release_mbid": "rel1", "label": "Original",
"track_count": 10, "year": "1976", "pressing_count": 6, "delta_vs_original": 0},
{"representative_release_mbid": "rel2", "label": "Reissue",
"track_count": 12, "year": "2014", "pressing_count": 1, "delta_vs_original": 2},
],
}
async def fake_batch(songs, concurrency=5):
return [{"artist": s["artist"], "title": s["title"], "available": True,
"brands": ["SNDL Karaoke"], "brand_count": 1,
"versions": [{"brand": "SNDL Karaoke", "url": "https://youtu.be/x"}]}
for s in songs]
monkeypatch.setattr(mbs, "get_musicbrainz_service", lambda: FakeMB())
monkeypatch.setattr(kn, "check_community_versions_batch", fake_batch)
resp = client.get("/api/bulk/album/tracklist",
params={"artist": "ABBA", "release_group_mbid": "rg", "locale": "ja"})
assert resp.status_code == 200
data = resp.json()
assert len(data["variants"]) == 2
assert data["variants"][0]["label"] == "Original"
assert data["variants"][1]["delta_vs_original"] == 2
assert data["selected_variant_mbid"] == "rel1"
assert data["tracks"][0]["versions"] == [{"brand": "SNDL Karaoke", "url": "https://youtu.be/x"}]
# Japanese locale → JP country preference threaded to MB service.
assert captured["prefs"] == ["JP"]
def test_availability_returns_versions(self, client, monkeypatch):
from backend.services import karaokenerds_service as kn
async def fake_batch(songs, concurrency=5):
return [{"artist": s["artist"], "title": s["title"], "available": True,
"brands": ["KV"], "brand_count": 1,
"versions": [{"brand": "KV", "url": "https://youtu.be/kv"}]} for s in songs]
monkeypatch.setattr(kn, "check_community_versions_batch", fake_batch)
resp = client.post("/api/bulk/availability", json={"tracks": [{"artist": "A", "title": "B"}]})
assert resp.status_code == 200
assert resp.json()["results"][0]["versions"] == [{"brand": "KV", "url": "https://youtu.be/kv"}]
+108
View File
@@ -0,0 +1,108 @@
"""Tests for Bulk Mode backend foundations.
Covers:
- batch_id summary projection regression (Task 1.1)
- pick_auto_selection tier-1 helper (Task 1.2), mirroring the frontend
tier rule in frontend/lib/audio-search-utils.ts (getSearchConfidence tier 1).
"""
class TestBatchIdProjection:
"""Regression: batch_id must be projected so the dashboard can group/filter."""
def test_batch_id_in_summary_field_paths(self):
from backend.services.firestore_service import FirestoreService
assert 'state_data.batch_id' in FirestoreService.SUMMARY_FIELD_PATHS
def test_batch_id_in_summary_state_data_keys(self):
from backend.api.routes.jobs import _SUMMARY_STATE_DATA_KEYS
assert 'batch_id' in _SUMMARY_STATE_DATA_KEYS
def _lossless_best(index=0, seeders=80, title="Bohemian Rhapsody", target_file=None):
"""A confident lossless result -> BEST CHOICE category."""
return {
"index": index,
"title": title,
"provider": "RED",
"is_lossless": True,
"seeders": seeders,
"release_type": "album",
"target_file": target_file,
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
}
def _lossy(index=0, title="Bohemian Rhapsody"):
return {
"index": index,
"title": title,
"provider": "YouTube",
"is_lossless": False,
"seeders": None,
"release_type": "",
"target_file": None,
"quality_data": {"format": "OPUS", "bitrate": 160},
}
def _vinyl_lossless(index=0, seeders=120, title="Bohemian Rhapsody"):
return {
"index": index,
"title": title,
"provider": "RED",
"is_lossless": True,
"seeders": seeders,
"release_type": "album",
"target_file": None,
"quality_data": {"format": "FLAC", "bit_depth": 24, "media": "vinyl"},
}
class TestPickAutoSelection:
"""pick_auto_selection returns an index ONLY for a confident lossless (tier-1) pick."""
def test_confident_lossless_returns_its_index(self):
from backend.services.audio_search_service import pick_auto_selection
results = [_lossy(0), _lossless_best(1, seeders=80)]
assert pick_auto_selection(results, "Bohemian Rhapsody") == 1
def test_only_lossy_returns_none(self):
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([_lossy(0), _lossy(1)], "Bohemian Rhapsody") is None
def test_lossless_but_low_seeders_returns_none(self):
# seeders < 50 -> STUDIO ALBUMS, not BEST CHOICE -> tier 2, no auto-pick
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([_lossless_best(0, seeders=10)], "Bohemian Rhapsody") is None
def test_filename_mismatch_returns_none(self):
# best is lossless+well-seeded but the file is clearly a different track
from backend.services.audio_search_service import pick_auto_selection
r = _lossless_best(0, seeders=80, title="Bohemian Rhapsody",
target_file="03 - Love of My Life.flac")
assert pick_auto_selection([r], "Bohemian Rhapsody") is None
def test_only_vinyl_lossless_returns_none(self):
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([_vinyl_lossless(0)], "Bohemian Rhapsody") is None
def test_empty_returns_none(self):
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([], "Bohemian Rhapsody") is None
def test_picks_highest_seeders_among_best_choice(self):
from backend.services.audio_search_service import pick_auto_selection
results = [_lossless_best(0, seeders=60), _lossless_best(1, seeders=200)]
assert pick_auto_selection(results, "Bohemian Rhapsody") == 1
def test_short_title_is_not_auto_selected(self):
# Too-short titles can't be verified against the filename -> defer to human.
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([_lossless_best(0, seeders=80, title="Go")], "Go") is None
def test_partial_word_filename_is_a_mismatch(self):
# Title "One" must NOT match a file for "Someone" (whole-word matching).
from backend.services.audio_search_service import pick_auto_selection
r = _lossless_best(0, seeders=80, title="Someone", target_file="04 - Someone.flac")
assert pick_auto_selection([r], "One") is None
+84
View File
@@ -0,0 +1,84 @@
"""Tests for GET /api/bulk/{batch_id} progress summary."""
from unittest.mock import MagicMock
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_auth, AuthResult, UserType
from backend.models.job import JobStatus
def _auth(is_admin=False, email="t@example.com"):
def _dep():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN if is_admin else UserType.STRIPE,
remaining_uses=999, message="ok", user_email=email, is_admin=is_admin,
)
return _dep
def _job(job_id, status, email="t@example.com", pending=False, auto=False, artist="A", title="T"):
j = MagicMock()
j.job_id = job_id
j.status = status
j.user_email = email
j.artist = artist
j.title = title
j.audio_search_artist = artist
j.audio_search_title = title
j.state_data = {"batch_id": "b1", "bulk_pending_search": pending, "bulk_auto_selected": auto}
return j
@pytest.fixture
def client():
c = TestClient(app)
yield c
app.dependency_overrides.clear()
def test_progress_buckets(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth()
jm = MagicMock()
jm.list_jobs_by_batch_id.return_value = [
_job("j1", JobStatus.AWAITING_AUDIO_SELECTION),
_job("j2", JobStatus.DOWNLOADING_AUDIO, auto=True),
_job("j3", JobStatus.COMPLETE, auto=True),
_job("j4", JobStatus.SEARCHING_AUDIO, pending=True),
]
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
resp = client.get("/api/bulk/b1")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["total"] == 4
assert data["counts"]["awaiting_selection"] == 1
assert data["counts"]["processing"] == 1
assert data["counts"]["complete"] == 1
assert data["counts"]["searching"] == 1
j2 = next(j for j in data["jobs"] if j["job_id"] == "j2")
assert j2["auto_selected"] is True
def test_other_users_batch_is_404(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth(email="me@example.com")
jm = MagicMock()
jm.list_jobs_by_batch_id.return_value = [_job("j1", JobStatus.COMPLETE, email="someone@else.com")]
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
resp = client.get("/api/bulk/b1")
assert resp.status_code == 404
def test_admin_sees_any_batch(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth(is_admin=True, email="admin@example.com")
jm = MagicMock()
jm.list_jobs_by_batch_id.return_value = [_job("j1", JobStatus.COMPLETE, email="someone@else.com")]
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
resp = client.get("/api/bulk/b1")
assert resp.status_code == 200
assert resp.json()["total"] == 1
+178
View File
@@ -0,0 +1,178 @@
"""Tests for the Bulk Mode search worker: auto-select vs park branching."""
from unittest.mock import MagicMock
import pytest
import backend.workers.bulk_search_worker as worker
from backend.models.job import JobStatus
from backend.services.audio_search_service import NoResultsError
class FakeResult:
def __init__(self, d):
self._d = d
def to_dict(self):
return self._d
def _lossless_best(index=0, seeders=80, duration=240):
return {
"index": index, "title": "One More Time", "artist": "Daft Punk",
"provider": "RED", "is_lossless": True, "seeders": seeders,
"release_type": "album", "target_file": "01 - One More Time.flac",
"duration": duration, "source_id": "abc",
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
}
def _lossy(index=0):
return {
"index": index, "title": "One More Time", "artist": "Daft Punk",
"provider": "YouTube", "is_lossless": False, "seeders": None,
"release_type": "", "duration": 240, "quality_data": {"format": "OPUS"},
}
def _make_job(job_id="job1", auto=True, state_extra=None):
job = MagicMock()
job.job_id = job_id
job.artist = "Daft Punk"
job.title = "One More Time"
job.audio_search_artist = "Daft Punk"
job.audio_search_title = "One More Time"
job.theme_id = None # skip theme prep
job.user_email = "t@example.com"
job.state_data = {"batch_id": "b1", "bulk_settings": {"auto_select_if_lossless": auto},
"bulk_pending_search": True, "credits_charged": 1}
if state_extra:
job.state_data.update(state_extra)
return job
@pytest.fixture
def patched(monkeypatch):
jm = MagicMock()
transitions = []
jm.transition_to_state.side_effect = lambda **kw: transitions.append(kw["new_status"]) or True
ass = MagicMock()
ass.last_remote_search_id = "remote-1"
# default no theme prep import path needed (theme_id None)
monkeypatch.setattr(worker, "get_worker_service", lambda: _async_worker_service())
return jm, ass, transitions
def _async_worker_service():
ws = MagicMock()
async def _dl(job_id):
return True
ws.trigger_audio_download_worker = _dl
return ws
@pytest.mark.asyncio
async def test_auto_selects_confident_lossless(monkeypatch, patched):
jm, ass, transitions = patched
job = _make_job(auto=True)
jm.get_job.return_value = job
async def _search(artist, title):
return [FakeResult(_lossy(0)), FakeResult(_lossless_best(1))]
ass.search_async = _search
# No duration delta owed (240s -> 1 credit, already charged 1)
monkeypatch.setattr(worker, "_validate_and_prepare_selection_imported", None, raising=False)
monkeypatch.setattr("backend.api.routes.audio_search._validate_and_prepare_selection",
lambda job_id, idx: {"ok": True})
await worker.process_job("job1", jm, ass)
# Auto path: should NOT end in AWAITING_AUDIO_SELECTION; SEARCHING_AUDIO only
assert JobStatus.AWAITING_AUDIO_SELECTION not in transitions
# bulk_auto_selected True recorded
final = jm.update_job.call_args[0][1]
assert final["state_data.bulk_auto_selected"] is True
assert final["state_data.bulk_pending_search"] is False
@pytest.mark.asyncio
async def test_parks_when_only_lossy(monkeypatch, patched):
jm, ass, transitions = patched
jm.get_job.return_value = _make_job(auto=True)
async def _search(artist, title):
return [FakeResult(_lossy(0))]
ass.search_async = _search
await worker.process_job("job1", jm, ass)
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
final = jm.update_job.call_args[0][1]
assert final["state_data.bulk_pending_search"] is False
@pytest.mark.asyncio
async def test_parks_when_auto_disabled_even_if_lossless(monkeypatch, patched):
jm, ass, transitions = patched
jm.get_job.return_value = _make_job(auto=False)
async def _search(artist, title):
return [FakeResult(_lossless_best(0))]
ass.search_async = _search
await worker.process_job("job1", jm, ass)
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
@pytest.mark.asyncio
async def test_no_results_parks(monkeypatch, patched):
jm, ass, transitions = patched
jm.get_job.return_value = _make_job(auto=True)
async def _search(artist, title):
raise NoResultsError("nope")
ass.search_async = _search
await worker.process_job("job1", jm, ass)
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
@pytest.mark.asyncio
async def test_auto_select_charges_duration_delta(monkeypatch, patched):
jm, ass, transitions = patched
# 1300s -> ceil(1300/600)=3 credits; already charged 1 -> owed 2
job = _make_job(auto=True)
jm.get_job.return_value = job
async def _search(artist, title):
return [FakeResult(_lossless_best(0, duration=1300))]
ass.search_async = _search
us = MagicMock()
us.deduct_credits.return_value = (True, 0, "ok")
monkeypatch.setattr(worker, "get_user_service", lambda: us)
monkeypatch.setattr("backend.api.routes.audio_search._validate_and_prepare_selection",
lambda job_id, idx: {"ok": True})
await worker.process_job("job1", jm, ass)
us.deduct_credits.assert_called_once()
_, kwargs = us.deduct_credits.call_args
assert kwargs["amount"] == 2 # the delta
@pytest.mark.asyncio
async def test_auto_select_parks_when_delta_unaffordable(monkeypatch, patched):
jm, ass, transitions = patched
jm.get_job.return_value = _make_job(auto=True)
async def _search(artist, title):
return [FakeResult(_lossless_best(0, duration=1300))]
ass.search_async = _search
us = MagicMock()
us.deduct_credits.return_value = (False, 0, "insufficient")
monkeypatch.setattr(worker, "get_user_service", lambda: us)
await worker.process_job("job1", jm, ass)
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
+150
View File
@@ -0,0 +1,150 @@
"""Tests for POST /api/bulk/submit — upfront credit gate + batch job creation."""
from unittest.mock import MagicMock
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_auth, AuthResult, UserType
from backend.exceptions import InsufficientCreditsError
def _auth(is_admin=False, email="t@example.com"):
def _dep():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN if is_admin else UserType.STRIPE,
remaining_uses=999,
message="ok",
user_email=email,
is_admin=is_admin,
)
return _dep
@pytest.fixture(autouse=True)
def _patch_deps(monkeypatch):
"""Patch the heavy collaborators used by bulk_submit."""
import backend.api.routes.bulk as bulk
# Theme + settings + cdg/txt
theme = MagicMock()
theme.get_default_theme_id.return_value = "nomad"
monkeypatch.setattr("backend.services.theme_service.get_theme_service", lambda: theme)
monkeypatch.setattr("backend.services.job_defaults_service.resolve_cdg_txt_defaults", lambda *a, **k: (False, False))
settings = MagicMock(
default_brand_prefix="NOMAD", default_enable_youtube_upload=False,
default_youtube_description="", default_discord_webhook_url=None,
default_dropbox_path=None, default_gdrive_folder_id=None,
)
monkeypatch.setattr("backend.config.get_settings", lambda: settings)
# Worker trigger
worker = MagicMock()
async def _trigger(batch_id):
return True
worker.trigger_bulk_search_worker = _trigger
monkeypatch.setattr("backend.services.worker_service.get_worker_service", lambda: worker)
yield
def _patch_user_service(monkeypatch, credits):
us = MagicMock()
us.check_credits.return_value = credits
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: us)
return us
def _patch_job_manager(monkeypatch, fail_after=None):
"""JobManager whose create_job returns sequential ids, optionally failing after N."""
created = {"count": 0}
jm = MagicMock()
def _create_job(job_create, is_admin=False):
if fail_after is not None and created["count"] >= fail_after:
raise InsufficientCreditsError(message="out", credits_available=0, credits_required=1)
created["count"] += 1
job = MagicMock()
job.job_id = f"job{created['count']}"
return job
jm.create_job.side_effect = _create_job
jm.update_job.return_value = None
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
return jm
@pytest.fixture
def client():
c = TestClient(app)
yield c
app.dependency_overrides.clear()
def test_happy_path_creates_jobs_and_dispatches(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth()
_patch_user_service(monkeypatch, credits=10)
jm = _patch_job_manager(monkeypatch)
resp = client.post("/api/bulk/submit", json={
"songs": [{"artist": "Daft Punk", "title": "One More Time"},
{"artist": "Daft Punk", "title": "Aerodynamic"}],
"settings": {"auto_select_if_lossless": True, "is_private": False},
})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["total"] == 2
assert len(data["job_ids"]) == 2
assert jm.create_job.call_count == 2
# batch_id + bulk settings stamped via update_job
assert jm.update_job.call_count == 2
_, kwargs_call = jm.update_job.call_args
stamped = jm.update_job.call_args[0][1]
assert "state_data.batch_id" in stamped
assert stamped["state_data.bulk_pending_search"] is True
def test_insufficient_credits_creates_nothing(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth()
_patch_user_service(monkeypatch, credits=1)
jm = _patch_job_manager(monkeypatch)
resp = client.post("/api/bulk/submit", json={
"songs": [{"artist": "A", "title": "B"}, {"artist": "C", "title": "D"}],
})
assert resp.status_code == 402
assert jm.create_job.call_count == 0
def test_admin_bypasses_credit_gate(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth(is_admin=True)
us = _patch_user_service(monkeypatch, credits=0)
jm = _patch_job_manager(monkeypatch)
resp = client.post("/api/bulk/submit", json={"songs": [{"artist": "A", "title": "B"}]})
assert resp.status_code == 200
us.check_credits.assert_not_called()
assert jm.create_job.call_count == 1
def test_rejects_over_100(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth()
_patch_user_service(monkeypatch, credits=1000)
_patch_job_manager(monkeypatch)
songs = [{"artist": f"A{i}", "title": f"T{i}"} for i in range(101)]
resp = client.post("/api/bulk/submit", json={"songs": songs})
assert resp.status_code == 422
def test_partial_failure_returns_created_jobs(client, monkeypatch):
app.dependency_overrides[require_auth] = _auth()
_patch_user_service(monkeypatch, credits=3) # gate passes for 3
jm = _patch_job_manager(monkeypatch, fail_after=2) # but only 2 succeed
resp = client.post("/api/bulk/submit", json={
"songs": [{"artist": "A", "title": "1"}, {"artist": "A", "title": "2"}, {"artist": "A", "title": "3"}],
})
assert resp.status_code == 200
assert resp.json()["total"] == 2
+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."""
+77 -14
View File
@@ -2,6 +2,12 @@
Unit tests for encoding worker lifecycle endpoints.
Tests the warmup and heartbeat API endpoints.
These endpoints are called from the customer-facing lyrics-review page to
pre-warm the encoding VM. They are therefore gated on ``require_review_auth``
(review access to a specific job), NOT ``require_admin`` — otherwise every
non-admin customer 403s and the pre-warm silently never happens (the bug this
suite guards against).
"""
import logging
@@ -10,16 +16,24 @@ from unittest.mock import MagicMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.encoding_worker import router, get_worker_manager
from backend.api.dependencies import require_admin
from backend.api.dependencies import require_admin, require_review_auth
from backend.services.encoding_errors import (
EncodingWorkerCapacityError,
EncodingWorkerStartError,
)
JOB_ID = "test-job-123"
WARMUP_URL = f"/api/internal/encoding-worker/warmup/{JOB_ID}"
HEARTBEAT_URL = f"/api/internal/encoding-worker/heartbeat/{JOB_ID}"
def get_mock_admin():
"""Override for require_admin dependency."""
return ("admin-token", "admin", 0)
async def fake_review_auth():
"""Override for require_review_auth — stands in for a review user.
Deliberately returns a *non-admin* auth result (auth_type="full") so the
tests exercise the review-scoped path, not admin access.
"""
return (JOB_ID, "full")
class TestWarmupEndpoint:
@@ -27,7 +41,7 @@ class TestWarmupEndpoint:
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[require_review_auth] = fake_review_auth
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
@@ -37,7 +51,7 @@ class TestWarmupEndpoint:
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
data = response.json()
assert data["started"] is True
@@ -49,7 +63,7 @@ class TestWarmupEndpoint:
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert response.json()["started"] is False
@@ -57,7 +71,7 @@ class TestWarmupEndpoint:
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
"VM not found"
)
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert response.json()["started"] is False
assert "error" in response.json()
@@ -78,7 +92,7 @@ class TestWarmupEndpoint:
)
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert response.json()["started"] is False
warmup_records = [
@@ -106,7 +120,7 @@ class TestWarmupEndpoint:
)
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert not [
r
@@ -121,7 +135,7 @@ class TestWarmupEndpoint:
"misconfigured service account"
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
error_records = [
r
@@ -137,12 +151,12 @@ class TestHeartbeatEndpoint:
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[require_review_auth] = fake_review_auth
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
def test_heartbeat_updates_activity(self):
response = self.client.post("/api/internal/encoding-worker/heartbeat")
response = self.client.post(HEARTBEAT_URL)
assert response.status_code == 200
assert response.json()["status"] == "ok"
self.mock_manager.update_activity.assert_called_once()
@@ -151,6 +165,55 @@ class TestHeartbeatEndpoint:
self.mock_manager.update_activity.side_effect = RuntimeError(
"Firestore error"
)
response = self.client.post("/api/internal/encoding-worker/heartbeat")
response = self.client.post(HEARTBEAT_URL)
assert response.status_code == 200
assert response.json()["status"] == "error"
class TestReviewAuthGating:
"""Regression guard: these endpoints must be review-auth gated, not admin.
Before this fix they used ``require_admin``, so every non-admin customer on
the lyrics-review page got a 403 and the JIT pre-warm never happened.
"""
def test_routes_depend_on_review_auth_not_admin(self):
"""The route dependencies reference require_review_auth, never require_admin."""
deps = set()
for route in router.routes:
dependant = getattr(route, "dependant", None)
if dependant is None:
continue
# Flatten the whole dependency tree for the route.
stack = list(dependant.dependencies)
while stack:
d = stack.pop()
deps.add(d.call)
stack.extend(d.dependencies)
assert require_review_auth in deps, (
"warmup/heartbeat must be gated on require_review_auth"
)
assert require_admin not in deps, (
"warmup/heartbeat must NOT require admin (regresses pre-warm for "
"all non-admin customers)"
)
def test_unauthenticated_request_is_rejected(self):
"""With real auth (no override, no token), warmup is rejected — not 200/500."""
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
client = TestClient(app, raise_server_exceptions=False)
response = client.post(WARMUP_URL)
# require_review_auth with no credentials raises 401.
assert response.status_code == 401
def test_job_id_is_required_in_path(self):
"""The old job-less path no longer exists (404), forcing job scoping."""
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[require_review_auth] = fake_review_auth
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
client = TestClient(app)
response = client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 404
+146 -2
View File
@@ -1249,7 +1249,7 @@ class TestURLValidation:
def test_other_supported_platforms(self):
"""Test other supported video platforms."""
from backend.api.routes.file_upload import _validate_url
valid_urls = [
"https://twitter.com/user/status/123",
"https://x.com/user/status/123",
@@ -1257,11 +1257,155 @@ class TestURLValidation:
"https://www.instagram.com/reel/abc123/",
"https://www.tiktok.com/@user/video/123",
]
for url in valid_urls:
assert _validate_url(url), f"URL should be valid: {url}"
class TestUnsupportedDrmUrl:
"""Test detection of DRM-protected streaming URLs that can't be downloaded."""
def test_apple_music_urls_detected(self):
from backend.api.routes.file_upload import _unsupported_url_platform
urls = [
# The exact URL from the prod incident (job 7f36304a)
"https://music.apple.com/us/album/gone-country-apple-music-sessions/1752594347?i=1752594711",
"https://music.apple.com/gb/album/whatever/123",
"https://itunes.apple.com/us/album/whatever/123",
]
for url in urls:
assert _unsupported_url_platform(url) == "Apple Music", url
def test_spotify_urls_detected(self):
from backend.api.routes.file_upload import _unsupported_url_platform
urls = [
"https://open.spotify.com/track/abc123",
"https://play.spotify.com/track/abc123",
"https://spotify.com/track/abc123",
]
for url in urls:
assert _unsupported_url_platform(url) == "Spotify", url
def test_other_drm_platforms_detected(self):
from backend.api.routes.file_upload import _unsupported_url_platform
cases = {
"https://tidal.com/browse/track/123": "Tidal",
"https://listen.tidal.com/track/123": "Tidal",
"https://music.amazon.com/albums/B0ABC": "Amazon Music",
"https://music.amazon.co.uk/albums/B0ABC": "Amazon Music",
"https://music.amazon.co.jp/albums/B0ABC": "Amazon Music",
"https://music.amazon.fr/albums/B0ABC": "Amazon Music",
"https://www.deezer.com/track/123": "Deezer",
"https://www.pandora.com/artist/song": "Pandora",
}
for url, platform in cases.items():
assert _unsupported_url_platform(url) == platform, url
def test_supported_urls_not_flagged(self):
from backend.api.routes.file_upload import _unsupported_url_platform
# YouTube Music IS downloadable and must NOT be flagged.
ok_urls = [
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"https://youtu.be/dQw4w9WgXcQ",
"https://music.youtube.com/watch?v=dQw4w9WgXcQ",
"https://vimeo.com/123",
"https://soundcloud.com/artist/track",
"https://example.com/some/audio.mp3",
"",
None,
]
for url in ok_urls:
assert _unsupported_url_platform(url) is None, url
def test_downloader_suggestions_are_valid(self):
"""Every downloader suggestion maps a real platform to a list of https URLs."""
from backend.api.routes.file_upload import (
_DRM_DOWNLOADER_SUGGESTIONS,
_UNSUPPORTED_DRM_HOSTS,
)
known_platforms = set(_UNSUPPORTED_DRM_HOSTS.values()) | {"Amazon Music"}
for platform, urls in _DRM_DOWNLOADER_SUGGESTIONS.items():
assert platform in known_platforms, f"{platform} is not a known DRM platform"
assert isinstance(urls, list) and urls, f"{platform} must list downloaders"
for url in urls:
assert url.startswith("https://"), f"{platform} downloader must be https"
# The verified cases driving this feature.
assert "https://am-dl.pages.dev" in _DRM_DOWNLOADER_SUGGESTIONS["Apple Music"]
assert "https://aplmate.com" in _DRM_DOWNLOADER_SUGGESTIONS["Apple Music"]
assert "https://spotdown.org" in _DRM_DOWNLOADER_SUGGESTIONS["Spotify"]
assert "https://spotmate.online" in _DRM_DOWNLOADER_SUGGESTIONS["Spotify"]
def test_drm_detail_links_known_downloaders(self):
"""Platforms with known tools get a message naming each downloader URL."""
from backend.api.routes.file_upload import _drm_unsupported_detail
apple = _drm_unsupported_detail("en", "Apple Music")
assert "https://am-dl.pages.dev" in apple
assert "https://aplmate.com" in apple
spotify = _drm_unsupported_detail("en", "Spotify")
assert "https://spotdown.org" in spotify
assert "https://spotmate.online" in spotify
def test_drm_detail_falls_back_to_web_search(self):
"""Platforms without a known tool get a Google search link for a downloader."""
from backend.api.routes.file_upload import _drm_unsupported_detail
detail = _drm_unsupported_detail("en", "Tidal")
assert "https://www.google.com/search?q=Tidal+downloader" in detail
assert "Tidal" in detail
class TestValidateJobUrlEndpoint:
"""The /jobs/validate-url pre-flight check used by the guided submission flow."""
def _call(self, url):
import asyncio
from unittest.mock import MagicMock, patch
from backend.api.routes.file_upload import validate_job_url, ValidateUrlRequest
req = MagicMock()
req.headers = {}
with patch("backend.api.routes.file_upload.get_locale_from_request", return_value="en"):
return asyncio.run(
validate_job_url(
request=req,
body=ValidateUrlRequest(url=url),
auth_result=MagicMock(),
)
)
def test_apple_music_rejected_with_links(self):
r = self._call("https://music.apple.com/us/album/x/1?i=2")
assert r.supported is False
assert "am-dl.pages.dev" in r.detail
def test_spotify_rejected_with_links(self):
r = self._call("https://open.spotify.com/track/abc")
assert r.supported is False
assert "spotdown.org" in r.detail
def test_tidal_rejected_with_search_link(self):
r = self._call("https://tidal.com/browse/track/123")
assert r.supported is False
assert "google.com/search" in r.detail
def test_youtube_supported(self):
r = self._call("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
assert r.supported is True
assert r.detail is None
def test_garbage_url_rejected(self):
r = self._call("not a real url")
assert r.supported is False
class TestCreateJobFromUrlRequest:
"""Test CreateJobFromUrlRequest Pydantic model."""
+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()
+216 -9
View File
@@ -419,10 +419,11 @@ class TestUploadToPublicShare:
cdg_file.write_bytes(b"cdg package")
service = GoogleDriveService()
# Mock methods
with patch.object(service, "get_or_create_folder") as mock_get_folder:
with patch.object(service, "upload_file") as mock_upload:
with patch.object(service, "get_or_create_folder") as mock_get_folder, \
patch.object(service, "upload_file") as mock_upload, \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
mock_get_folder.side_effect = [
"mp4-folder-id",
"mp4-720-folder-id",
@@ -433,31 +434,187 @@ class TestUploadToPublicShare:
"720p-file-id",
"cdg-file-id",
]
output_files = {
"final_karaoke_lossy_mp4": str(mp4_file),
"final_karaoke_lossy_720p_mp4": str(mp4_720_file),
"final_karaoke_cdg_zip": str(cdg_file),
}
result = service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files=output_files,
)
# Should have created/found 3 folders
assert mock_get_folder.call_count == 3
# Should have uploaded 3 files
assert mock_upload.call_count == 3
# Check result
assert result["mp4"] == "mp4-file-id"
assert result["mp4_720p"] == "720p-file-id"
assert result["cdg"] == "cdg-file-id"
# Nomad brand → the 720p master is fast-synced to the Divebar GCS
# mirror with the exact "{brand_code} - {base_name}.mp4" object name.
mock_mirror_cls.return_value.push_720p.assert_called_once_with(
str(mp4_720_file), "NOMAD-1163 - Artist - Title.mp4"
)
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_no_fast_sync_for_non_nomad_brand(self, mock_get_settings, tmp_path):
"""Non-Nomad brands (and NOMADNP privates) must NOT touch the divebar mirror."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
mp4_720_file = tmp_path / "output_720p.mp4"
mp4_720_file.write_bytes(b"720p video")
service = GoogleDriveService()
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
for brand in ("VOCALSTAR-12", "NOMADNP-1163"):
service.upload_to_public_share(
root_folder_id="root-123",
brand_code=brand,
base_name="Artist - Title",
output_files={"final_karaoke_lossy_720p_mp4": str(mp4_720_file)},
)
mock_mirror_cls.assert_not_called()
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_fast_sync_failure_is_non_fatal(self, mock_get_settings, tmp_path):
"""A mirror failure must never break the (already-succeeded) Drive upload."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
mp4_720_file = tmp_path / "output_720p.mp4"
mp4_720_file.write_bytes(b"720p video")
service = GoogleDriveService()
warnings: list = []
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="720p-file-id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror",
side_effect=RuntimeError("gcs down")):
result = service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files={"final_karaoke_lossy_720p_mp4": str(mp4_720_file)},
warnings=warnings,
)
# Drive upload still reports success despite the mirror blowing up...
assert result["mp4_720p"] == "720p-file-id"
# ...and the failure is surfaced as a distribution warning (admin alert),
# not silently swallowed.
assert any("fast-sync" in w for w in warnings)
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_pushes_vocals_guide_for_nomad(self, mock_get_settings, tmp_path):
"""A pre-built original-vocals guide is pushed to the vocals prefix with the exact
"{brand_code} - {base_name}.flac" object name (matches the master's naming)."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
mp4_720_file = tmp_path / "output_720p.mp4"
mp4_720_file.write_bytes(b"720p video")
guide_file = tmp_path / "original_vocals_guide.flac"
guide_file.write_bytes(b"guide flac")
service = GoogleDriveService()
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
mock_mirror_cls.return_value.push_vocals_guide.return_value = True
service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files={
"final_karaoke_lossy_720p_mp4": str(mp4_720_file),
"original_vocals_guide": str(guide_file),
},
)
mock_mirror_cls.return_value.push_vocals_guide.assert_called_once_with(
str(guide_file), "NOMAD-1163 - Artist - Title.flac"
)
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_no_vocals_guide_for_non_nomad(self, mock_get_settings, tmp_path):
"""Non-Nomad / NOMADNP brands must never push a guide to the public mirror."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
guide_file = tmp_path / "original_vocals_guide.flac"
guide_file.write_bytes(b"guide flac")
service = GoogleDriveService()
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMADNP-1163",
base_name="Artist - Title",
output_files={"original_vocals_guide": str(guide_file)},
)
mock_mirror_cls.assert_not_called()
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_vocals_guide_failure_is_non_fatal(self, mock_get_settings, tmp_path):
"""A guide push failure surfaces a warning but never breaks the Drive upload."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
guide_file = tmp_path / "original_vocals_guide.flac"
guide_file.write_bytes(b"guide flac")
service = GoogleDriveService()
warnings: list = []
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
mock_mirror_cls.return_value.push_vocals_guide.return_value = False
service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files={"original_vocals_guide": str(guide_file)},
warnings=warnings,
)
assert any("guide" in w.lower() for w in warnings)
@patch("backend.services.gdrive_service.get_settings")
def test_upload_to_public_share_skips_missing_files(
self, mock_get_settings, tmp_path
@@ -928,6 +1085,56 @@ class TestFindFilesByBrandCode:
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
@patch("backend.services.gdrive_service.get_settings")
def test_recovers_from_transient_connection_error(self, mock_get_settings):
"""A transient BrokenPipe/SSL EOF within a subfolder search is retried, not fatal.
Regression for the "GDrive brand_code search incomplete: 2/3 subfolder(s) failed"
alerts caused by [SSL: UNEXPECTED_EOF_WHILE_READING] / [Errno 32] Broken pipe
against idle Cloud Run containers.
"""
service = self._make_service(mock_get_settings)
# Prevent _reset_service (called in before_sleep) from nulling our mock.
service._reset_service = Mock()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
BrokenPipeError("Errno 32 Broken pipe"), # transient drop mid-search
{"files": [{"id": "cdg-folder"}]}, # retry: subfolder found again
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
{"files": []}, # MP4 not found
{"files": []}, # MP4-720p not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == ["cdg-file-1"]
service._reset_service.assert_called() # a retry actually happened
@patch("backend.services.gdrive_service.get_settings")
def test_persistent_transient_error_still_raises_incomplete(self, mock_get_settings):
"""If retries are exhausted, the search is still reported as incomplete (not clean)."""
service = self._make_service(mock_get_settings)
service._reset_service = Mock()
mock_files_api = Mock()
mock_list_result = Mock()
# Every call drops the connection — retries exhaust for all subfolders.
mock_list_result.execute.side_effect = BrokenPipeError("Errno 32 Broken pipe")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
class TestGetGdriveService:
"""Test get_gdrive_service singleton."""
+167
View File
@@ -9,6 +9,8 @@ from backend.services.karaokenerds_service import (
parse_results,
_clean_youtube_url,
_parse_single_track,
check_community_versions,
check_community_versions_batch,
)
from bs4 import BeautifulSoup
@@ -207,3 +209,168 @@ def test_parse_results_empty_html():
def test_parse_results_no_table():
assert parse_results("<div>No results</div>") == []
# --- Batch availability: per-version data with YouTube URLs (Bulk Mode) ---
@pytest.mark.asyncio
async def test_batch_returns_versions_with_urls_deduped_by_brand(monkeypatch):
"""Each result carries `versions: [{brand, url}]` (community only), deduped by
brand keeping the first URL, alongside the existing brands/brand_count."""
async def fake_check(artist, title):
return {
"has_community": True,
"songs": [
{
"title": title,
"artist": artist,
"community_tracks": [
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
"youtube_url": "https://www.youtube.com/watch?v=aaa", "is_community": True},
{"brand_name": "Nomad Karaoke", "brand_code": "NK",
"youtube_url": "https://www.youtube.com/watch?v=bbb", "is_community": True},
# Duplicate brand — should be collapsed, keeping the first URL.
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
"youtube_url": "https://www.youtube.com/watch?v=ccc", "is_community": True},
],
}
],
"best_youtube_url": "https://www.youtube.com/watch?v=aaa",
}
monkeypatch.setattr(
"backend.services.karaokenerds_service.check_community_versions", fake_check
)
results = await check_community_versions_batch(
[{"artist": "ABBA", "title": "Dancing Queen"}]
)
assert len(results) == 1
r = results[0]
assert r["available"] is True
assert r["versions"] == [
{"brand": "SNDL Karaoke", "url": "https://www.youtube.com/watch?v=aaa"},
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=bbb"},
]
# Back-compat retained.
assert r["brands"] == ["SNDL Karaoke", "Nomad Karaoke"]
assert r["brand_count"] == 2
@pytest.mark.asyncio
async def test_batch_empty_song_has_empty_versions():
results = await check_community_versions_batch([{"artist": "", "title": ""}])
assert results[0]["available"] is False
assert results[0]["versions"] == []
# --- check_community_versions: overlong-query fallback (KaraokeNerds term cap) ---
def _community_song(title, artist, brand="Nomad Karaoke", url="https://youtu.be/x"):
return {
"title": title,
"artist": artist,
"tracks": [
{"brand_name": brand, "brand_code": "NK", "youtube_url": url, "is_community": True}
],
}
@pytest.fixture(autouse=True)
def _clear_community_cache():
"""check_community_versions caches in-process; isolate each test."""
from backend.services import karaokenerds_service as svc
svc._cache.clear()
yield
svc._cache.clear()
@pytest.mark.asyncio
async def test_overlong_query_falls_back_to_title_only(monkeypatch):
"""An overlong "artist title" query that returns nothing retries title-only
and matches by artist (the ABBA 'I Do, I Do, I Do, I Do, I Do' bug)."""
title = "I Do, I Do, I Do, I Do, I Do"
calls = []
async def fake_search(query):
calls.append(query)
if query == f"ABBA {title}":
return [] # combined query is too long -> KaraokeNerds returns nothing
if query == title:
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
return []
monkeypatch.setattr(
"backend.services.karaokenerds_service._search_songs", fake_search
)
result = await check_community_versions("ABBA", title)
assert result["has_community"] is True
assert result["songs"][0]["artist"] == "ABBA"
assert calls == [f"ABBA {title}", title] # combined first, then title-only fallback
@pytest.mark.asyncio
async def test_fallback_filters_out_wrong_artist(monkeypatch):
"""Title-only fallback is broader, so same-titled songs by other artists
must be discarded — no false positive."""
title = "I Do, I Do, I Do, I Do, I Do"
async def fake_search(query):
if query == title:
return [_community_song("I Do I Do I Do I Do I Do", "Some Other Band")]
return []
monkeypatch.setattr(
"backend.services.karaokenerds_service._search_songs", fake_search
)
result = await check_community_versions("ABBA", title)
assert result["has_community"] is False
assert result["songs"] == []
@pytest.mark.asyncio
async def test_short_empty_query_does_not_fall_back(monkeypatch):
"""A short query that legitimately returns nothing must NOT trigger a second
request (avoids doubling load for songs with no community version)."""
calls = []
async def fake_search(query):
calls.append(query)
return []
monkeypatch.setattr(
"backend.services.karaokenerds_service._search_songs", fake_search
)
result = await check_community_versions("ABBA", "Dancing Queen")
assert result["has_community"] is False
assert calls == ["ABBA Dancing Queen"] # no fallback request
@pytest.mark.asyncio
async def test_nonempty_combined_result_skips_fallback(monkeypatch):
"""If the combined query returns results, never fall back even when long."""
title = "I Do, I Do, I Do, I Do, I Do"
calls = []
async def fake_search(query):
calls.append(query)
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
monkeypatch.setattr(
"backend.services.karaokenerds_service._search_songs", fake_search
)
result = await check_community_versions("ABBA", title)
assert result["has_community"] is True
assert calls == [f"ABBA {title}"] # only the combined query ran
+132
View File
@@ -0,0 +1,132 @@
"""
Unit tests for UserService.get_magic_link_status.
This is a READ-ONLY status check used by the verify page to decide, on load,
whether to show the "Complete Sign-In" gate (valid link) or an "already used /
expired" message (dead link). It must NEVER consume the token — otherwise an
email link-scanner that renders the verify page would burn a valid link before
the real user clicks, which is exactly the bug this whole feature prevents.
"""
import sys
from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
import pytest
# Mock Firestore before importing modules that use it.
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from fastapi.testclient import TestClient
def _service_with_doc(mock_fs, mock_settings, doc_dict, exists=True):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_doc = MagicMock()
mock_doc.exists = exists
mock_doc.to_dict.return_value = doc_dict
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
return UserService(), mock_db
def _link_dict(**overrides):
d = {
'token': 'tok123',
'email': 'user@example.com',
'created_at': datetime.utcnow(),
'expires_at': datetime.utcnow() + timedelta(hours=1),
'used': False,
'used_at': None,
}
d.update(overrides)
return d
class TestGetMagicLinkStatus:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_valid_link_returns_valid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
assert service.get_magic_link_status('tok123') == 'valid'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_valid_link_is_not_consumed(self, mock_fs, mock_settings):
"""The scanner-safety guarantee: a status check must not mutate the token."""
service, mock_db = _service_with_doc(mock_fs, mock_settings, _link_dict())
service.get_magic_link_status('tok123')
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_not_called()
doc_ref.set.assert_not_called()
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_used_link_returns_used(self, mock_fs, mock_settings):
service, _ = _service_with_doc(
mock_fs, mock_settings, _link_dict(used=True, used_at=datetime.utcnow())
)
assert service.get_magic_link_status('tok123') == 'used'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_expired_link_returns_expired(self, mock_fs, mock_settings):
service, _ = _service_with_doc(
mock_fs, mock_settings, _link_dict(expires_at=datetime.utcnow() - timedelta(minutes=1))
)
assert service.get_magic_link_status('tok123') == 'expired'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_missing_link_returns_invalid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, {}, exists=False)
assert service.get_magic_link_status('missing') == 'invalid'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_empty_token_returns_invalid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
assert service.get_magic_link_status(' ') == 'invalid'
class TestLinkStatusEndpoint:
"""GET /api/users/auth/link-status — thin, read-only wrapper over the service."""
def _client(self, status_value):
from backend.main import app
from backend.services.user_service import get_user_service
svc = MagicMock()
svc.get_magic_link_status.return_value = status_value
app.dependency_overrides[get_user_service] = lambda: svc
return TestClient(app), app, svc
def test_endpoint_returns_status_for_valid(self):
client, app, svc = self._client("valid")
try:
r = client.get("/api/users/auth/link-status", params={"token": "tok123"})
assert r.status_code == 200
assert r.json()["status"] == "valid"
svc.get_magic_link_status.assert_called_once_with("tok123")
finally:
app.dependency_overrides.clear()
def test_endpoint_returns_used(self):
client, app, svc = self._client("used")
try:
r = client.get("/api/users/auth/link-status", params={"token": "burned"})
assert r.status_code == 200
assert r.json()["status"] == "used"
finally:
app.dependency_overrides.clear()
def test_endpoint_returns_invalid_for_empty_token_without_touching_firestore(self):
client, app, svc = self._client("valid") # service would say valid, but route must short-circuit
try:
r = client.get("/api/users/auth/link-status", params={"token": " "})
assert r.status_code == 200
assert r.json()["status"] == "invalid"
svc.get_magic_link_status.assert_not_called()
finally:
app.dependency_overrides.clear()
+278
View File
@@ -0,0 +1,278 @@
"""Tests for the MusicBrainz lookup service (Bulk Mode album lookup).
HTTP is mocked; fixtures mirror real API shapes captured 2026-06.
"""
import pytest
from backend.services.musicbrainz_service import (
MusicBrainzService,
classify_extra,
)
class TestClassifyExtra:
def test_plain_studio_track_is_not_extra(self):
assert classify_extra("One More Time") == (False, "")
def test_live_in_parens_is_extra(self):
is_extra, reason = classify_extra("Bohemian Rhapsody (Live at Wembley)")
assert is_extra is True
assert "live" in reason.lower()
def test_remix_after_dash_is_extra(self):
is_extra, _ = classify_extra("Get Lucky - Daft Punk Remix")
assert is_extra is True
def test_bonus_disambiguation_is_extra(self):
is_extra, _ = classify_extra("Some Song", disambiguation="bonus track")
assert is_extra is True
def test_word_in_normal_title_not_flagged(self):
# "Alive" contains "live" but not as a standalone qualifier keyword
assert classify_extra("Alive") == (False, "")
# "Living on a Prayer" should not be flagged
assert classify_extra("Living on a Prayer") == (False, "")
class TestPickCanonical:
def test_prefers_modal_track_count_then_earliest(self):
editions = [
{"release_mbid": "deluxe", "status": "Official", "date": "2011", "country": "US", "track_count": 20},
{"release_mbid": "std-2001", "status": "Official", "date": "2001-03-12", "country": "XE", "track_count": 14},
{"release_mbid": "std-2005", "status": "Official", "date": "2005", "country": "US", "track_count": 14},
{"release_mbid": "promo", "status": "Promotion", "date": "2000", "country": "US", "track_count": 14},
]
chosen = MusicBrainzService.pick_canonical_edition(editions)
# modal count is 14 (std-2001, std-2005, promo-but-not-official filtered);
# earliest official among 14-track -> std-2001
assert chosen["release_mbid"] == "std-2001"
def test_empty_returns_none(self):
assert MusicBrainzService.pick_canonical_edition([]) is None
class TestBuildVariants:
"""Collapse a release-group's editions into distinct tracklist variants."""
def test_same_track_count_editions_collapse_to_one_variant(self):
editions = [
{"release_mbid": "us76", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
{"release_mbid": "se76", "status": "Official", "date": "1976", "country": "SE", "track_count": 10},
{"release_mbid": "nl76", "status": "Official", "date": "1976", "country": "NL", "track_count": 10},
]
variants = MusicBrainzService.build_variants(editions)
assert len(variants) == 1
v = variants[0]
assert v["track_count"] == 10
assert v["pressing_count"] == 3
assert v["label"] == "Original"
assert v["year"] == "1976"
assert v["delta_vs_original"] == 0
# earliest date (all 1976) then preferred country US over SE/NL
assert v["representative_release_mbid"] == "us76"
def test_distinct_track_counts_form_separate_variants_sorted_original_first(self):
editions = [
{"release_mbid": "reissue2014", "status": "Official", "date": "2014", "country": "XW", "track_count": 12},
{"release_mbid": "orig1976", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
]
variants = MusicBrainzService.build_variants(editions)
assert [v["representative_release_mbid"] for v in variants] == ["orig1976", "reissue2014"]
assert variants[0]["label"] == "Original"
assert variants[0]["delta_vs_original"] == 0
assert variants[1]["label"] == "Reissue"
assert variants[1]["delta_vs_original"] == 2
assert variants[1]["year"] == "2014"
def test_single_edition_is_one_original_variant(self):
editions = [{"release_mbid": "only", "status": "Official", "date": "1990", "country": "GB", "track_count": 11}]
variants = MusicBrainzService.build_variants(editions)
assert len(variants) == 1
assert variants[0]["label"] == "Original"
assert variants[0]["pressing_count"] == 1
def test_no_editions_no_variants(self):
assert MusicBrainzService.build_variants([]) == []
def test_editions_without_tracks_excluded(self):
editions = [
{"release_mbid": "real", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
{"release_mbid": "empty", "status": "Official", "date": "1976", "country": "GB", "track_count": 0},
]
variants = MusicBrainzService.build_variants(editions)
assert len(variants) == 1
assert variants[0]["representative_release_mbid"] == "real"
def test_preferred_countries_override_picks_representative(self):
editions = [
{"release_mbid": "us76", "status": "Official", "date": "1976", "country": "US", "track_count": 10},
{"release_mbid": "jp76", "status": "Official", "date": "1976", "country": "JP", "track_count": 10},
]
variants = MusicBrainzService.build_variants(editions, preferred_countries=["JP"])
assert variants[0]["representative_release_mbid"] == "jp76"
class TestLocaleCountryPrefs:
def test_english_locale_prefers_anglophone_countries(self):
from backend.services.musicbrainz_service import country_prefs_for_locale
assert country_prefs_for_locale("en") == ["GB", "US", "AU", "CA", "IE", "NZ"]
def test_region_suffix_is_stripped(self):
from backend.services.musicbrainz_service import country_prefs_for_locale
assert country_prefs_for_locale("en-US") == ["GB", "US", "AU", "CA", "IE", "NZ"]
def test_japanese_locale(self):
from backend.services.musicbrainz_service import country_prefs_for_locale
assert country_prefs_for_locale("ja") == ["JP"]
def test_unknown_and_none_fall_back_to_default(self):
from backend.services.musicbrainz_service import country_prefs_for_locale
default = ["XW", "XE", "US", "GB"]
assert country_prefs_for_locale("zz") == default
assert country_prefs_for_locale(None) == default
assert country_prefs_for_locale("") == default
@pytest.mark.asyncio
class TestServiceCalls:
async def _svc_with(self, monkeypatch, responses):
"""Return a service whose _get returns canned responses keyed by path prefix."""
svc = MusicBrainzService()
async def fake_get(path, params):
for key, val in responses.items():
if path.startswith(key):
return val
raise AssertionError(f"unexpected path {path}")
monkeypatch.setattr(svc, "_get", fake_get)
return svc
async def test_search_artists_parses(self, monkeypatch):
svc = await self._svc_with(
monkeypatch,
{
"artist": {
"artists": [
{"id": "abc", "name": "Daft Punk", "disambiguation": "", "type": "Group", "country": "FR", "score": 100}
]
}
},
)
out = await svc.search_artists("Daft Punk")
assert out[0]["mbid"] == "abc"
assert out[0]["name"] == "Daft Punk"
async def test_album_tracklist_resolves_canonical_and_flags_extras(self, monkeypatch):
editions = {
"release": {
"releases": [
{"id": "rel-std", "title": "Discovery", "status": "Official", "date": "2001-03-12", "country": "XE", "media": [{"track-count": 3}]},
{"id": "rel-deluxe", "title": "Discovery (Deluxe)", "status": "Official", "date": "2021", "country": "US", "media": [{"track-count": 5}]},
]
}
}
tracklist = {
"release/rel-std": {
"id": "rel-std",
"title": "Discovery",
"date": "2001-03-12",
"country": "XE",
"media": [
{
"format": "CD",
"track-count": 3,
"tracks": [
{"position": 1, "title": "One More Time", "length": 320840, "recording": {"id": "r1", "title": "One More Time", "disambiguation": "", "length": 320840}},
{"position": 2, "title": "Aerodynamic", "length": 207533, "recording": {"id": "r2", "title": "Aerodynamic", "disambiguation": "", "length": 207533}},
{"position": 3, "title": "Aerodynamic (Live)", "length": 210000, "recording": {"id": "r3", "title": "Aerodynamic", "disambiguation": "live", "length": 210000}},
],
}
],
}
}
# _list_editions calls _get("release", {release-group...}); tracklist calls _get("release/<id>", ...)
# Order matters: "release/rel-std" must match before "release".
svc = MusicBrainzService()
async def fake_get(path, params):
if path.startswith("release/"):
return tracklist[path]
if path == "release":
return editions["release"]
raise AssertionError(path)
monkeypatch.setattr(svc, "_get", fake_get)
result = await svc.get_album_tracklist("rg-discovery")
assert result["canonical_release_mbid"] == "rel-std" # modal 3-track studio edition
assert len(result["tracks"]) == 3
assert result["tracks"][0]["is_extra"] is False
assert result["tracks"][2]["is_extra"] is True # the (Live) track
assert len(result["editions"]) == 2
# Variants: 3-track original + 5-track reissue; selected = canonical.
variants = result["variants"]
assert len(variants) == 2
assert variants[0]["label"] == "Original"
assert variants[0]["track_count"] == 3
assert variants[1]["label"] == "Reissue"
assert variants[1]["delta_vs_original"] == 2
assert result["selected_variant_mbid"] == result["canonical_release_mbid"]
import httpx as _httpx
class _FakeResp:
def __init__(self, status, json_data=None):
self.status_code = status
self._json = json_data
self.request = _httpx.Request("GET", "https://musicbrainz.org/ws/2/artist")
def raise_for_status(self):
if self.status_code >= 400:
raise _httpx.HTTPStatusError(
f"{self.status_code}", request=self.request, response=self
)
def json(self):
return self._json
def _patch_http(monkeypatch, mbs, svc, responses):
"""Make AsyncClient.get return queued _FakeResp objects; disable throttle/backoff."""
async def _noop():
return None
monkeypatch.setattr(svc, "_throttle", _noop)
monkeypatch.setattr(mbs, "_RETRY_BACKOFF_S", 0)
calls = {"n": 0}
async def fake_get(self, url, **kwargs):
r = responses[min(calls["n"], len(responses) - 1)]
calls["n"] += 1
return r
monkeypatch.setattr(_httpx.AsyncClient, "get", fake_get)
return calls
@pytest.mark.asyncio
class TestRetry:
async def test_retries_503_then_succeeds(self, monkeypatch):
from backend.services import musicbrainz_service as mbs
svc = mbs.MusicBrainzService()
calls = _patch_http(monkeypatch, mbs, svc, [
_FakeResp(503),
_FakeResp(200, {"artists": [{"id": "x", "name": "Queen"}]}),
])
out = await svc.search_artists("Queen")
assert out[0]["mbid"] == "x"
assert calls["n"] == 2 # one 503 retry, then success
async def test_exhausts_retries_raises(self, monkeypatch):
from backend.services import musicbrainz_service as mbs
svc = mbs.MusicBrainzService()
_patch_http(monkeypatch, mbs, svc, [_FakeResp(503)])
with pytest.raises(_httpx.HTTPStatusError):
await svc.search_artists("Queen")
+208
View File
@@ -0,0 +1,208 @@
"""Unit tests for the Nomad master fast-sync mirror (Phase 1)."""
from unittest.mock import MagicMock
import pytest
from google.cloud.exceptions import NotFound
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
@pytest.mark.parametrize(
"brand_code, expected",
[
("NOMAD-1500", True),
("NOMAD-0001", True),
("NOMAD-1500", True),
("NOMADNP-1234", False), # private tracks must never enter the public mirror
("nomadnp-1", False),
("TRACK-0000", False),
("VOCALSTAR-12", False),
("", False),
(None, False),
],
)
def test_is_nomad_public_brand(brand_code, expected):
assert is_nomad_public_brand(brand_code) is expected
def _mirror_with_mock():
"""NomadMasterMirror wired to a mock GCS client; returns (mirror, blob)."""
blob = MagicMock()
bucket = MagicMock()
bucket.blob.return_value = blob
client = MagicMock()
client.bucket.return_value = bucket
mirror = NomadMasterMirror(client=client)
return mirror, bucket, blob
def test_push_720p_uses_exact_divebar_object_name_and_uploads():
mirror, bucket, blob = _mirror_with_mock()
ok = mirror.push_720p(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
"NOMAD-1500 - Rush - The Spirit of Radio.mp4",
)
assert ok is True
# Object name MUST match the nightly VM's layout exactly (idempotency).
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
blob.upload_from_filename.assert_called_once_with(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
def test_push_720p_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.upload_from_filename.side_effect = RuntimeError("boom")
# Must not raise; returns False so the pipeline continues.
assert mirror.push_720p("/tmp/x.mp4", "NOMAD-1 - A - B.mp4") is False
def test_delete_720p_removes_blob():
mirror, bucket, blob = _mirror_with_mock()
assert mirror.delete_720p("NOMAD-1500 - Rush - The Spirit of Radio.mp4") is True
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
blob.delete.assert_called_once()
def test_delete_720p_missing_is_noop():
mirror, _bucket, blob = _mirror_with_mock()
blob.delete.side_effect = NotFound("gone")
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
def test_delete_720p_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.delete.side_effect = RuntimeError("boom")
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
# --- delete_masters_by_brand (prefix delete; covers renames) ---
def _mirror_with_blobs(names):
blobs = []
for n in names:
b = MagicMock()
b.name = n
blobs.append(b)
bucket = MagicMock()
bucket.list_blobs.return_value = blobs
client = MagicMock()
client.bucket.return_value = bucket
return NomadMasterMirror(client=client), bucket, blobs
def test_delete_masters_by_brand_deletes_all_matching_by_prefix():
# Two objects for the same release (e.g. an old + renamed title) both go.
mirror, bucket, blobs = _mirror_with_blobs([
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - Spirit of Radio.mp4",
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
])
n = mirror.delete_masters_by_brand("NOMAD-1500")
assert n == 2
bucket.list_blobs.assert_called_once_with(
prefix="files/Nomad Karaoke/MP4-720p/NOMAD-1500 - "
)
for b in blobs:
b.delete.assert_called_once()
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
def test_delete_masters_by_brand_refuses_non_nomad_or_bare(brand):
# Must never list/delete for a non-Nomad or bare brand — a broad prefix could
# wipe unrelated objects.
mirror, bucket, _blobs = _mirror_with_blobs([])
assert mirror.delete_masters_by_brand(brand) == 0
bucket.list_blobs.assert_not_called()
def test_delete_masters_by_brand_is_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
assert mirror.delete_masters_by_brand("NOMAD-1500") == 0
# --- vocals guide push / delete (parallel to the master methods) ---
def test_push_vocals_guide_uses_vocals_prefix_and_uploads():
mirror, bucket, blob = _mirror_with_mock()
ok = mirror.push_vocals_guide(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac",
"NOMAD-1500 - Rush - The Spirit of Radio.flac",
)
assert ok is True
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac"
)
blob.upload_from_filename.assert_called_once_with(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac"
)
def test_push_vocals_guide_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.upload_from_filename.side_effect = RuntimeError("boom")
assert mirror.push_vocals_guide("/tmp/x.flac", "NOMAD-1 - A - B.flac") is False
def test_delete_vocals_guides_by_brand_deletes_all_matching_by_prefix():
mirror, bucket, blobs = _mirror_with_blobs([
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - Spirit of Radio.flac",
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac",
])
n = mirror.delete_vocals_guides_by_brand("NOMAD-1500")
assert n == 2
bucket.list_blobs.assert_called_once_with(
prefix="files/Nomad Karaoke/vocals-padded/NOMAD-1500 - "
)
for b in blobs:
b.delete.assert_called_once()
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
def test_delete_vocals_guides_by_brand_refuses_non_nomad_or_bare(brand):
mirror, bucket, _blobs = _mirror_with_blobs([])
assert mirror.delete_vocals_guides_by_brand(brand) == 0
bucket.list_blobs.assert_not_called()
def test_delete_vocals_guides_by_brand_is_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
assert mirror.delete_vocals_guides_by_brand("NOMAD-1500") == 0
def test_cleanup_nomad_masters_delegates_for_nomad(monkeypatch):
from backend.services import nomad_master_mirror as mod
inst = MagicMock()
inst.delete_masters_by_brand.return_value = 3
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: inst)
assert mod.cleanup_nomad_masters("NOMAD-1500") == 3
inst.delete_masters_by_brand.assert_called_once_with("NOMAD-1500")
# Brand recycle must also clear the release's original-vocals guide(s).
inst.delete_vocals_guides_by_brand.assert_called_once_with("NOMAD-1500")
@pytest.mark.parametrize("brand", ["NOMADNP-1", "OTHER-1", "", None])
def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
from backend.services import nomad_master_mirror as mod
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
assert mod.cleanup_nomad_masters(brand) == 0
+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
+112
View File
@@ -0,0 +1,112 @@
"""Unit tests for the padded original-vocals guide builder."""
import os
import shutil
import subprocess
import pytest
from backend.services.original_vocals_guide import (
build_original_vocals_guide,
probe_duration,
)
pytestmark = pytest.mark.skipif(
shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None,
reason="ffmpeg/ffprobe not available",
)
@pytest.fixture
def tone(tmp_path):
"""A 4-second 440Hz tone standing in for the mixed-vocals stem."""
src = tmp_path / "vocals.flac"
subprocess.run(
["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
"-i", "sine=frequency=440:duration=4", "-c:a", "flac", str(src)],
check=True,
)
return str(src)
def _first_sound_onset(path):
"""Seconds until audio first exceeds the silence threshold (leading-silence length)."""
out = subprocess.run(
["ffmpeg", "-hide_banner", "-i", path, "-af",
"silencedetect=noise=-50dB:d=0.1", "-f", "null", "-"],
capture_output=True, text=True,
).stderr
# A guide with N seconds of leading silence reports "silence_end: N".
for line in out.splitlines():
if "silence_end:" in line:
return float(line.split("silence_end:")[1].split("|")[0].strip())
return 0.0
def test_prepends_intro_silence_and_reports_expected_duration(tmp_path, tone):
dest = str(tmp_path / "NOMAD-1500 - A - B.flac")
out = build_original_vocals_guide(tone, intro_seconds=5, dest_path=dest)
assert out == dest
assert os.path.isfile(dest)
# silence[5] + 4s tone ≈ 9s total, with the tone starting ~5s in.
total = probe_duration(dest)
assert total == pytest.approx(9.0, abs=0.3)
assert _first_sound_onset(dest) == pytest.approx(5.0, abs=0.3)
def test_respects_non_default_intro(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
build_original_vocals_guide(tone, intro_seconds=10, dest_path=dest)
# Proves we honour the job's actual intro, not a hardcoded 5s.
assert _first_sound_onset(dest) == pytest.approx(10.0, abs=0.3)
def test_caps_to_master_duration(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
# silence[5] + 4s tone would be 9s; cap to 7s.
build_original_vocals_guide(tone, intro_seconds=5, dest_path=dest, master_duration=7.0)
assert probe_duration(dest) == pytest.approx(7.0, abs=0.3)
def test_output_is_valid_flac(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
build_original_vocals_guide(tone, intro_seconds=1, dest_path=dest)
codec = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "a:0",
"-show_entries", "stream=codec_name", "-of",
"default=noprint_wrappers=1:nokey=1", dest],
capture_output=True, text=True,
).stdout.strip()
assert codec == "flac"
def test_no_part_file_left_behind(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
build_original_vocals_guide(tone, intro_seconds=1, dest_path=dest)
assert not os.path.exists(dest + ".part")
def test_missing_input_returns_none(tmp_path):
out = build_original_vocals_guide(
str(tmp_path / "nope.flac"), intro_seconds=5, dest_path=str(tmp_path / "g.flac")
)
assert out is None
assert not os.path.exists(tmp_path / "g.flac")
def test_negative_intro_returns_none(tmp_path, tone):
assert build_original_vocals_guide(tone, intro_seconds=-1, dest_path=str(tmp_path / "g.flac")) is None
def test_ffmpeg_failure_is_non_fatal(tmp_path, tone):
# A bogus ffmpeg binary must not raise; just returns None.
out = build_original_vocals_guide(
tone, intro_seconds=5, dest_path=str(tmp_path / "g.flac"),
ffmpeg_path="/nonexistent/ffmpeg",
)
assert out is None
assert not os.path.exists(str(tmp_path / "g.flac") + ".part")
def test_probe_duration_missing_file_returns_none(tmp_path):
assert probe_duration(str(tmp_path / "nope.flac")) is None
+174
View File
@@ -0,0 +1,174 @@
import asyncio
from backend.services.parse_titles import ai
from backend.services.parse_titles import service
def test_settings_parse_titles_defaults():
from backend.config import Settings
s = Settings()
assert s.parse_titles_enabled is True
assert s.parse_titles_model == "gemini-3.5-flash"
assert s.parse_titles_timeout_ms == 20000
assert s.parse_titles_max_items == 200
def test_build_prompts_lists_items_with_ids():
system, user = ai.build_prompts(
[{"id": "a", "filename": "Santeria - Sublime _ Karaoke _ KaraFun.mp4",
"channel": "KaraFun", "source": "youtube"}]
)
assert "artist" in system.lower() and "title" in system.lower()
assert "id='a'" in user or '"a"' in user or "id=a" in user # id must be echoed
assert "Santeria" in user
def test_parse_map_from_response_aligns_by_id_and_fills_misses():
items = [{"id": "a", "filename": "x"}, {"id": "b", "filename": "y"}]
data = {"results": [{"id": "a", "artist": "Sublime", "title": "Santeria",
"confidence": 0.9}]}
out = ai.parse_map_from_response(data, items)
assert {r["id"] for r in out} == {"a", "b"}
a = next(r for r in out if r["id"] == "a")
assert (a["artist"], a["title"]) == ("Sublime", "Santeria")
b = next(r for r in out if r["id"] == "b")
assert b["artist"] == "" and b["title"] == "" and b["confidence"] == 0.0
def test_ai_parse_uses_injected_generate():
items = [{"id": "a", "filename": "Bella Kay - iloveit (Karaoke Version).mp4"}]
async def fake_generate(model, system, user):
return {"results": [{"id": "a", "artist": "Bella Kay",
"title": "iloveit", "confidence": 0.82}]}
out = asyncio.run(ai.ai_parse(items, generate=fake_generate))
assert out[0]["artist"] == "Bella Kay" and out[0]["confidence"] == 0.82
def test_parse_map_handles_garbage_response():
items = [{"id": "a", "filename": "x"}]
assert ai.parse_map_from_response("not a dict", items) == [
{"id": "a", "artist": "", "title": "", "confidence": 0.0}
]
def test_parse_titles_disabled_returns_blanks(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", False)
out = asyncio.run(service.parse_titles([{"id": "a", "filename": "x"}]))
assert out == [{"id": "a", "artist": "", "title": "", "confidence": 0.0}]
def test_parse_titles_degrades_on_generate_error(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
async def boom(model, system, user):
raise RuntimeError("vertex down")
out = asyncio.run(service.parse_titles(
[{"id": "a", "filename": "x"}], generate=boom))
assert out == [{"id": "a", "artist": "", "title": "", "confidence": 0.0}]
def test_parse_titles_happy_path(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
async def gen(model, system, user):
return {"results": [{"id": "a", "artist": "Queen",
"title": "Bohemian Rhapsody", "confidence": 0.95}]}
out = asyncio.run(service.parse_titles([{"id": "a", "filename": "x"}], generate=gen))
assert out[0]["artist"] == "Queen" and out[0]["confidence"] == 0.95
def test_parse_titles_empty_returns_empty():
assert asyncio.run(service.parse_titles([])) == []
# --- auto-chunking: large batches must not ride one >20s Gemini call ---
def _items(n):
return [{"id": str(i), "filename": f"file {i}.mp4"} for i in range(n)]
def _ok_results(model, system, user):
"""Echo one parsed result per '- id=' line in the user prompt."""
ids = [line.split("id='", 1)[1].split("'", 1)[0]
for line in user.splitlines() if line.startswith("- id=")]
return {"results": [{"id": i, "artist": f"A{i}", "title": f"T{i}",
"confidence": 0.9} for i in ids]}
def test_settings_parse_titles_chunk_size_default():
from backend.config import Settings
assert Settings().parse_titles_chunk_size == 10
def test_parse_titles_chunks_large_batches(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
calls = []
async def gen(model, system, user):
n = sum(1 for line in user.splitlines() if line.startswith("- id="))
calls.append(n)
return _ok_results(model, system, user)
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
assert sorted(calls, reverse=True) == [10, 10, 5] # 25 items -> 3 Gemini calls
assert [r["id"] for r in out] == [str(i) for i in range(25)] # id-aligned
assert all(r["artist"] == f'A{r["id"]}' for r in out)
def test_parse_titles_chunk_failure_degrades_only_that_chunk(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
async def gen(model, system, user):
if "id='10'" in user: # the middle chunk (items 10-19)
raise RuntimeError("vertex timeout")
return _ok_results(model, system, user)
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
assert out[0]["artist"] == "A0" and out[24]["artist"] == "A24"
assert all(out[i]["artist"] == "" and out[i]["confidence"] == 0.0
for i in range(10, 20)) # only that chunk blank
assert [r["id"] for r in out] == [str(i) for i in range(25)]
def test_parse_titles_chunks_run_concurrently(monkeypatch):
"""The chunks must be issued in parallel — a 100-item batch shouldn't pay
10 sequential Gemini round-trips."""
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
started = 0
all_started = asyncio.Event()
async def gen(model, system, user):
nonlocal started
started += 1
if started == 3:
all_started.set()
# Sequential execution would deadlock here on the first chunk.
await asyncio.wait_for(all_started.wait(), timeout=5)
return _ok_results(model, system, user)
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
assert len(out) == 25 and out[0]["artist"] == "A0"
def test_parse_titles_respects_configured_chunk_size(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
monkeypatch.setattr(settings, "parse_titles_chunk_size", 4, raising=False)
calls = []
async def gen(model, system, user):
calls.append(sum(1 for line in user.splitlines() if line.startswith("- id=")))
return _ok_results(model, system, user)
asyncio.run(service.parse_titles(_items(10), generate=gen))
assert sorted(calls, reverse=True) == [4, 4, 2]
+59
View File
@@ -0,0 +1,59 @@
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_admin
def _admin_result():
from backend.services.auth_service import AuthResult, UserType
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=-1,
message="ok", user_email="a@nomadkaraoke.com", is_admin=True)
def test_parse_route_happy_path(monkeypatch):
# Self-contained: set our own admin override rather than relying on the
# conftest autouse fixture (which can be disturbed by earlier tests in a
# full-suite run and leave the endpoint returning 401).
from backend.api.routes import parse_titles as route
async def fake_parse(items, **kw):
return [{"id": str(it["id"]), "artist": "Queen",
"title": "Bohemian Rhapsody", "confidence": 0.9} for it in items]
monkeypatch.setattr(route, "parse_titles", fake_parse)
original = app.dependency_overrides.get(require_admin)
app.dependency_overrides[require_admin] = _admin_result
try:
client = TestClient(app)
resp = client.post("/api/parse-karaoke-titles", json={
"items": [{"id": "1", "filename": "x.mp4", "source": "youtube"}]})
assert resp.status_code == 200
body = resp.json()
assert body["results"][0]["id"] == "1"
assert body["results"][0]["artist"] == "Queen"
finally:
if original is not None:
app.dependency_overrides[require_admin] = original
else:
app.dependency_overrides.pop(require_admin, None)
def test_parse_route_requires_admin():
"""The route is gated by require_admin: a non-admin dependency -> 403."""
original = app.dependency_overrides.get(require_admin)
def non_admin():
from fastapi import HTTPException
raise HTTPException(status_code=403, detail="Admin access required")
app.dependency_overrides[require_admin] = non_admin
try:
client = TestClient(app)
resp = client.post("/api/parse-karaoke-titles",
json={"items": [{"id": "1", "filename": "x"}]})
assert resp.status_code == 403
finally:
if original is not None:
app.dependency_overrides[require_admin] = original
else:
app.dependency_overrides.pop(require_admin, None)
+84 -3
View File
@@ -397,9 +397,90 @@ class TestRetryEndpoint:
file_urls={}
)
# This job has no input audio - should not be retryable
has_input = job.input_media_gcs_path or job.url
assert not has_input
# This job has no input audio - should not be retryable.
# Restart-from-beginning is gated on audio actually being in GCS, NOT on
# job.url (a URL whose download failed has no audio to re-fetch).
has_input_audio_in_gcs = job.input_media_gcs_path
assert not has_input_audio_in_gcs
class TestRetryUrlJobWithoutDownload:
"""Regression tests for the retry routing fix (incident: job 7f36304a).
A URL job whose download failed has `job.url` set but NO audio in GCS.
Retrying it must NOT trigger the audio/lyrics workers (which would fail with
"Failed to download audio file" and be retried by Cloud Run); it must refuse
cleanly with a 400 telling the user to resubmit.
"""
def _call_retry(self, job, mock_jm, mock_ws, background_tasks):
import asyncio
from backend.api.routes.jobs import retry_job
mock_jm.get_job.return_value = job
mock_request = MagicMock()
mock_request.headers = {}
async def _run():
return await retry_job(
job_id=job.job_id,
request=mock_request,
background_tasks=background_tasks,
auth_result=MagicMock(is_admin=True, user_email="t@t.com"),
)
with patch("backend.api.routes.jobs.job_manager", mock_jm), \
patch("backend.api.routes.jobs.worker_service", mock_ws), \
patch("backend.api.routes.jobs._check_job_ownership", return_value=True), \
patch("backend.api.routes.jobs._is_auto_retry_pending", return_value=False), \
patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"):
return asyncio.run(_run())
def _make_url_job(self, *, input_media_gcs_path=None):
return Job(
job_id="urljob1",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Hailey Whitters",
title="Gone Country",
url="https://music.apple.com/us/album/gone-country/1752594347?i=1752594711",
input_media_gcs_path=input_media_gcs_path,
file_urls={},
)
def test_url_job_without_download_refuses_and_triggers_no_workers(self):
"""URL job with no downloaded audio → 400 resubmit, no workers triggered."""
from fastapi import HTTPException
job = self._make_url_job(input_media_gcs_path=None)
mock_jm, mock_ws = MagicMock(), MagicMock()
background_tasks = MagicMock()
with pytest.raises(HTTPException) as exc:
self._call_retry(job, mock_jm, mock_ws, background_tasks)
assert exc.value.status_code == 400
assert "resubmit" in str(exc.value.detail).lower()
# The doomed workers must NOT have been scheduled.
scheduled = [c.args[0] for c in background_tasks.add_task.call_args_list]
assert mock_ws.trigger_audio_worker not in scheduled
assert mock_ws.trigger_lyrics_worker not in scheduled
def test_url_job_with_downloaded_audio_restarts_from_beginning(self):
"""URL job whose download succeeded (audio in GCS) → restarts + workers."""
job = self._make_url_job(input_media_gcs_path="uploads/urljob1/audio/in.flac")
mock_jm, mock_ws = MagicMock(), MagicMock()
mock_jm.transition_to_state.return_value = True
background_tasks = MagicMock()
result = self._call_retry(job, mock_jm, mock_ws, background_tasks)
assert result["status"] == "success"
assert result["retry_stage"] == "from_beginning"
scheduled = [c.args[0] for c in background_tasks.add_task.call_args_list]
assert mock_ws.trigger_audio_worker in scheduled
assert mock_ws.trigger_lyrics_worker in scheduled
class TestCompleteReviewWithInstrumentalSelection:
@@ -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,156 @@ 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)
class TestOriginalVocalsGuideEmit:
"""The write-path emit of the padded original-vocals guide at finalize."""
def _orch(self, brand="NOMAD-1500", video_720p=None, job_manager=None):
config = OrchestratorConfig(
job_id="job-1", artist="A", title="B",
title_video_path="/t.mov", karaoke_video_path="/k.mov",
instrumental_audio_path="/a.flac",
)
orch = VideoWorkerOrchestrator(config, job_manager=job_manager, storage=MagicMock())
orch.result.brand_code = brand
orch.result.final_video_720p = video_720p
return orch
@pytest.mark.asyncio
async def test_emit_skips_non_nomad(self, tmp_path):
v = tmp_path / "v.mp4"; v.write_bytes(b"x")
orch = self._orch(brand="VOCALSTAR-1", video_720p=str(v))
assert await orch._emit_original_vocals_guide("VOCALSTAR-1") is None
orch.storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_emit_none_when_no_720p(self):
orch = self._orch(brand="NOMAD-1500", video_720p=None)
assert await orch._emit_original_vocals_guide("NOMAD-1500") is None
@pytest.mark.asyncio
async def test_emit_builds_guide_for_nomad(self, tmp_path):
v = tmp_path / "v.mp4"; v.write_bytes(b"video")
orch = self._orch(brand="NOMAD-1500", video_720p=str(v), job_manager=None)
with patch("backend.services.original_vocals_guide.build_original_vocals_guide",
return_value="/tmp/guide.flac") as mb, \
patch("backend.services.original_vocals_guide.probe_duration", return_value=200.0):
out = await orch._emit_original_vocals_guide("NOMAD-1500")
assert out == "/tmp/guide.flac"
# The mixed-vocals stem is pulled from the job's GCS stems path.
assert orch.storage.download_file.call_args[0][0] == "jobs/job-1/stems/vocals_clean.flac"
# Built with the resolved intro (5s fallback, no job_manager) capped to master dur.
assert mb.call_args[0][1] == 5.0
assert mb.call_args.kwargs.get("master_duration") == 200.0
@pytest.mark.asyncio
async def test_emit_none_when_stem_download_fails(self, tmp_path):
v = tmp_path / "v.mp4"; v.write_bytes(b"video")
orch = self._orch(brand="NOMAD-1500", video_720p=str(v))
orch.storage.download_file.side_effect = RuntimeError("gone")
assert await orch._emit_original_vocals_guide("NOMAD-1500") is None
@pytest.mark.asyncio
async def test_resolve_intro_seconds_defaults_to_5_without_job_manager(self):
orch = self._orch(job_manager=None)
assert await orch._resolve_intro_seconds() == 5.0
@pytest.mark.asyncio
async def test_resolve_intro_seconds_preserves_explicit_zero(self):
# A style with no title card (video_duration=0) must NOT collapse to the 5s
# default — that would push the guide's vocals 5s late.
orch = self._orch(job_manager=MagicMock())
orch.job_manager.get_job.return_value = MagicMock()
fake_style = MagicMock()
fake_style.get_intro_format.return_value = {"video_duration": 0}
async def fake_load(*a, **k):
return fake_style
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 0.0
@pytest.mark.asyncio
async def test_resolve_intro_seconds_honors_long_intro_style(self):
# A long-intro style (e.g. 8s) must be read, not assumed to be 5s.
orch = self._orch(job_manager=MagicMock())
orch.job_manager.get_job.return_value = MagicMock()
fake_style = MagicMock()
fake_style.get_intro_format.return_value = {"video_duration": 8}
async def fake_load(*a, **k):
return fake_style
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 8.0
+3
View File
@@ -83,6 +83,9 @@
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
"selectionError": "Error during audio selection for job {job_id}: {error}",
"youtubeDownloadError": "YouTube download failed: {error}",
"drmUrlUnsupported": "{platform} links are copy-protected, so we can't download them directly. Try downloading the audio with a third-party tool first, then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedWithLink": "{platform} links are copy-protected, so we can't download them directly. You can download the track using a tool like {downloader} and then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedSearch": "{platform} links are copy-protected, so we can't download them directly. Search the web for a \"{platform} downloader\" to get the audio — for example {searchUrl} — then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download",
"remoteDownloadCompleteNoPath": "Remote download completed but no file path returned",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "خطأ في تحديد الصوت للمهمة {job_id}: {error}",
"searchAudioError": "خطأ في البحث عن الصوت: {error}",
"searchCreatedSuccessfully": "تم إنشاء المهمة. جاري البحث عن الصوت...",
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل..."
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل...",
"drmUrlUnsupported": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. حاول تنزيل الصوت باستخدام أداة خارجية أولاً، ثم قم برفع ملف الصوت هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية.",
"drmUrlUnsupportedWithLink": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. يمكنك تنزيل المقطع الصوتي باستخدام أداة مثل {downloader} ثم رفع الملف الصوتي هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية.",
"drmUrlUnsupportedSearch": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. ابحث في الويب عن \"أداة تنزيل {platform}\" للحصول على الصوت — على سبيل المثال {searchUrl} — ثم قم برفع ملف الصوت هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Error en seleccionar l'àudio per a la tasca {job_id}: {error}",
"searchAudioError": "Error en cercar l'àudio: {error}",
"searchCreatedSuccessfully": "Tasca creada. Cercant àudio...",
"autoDownloadStarted": "Millor resultat seleccionat automàticament. Iniciant la descàrrega..."
"autoDownloadStarted": "Millor resultat seleccionat automàticament. Iniciant la descàrrega...",
"drmUrlUnsupported": "Els enllaços de {platform} estan protegits contra còpia, així que no els podem descarregar directament. Prova de descarregar l'àudio amb una eina de tercers primer i, a continuació, puja el fitxer d'àudio aquí. També pots enganxar un enllaç de YouTube o utilitzar la Cerca d'àudio per trobar aquesta cançó.",
"drmUrlUnsupportedWithLink": "Els enllaços de {platform} estan protegits contra còpia, de manera que no els podem descarregar directament. Pots descarregar la pista utilitzant una eina com {downloader} i després pujar el fitxer d'àudio aquí. També pots enganxar un enllaç de YouTube o utilitzar la Cerca d'àudio per trobar aquesta cançó.",
"drmUrlUnsupportedSearch": "Els enllaços de {platform} estan protegits contra còpia, així que no els podem descarregar directament. Cerca a la web un \"{platform} downloader\" per obtenir l'àudio — per exemple {searchUrl} — i després puja el fitxer d'àudio aquí. També pots enganxar un enllaç de YouTube, o utilitzar la Cerca d'àudio per trobar aquesta cançó."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Chyba při výběru zvuku pro úlohu {job_id}: {error}",
"searchAudioError": "Chyba při vyhledávání zvuku: {error}",
"searchCreatedSuccessfully": "Úloha vytvořena. Vyhledávám zvuk...",
"autoDownloadStarted": "Nejlepší výsledek byl vybrán automaticky. Začíná stahování..."
"autoDownloadStarted": "Nejlepší výsledek byl vybrán automaticky. Začíná stahování...",
"drmUrlUnsupported": "Odkazy z {platform} jsou chráněny proti kopírování, takže je nemůžeme stáhnout přímo. Zkus nejprve stáhnout zvuk pomocí nástroje třetí strany a poté sem nahraj zvukový soubor. Můžeš také vložit odkaz na YouTube nebo použít Audio Search k vyhledání této písně.",
"drmUrlUnsupportedWithLink": "Odkazy z {platform} jsou chráněny proti kopírování, takže je nemůžeme stáhnout přímo. Skladbu si můžeš stáhnout pomocí nástroje jako {downloader} a poté sem nahrát zvukový soubor. Můžeš také vložit odkaz na YouTube, nebo k nalezení této písně použít Vyhledávání zvuku.",
"drmUrlUnsupportedSearch": "Odkazy z {platform} jsou chráněny proti kopírování, takže je nemůžeme stáhnout přímo. Vyhledej na webu „{platform} downloader“ pro získání zvuku — například {searchUrl} — a poté sem nahraj zvukový soubor. Můžeš také vložit odkaz na YouTube nebo použít vyhledávání zvuku k nalezení této písničky."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Fejl ved valg af lyd for job {job_id}: {error}",
"searchAudioError": "Fejl ved søgning efter lyd: {error}",
"searchCreatedSuccessfully": "Jobbet er oprettet. Søger efter lyd...",
"autoDownloadStarted": "Det bedste resultat blev valgt automatisk. Download starter..."
"autoDownloadStarted": "Det bedste resultat blev valgt automatisk. Download starter...",
"drmUrlUnsupported": "{platform}-links er kopibeskyttede, så vi kan ikke downloade dem direkte. Prøv at downloade lyden med et tredjepartsværktøj først, og upload derefter lydfilen her. Du kan også indsætte et YouTube-link eller bruge Audio Search til at finde denne sang.",
"drmUrlUnsupportedWithLink": "{platform}-links er kopibeskyttede, så vi kan ikke downloade dem direkte. Du kan downloade nummeret ved hjælp af et værktøj som {downloader} og derefter uploade lydfilen her. Du kan også indsætte et YouTube-link eller bruge Lydsøgning til at finde denne sang.",
"drmUrlUnsupportedSearch": "{platform}-links er kopibeskyttede, så vi kan ikke downloade dem direkte. Søg på nettet efter en \"{platform} downloader\" for at hente lyden — for eksempel {searchUrl} — og upload derefter lydfilen her. Du kan også indsætte et YouTube-link eller bruge Lydsøgning til at finde denne sang."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
"searchAudioError": "Fehler bei der Audiosuche: {error}",
"searchCreatedSuccessfully": "Auftrag erstellt. Suche nach Audio...",
"autoDownloadStarted": "Bestes Ergebnis automatisch ausgewählt. Download startet..."
"autoDownloadStarted": "Bestes Ergebnis automatisch ausgewählt. Download startet...",
"drmUrlUnsupported": "{platform}-Links sind kopiergeschützt, daher können wir sie nicht direkt herunterladen. Versuche zuerst, das Audio mit einem Drittanbieter-Tool herunterzuladen, und lade die Audiodatei dann hier hoch. Du kannst auch einen YouTube-Link einfügen oder die Audiosuche verwenden, um diesen Song zu finden.",
"drmUrlUnsupportedWithLink": "{platform}-Links sind kopiergeschützt, daher können wir sie nicht direkt herunterladen. Du kannst den Titel mit einem Tool wie {downloader} herunterladen und die Audiodatei dann hier hochladen. Du kannst auch einen YouTube-Link einfügen oder die Audiosuche verwenden, um diesen Song zu finden.",
"drmUrlUnsupportedSearch": "{platform}-Links sind kopiergeschützt, daher können wir sie nicht direkt herunterladen. Suche im Internet nach einem \"{platform} Downloader\", um das Audio zu erhalten — zum Beispiel {searchUrl} — und lade die Audiodatei dann hier hoch. Du kannst auch einen YouTube-Link einfügen oder die Audio-Suche verwenden, um diesen Song zu finden."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
"searchAudioError": "Σφάλμα κατά την αναζήτηση ήχου: {error}",
"searchCreatedSuccessfully": "Η εργασία δημιουργήθηκε. Αναζήτηση για ήχο...",
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά..."
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά...",
"drmUrlUnsupported": "Οι σύνδεσμοι του {platform} προστατεύονται από αντιγραφή, οπότε δεν μπορούμε να τους κατεβάσουμε απευθείας. Δοκίμασε να κατεβάσεις τον ήχο με ένα εργαλείο τρίτου πρώτα, και μετά ανέβασε το αρχείο ήχου εδώ. Μπορείς επίσης να επικολλήσεις έναν σύνδεσμο YouTube, ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι.",
"drmUrlUnsupportedWithLink": "Οι σύνδεσμοι {platform} προστατεύονται από αντιγραφή, επομένως δεν μπορούμε να τους κατεβάσουμε απευθείας. Μπορείς να κατεβάσεις το κομμάτι χρησιμοποιώντας ένα εργαλείο όπως το {downloader} και μετά να ανεβάσεις το αρχείο ήχου εδώ. Μπορείς επίσης να κάνεις επικόλληση έναν σύνδεσμο YouTube ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι.",
"drmUrlUnsupportedSearch": "Οι σύνδεσμοι του {platform} έχουν προστασία αντιγραφής, οπότε δεν μπορούμε να τους κατεβάσουμε απευθείας. Ψάξε στο διαδίκτυο για ένα \"{platform} downloader\" για να κατεβάσεις τον ήχο — για παράδειγμα {searchUrl} — και μετά ανέβασε το αρχείο ήχου εδώ. Μπορείς επίσης να επικολλήσεις έναν σύνδεσμο YouTube ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3
View File
@@ -83,6 +83,9 @@
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
"selectionError": "Error during audio selection for job {job_id}: {error}",
"youtubeDownloadError": "YouTube download failed: {error}",
"drmUrlUnsupported": "{platform} links are copy-protected, so we can't download them directly. Try downloading the audio with a third-party tool first, then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedWithLink": "{platform} links are copy-protected, so we can't download them directly. You can download the track using a tool like {downloader} and then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedSearch": "{platform} links are copy-protected, so we can't download them directly. Search the web for a \"{platform} downloader\" to get the audio — for example {searchUrl} — then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download",
"remoteDownloadCompleteNoPath": "Remote download completed but no file path returned",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Error al seleccionar el audio para el trabajo {job_id}: {error}",
"searchAudioError": "Error al buscar audio: {error}",
"searchCreatedSuccessfully": "Trabajo creado. Buscando audio...",
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga..."
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga...",
"drmUrlUnsupported": "Los enlaces de {platform} están protegidos contra copia, así que no podemos descargarlos directamente. Intenta descargar el audio con una herramienta de terceros primero, y luego sube el archivo de audio aquí. También puedes pegar un enlace de YouTube, o usar la Búsqueda de Audio para encontrar esta canción.",
"drmUrlUnsupportedWithLink": "Los enlaces de {platform} están protegidos contra copia, por lo que no podemos descargarlos directamente. Puedes descargar la pista usando una herramienta como {downloader} y luego subir el archivo de audio aquí. También puedes pegar un enlace de YouTube, o usar la Búsqueda de Audio para encontrar esta canción.",
"drmUrlUnsupportedSearch": "Los enlaces de {platform} están protegidos por derechos de autor, así que no podemos descargarlos directamente. Busca en la web un \"descargador de {platform}\" para obtener el audio — por ejemplo {searchUrl} — y luego sube el archivo de audio aquí. También puedes pegar un enlace de YouTube, o usar la Búsqueda de Audio para encontrar esta canción."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Virhe valittaessa ääntä työlle {job_id}: {error}",
"searchAudioError": "Virhe haettaessa ääntä: {error}",
"searchCreatedSuccessfully": "Työ luotu. Etsitään ääntä...",
"autoDownloadStarted": "Paras tulos valittu automaattisesti. Lataus alkaa..."
"autoDownloadStarted": "Paras tulos valittu automaattisesti. Lataus alkaa...",
"drmUrlUnsupported": "{platform}-linkit ovat kopiosuojattuja, joten emme voi ladata niitä suoraan. Kokeile ladata ääni ensin kolmannen osapuolen työkalulla ja lataa äänitiedosto sitten tänne. Voit myös liittää YouTube-linkin tai etsiä tämän kappaleen Äänihaun avulla.",
"drmUrlUnsupportedWithLink": "{platform}-linkit ovat kopiosuojattuja, joten emme voi ladata niitä suoraan. Voit ladata kappaleen esimerkiksi {downloader}-työkalulla ja ladata äänitiedoston sitten tänne. Voit myös liittää YouTube-linkin tai etsiä kappaleen Äänihaun avulla.",
"drmUrlUnsupportedSearch": "{platform}-linkit ovat kopiosuojattuja, joten emme voi ladata niitä suoraan. Etsi netistä \"{platform} downloader\" saadaksesi äänen — esimerkiksi {searchUrl} — ja lataa äänitiedosto sitten tänne. Voit myös liittää YouTube-linkin tai käyttää äänihakua löytääksesi tämän kappaleen."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Erreur lors de la sélection de l'audio pour la tâche {job_id} : {error}",
"searchAudioError": "Erreur lors de la recherche audio : {error}",
"searchCreatedSuccessfully": "Tâche créée. Recherche de l'audio en cours...",
"autoDownloadStarted": "Meilleur résultat sélectionné automatiquement. Le téléchargement commence..."
"autoDownloadStarted": "Meilleur résultat sélectionné automatiquement. Le téléchargement commence...",
"drmUrlUnsupported": "Les liens {platform} sont protégés par le droit d'auteur, nous ne pouvons donc pas les télécharger directement. Essaie d'abord de télécharger l'audio avec un outil tiers, puis téléverse le fichier audio ici. Tu peux aussi coller un lien YouTube, ou utiliser la Recherche Audio pour trouver cette chanson.",
"drmUrlUnsupportedWithLink": "Les liens {platform} sont protégés contre la copie, nous ne pouvons donc pas les télécharger directement. Tu peux télécharger le morceau en utilisant un outil comme {downloader}, puis importer le fichier audio ici. Tu peux également coller un lien YouTube, ou utiliser la recherche audio pour trouver cette chanson.",
"drmUrlUnsupportedSearch": "Les liens {platform} sont protégés contre la copie, nous ne pouvons donc pas les télécharger directement. Cherche sur le web un « {platform} downloader » pour récupérer l'audio — par exemple {searchUrl} — puis importe le fichier audio ici. Tu peux aussi coller un lien YouTube, ou utiliser la Recherche Audio pour trouver cette chanson."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "שגיאה בבחירת אודיו עבור המשימה {job_id}: {error}",
"searchAudioError": "שגיאה בחיפוש אודיו: {error}",
"searchCreatedSuccessfully": "המשימה נוצרה. מחפש אודיו...",
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה..."
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה...",
"drmUrlUnsupported": "הקישורים של {platform} מוגנים מפני העתקה, ולכן איננו יכולים להוריד אותם ישירות. נסו להוריד את האודיו בעזרת כלי צד שלישי תחילה, ואז העלו את קובץ האודיו לכאן. תוכלו גם להדביק קישור ל-YouTube, או להשתמש בחיפוש אודיו כדי למצוא את השיר הזה.",
"drmUrlUnsupportedWithLink": "קישורים מ-{platform} מוגנים מפני העתקה, ולכן איננו יכולים להוריד אותם ישירות. ניתן להוריד את השיר באמצעות כלי כמו {downloader} ולאחר מכן להעלות את קובץ השמע לכאן. אפשר גם להדביק קישור של YouTube, או להשתמש בחיפוש שמע כדי למצוא את השיר הזה.",
"drmUrlUnsupportedSearch": "קישורים של {platform} מוגנים בזכויות יוצרים, ולכן איננו יכולים להוריד אותם ישירות. חפשו ברשת \"{platform} downloader\" כדי להשיג את קובץ השמע — לדוגמה {searchUrl} — ואז העלו את קובץ השמע לכאן. אפשר גם להדביק קישור של YouTube, או להשתמש בחיפוש שמע כדי למצוא את השיר הזה."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "जॉब {job_id} के लिए ऑडियो चुनने में त्रुटि: {error}",
"searchAudioError": "ऑडियो खोजने में त्रुटि: {error}",
"searchCreatedSuccessfully": "जॉब बन गई। ऑडियो खोजा जा रहा है...",
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है..."
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है...",
"drmUrlUnsupported": "{platform} लिंक्स कॉपी-प्रोटेक्टेड हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। पहले किसी थर्ड-पार्टी टूल से ऑडियो डाउनलोड करने की कोशिश करो, फिर ऑडियो फ़ाइल को यहाँ अपलोड करो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।",
"drmUrlUnsupportedWithLink": "{platform} लिंक कॉपी-प्रोटेक्टेड होते हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। तुम {downloader} जैसे टूल का उपयोग करके ट्रैक डाउनलोड कर सकते हो और फिर ऑडियो फ़ाइल को यहाँ अपलोड कर सकते हो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।",
"drmUrlUnsupportedSearch": "{platform} लिंक्स कॉपी-प्रोटेक्टेड होते हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। ऑडियो पाने के लिए वेब पर \"{platform} downloader\" सर्च करो — उदाहरण के लिए {searchUrl} — फिर ऑडियो फ़ाइल को यहाँ अपलोड करो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।"
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Pogreška pri odabiru zvuka za zadatak {job_id}: {error}",
"searchAudioError": "Pogreška pri pretraživanju zvuka: {error}",
"searchCreatedSuccessfully": "Zadatak je kreiran. Pretražujem zvuk...",
"autoDownloadStarted": "Najbolji rezultat je automatski odabran. Preuzimanje započinje..."
"autoDownloadStarted": "Najbolji rezultat je automatski odabran. Preuzimanje započinje...",
"drmUrlUnsupported": "{platform} poveznice su zaštićene od kopiranja, pa ih ne možemo izravno preuzeti. Pokušaj prvo preuzeti zvuk pomoću alata treće strane, a zatim ovdje prenesi audio datoteku. Također možeš zalijepiti YouTube poveznicu ili koristiti pretraživanje zvuka da pronađeš ovu pjesmu.",
"drmUrlUnsupportedWithLink": "{platform} poveznice su zaštićene od kopiranja, pa ih ne možemo izravno preuzeti. Pjesmu možeš preuzeti pomoću alata kao što je {downloader} i zatim ovdje učitati audio datoteku. Također možeš zalijepiti YouTube poveznicu ili upotrijebiti Audio pretraživanje da pronađeš ovu pjesmu.",
"drmUrlUnsupportedSearch": "{platform} poveznice su zaštićene od kopiranja, pa ih ne možemo izravno preuzeti. Potraži na webu \"{platform} downloader\" kako bi preuzeo/la audio — na primjer {searchUrl} — a zatim ovdje prenesi audio datoteku. Također možeš zalijepiti YouTube poveznicu ili koristiti Pretraživanje zvuka da pronađeš ovu pjesmu."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Hiba a hang kiválasztásakor a(z) {job_id} feladatnál: {error}",
"searchAudioError": "Hiba a hang keresésekor: {error}",
"searchCreatedSuccessfully": "Feladat létrehozva. Hang keresése...",
"autoDownloadStarted": "A legjobb eredmény automatikusan kiválasztva. Letöltés indítása..."
"autoDownloadStarted": "A legjobb eredmény automatikusan kiválasztva. Letöltés indítása...",
"drmUrlUnsupported": "A(z) {platform} linkek másolásvédettek, így nem tudjuk őket közvetlenül letölteni. Próbáld meg először letölteni a hanganyagot egy külső eszközzel, majd töltsd fel ide a hangfájlt. Beilleszthetsz egy YouTube linket is, vagy használd az Audio Search funkciót a dal megtalálásához.",
"drmUrlUnsupportedWithLink": "A(z) {platform} linkek másolásvédettek, ezért nem tudjuk őket közvetlenül letölteni. A számot letöltheted egy olyan eszközzel, mint a(z) {downloader}, majd feltöltheted ide a hangfájlt. Beilleszthetsz egy YouTube linket is, vagy használhatod a Hangkeresést a dal megtalálásához.",
"drmUrlUnsupportedSearch": "A(z) {platform} linkek másolásvédettek, így nem tudjuk őket közvetlenül letölteni. Keress rá a weben egy „{platform} downloader” kifejezésre a hanganyag letöltéséhez — például: {searchUrl} —, majd töltsd fel ide az audiofájlt. Beilleszthetsz egy YouTube linket is, vagy használd a Hangkeresőt a dal megtalálásához."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Kesalahan saat memilih audio untuk tugas {job_id}: {error}",
"searchAudioError": "Kesalahan saat mencari audio: {error}",
"searchCreatedSuccessfully": "Tugas dibuat. Mencari audio...",
"autoDownloadStarted": "Hasil terbaik dipilih secara otomatis. Unduhan dimulai..."
"autoDownloadStarted": "Hasil terbaik dipilih secara otomatis. Unduhan dimulai...",
"drmUrlUnsupported": "Tautan {platform} dilindungi hak cipta, jadi kami tidak dapat mengunduhnya secara langsung. Coba unduh audionya dengan alat pihak ketiga terlebih dahulu, lalu unggah file audionya di sini. Anda juga dapat menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini.",
"drmUrlUnsupportedWithLink": "Tautan {platform} dilindungi hak cipta, sehingga kami tidak dapat mengunduhnya secara langsung. Anda dapat mengunduh lagu tersebut menggunakan alat seperti {downloader} lalu mengunggah file audionya di sini. Anda juga dapat menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini.",
"drmUrlUnsupportedSearch": "Tautan {platform} dilindungi hak cipta, jadi kami tidak bisa mengunduhnya secara langsung. Cari \"downloader {platform}\" di internet untuk mendapatkan audionya — misalnya {searchUrl} — lalu unggah file audio di sini. Anda juga bisa menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Errore durante la selezione dell'audio per il lavoro {job_id}: {error}",
"searchAudioError": "Errore durante la ricerca dell'audio: {error}",
"searchCreatedSuccessfully": "Lavoro creato. Ricerca dell'audio in corso...",
"autoDownloadStarted": "Miglior risultato selezionato automaticamente. Avvio del download..."
"autoDownloadStarted": "Miglior risultato selezionato automaticamente. Avvio del download...",
"drmUrlUnsupported": "I link di {platform} sono protetti da copyright, quindi non possiamo scaricarli direttamente. Prova prima a scaricare l'audio con uno strumento di terze parti, poi carica il file audio qui. Puoi anche incollare un link di YouTube, oppure usare la Ricerca Audio per trovare questa canzone.",
"drmUrlUnsupportedWithLink": "I link di {platform} sono protetti da copyright, quindi non possiamo scaricarli direttamente. Puoi scaricare il brano usando uno strumento come {downloader} e poi caricare il file audio qui. Puoi anche incollare un link di YouTube, oppure usare la Ricerca Audio per trovare questa canzone.",
"drmUrlUnsupportedSearch": "I link di {platform} sono protetti da copyright, quindi non possiamo scaricarli direttamente. Cerca sul web un \"{platform} downloader\" per ottenere l'audio — ad esempio {searchUrl} — poi carica il file audio qui. Puoi anche incollare un link di YouTube, oppure usare la Ricerca Audio per trovare questa canzone."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
"searchAudioError": "オーディオの検索中にエラーが発生しました: {error}",
"searchCreatedSuccessfully": "ジョブが作成されました。オーディオを検索しています...",
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します..."
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します...",
"drmUrlUnsupported": "{platform}のリンクはコピー保護されているため、直接ダウンロードできません。サードパーティのツールでオーディオをダウンロードしてから、ここにアップロードしてみてください。または、YouTubeのリンクを貼り付けるか、オーディオ検索を使ってこの曲を探すこともできます。",
"drmUrlUnsupportedWithLink": "{platform}のリンクはコピーガードで保護されているため、直接ダウンロードすることはできません。{downloader}のようなツールを使用してトラックをダウンロードし、その音声ファイルをここにアップロードしてください。また、YouTubeのリンクを貼り付けるか、オーディオ検索を使用してこの曲を見つけることもできます。",
"drmUrlUnsupportedSearch": "{platform}のリンクはコピープロテクトされているため、直接ダウンロードすることはできません。音声を取得するには、ウェブで「{platform} downloader」を検索し(例:{searchUrl})、その音声ファイルをここにアップロードしてください。また、YouTubeのリンクを貼り付けるか、オーディオ検索を使用してこの曲を見つけることもできます。"
},
"users": {
"disposableEmailBlocked": "使い捨てメールアドレスは許可されていません",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
"searchAudioError": "오디오 검색 중 오류 발생: {error}",
"searchCreatedSuccessfully": "작업이 생성되었습니다. 오디오를 검색하는 중...",
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다..."
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다...",
"drmUrlUnsupported": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. 먼저 타사 도구를 사용하여 오디오를 다운로드한 다음, 여기에 오디오 파일을 업로드해 보세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용하여 이 노래를 찾을 수도 있습니다.",
"drmUrlUnsupportedWithLink": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. {downloader} 같은 도구를 사용해 음원을 다운로드한 후, 여기에 오디오 파일을 업로드해 주세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용해 이 노래를 찾을 수도 있습니다.",
"drmUrlUnsupportedSearch": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. 오디오를 추출하려면 웹에서 '{platform} 다운로더'를 검색한 후(예: {searchUrl}) 여기에 오디오 파일을 업로드해 주세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용하여 이 노래를 찾을 수도 있습니다."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Ralat memilih audio untuk tugasan {job_id}: {error}",
"searchAudioError": "Ralat mencari audio: {error}",
"searchCreatedSuccessfully": "Tugasan dicipta. Sedang mencari audio...",
"autoDownloadStarted": "Hasil terbaik dipilih secara automatik. Muat turun bermula..."
"autoDownloadStarted": "Hasil terbaik dipilih secara automatik. Muat turun bermula...",
"drmUrlUnsupported": "Pautan {platform} dilindungi hak cipta, jadi kami tidak dapat memuat turunnya secara terus. Cuba muat turun audio menggunakan alat pihak ketiga terlebih dahulu, kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau menggunakan Carian Audio untuk mencari lagu ini.",
"drmUrlUnsupportedWithLink": "Pautan {platform} dilindungi hak cipta, jadi kami tidak dapat memuat turunnya secara terus. Anda boleh memuat turun trek tersebut menggunakan alat seperti {downloader} dan kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau menggunakan Carian Audio untuk mencari lagu ini.",
"drmUrlUnsupportedSearch": "Pautan {platform} dilindungi hak cipta, jadi kami tidak dapat memuat turunnya secara terus. Cari di web untuk \"{platform} downloader\" untuk mendapatkan audio — contohnya {searchUrl} — kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau guna Carian Audio untuk mencari lagu ini."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Feil ved valg av lyd for jobb {job_id}: {error}",
"searchAudioError": "Feil ved søk etter lyd: {error}",
"searchCreatedSuccessfully": "Jobb opprettet. Søker etter lyd...",
"autoDownloadStarted": "Beste resultat valgt automatisk. Nedlasting starter..."
"autoDownloadStarted": "Beste resultat valgt automatisk. Nedlasting starter...",
"drmUrlUnsupported": "{platform}-lenker er kopibeskyttet, så vi kan ikke laste dem ned direkte. Prøv å laste ned lyden med et tredjepartsverktøy først, og last deretter opp lydfilen her. Du kan også lime inn en YouTube-lenke, eller bruke Lydsøk for å finne denne sangen.",
"drmUrlUnsupportedWithLink": "{platform}-lenker er kopibeskyttet, så vi kan ikke laste dem ned direkte. Du kan laste ned sporet ved å bruke et verktøy som {downloader} og deretter laste opp lydfilen her. Du kan også lime inn en YouTube-lenke, eller bruke Lydsøk for å finne denne sangen.",
"drmUrlUnsupportedSearch": "{platform}-lenker er kopibeskyttet, så vi kan ikke laste dem ned direkte. Søk på nettet etter en \"{platform} downloader\" for å hente lyden — for eksempel {searchUrl} — og last deretter opp lydfilen her. Du kan også lime inn en YouTube-lenke, eller bruke Lydsøk for å finne denne sangen."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Fout bij het selecteren van audio voor taak {job_id}: {error}",
"searchAudioError": "Fout bij het zoeken naar audio: {error}",
"searchCreatedSuccessfully": "Taak aangemaakt. Zoeken naar audio...",
"autoDownloadStarted": "Beste resultaat automatisch geselecteerd. Downloaden wordt gestart..."
"autoDownloadStarted": "Beste resultaat automatisch geselecteerd. Downloaden wordt gestart...",
"drmUrlUnsupported": "{platform}-links zijn kopieerbeveiligd, dus we kunnen ze niet direct downloaden. Probeer de audio eerst te downloaden met een externe tool en upload het audiobestand vervolgens hier. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden.",
"drmUrlUnsupportedWithLink": "{platform}-links zijn kopieerbeveiligd, dus we kunnen ze niet direct downloaden. Je kunt het nummer downloaden met een tool zoals {downloader} en vervolgens het audiobestand hier uploaden. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden.",
"drmUrlUnsupportedSearch": "{platform}-links zijn kopieerbeveiligd, dus we kunnen ze niet direct downloaden. Zoek op het web naar een \"{platform} downloader\" om de audio te verkrijgen — bijvoorbeeld {searchUrl} — en upload het audiobestand vervolgens hier. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Błąd podczas wybierania audio dla zadania {job_id}: {error}",
"searchAudioError": "Błąd podczas wyszukiwania audio: {error}",
"searchCreatedSuccessfully": "Zadanie utworzone. Wyszukiwanie audio...",
"autoDownloadStarted": "Najlepszy wynik wybrany automatycznie. Rozpoczynanie pobierania..."
"autoDownloadStarted": "Najlepszy wynik wybrany automatycznie. Rozpoczynanie pobierania...",
"drmUrlUnsupported": "Linki z {platform} są chronione przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Spróbuj najpierw pobrać dźwięk za pomocą zewnętrznego narzędzia, a następnie prześlij plik audio tutaj. Możesz też wkleić link do YouTube lub użyć wyszukiwania audio, aby znaleźć tę piosenkę.",
"drmUrlUnsupportedWithLink": "Linki z {platform} są zabezpieczone przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Możesz pobrać utwór za pomocą narzędzia takiego jak {downloader}, a następnie przesłać plik audio tutaj. Możesz również wkleić link do YouTube lub użyć Wyszukiwania Audio, aby znaleźć tę piosenkę.",
"drmUrlUnsupportedSearch": "Linki z {platform} są zabezpieczone przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Wyszukaj w sieci „{platform} downloader”, aby pobrać plik audio — na przykład {searchUrl} — a następnie prześlij plik audio tutaj. Możesz również wkleić link do YouTube lub użyć Wyszukiwania Audio, aby znaleźć tę piosenkę."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Erro ao selecionar áudio para o job {job_id}: {error}",
"searchAudioError": "Erro ao pesquisar áudio: {error}",
"searchCreatedSuccessfully": "Job criado. Pesquisando áudio...",
"autoDownloadStarted": "Melhor resultado selecionado automaticamente. Iniciando download..."
"autoDownloadStarted": "Melhor resultado selecionado automaticamente. Iniciando download...",
"drmUrlUnsupported": "Os links do {platform} são protegidos contra cópia, então não podemos baixá-los diretamente. Tente baixar o áudio com uma ferramenta de terceiros primeiro e depois faça o upload do arquivo de áudio aqui. Você também pode colar um link do YouTube ou usar a Pesquisa de Áudio para encontrar esta música.",
"drmUrlUnsupportedWithLink": "Os links do {platform} são protegidos contra cópia, então não podemos baixá-los diretamente. Você pode baixar a faixa usando uma ferramenta como o {downloader} e depois fazer o upload do arquivo de áudio aqui. Você também pode colar um link do YouTube ou usar a Pesquisa de Áudio para encontrar esta música.",
"drmUrlUnsupportedSearch": "Os links do {platform} são protegidos contra cópia, então não podemos baixá-los diretamente. Pesquise na web por um \"{platform} downloader\" para obter o áudio — por exemplo, {searchUrl} — e depois faça o upload do arquivo de áudio aqui. Você também pode colar um link do YouTube ou usar a Pesquisa de Áudio para encontrar esta música."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Eroare la selectarea fișierului audio pentru jobul {job_id}: {error}",
"searchAudioError": "Eroare la căutarea audio: {error}",
"searchCreatedSuccessfully": "Job creat. Se caută fișierul audio...",
"autoDownloadStarted": "Cel mai bun rezultat a fost selectat automat. Descărcarea începe..."
"autoDownloadStarted": "Cel mai bun rezultat a fost selectat automat. Descărcarea începe...",
"drmUrlUnsupported": "Linkurile {platform} sunt protejate la copiere, așa că nu le putem descărca direct. Încearcă să descarci mai întâi conținutul audio cu un instrument terț, apoi încarcă fișierul audio aici. De asemenea, poți lipi un link YouTube sau poți folosi Căutare Audio pentru a găsi această melodie.",
"drmUrlUnsupportedWithLink": "Linkurile {platform} sunt protejate la copiere, așa că nu le putem descărca direct. Poți descărca piesa folosind un instrument precum {downloader} și apoi poți încărca fișierul audio aici. De asemenea, poți lipi un link YouTube sau poți folosi Căutarea Audio pentru a găsi această melodie.",
"drmUrlUnsupportedSearch": "Linkurile {platform} sunt protejate la copiere, așa că nu le putem descărca direct. Caută pe web un „{platform} downloader” pentru a obține fișierul audio — de exemplu {searchUrl} — apoi încarcă fișierul audio aici. De asemenea, poți lipi un link YouTube sau poți folosi Căutarea Audio pentru a găsi această piesă."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Ошибка при выборе аудио для задачи {job_id}: {error}",
"searchAudioError": "Ошибка при поиске аудио: {error}",
"searchCreatedSuccessfully": "Задача создана. Ищем аудио...",
"autoDownloadStarted": "Лучший результат выбран автоматически. Начинается скачивание..."
"autoDownloadStarted": "Лучший результат выбран автоматически. Начинается скачивание...",
"drmUrlUnsupported": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Попробуй сначала скачать аудио с помощью стороннего инструмента, а затем загрузи аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать Поиск аудио, чтобы найти эту песню.",
"drmUrlUnsupportedWithLink": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Ты можешь скачать трек с помощью такого инструмента, как {downloader}, а затем загрузить аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать поиск аудио, чтобы найти эту песню.",
"drmUrlUnsupportedSearch": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Поищи в интернете «{platform} downloader», чтобы получить аудио — например, {searchUrl} — а затем загрузи аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать Поиск аудио, чтобы найти эту песню."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Chyba pri výbere zvuku pre úlohu {job_id}: {error}",
"searchAudioError": "Chyba pri vyhľadávaní zvuku: {error}",
"searchCreatedSuccessfully": "Úloha bola vytvorená. Vyhľadáva sa zvuk...",
"autoDownloadStarted": "Najlepší výsledok bol vybraný automaticky. Sťahovanie sa začína..."
"autoDownloadStarted": "Najlepší výsledok bol vybraný automaticky. Sťahovanie sa začína...",
"drmUrlUnsupported": "Odkazy {platform} sú chránené proti kopírovaniu, takže ich nemôžeme stiahnuť priamo. Skús najprv stiahnuť zvuk pomocou nástroja tretej strany a potom sem nahraj zvukový súbor. Môžeš tiež vložiť odkaz na YouTube alebo použiť vyhľadávanie zvuku na nájdenie tejto piesne.",
"drmUrlUnsupportedWithLink": "Odkazy {platform} sú chránené proti kopírovaniu, takže ich nemôžeme stiahnuť priamo. Skladbu si môžeš stiahnuť pomocou nástroja ako {downloader} a potom sem nahrať zvukový súbor. Môžeš tiež vložiť odkaz na YouTube, alebo použiť Vyhľadávanie zvuku na nájdenie tejto piesne.",
"drmUrlUnsupportedSearch": "Odkazy z {platform} sú chránené proti kopírovaniu, takže ich nemôžeme stiahnuť priamo. Vyhľadaj na webe „{platform} downloader“, aby si získal zvuk — napríklad {searchUrl} — a potom sem nahraj zvukový súbor. Môžeš tiež vložiť odkaz na YouTube alebo použiť vyhľadávanie zvuku na nájdenie tejto piesne."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Fel vid val av ljud för jobb {job_id}: {error}",
"searchAudioError": "Fel vid sökning efter ljud: {error}",
"searchCreatedSuccessfully": "Jobbet har skapats. Söker efter ljud...",
"autoDownloadStarted": "Bästa resultatet valdes automatiskt. Nedladdningen startar..."
"autoDownloadStarted": "Bästa resultatet valdes automatiskt. Nedladdningen startar...",
"drmUrlUnsupported": "{platform}-länkar är kopieringsskyddade, så vi kan inte ladda ner dem direkt. Försök att ladda ner ljudet med ett tredjepartsverktyg först och ladda sedan upp ljudfilen här. Du kan också klistra in en YouTube-länk eller använda Ljudsökning för att hitta den här låten.",
"drmUrlUnsupportedWithLink": "{platform}-länkar är kopieringsskyddade, så vi kan inte ladda ner dem direkt. Du kan ladda ner låten med ett verktyg som {downloader} och sedan ladda upp ljudfilen här. Du kan också klistra in en YouTube-länk, eller använda Audio Search för att hitta den här låten.",
"drmUrlUnsupportedSearch": "{platform}-länkar är kopieringsskyddade, så vi kan inte ladda ner dem direkt. Sök på nätet efter en \"{platform} downloader\" för att hämta ljudet — till exempel {searchUrl} — och ladda sedan upp ljudfilen här. Du kan också klistra in en YouTube-länk, eller använda Audio Search för att hitta den här låten."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "เกิดข้อผิดพลาดในการเลือกเสียงสำหรับงาน {job_id}: {error}",
"searchAudioError": "เกิดข้อผิดพลาดในการค้นหาเสียง: {error}",
"searchCreatedSuccessfully": "สร้างงานแล้ว กำลังค้นหาเสียง...",
"autoDownloadStarted": "เลือกผลลัพธ์ที่ดีที่สุดโดยอัตโนมัติ กำลังเริ่มดาวน์โหลด..."
"autoDownloadStarted": "เลือกผลลัพธ์ที่ดีที่สุดโดยอัตโนมัติ กำลังเริ่มดาวน์โหลด...",
"drmUrlUnsupported": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง ลองดาวน์โหลดเสียงด้วยเครื่องมือของบุคคลที่สามก่อน แล้วจึงอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้อีกด้วย",
"drmUrlUnsupportedWithLink": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง คุณสามารถดาวน์โหลดเพลงโดยใช้เครื่องมืออย่าง {downloader} แล้วอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้เช่นกัน",
"drmUrlUnsupportedSearch": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง ลองค้นหาบนเว็บด้วยคำว่า \"{platform} downloader\" เพื่อรับไฟล์เสียง — ตัวอย่างเช่น {searchUrl} — จากนั้นอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้อีกด้วย"
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Error sa pagpili ng audio para sa job {job_id}: {error}",
"searchAudioError": "Error sa paghahanap ng audio: {error}",
"searchCreatedSuccessfully": "Nagawa na ang job. Naghahanap ng audio...",
"autoDownloadStarted": "Awtomatikong napili ang pinakamagandang resulta. Nagsisimula na ang pag-download..."
"autoDownloadStarted": "Awtomatikong napili ang pinakamagandang resulta. Nagsisimula na ang pag-download...",
"drmUrlUnsupported": "Ang mga link ng {platform} ay copy-protected, kaya hindi namin ito direktang ma-download. Subukan munang i-download ang audio gamit ang isang third-party na tool, pagkatapos ay i-upload ang audio file dito. Maaari ka ring mag-paste ng YouTube link, o gamitin ang Audio Search para hanapin ang kantang ito.",
"drmUrlUnsupportedWithLink": "Ang mga {platform} link ay copy-protected, kaya hindi namin ito direktang ma-download. Maaari mong i-download ang track gamit ang tool tulad ng {downloader} at i-upload ang audio file dito. Maaari ka ring mag-paste ng YouTube link, o gumamit ng Audio Search para hanapin ang kantang ito.",
"drmUrlUnsupportedSearch": "Ang mga {platform} link ay copy-protected, kaya hindi namin ito direktang ma-download. Maghanap sa web ng \"{platform} downloader\" para makuha ang audio — halimbawa {searchUrl} — pagkatapos ay i-upload ang audio file dito. Maaari ka ring mag-paste ng YouTube link, o gumamit ng Audio Search para hanapin ang kantang ito."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "{job_id} işi için ses seçme hatası: {error}",
"searchAudioError": "Ses arama hatası: {error}",
"searchCreatedSuccessfully": "İş oluşturuldu. Ses aranıyor...",
"autoDownloadStarted": "En iyi sonuç otomatik olarak seçildi. İndirme başlıyor..."
"autoDownloadStarted": "En iyi sonuç otomatik olarak seçildi. İndirme başlıyor...",
"drmUrlUnsupported": "{platform} bağlantıları kopya korumalı olduğu için onları doğrudan indiremiyoruz. Sesi önce üçüncü taraf bir araçla indirmeyi dene, ardından ses dosyasını buraya yükle. Ayrıca bir YouTube bağlantısı yapıştırabilir veya bu şarkıyı bulmak için Ses Arama'yı kullanabilirsin.",
"drmUrlUnsupportedWithLink": "{platform} bağlantıları kopyalamaya karşı korumalı, bu yüzden onları doğrudan indiremiyoruz. Parçayı {downloader} gibi bir araç kullanarak indirebilir ve ardından ses dosyasını buraya yükleyebilirsin. Ayrıca bir YouTube bağlantısı yapıştırabilir veya bu şarkıyı bulmak için Ses Araması'nı kullanabilirsin.",
"drmUrlUnsupportedSearch": "{platform} bağlantıları kopya korumalı olduğu için onları doğrudan indiremiyoruz. Sesi elde etmek için internette bir \"{platform} downloader\" ara — örneğin {searchUrl} — ardından ses dosyasını buraya yükle. Ayrıca bir YouTube bağlantısı yapıştırabilir veya bu şarkıyı bulmak için Ses Arama'yı kullanabilirsin."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Помилка вибору аудіо для завдання {job_id}: {error}",
"searchAudioError": "Помилка пошуку аудіо: {error}",
"searchCreatedSuccessfully": "Завдання створено. Шукаємо аудіо...",
"autoDownloadStarted": "Найкращий результат вибрано автоматично. Починається завантаження..."
"autoDownloadStarted": "Найкращий результат вибрано автоматично. Починається завантаження...",
"drmUrlUnsupported": "Посилання {platform} захищені від копіювання, тому ми не можемо завантажити їх безпосередньо. Спробуй спочатку завантажити аудіо за допомогою стороннього інструменту, а потім завантаж аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню.",
"drmUrlUnsupportedWithLink": "Посилання з {platform} захищені від копіювання, тому ми не можемо завантажити їх напряму. Ти можеш завантажити трек за допомогою такого інструменту, як {downloader}, а потім завантажити аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню.",
"drmUrlUnsupportedSearch": "Посилання {platform} захищені від копіювання, тому ми не можемо завантажити їх безпосередньо. Знайди в інтернеті \"{platform} downloader\", щоб отримати аудіо — наприклад, {searchUrl} — а потім завантаж аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "Lỗi khi chọn âm thanh cho công việc {job_id}: {error}",
"searchAudioError": "Lỗi khi tìm kiếm âm thanh: {error}",
"searchCreatedSuccessfully": "Đã tạo công việc. Đang tìm kiếm âm thanh...",
"autoDownloadStarted": "Kết quả tốt nhất được chọn tự động. Đang bắt đầu tải xuống..."
"autoDownloadStarted": "Kết quả tốt nhất được chọn tự động. Đang bắt đầu tải xuống...",
"drmUrlUnsupported": "Các liên kết {platform} được bảo vệ bản quyền, vì vậy chúng tôi không thể tải chúng xuống trực tiếp. Hãy thử tải âm thanh bằng công cụ của bên thứ ba trước, sau đó tải tệp âm thanh lên đây. Bạn cũng có thể dán liên kết YouTube hoặc sử dụng Tìm kiếm Âm thanh để tìm bài hát này.",
"drmUrlUnsupportedWithLink": "Các liên kết {platform} được bảo vệ bản quyền, nên chúng tôi không thể tải xuống trực tiếp. Bạn có thể tải bài hát bằng công cụ như {downloader} rồi tải tệp âm thanh lên đây. Bạn cũng có thể dán liên kết YouTube, hoặc dùng Tìm kiếm Âm thanh để tìm bài hát này.",
"drmUrlUnsupportedSearch": "Các liên kết {platform} được bảo vệ bản quyền, nên chúng tôi không thể tải xuống trực tiếp. Hãy tìm kiếm trên mạng công cụ \"{platform} downloader\" để lấy tệp âm thanh — ví dụ {searchUrl} — sau đó tải tệp âm thanh lên đây. Bạn cũng có thể dán liên kết YouTube, hoặc dùng tính năng Tìm kiếm Âm thanh để tìm bài hát này."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+4 -1
View File
@@ -92,7 +92,10 @@
"selectAudioError": "为任务 {job_id} 选择音频时出错:{error}",
"searchAudioError": "搜索音频时出错:{error}",
"searchCreatedSuccessfully": "任务已创建。正在搜索音频...",
"autoDownloadStarted": "已自动选择最佳结果。开始下载..."
"autoDownloadStarted": "已自动选择最佳结果。开始下载...",
"drmUrlUnsupported": "{platform} 链接受版权保护,因此我们无法直接下载。请先尝试使用第三方工具下载音频,然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或者使用音频搜索来查找这首歌。",
"drmUrlUnsupportedWithLink": "{platform} 链接受版权保护,因此我们无法直接下载。您可以使用 {downloader} 等工具下载该曲目,然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或使用“音频搜索”来查找这首歌。",
"drmUrlUnsupportedSearch": "{platform} 链接受防复制保护,因此我们无法直接下载。请在网上搜索“{platform} downloader”来获取音频——例如 {searchUrl} ——然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或者使用音频搜索来查找这首歌。"
},
"users": {
"disposableEmailBlocked": "不允许使用一次性邮箱",
+53 -5
View File
@@ -80,6 +80,15 @@ DOWNLOAD_ALREADY_DONE_STATUSES = frozenset({
JobStatus.CANCELLED,
})
# How long to wait for a flacfetch download before giving up. This MUST stay
# strictly below the Cloud Run task `timeout` for audio-download-job (see
# infrastructure/modules/cloud_run.py::create_audio_download_job). If they are
# equal, Cloud Run SIGKILLs the task before this timeout can fire, so the
# worker never records retry-pending or fails gracefully — leaving an in-flight
# auto-retry that races manual retries (job 1cd29294). The headroom below the
# task timeout covers the final GCS upload + state transition.
DOWNLOAD_WAIT_TIMEOUT_SECONDS = 1080 # task timeout is 1200s
def _current_task_attempt() -> int:
"""Read CLOUD_RUN_TASK_ATTEMPT env var injected by Cloud Run Jobs.
@@ -227,23 +236,62 @@ async def process_audio_download(job_id: str) -> bool:
storage_service=storage_service,
)
# Concurrency guard: a second download run may have completed while we
# were downloading — e.g. a manual /retry racing this task's Cloud Run
# auto-retry. Re-read status now (it was read once at entry, before a
# potentially minutes-long download). If another run already advanced
# the job, treat this as an idempotent success: don't re-write the input
# path, don't re-transition (that would be an invalid
# downloading -> downloading), and don't re-trigger downstream workers.
# The winning run owns all of that.
latest = job_manager.get_job(job_id)
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
logger.info(
f"[job:{job_id}] Another run already advanced the job "
f"(status={latest.status}); skipping duplicate transition/triggers"
)
return True
# Update job with GCS path
job_manager.update_job(job_id, {
'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.
_clear_retry_pending_and_error(job_manager, job_id)
# Transition from DOWNLOADING_AUDIO to DOWNLOADING
job_manager.transition_to_state(
# Transition from DOWNLOADING_AUDIO (or FAILED, on recovery) to
# DOWNLOADING. Use raise_on_invalid=False so a tight race that slipped
# past the guard above (another run advancing the job between our
# re-read and here) does NOT raise into the generic except and fail_job
# a job another run already succeeded on.
transitioned = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=15,
message="Audio downloaded, starting processing"
message="Audio downloaded, starting processing",
raise_on_invalid=False,
)
if not transitioned:
latest = job_manager.get_job(job_id)
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
logger.info(
f"[job:{job_id}] Concurrent run advanced job during transition "
f"(status={latest.status}); treating as idempotent success"
)
return True
# Genuinely unexpected state (not a concurrency case) — surface it
# through the normal failure path so retry-pending is recorded.
raise DownloadError(
f"Could not transition to DOWNLOADING "
f"(status={latest.status if latest else 'missing'})"
)
# Check if audio editing was requested — enter blocking state instead of processing
job = job_manager.get_job(job_id)
@@ -419,7 +467,7 @@ async def _download_torrent(
final_status = await flacfetch_client.wait_for_download(
download_id,
timeout=600,
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
)
filepath = final_status.get("gcs_path") or final_status.get("output_path")
@@ -457,7 +505,7 @@ async def _download_spotify(
final_status = await flacfetch_client.wait_for_download(
download_id,
timeout=600,
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
)
filepath = final_status.get("gcs_path") or final_status.get("output_path")
+260
View File
@@ -0,0 +1,260 @@
"""Bulk Mode search worker.
Processes every job in a batch (state_data.batch_id == batch_id): runs the audio
search, auto-selects a confident lossless ("tier 1") match when the batch enabled
it, and otherwise parks the job in AWAITING_AUDIO_SELECTION for the review queue.
Runs as a Cloud Run Job (one execution per batch) so it survives API instance
scale-down and the user can close the tab. Mirrors the single-job search flow in
backend/api/routes/audio_search.py:search_audio.
Usage:
python -m backend.workers.bulk_search_worker --batch-id <batch_id>
"""
import asyncio
import logging
from backend.models.job import JobStatus
from backend.services.audio_search_service import (
AudioSearchError,
AudioSearchService,
NoResultsError,
pick_auto_selection,
)
from backend.services.job_manager import JobManager
from backend.services.pricing import duration_to_credits, is_blocked
from backend.services.user_service import get_user_service
from backend.services.worker_service import get_worker_service
logger = logging.getLogger(__name__)
# How many per-song searches to run concurrently within a batch.
SEARCH_CONCURRENCY = 4
def _prepare_theme(job, job_manager: JobManager) -> None:
"""Best-effort: copy the job's theme style into its folder (mirrors search_audio)."""
theme_id = getattr(job, "theme_id", None)
if not theme_id:
return
try:
from backend.api.routes.file_upload import _prepare_theme_for_job
color_overrides = getattr(job, "color_overrides", None) or {}
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
job.job_id, theme_id, color_overrides
)
updates = {
"style_params_gcs_path": style_params_path,
"style_assets": theme_style_assets,
}
if youtube_desc:
updates["youtube_description_template"] = youtube_desc
job_manager.update_job(job.job_id, updates)
except Exception as e: # noqa: BLE001
logger.warning("[bulk] theme prep failed for job %s: %s", job.job_id, e)
async def _auto_select(job, selection_index: int, selected: dict,
job_manager: JobManager) -> bool:
"""Charge the duration delta and start the download for an auto-selected job.
Returns True if the job was successfully auto-selected and the download
triggered; False if it should instead be parked for human selection (e.g.
track too long, or insufficient credits for the duration delta).
NOTE (money path): this replicates the duration-delta charge from
audio_search.select_audio_source using the SAME primitives and state keys
(credits_charged / select_charge_applied) rather than refactoring the proven
route. Keep the two in sync; covered by test_bulk_search_worker.
"""
job_id = job.job_id
sd = job.state_data or {}
duration = selected.get("duration")
# Track too long → defer to human (they may pick a different source).
if duration is not None and is_blocked(duration):
logger.info("[bulk] job %s auto-pick is over 60min; parking for selection", job_id)
return False
if not sd.get("select_charge_applied"):
credits_charged = int(sd.get("credits_charged", 1))
target_total = duration_to_credits(duration) if duration is not None else credits_charged
owed = max(0, target_total - credits_charged)
bypass = bool(sd.get("payment_bypassed", False))
if owed > 0 and not bypass:
user_email = job.user_email
if not user_email:
return False
# Crash-safety: if a previous attempt already marked the charge as
# pending, the deduction may have gone through — do NOT deduct again
# (bias toward under-charge over double-charge on worker retry).
if sd.get("bulk_charge_pending"):
logger.warning(
"[bulk] job %s had a pending charge from a prior attempt; "
"skipping re-deduction to avoid double-charge", job_id
)
else:
job_manager.update_job(job_id, {"state_data.bulk_charge_pending": owed})
ok, _, _ = get_user_service().deduct_credits(
user_email, job_id, amount=owed, reason="job_creation",
count_as_job_creation=False,
)
if not ok:
job_manager.update_job(job_id, {"state_data.bulk_charge_pending": None})
logger.info("[bulk] job %s lacks credits for duration delta; parking", job_id)
return False
update = {
"state_data.credits_charged": target_total,
"state_data.select_charge_applied": True,
"state_data.bulk_charge_pending": None,
}
if duration is not None:
update["state_data.duration_estimate_seconds"] = duration
update["state_data.duration_estimate_source"] = "search_metadata"
job_manager.update_job(job_id, update)
# Reuse the proven route helper to validate + transition to DOWNLOADING_AUDIO.
from backend.api.routes.audio_search import _validate_and_prepare_selection
try:
_validate_and_prepare_selection(job_id, selection_index)
except Exception as e: # noqa: BLE001 (route helper raises HTTPException)
logger.warning("[bulk] job %s validate/prepare failed: %s", job_id, e)
return False
return await get_worker_service().trigger_audio_download_worker(job_id)
async def process_job(job_id: str, job_manager: JobManager, audio_search_service) -> None:
"""Search one batch job and either auto-select or park it."""
job = job_manager.get_job(job_id)
if not job:
logger.warning("[bulk] job %s not found", job_id)
return
artist = job.audio_search_artist or job.artist
title = job.audio_search_title or job.title
sd = job.state_data or {}
bulk_settings = sd.get("bulk_settings", {}) or {}
auto_enabled = bulk_settings.get("auto_select_if_lossless", True)
_prepare_theme(job, job_manager)
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.SEARCHING_AUDIO,
progress=5,
message=f"Searching for: {artist} - {title}",
raise_on_invalid=False,
)
try:
results = await audio_search_service.search_async(artist, title)
except (NoResultsError, AudioSearchError) as e:
logger.warning("[bulk] search failed for job %s (%s); parking", job_id, e)
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message="No automatic audio sources found. Please choose a source.",
raise_on_invalid=False,
)
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
return
results_dicts = [r.to_dict() for r in results]
store = {"state_data.audio_search_results": results_dicts}
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
if remote_id:
store["state_data.remote_search_id"] = remote_id
job_manager.update_job(job_id, store)
selection_index = pick_auto_selection(results_dicts, title) if auto_enabled else None
if selection_index is None:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=f"Found {len(results_dicts)} sources. Please choose one.",
raise_on_invalid=False,
)
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
return
auto_ok = await _auto_select(job, selection_index, results_dicts[selection_index], job_manager)
if not auto_ok:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=f"Found {len(results_dicts)} sources. Please choose one.",
raise_on_invalid=False,
)
job_manager.update_job(
job_id,
{"state_data.bulk_pending_search": False, "state_data.bulk_auto_selected": bool(auto_ok)},
)
async def process_batch(batch_id: str) -> int:
"""Process all pending-search jobs in a batch. Returns the count processed."""
job_manager = JobManager()
jobs = job_manager.list_jobs_by_batch_id(batch_id)
pending = [j for j in jobs if (j.state_data or {}).get("bulk_pending_search")]
logger.info("[batch:%s] processing %d/%d jobs needing search", batch_id, len(pending), len(jobs))
sem = asyncio.Semaphore(SEARCH_CONCURRENCY)
async def _guarded(job_id: str) -> None:
async with sem:
# Fresh service per task: last_remote_search_id is instance state and
# would be cross-contaminated if shared across concurrent searches.
audio_search_service = AudioSearchService()
try:
await process_job(job_id, job_manager, audio_search_service)
except Exception as e: # noqa: BLE001 (one job must not kill the batch)
logger.error("[batch:%s] job %s crashed: %s", batch_id, job_id, e, exc_info=True)
try:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message="Search error. Please choose a source.",
raise_on_invalid=False,
)
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
except Exception: # noqa: BLE001
pass
await asyncio.gather(*[_guarded(j.job_id) for j in pending])
return len(pending)
def main():
import argparse
import sys
parser = argparse.ArgumentParser(description="Bulk Mode search worker")
parser.add_argument("--batch-id", required=True, help="Batch ID to process")
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger.info("Starting bulk search worker for batch %s", args.batch_id)
try:
count = asyncio.run(process_batch(args.batch_id))
logger.info("Bulk search worker finished batch %s (%d jobs)", args.batch_id, count)
sys.exit(0)
except Exception as e: # noqa: BLE001
logger.error("Bulk search worker crashed: %s", e, exc_info=True)
sys.exit(1)
if __name__ == "__main__":
main()
+17
View File
@@ -57,6 +57,10 @@ RENDER_WORKER_SHUTDOWN_CODE = "WORKER_SHUTDOWN"
# Import from lyrics_transcriber (submodule)
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.timing_validation import (
LyricsTimingError,
validate_segment_timing,
)
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
@@ -362,6 +366,19 @@ async def process_render_video(job_id: str) -> bool:
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 4b. Reject untimed lyrics BEFORE any expensive work or encoder
# dispatch. Custom/replaced lyrics that were never tap-synced carry
# None start/end times and otherwise crash the encoder with a cryptic
# "'<' not supported between instances of 'NoneType' and 'float'".
# Failing here gives the user an actionable message and never sends a
# broken job to the GCE encoder (which runs its own pinned wheel).
try:
validate_segment_timing(correction_result.corrected_segments)
except LyricsTimingError as timing_err:
job_log.error(f"Render rejected — lyrics not synchronized: {timing_err}")
logger.error(f"Job {job_id}: Render rejected — lyrics not synchronized: {timing_err}")
raise ValueError(str(timing_err)) from timing_err
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff. Show more