Compare commits

...
31 Commits
Author SHA1 Message Date
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
Andrew Beveridge ☄️andClaude Opus 4.8 b6dcf6602d feat: match-judge improvements — parallel tidy + hard gate, two-way toggle, weak-tier AI verify, preview perf (#841)
## Summary

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

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

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

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

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

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

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

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

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

@coderabbitai ignore

---------

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

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

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

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

## Fix

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

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

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

## Tests

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

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

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

@coderabbitai ignore

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

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

Docs-only, no version bump.

@coderabbitai ignore

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

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

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

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

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

@coderabbitai ignore

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

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

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

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

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

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

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

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

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

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

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

@coderabbitai ignore

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

---------

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

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

@coderabbitai ignore

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

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

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

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

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

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

@coderabbitai ignore

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

---------

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

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

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

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

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

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

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

CI/workflow-config only.

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

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

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

Test/docs only — no production code change.

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

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

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

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

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

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

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

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

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

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

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

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

## Final render blocker (bug #8)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 03:22:53 -04:00
203 changed files with 14658 additions and 1276 deletions

No files matched your search

+48 -23
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)"
@@ -1399,29 +1406,47 @@ jobs:
run: |
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
# Probe the worker's active_jobs. Echoes a non-negative integer on a
# successful /health response, or "unknown" if /health can't be
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
# encoder running a 4K render pins all 32 cores and can miss the 5s
# health window, and treating that as idle previously let us stop the
# VM mid-render — orphaning the job and surfacing as "lost contact
# with worker ... not found" (incident 2026-06-15).
probe_active_jobs() {
local body n
body=$(curl -sf --connect-timeout 3 --max-time 5 \
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
case "$n" in
''|*[!0-9]*) echo "unknown" ;;
*) echo "$n" ;;
esac
}
if [ "$ACTIVE_JOBS" -gt 0 ]; then
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
DRAIN_TIMEOUT=600
ELAPSED=0
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
if [ "$ACTIVE_JOBS" -eq 0 ]; then
break
fi
done
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
# waiting — we only stop on a definitive 0 (or after the timeout, so
# a wedged worker can't block the deploy forever). 20 min comfortably
# covers a full 4K render; the old primary only drains in-flight work
# since new renders already route to the just-swapped new primary.
DRAIN_TIMEOUT=1200
ELAPSED=0
ACTIVE_JOBS=$(probe_active_jobs)
echo "Initial active_jobs: $ACTIVE_JOBS"
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(probe_active_jobs)
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
done
if [ "$ACTIVE_JOBS" = "0" ]; then
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
else
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
fi
echo "Stopping old primary: $OLD_PRIMARY"
gcloud compute instances stop "$OLD_PRIMARY" \
--zone=us-central1-c --project=nomadkaraoke || true
+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),
+104
View File
@@ -0,0 +1,104 @@
name: E2E Daily Test (Tenant Portals)
# Full production E2E per white-label tenant: submit a job with the tenant's own
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
on:
schedule:
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
# top-of-hour scheduler herd.
- cron: '7 0 * * *'
workflow_dispatch: {}
permissions:
contents: read
id-token: write # for Workload Identity Federation
jobs:
e2e-tenant:
name: "Tenant E2E: ${{ matrix.tenant }}"
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
max-parallel: 1
matrix:
tenant: [vocalstar, singa]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Authenticate to GCP
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Install dependencies
run: pip install google-cloud-storage google-cloud-secret-manager
- name: Run tenant E2E
id: run_test
env:
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
run: |
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Upload logs
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
path: e2e-output.log
retention-days: 14
- name: Discord notification (failure)
if: ${{ steps.run_test.outputs.exit_code != '0' }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
run: |
if [ -n "$DISCORD_WEBHOOK" ]; then
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
"$DISCORD_WEBHOOK" || true
fi
- name: Fail the job if the test failed
if: ${{ steps.run_test.outputs.exit_code != '0' }}
run: exit 1
notify-email:
name: "Email summary"
runs-on: ubuntu-latest
needs: e2e-tenant
if: ${{ always() && github.event_name == 'schedule' }}
steps:
- name: Send email notification
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.postmarkapp.com
server_port: 587
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
body: |
Tenant E2E Daily Test (Vocal Star + Singa)
Result: ${{ needs.e2e-tenant.result }}
Run: #${{ github.run_number }}
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
+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
)
+61 -1
View File
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
import logging
import time
from typing import Optional
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
@@ -103,6 +103,38 @@ class CommunityCheckResponse(BaseModel):
best_youtube_url: Optional[str] = None
class MatchJudgeRequest(BaseModel):
"""Request body for the artist/title match judge."""
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
# The audio search's confidence tier (1=strong..3=weak), so the judge can
# tell whether weak results hint at a typo. Optional.
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
# parallel with the audio search; "full" = complete pipeline once the tier is
# known. Defaults to "full" so a single legacy call still works.
stage: Literal["fast", "full"] = "full"
class MatchJudgeAlternative(BaseModel):
artist: str
title: str
class MatchJudgeResponse(BaseModel):
"""Verdict on a typed artist/title — formatting + match acceptance."""
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
confident: bool
canonical_artist: str
canonical_title: str
alternatives: list[MatchJudgeAlternative] = []
engine: str # "deterministic" | "catalog" | "ai"
reason: str = ""
# Set by a "fast" pass that couldn't decide — the client should follow up with
# a "full" call once the audio tier is known.
needs_ai: bool = False
# --- Routes ---
@@ -161,3 +193,31 @@ async def check_community_versions(
from backend.services.karaokenerds_service import check_community_versions
result = await check_community_versions(body.artist, body.title)
return result
@router.post("/match-judge", response_model=MatchJudgeResponse)
async def match_judge(
request: Request,
body: MatchJudgeRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Judge a typed artist/title: decide official formatting + whether it matches a
real song. Deterministic + catalog layers run first; a light AI model fires
only when those aren't confident. Never blocks the submission flow — failures
degrade to a "none" verdict.
"""
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.match_judge.service import judge_match
verdict = await judge_match(
body.artist, body.title,
audio_tier=body.audio_confidence_tier,
stage=body.stage,
)
logger.info(
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
)
return verdict.to_dict()
+97 -2
View File
@@ -57,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
router = APIRouter(tags=["jobs"])
def _select_mixed_audio_files(files):
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
the instrumental — so transcription would run on the backing track instead of the
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
"""
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
def _apply_tenant_overrides(
dist: EffectiveDistributionSettings,
tenant_config,
@@ -1388,12 +1401,14 @@ async def mark_uploads_complete(
# List files with this prefix to find the actual uploaded file
files = storage_service.list_files(prefix)
if file_type == 'audio':
files = _select_mixed_audio_files(files)
if not files:
raise HTTPException(
status_code=400,
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
)
# Use the first (and should be only) file found
gcs_path = files[0]
@@ -1566,11 +1581,72 @@ 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. Only listed where we've verified one works; platforms
# without an entry get a generic "download elsewhere, then upload" suggestion.
_DRM_DOWNLOADER_SUGGESTIONS = {
'Apple Music': 'https://am-dl.pages.dev',
}
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:
domain = urlparse(url).netloc.lower()
except (ValueError, TypeError):
return None
# Remove port if present
if ':' in domain:
domain = domain.split(':')[0]
# 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
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
async def create_job_from_url(
request: Request,
@@ -1604,6 +1680,25 @@ 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:
downloader = _DRM_DOWNLOADER_SUGGESTIONS.get(unsupported_platform)
if downloader:
detail = t(
locale, "audioSearch.drmUrlUnsupportedWithLink",
platform=unsupported_platform, downloader=downloader,
)
else:
detail = t(
locale, "audioSearch.drmUrlUnsupported",
platform=unsupported_platform,
)
raise HTTPException(status_code=400, detail=detail)
# Validate URL
if not _validate_url(body.url):
raise HTTPException(
+21 -3
View File
@@ -576,6 +576,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']
@@ -1475,6 +1477,13 @@ async def complete_review(
try:
# Store instrumental selection if provided (combined review flow)
instrumental_selection = body.instrumental_selection if body else None
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
# render uses the provided instrumental instead of a separated stem that was never
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
instrumental_selection = 'custom'
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
if instrumental_selection:
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
@@ -1973,9 +1982,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, {
+13
View File
@@ -104,6 +104,19 @@ class Settings(BaseSettings):
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
# Match judge — artist/title formatting + match-acceptance for the job
# submission flow. Deterministic + catalog layers always run; the light AI
# layer (Vertex Gemini Flash) fires only when those aren't confident.
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
"true", "1", "yes",
)
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
# Bounds the AI call so a hung model never strands the submission UI. Kept
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
# call still runs off the critical path and degrades to "none" on timeout.
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
# Cloud Tasks (for scalable worker coordination)
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
# When disabled (default), workers are triggered via direct HTTP (for development)
+2 -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
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,7 @@ 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(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.
+31
View File
@@ -151,6 +151,37 @@ class DropboxService:
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
return next_code
def file_exists(self, remote_path: str) -> bool:
"""
Check whether a file exists at the given Dropbox path.
Args:
remote_path: Dropbox path (must start with /)
Returns:
True if a file exists at the path, False otherwise.
"""
from dropbox.exceptions import ApiError
if not remote_path.startswith("/"):
remote_path = f"/{remote_path}"
try:
self.client.files_get_metadata(remote_path)
return True
except ApiError as e:
# Only a genuine "not found" means the file is absent. Re-raise other
# API errors (auth, network, rate limit) so callers don't mistake a
# transient failure for "missing" (e.g. the backfill uploading a dup).
err = e.error
if (
hasattr(err, "is_path")
and err.is_path()
and err.get_path().is_not_found()
):
return False
raise
def upload_file(self, local_path: str, remote_path: str) -> None:
"""
Upload a single file to Dropbox.
+12
View File
@@ -65,6 +65,12 @@ class EncodingOutput:
lossless_mkv_path: Optional[str] = None # MKV with FLAC (for YouTube)
lossy_720p_mp4_path: Optional[str] = None # 720p web version
# Standalone 5-second screen videos generated from the title/end images.
# Kept so they land in the Dropbox folder (regression after #647/#650 moved
# screen generation to the encoder). Not used downstream.
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
# All output files as a dict for convenience
output_files: Dict[str, str] = field(default_factory=dict)
@@ -385,6 +391,10 @@ class GCEEncodingBackend(EncodingBackend):
output_files["mp4_720p"] = path
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
output_files["with_vocals_mp4"] = path
elif filename_lower.endswith("(title).mov"):
output_files["title_mov"] = path
elif filename_lower.endswith("(end).mov"):
output_files["end_mov"] = path
self.logger.info(f"Converted output_files list to dict: {output_files}")
else:
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
@@ -396,6 +406,8 @@ class GCEEncodingBackend(EncodingBackend):
lossless_mkv_path=output_files.get("mkv_4k"),
lossy_720p_mp4_path=output_files.get("mp4_720p"),
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
title_mov_path=output_files.get("title_mov"),
end_mov_path=output_files.get("end_mov"),
output_files=output_files,
encoding_time_seconds=encoding_time,
encoding_backend=self.name
+53 -8
View File
@@ -350,6 +350,7 @@ class EncodingService:
timeout: float = 30.0,
job_id: str = "unknown",
path: Optional[str] = None,
allow_failover: bool = True,
) -> Dict[str, Any]:
"""
Make an HTTP request with retry logic for transient failures.
@@ -371,6 +372,13 @@ class EncodingService:
fallback VM in another zone) and invalidate the URL cache; the
next retry then targets the freshly-routed URL instead of the
original primary which is dead.
allow_failover: When True (default), a connection error fires the
fallback-VM warmup and lets retries re-resolve the URL. Set False
for requests pinned to a specific worker (in-flight status polls):
a pinned poll must never re-route to active_url nor spin up a
fallback VM, because a different/fresh VM cannot have the job — it
would only return "not found" and orphan a render that is actually
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
Returns:
Dict with keys:
@@ -392,7 +400,7 @@ class EncodingService:
# active_override change made by the warmup actually takes effect.
# Without this, all 8 retry attempts hammer the original (dead)
# URL even though the warmup successfully routed to a fallback VM.
if path and warmup_ran and self._worker_manager is not None:
if allow_failover and path and warmup_ran and self._worker_manager is not None:
resolved = f"{self._get_worker_url()}{path}"
if resolved != url:
logger.info(
@@ -424,7 +432,7 @@ class EncodingService:
}
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
last_exception = e
if attempt == 0:
if allow_failover and attempt == 0:
try:
await self._warmup_encoding_worker_fallback(job_id)
warmup_ran = True
@@ -530,12 +538,23 @@ class EncodingService:
return resp["json"]
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
async def get_job_status(
self, job_id: str, worker_url: Optional[str] = None
) -> Dict[str, Any]:
"""
Get the status of an encoding job.
Args:
job_id: Job identifier
worker_url: When set, pin the request to this worker base URL instead
of resolving the current active_url. In-flight polls must stay on
the worker that accepted the job: a blue-green deploy can swap the
active_url primary pointer mid-render, and an unpinned poll would
migrate to the new primary — which never received the job and 404s
"not found", orphaning a render that is succeeding on the original
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
disables failover (allow_failover=False) so it never re-routes nor
starts a fallback VM.
Returns:
Job status including: status, progress, error, output_files
@@ -546,7 +565,10 @@ class EncodingService:
raise RuntimeError("Encoding service not configured")
path = f"/status/{job_id}"
url = f"{self._get_worker_url()}{path}"
if worker_url:
url = f"{worker_url}{path}"
else:
url = f"{self._get_worker_url()}{path}"
headers = {"X-API-Key": self._api_key}
resp = await self._request_with_retry(
@@ -555,7 +577,10 @@ class EncodingService:
headers=headers,
timeout=30.0,
job_id=job_id,
path=path,
# When pinned, never re-resolve or fail over — the job lives on this
# exact worker; do not pass `path` (which drives re-resolution).
path=None if worker_url else path,
allow_failover=not worker_url,
)
if resp["status"] == 401:
@@ -573,6 +598,7 @@ class EncodingService:
poll_interval: float = 10.0,
timeout: float = 3600.0,
progress_callback=None,
worker_url: Optional[str] = None,
) -> Dict[str, Any]:
"""
Poll for encoding job completion with tolerance for transient failures.
@@ -587,6 +613,11 @@ class EncodingService:
poll_interval: Seconds between status checks
timeout: Maximum time to wait (default 1 hour)
progress_callback: Optional callback(progress: int) for progress updates
worker_url: Worker base URL the job was submitted to. When set, every
poll is pinned to this worker (see get_job_status) so a mid-render
blue-green primary swap can't migrate the poll to a worker that
never received the job. When None, polls resolve active_url (legacy
behaviour, e.g. direct callers/tests).
Returns:
Final job status with output files
@@ -607,7 +638,7 @@ class EncodingService:
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
try:
status = await self.get_job_status(job_id)
status = await self.get_job_status(job_id, worker_url=worker_url)
# Reset failure counter on successful poll
consecutive_failures = 0
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
@@ -708,11 +739,14 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion (still holding the slot — the worker is
# actually doing CPU work for `job_id` until poll returns
# complete/failed).
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
job_id, progress_callback=progress_callback, worker_url=pinned_url
)
async def submit_preview_encoding_job(
@@ -837,11 +871,15 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion with shorter timeout
return await self.wait_for_completion(
job_id=job_id,
poll_interval=poll_interval,
timeout=timeout,
worker_url=pinned_url,
)
async def submit_render_video_job(
@@ -961,11 +999,18 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# Pin status polls to the worker the job actually landed on. Resolving
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
# the URL cache) while being BEFORE any later blue-green deploy swap —
# so the poll follows the job, not the floating active_url primary
# pointer (incident 2026-06-16, job d3af33ae).
pinned_url = self._get_worker_url()
# Wait for completion (still holding the slot — the worker is
# actively rendering for `job_id` until poll returns
# complete/failed).
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
job_id, progress_callback=progress_callback, worker_url=pinned_url
)
async def health_check(self) -> Dict[str, Any]:
+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
+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])
+8
View File
@@ -0,0 +1,8 @@
"""Artist/title match-judge: deterministic + catalog + light-AI formatting and
match-acceptance decisions for the job-submission flow.
See docs/archive/2026-06-15-artist-title-matching-rework-plan.md.
"""
from backend.services.match_judge.verdict import MatchVerdict
__all__ = ["MatchVerdict"]
+174
View File
@@ -0,0 +1,174 @@
"""The light-AI layer of the match judge.
Invoked only when the deterministic+catalog classifier can't decide. Uses a
small Vertex Gemini model to judge whether the typed artist/title is a real
song, what its canonical formatting is, and whether any change is cosmetic,
content-level, or ambiguous. The model call is injectable for testing.
"""
from __future__ import annotations
import asyncio
import json
import logging
from typing import Awaitable, Callable, Optional
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_CONTENT,
KIND_COSMETIC,
KIND_NONE,
MatchVerdict,
)
logger = logging.getLogger(__name__)
_VALID_KINDS = {KIND_COSMETIC, KIND_CONTENT, KIND_AMBIGUOUS}
Generate = Callable[[str, str, str], Awaitable[dict]]
_SYSTEM_PROMPT = (
"You normalise song metadata for a karaoke service. Given what a user typed "
"for an artist and title (plus optional catalog candidates), decide whether it "
"refers to a real, released song and how its artist/title should be formatted.\n"
"Return JSON with: kind, confident, canonical_artist, canonical_title, "
"alternatives, reason.\n"
"kind:\n"
" 'cosmetic' – same song, only formatting/casing/punctuation/diacritics differ.\n"
" 'content' – the user made a typo or used a wrong/variant title; the correct "
"song text differs in actual characters.\n"
" 'ambiguous' – more than one plausible song matches; list them in alternatives.\n"
" 'none' – already correct, or you cannot confidently suggest anything.\n"
"confident: true only when you are sure. Never invent songs. Prefer the user's "
"input when unsure (kind='none'). canonical_artist/canonical_title must use "
"official formatting. alternatives is a list of {artist,title}."
)
# OpenAPI-style schema handed to the Vertex genai client at runtime.
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
"confident": {"type": "boolean"},
"canonical_artist": {"type": "string"},
"canonical_title": {"type": "string"},
"alternatives": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artist": {"type": "string"},
"title": {"type": "string"},
},
},
},
"reason": {"type": "string"},
},
"required": ["kind", "confident"],
}
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
except Exception: # pragma: no cover - config import guard
return "gemini-3.5-flash"
def build_prompts(
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
) -> tuple[str, str]:
lines = [f'User typed: artist="{artist}" title="{title}"']
if audio_tier is not None:
lines.append(
f"Audio-search confidence tier: {audio_tier} "
"(1 = strong match found, 3 = weak/no results — a weak tier hints the "
"title may be misspelled)."
)
if candidates:
lines.append("Catalog candidates (canonical formatting):")
for c in candidates:
lines.append(f'- {c.get("artist_name", "")} — {c.get("track_name", "")}')
else:
lines.append("No catalog candidates were found.")
return _SYSTEM_PROMPT, "\n".join(lines)
def _verdict_from_response(
data: object, *, fallback_artist: str, fallback_title: str
) -> MatchVerdict:
if not isinstance(data, dict):
data = {}
kind = data.get("kind")
if kind not in _VALID_KINDS:
return MatchVerdict(
KIND_NONE, True, fallback_artist, fallback_title,
engine="ai", reason="no suggestion",
)
canonical_artist = (data.get("canonical_artist") or "").strip() or fallback_artist
canonical_title = (data.get("canonical_title") or "").strip() or fallback_title
alternatives = []
for alt in data.get("alternatives") or []:
if isinstance(alt, dict) and alt.get("artist") and alt.get("title"):
alternatives.append(
{"artist": str(alt["artist"]), "title": str(alt["title"])}
)
return MatchVerdict(
kind=kind,
confident=bool(data.get("confident", False)),
canonical_artist=canonical_artist,
canonical_title=canonical_title,
alternatives=alternatives,
engine="ai",
reason=str(data.get("reason") or ""),
)
async def ai_judge_match(
artist: str,
title: str,
candidates: list[dict],
audio_tier: Optional[int],
*,
model: Optional[str] = None,
generate: Optional[Generate] = None,
) -> MatchVerdict:
model = model or _model()
gen = generate or _default_generate
system_prompt, user_prompt = build_prompts(artist, title, candidates, audio_tier)
data = await gen(model, system_prompt, user_prompt)
return _verdict_from_response(
data, fallback_artist=artist, fallback_title=title
)
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
import copy
from google import genai
from google.genai import types
from backend.config import settings
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
response = client.models.generate_content(
model=model,
contents=[user_prompt],
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
),
)
return json.loads(response.text)
@@ -0,0 +1,82 @@
"""Deterministic + catalog match classification (no AI, no network).
`classify_catalog_match` returns a confident :class:`MatchVerdict` when the
typed artist/title clearly correspond to a catalog candidate (a cosmetic
formatting fix, or nothing to change). When it cannot confidently decide, it
returns ``None`` — the caller should then escalate to the AI judge.
"""
from __future__ import annotations
import re
import unicodedata
from typing import Optional
from karaoke_gen.utils import normalize_text
from backend.services.match_judge.verdict import (
KIND_COSMETIC,
KIND_NONE,
MatchVerdict,
)
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
_WS = re.compile(r"\s+")
def _fold_accents(text: str) -> str:
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
decomposed = unicodedata.normalize("NFKD", text)
return "".join(c for c in decomposed if not unicodedata.combining(c))
def normalize_for_match(text: str) -> str:
"""Aggressive key used only for equality comparison (never displayed).
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
"""
s = normalize_text(text or "")
s = s.replace("&", " and ")
s = _fold_accents(s)
s = s.casefold()
s = _NON_ALNUM.sub(" ", s)
s = _WS.sub(" ", s).strip()
return s
def classify_catalog_match(
artist: str, title: str, candidates: list[dict]
) -> Optional[MatchVerdict]:
"""Return a confident verdict from catalog candidates, or None to escalate.
candidates: dicts with ``artist_name`` and ``track_name`` (Spotify/MB canonical).
"""
key_artist = normalize_for_match(artist)
key_title = normalize_for_match(title)
for cand in candidates:
cand_artist = cand.get("artist_name") or ""
cand_title = cand.get("track_name") or ""
if (
normalize_for_match(cand_artist) == key_artist
and normalize_for_match(cand_title) == key_title
):
# Same song. Cosmetic fix unless the user already typed it exactly.
if cand_artist == artist and cand_title == title:
return MatchVerdict(
kind=KIND_NONE,
confident=True,
canonical_artist=artist,
canonical_title=title,
engine="catalog",
reason="already canonical",
)
return MatchVerdict(
kind=KIND_COSMETIC,
confident=True,
canonical_artist=cand_artist,
canonical_title=cand_title,
engine="catalog",
reason="formatting differs from catalog",
)
return None
+128
View File
@@ -0,0 +1,128 @@
"""Match-judge orchestration.
Composes the deterministic+catalog classifier with the AI judge. The AI judge
runs ONLY when the classifier can't confidently decide, and never blocks or
errors the caller — any failure degrades to "no suggestion".
"""
from __future__ import annotations
import logging
from typing import Awaitable, Callable, Literal, Optional
from backend.services.match_judge.classifier import classify_catalog_match
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
logger = logging.getLogger(__name__)
CATALOG_CANDIDATE_LIMIT = 8
Stage = Literal["fast", "full"]
# Audio tiers at or above this are "weak" (poor / no results). A weak tier hints
# the typed title may be a typo, so even a confident catalog match is verified
# with the AI judge (it can be a junk/misspelled Spotify entry).
WEAK_TIER = 3
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
from backend.services.catalog_proxy_service import search_tracks
return await search_tracks(query, artist, limit)
async def _default_ai_judge(
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
) -> MatchVerdict:
from backend.services.match_judge.ai import ai_judge_match
return await ai_judge_match(artist, title, candidates, audio_tier)
def _default_enabled() -> bool:
try:
from backend.config import settings
return bool(getattr(settings, "match_judge_enabled", True))
except Exception: # pragma: no cover - config import guard
return True
async def judge_match(
artist: str,
title: str,
audio_tier: Optional[int] = None,
*,
stage: Stage = "full",
search_tracks: Optional[SearchTracks] = None,
ai_judge: Optional[AiJudge] = None,
enabled: Optional[bool] = None,
) -> MatchVerdict:
"""Return a :class:`MatchVerdict` for the typed artist/title.
audio_tier: the audio search's confidence tier (1=best..3=poor), used by the
AI judge to decide whether weak results suggest a typo. May be None.
stage:
"fast" — catalog-only pass (no AI, tier ignored). Runs in parallel with the
audio search so the common cosmetic tidy is ready before results render.
Returns the catalog verdict if confident, else a ``needs_ai=True`` marker
telling the caller to make a "full" call once the tier is known.
"full" — the complete pipeline: catalog, then the AI judge when catalog isn't
confident OR (item 4) when a confident catalog match coincides with a weak
audio tier (the match may be a junk/typo'd entry — let AI override).
"""
search = search_tracks or _default_search_tracks
ai = ai_judge or _default_ai_judge
if enabled is None:
enabled = _default_enabled()
try:
candidates = await search(title, artist, CATALOG_CANDIDATE_LIMIT)
except Exception:
logger.warning(
"match-judge catalog search failed; continuing without candidates",
exc_info=True,
)
candidates = []
catalog_verdict = classify_catalog_match(artist, title, candidates)
# Fast pass: catalog only. Never touches the AI layer.
if stage == "fast":
if catalog_verdict is not None:
return catalog_verdict
return MatchVerdict(
KIND_NONE, False, artist, title,
engine="catalog", reason="needs ai", needs_ai=True,
)
# Full pass.
if catalog_verdict is not None:
weak = audio_tier is not None and audio_tier >= WEAK_TIER
if not (enabled and weak):
return catalog_verdict
# Item 4: weak audio results make the typo hypothesis plausible even though
# the catalog "matched" — verify with AI and let a confident verdict override.
try:
ai_verdict = await ai(artist, title, candidates, audio_tier)
except Exception:
logger.exception(
"match-judge AI verification failed; keeping catalog verdict"
)
return catalog_verdict
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
return ai_verdict
return catalog_verdict
if not enabled:
return MatchVerdict(
KIND_NONE, True, artist, title, engine="deterministic", reason="ai disabled"
)
try:
return await ai(artist, title, candidates, audio_tier)
except Exception:
logger.exception("match-judge AI call failed; returning no-suggestion")
return MatchVerdict(
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
)
+47
View File
@@ -0,0 +1,47 @@
"""The verdict returned by the match judge."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Literal
# kind values:
# "cosmetic" – same song, formatting-only fix → apply invisibly
# "content" – actual characters change (typo/different title) → surface + maybe re-search
# "ambiguous" – more than one plausible song → ask the user first
# "none" – nothing to change (already correct, or no confident suggestion)
KIND_COSMETIC = "cosmetic"
KIND_CONTENT = "content"
KIND_AMBIGUOUS = "ambiguous"
KIND_NONE = "none"
Kind = Literal["cosmetic", "content", "ambiguous", "none"]
Engine = Literal["deterministic", "catalog", "ai"]
@dataclass(frozen=True)
class MatchVerdict:
kind: Kind
confident: bool
canonical_artist: str
canonical_title: str
alternatives: list[dict] = field(default_factory=list) # [{"artist","title"}]
engine: Engine = "deterministic"
reason: str = ""
# True only from a "fast" (catalog-only) pass that couldn't confidently decide:
# the caller should escalate to a "full" pass (with the audio tier) for an AI
# verdict. Always False on a full-pass verdict.
needs_ai: bool = False
def to_dict(self) -> dict:
return {
"kind": self.kind,
"confident": self.confident,
"canonical_artist": self.canonical_artist,
"canonical_title": self.canonical_title,
"alternatives": self.alternatives,
"engine": self.engine,
"reason": self.reason,
"needs_ai": self.needs_ai,
}
+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
+73
View File
@@ -0,0 +1,73 @@
"""Helpers for locating and naming a job's original input audio.
The original downloaded/uploaded audio (the source used for separation,
transcription and the With Vocals video) is stored in GCS but is no longer
copied into the final output folder by the distributed pipeline. These helpers
let the orchestrator (and the backfill script) restore it to the Dropbox track
folder with the historical source-tagged name, e.g.::
<artist> - <title> (flacfetch).flac
<artist> - <title> (uploaded).mp3
<artist> - <title> (YouTube).webm
The naming mirrors the legacy monolith convention.
"""
import os
from typing import Optional
# Map a job's audio_source_type to the historical filename suffix.
_SOURCE_TAGS = {
"file_upload": "uploaded",
"youtube_url": "YouTube",
"audio_search": "flacfetch",
}
def original_audio_source_tag(job) -> str:
"""Return the parenthesised source suffix for a job's original audio.
Falls back gracefully for older jobs that predate ``audio_source_type``.
"""
tag = _SOURCE_TAGS.get(getattr(job, "audio_source_type", None))
if tag:
return tag
# Fallbacks for legacy jobs without an explicit source type.
if getattr(job, "url", None):
return "YouTube"
if getattr(job, "filename", None) or getattr(job, "input_media_gcs_path", None):
return "uploaded"
return "input"
def original_audio_gcs_path(job) -> Optional[str]:
"""Return the GCS blob path of the original input audio, or None.
Prefers ``input_media_gcs_path`` (uploads are persisted under jobs/ and URL
jobs record their downloaded file here), then falls back to
``file_urls['input']`` which may be a plain string or a nested
``{'audio': ...}`` dict depending on the code path that wrote it.
"""
path = getattr(job, "input_media_gcs_path", None)
if path:
return path
file_urls = getattr(job, "file_urls", None) or {}
inp = file_urls.get("input")
if isinstance(inp, dict):
return inp.get("audio")
if isinstance(inp, str):
return inp
return None
def original_audio_output_filename(job, base_name: str) -> Optional[str]:
"""Return the output filename for the original audio, or None if absent.
e.g. ``"<artist> - <title> (flacfetch).flac"``. The extension is preserved
from the GCS path.
"""
gcs_path = original_audio_gcs_path(job)
if not gcs_path:
return None
ext = os.path.splitext(gcs_path)[1]
return f"{base_name} ({original_audio_source_tag(job)}){ext}"
+11
View File
@@ -59,6 +59,17 @@ class StorageService:
logger.error(f"Error downloading file {source_path}: {e}")
raise
def copy_blob(self, source_path: str, destination_path: str) -> str:
"""Server-side copy of a blob within the bucket (no download/upload)."""
try:
src = self.bucket.blob(source_path)
self.bucket.copy_blob(src, self.bucket, destination_path)
logger.info(f"Copied gs://{settings.gcs_bucket_name}/{source_path} -> {destination_path}")
return destination_path
except Exception as e:
logger.error(f"Error copying blob {source_path} -> {destination_path}: {e}")
raise
def generate_signed_url(self, blob_path: str, expiration_minutes: int = 60) -> str:
"""Generate a signed URL for downloading a file.
+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.
Whitespace-only changes.
@@ -0,0 +1,103 @@
"""Tests for the AI judge: prompt construction + response→verdict mapping.
The model call (`generate`) is injected, so these tests are offline and
deterministic. The real `generate` wraps the Vertex genai client.
"""
import pytest
from backend.services.match_judge.ai import ai_judge_match, build_prompts
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_CONTENT,
KIND_NONE,
)
def _gen(response: dict):
async def generate(model, system_prompt, user_prompt):
return response
return generate
class TestBuildPrompts:
def test_prompt_includes_input_candidates_and_tier(self):
system, user = build_prompts(
"queen",
"bohemian rapsody",
[{"artist_name": "Queen", "track_name": "Bohemian Rhapsody"}],
audio_tier=3,
)
assert "bohemian rapsody" in user
assert "Bohemian Rhapsody" in user # candidate shown
# The poor-results signal must reach the model so it can favour a typo fix.
assert "3" in user
class TestResponseMapping:
@pytest.mark.asyncio
async def test_confident_content_correction(self):
verdict = await ai_judge_match(
"queen",
"bohemian rapsody",
[],
3,
generate=_gen(
{
"kind": "content",
"confident": True,
"canonical_artist": "Queen",
"canonical_title": "Bohemian Rhapsody",
"alternatives": [],
"reason": "typo",
}
),
)
assert verdict.kind == KIND_CONTENT
assert verdict.confident is True
assert verdict.canonical_title == "Bohemian Rhapsody"
assert verdict.engine == "ai"
@pytest.mark.asyncio
async def test_ambiguous_carries_alternatives(self):
verdict = await ai_judge_match(
"",
"bruises",
[],
3,
generate=_gen(
{
"kind": "ambiguous",
"confident": False,
"canonical_artist": "Lewis Capaldi",
"canonical_title": "Bruises",
"alternatives": [{"artist": "Fox Stevenson", "title": "Bruises"}],
"reason": "multiple artists",
}
),
)
assert verdict.kind == KIND_AMBIGUOUS
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
@pytest.mark.asyncio
async def test_unknown_kind_is_treated_as_none(self):
verdict = await ai_judge_match(
"queen",
"bohemian rhapsody",
[],
1,
generate=_gen({"kind": "garbage", "confident": True}),
)
assert verdict.kind == KIND_NONE
assert verdict.canonical_artist == "queen" # falls back to user input
@pytest.mark.asyncio
async def test_missing_canonical_falls_back_to_input(self):
verdict = await ai_judge_match(
"queen",
"bohemian rhapsody",
[],
1,
generate=_gen({"kind": "content", "confident": True}),
)
assert verdict.canonical_artist == "queen"
assert verdict.canonical_title == "bohemian rhapsody"
@@ -0,0 +1,66 @@
"""Tests for the deterministic + catalog match classifier.
The classifier decides, WITHOUT any AI/network call, whether a typed
artist/title cosmetically matches a catalog candidate (so we can silently
tidy formatting) or whether the decision must be escalated to the AI judge.
"""
from backend.services.match_judge.classifier import (
normalize_for_match,
classify_catalog_match,
)
def _cand(artist: str, title: str) -> dict:
return {"artist_name": artist, "track_name": title}
class TestNormalizeForMatch:
def test_casing_and_whitespace_collapse_to_same_key(self):
assert normalize_for_match("Paramore") == normalize_for_match(" paramore ")
def test_punctuation_is_ignored(self):
assert normalize_for_match("Big Man, Little Dignity") == normalize_for_match(
"big man little dignity"
)
def test_ampersand_and_and_are_equivalent(self):
assert normalize_for_match("Jay-Z & Beyonce") == normalize_for_match(
"Jay Z and Beyonce"
)
class TestClassifyCatalogMatch:
def test_casing_only_difference_is_cosmetic(self):
verdict = classify_catalog_match(
"paramore",
"big man, little dignity",
[_cand("Paramore", "Big Man, Little Dignity")],
)
assert verdict is not None
assert verdict.kind == "cosmetic"
assert verdict.confident is True
assert verdict.canonical_artist == "Paramore"
assert verdict.canonical_title == "Big Man, Little Dignity"
assert verdict.engine == "catalog"
def test_exact_match_needs_no_change(self):
verdict = classify_catalog_match(
"Paramore",
"Big Man, Little Dignity",
[_cand("Paramore", "Big Man, Little Dignity")],
)
assert verdict is not None
assert verdict.kind == "none"
assert verdict.confident is True
def test_no_catalog_match_escalates_to_ai(self):
# Returns None => the service should call the AI judge.
verdict = classify_catalog_match(
"queen",
"bohemian rhapsody",
[_cand("Paramore", "Big Man, Little Dignity")],
)
assert verdict is None
def test_empty_candidates_escalates_to_ai(self):
assert classify_catalog_match("queen", "bohemian rhapsody", []) is None
@@ -0,0 +1,272 @@
"""Orchestration tests for the match-judge service.
The service composes the deterministic+catalog classifier with the AI judge:
the AI judge is invoked ONLY when the classifier can't confidently decide.
Catalog search and the AI judge are injected so these tests touch no network.
"""
import pytest
from backend.services.match_judge.service import judge_match
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_COSMETIC,
KIND_CONTENT,
KIND_NONE,
MatchVerdict,
)
def _candidates(*pairs):
async def _search(query, artist, limit):
return [{"artist_name": a, "track_name": t} for a, t in pairs]
return _search
def _ai_never(*_a, **_k):
raise AssertionError("AI judge must not be called")
@pytest.mark.asyncio
async def test_catalog_cosmetic_match_skips_ai():
calls = {"ai": 0}
async def ai(*_a, **_k):
calls["ai"] += 1
raise AssertionError("should not run")
verdict = await judge_match(
"paramore",
"big man, little dignity",
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
assert calls["ai"] == 0
@pytest.mark.asyncio
async def test_no_catalog_match_calls_ai():
seen = {}
async def ai(artist, title, candidates, audio_tier):
seen["candidates"] = candidates
seen["tier"] = audio_tier
return MatchVerdict(
kind=KIND_CONTENT,
confident=True,
canonical_artist="Queen",
canonical_title="Bohemian Rhapsody",
engine="ai",
reason="typo fix",
)
verdict = await judge_match(
"queen",
"bohemian rapsody",
audio_tier=3,
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_CONTENT
assert verdict.engine == "ai"
assert seen["tier"] == 3
assert seen["candidates"] == [{"artist_name": "Queen", "track_name": "Radio Ga Ga"}]
@pytest.mark.asyncio
async def test_disabled_flag_skips_ai_and_returns_none():
verdict = await judge_match(
"queen",
"bohemian rapsody",
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=_ai_never,
enabled=False,
)
assert verdict.kind == KIND_NONE
assert verdict.confident is True
assert verdict.canonical_artist == "queen" # leaves user input untouched
@pytest.mark.asyncio
async def test_ai_failure_falls_back_to_none():
async def ai(*_a, **_k):
raise RuntimeError("model exploded")
verdict = await judge_match(
"queen",
"bohemian rapsody",
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_NONE
assert verdict.canonical_title == "bohemian rapsody"
# --- Fast stage (catalog-only parallel pass) ---
@pytest.mark.asyncio
async def test_fast_stage_returns_catalog_verdict_without_ai():
verdict = await judge_match(
"paramore",
"big man, little dignity",
stage="fast",
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=_ai_never,
enabled=True,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
assert verdict.needs_ai is False
@pytest.mark.asyncio
async def test_fast_stage_undecided_signals_needs_ai_without_calling_ai():
verdict = await judge_match(
"queen",
"bohemian rapsody",
stage="fast",
search_tracks=_candidates(("Queen", "Radio Ga Ga")),
ai_judge=_ai_never,
enabled=True,
)
assert verdict.kind == KIND_NONE
assert verdict.needs_ai is True
assert verdict.confident is False
@pytest.mark.asyncio
async def test_fast_stage_never_calls_ai_even_when_undecided():
# _ai_never raises if called; reaching here proves the fast pass skipped AI.
verdict = await judge_match(
"queen", "bohemian rapsody", stage="fast",
search_tracks=_candidates(), ai_judge=_ai_never, enabled=True,
)
assert verdict.needs_ai is True
# --- Item 4: verify a confident catalog match with AI when the audio tier is weak ---
@pytest.mark.asyncio
async def test_weak_tier_catalog_match_is_verified_and_overridden_by_ai():
async def ai(artist, title, candidates, audio_tier):
return MatchVerdict(
KIND_CONTENT, True, "Queen", "Bohemian Rhapsody",
engine="ai", reason="typo",
)
# Catalog "matched" the user's exact typo (junk entry) → would normally be
# 'none'/already-canonical. Weak tier (3) makes us verify with AI, which overrides.
verdict = await judge_match(
"Queen", "Bohemian Rapsody",
audio_tier=3,
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_CONTENT
assert verdict.canonical_title == "Bohemian Rhapsody"
assert verdict.engine == "ai"
@pytest.mark.asyncio
async def test_strong_tier_catalog_match_still_skips_ai():
verdict = await judge_match(
"Queen", "Bohemian Rapsody",
audio_tier=1,
search_tracks=_candidates(("Queen", "Bohemian Rapsody")),
ai_judge=_ai_never,
enabled=True,
)
# Strong audio results → trust the catalog match, no AI.
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_keeps_catalog_verdict_when_ai_unconfident():
async def ai(artist, title, candidates, audio_tier):
return MatchVerdict(KIND_NONE, False, artist, title, engine="ai")
verdict = await judge_match(
"paramore", "big man, little dignity",
audio_tier=3,
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=ai,
enabled=True,
)
# AI wasn't confident about a change → keep the cosmetic catalog tidy.
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_keeps_catalog_verdict_when_ai_fails():
async def ai(*_a, **_k):
raise RuntimeError("model exploded")
verdict = await judge_match(
"paramore", "big man, little dignity",
audio_tier=3,
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_does_not_verify_when_ai_disabled():
verdict = await judge_match(
"paramore", "big man, little dignity",
audio_tier=3,
search_tracks=_candidates(("Paramore", "Big Man, Little Dignity")),
ai_judge=_ai_never,
enabled=False,
)
assert verdict.kind == KIND_COSMETIC
assert verdict.engine == "catalog"
@pytest.mark.asyncio
async def test_weak_tier_ai_can_escalate_to_ambiguous():
async def ai(artist, title, candidates, audio_tier):
return MatchVerdict(
KIND_AMBIGUOUS, True, "Lewis Capaldi", "Bruises",
alternatives=[{"artist": "Fox Stevenson", "title": "Bruises"}],
engine="ai",
)
verdict = await judge_match(
"capaldi", "bruises",
audio_tier=3,
search_tracks=_candidates(("Lewis Capaldi", "Bruises")),
ai_judge=ai,
enabled=True,
)
assert verdict.kind == KIND_AMBIGUOUS
assert verdict.alternatives == [{"artist": "Fox Stevenson", "title": "Bruises"}]
@pytest.mark.asyncio
async def test_catalog_search_failure_still_lets_ai_run():
async def failing_search(query, artist, limit):
raise RuntimeError("catalog down")
async def ai(artist, title, candidates, audio_tier):
assert candidates == [] # gracefully degraded to no candidates
return MatchVerdict(KIND_NONE, True, artist, title, engine="ai")
verdict = await judge_match(
"queen",
"bohemian rhapsody",
search_tracks=failing_search,
ai_judge=ai,
enabled=True,
)
assert verdict.engine == "ai"
@@ -124,6 +124,11 @@ class TestProcessAudioDownload:
'input_media_gcs_path': "uploads/test-job-123/audio/song.mp3",
'filename': "song.mp3",
})
# Original audio recorded in file_urls so it shows in the admin files
# manifest (and can be staged into the Dropbox folder) for URL/search jobs.
mock_jm.update_file_url.assert_any_call(
"test-job-123", 'input', 'audio', "uploads/test-job-123/audio/song.mp3"
)
mock_jm.transition_to_state.assert_called_once()
mock_ws.trigger_audio_worker.assert_awaited_once_with("test-job-123")
mock_ws.trigger_lyrics_worker.assert_awaited_once_with("test-job-123")
+67
View File
@@ -0,0 +1,67 @@
"""
Regression tests for AudioShake leading-padding handling.
Some user-provided audio (e.g. the Vocal Star bulk-batch MP3s) begins with a block of
null bytes before the first ID3/MPEG frame. ffmpeg tolerates it, but AudioShake rejects
the asset with "Error fetching or processing asset" (400 on /tasks). The AudioUploadOptimizer
must detect this and losslessly remux before upload — while leaving clean files and
container formats (.mp4/.mov, which legitimately start with null box-size bytes) untouched.
"""
import os
import tempfile
from unittest.mock import MagicMock, patch
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioUploadOptimizer
def _write(tmp_path, name, head: bytes):
p = os.path.join(tmp_path, name)
with open(p, "wb") as f:
f.write(head + b"\x00" * 2048)
return p
def test_has_leading_padding_detects_null_start(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
assert opt._has_leading_padding(padded) is True
def test_has_leading_padding_false_for_id3(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
assert opt._has_leading_padding(clean) is False
def test_has_leading_padding_false_for_frame_sync(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "sync.mp3", b"\xff\xfb\xc0\x04")
assert opt._has_leading_padding(clean) is False
def test_padded_mp3_is_remuxed(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
with patch.object(opt, "_remux_clean", return_value=("/tmp/clean.mp3", "/tmp/clean.mp3")) as remux:
result = opt.prepare_for_upload(padded)
remux.assert_called_once()
assert result == ("/tmp/clean.mp3", "/tmp/clean.mp3")
def test_clean_mp3_uploaded_directly(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
with patch.object(opt, "_remux_clean") as remux:
result = opt.prepare_for_upload(clean)
remux.assert_not_called()
assert result == (clean, None)
def test_container_format_not_remuxed_despite_null_start(tmp_path):
""".mp4/.mov begin with a null box-size prefix — must NOT be treated as padding."""
opt = AudioUploadOptimizer(MagicMock())
mp4 = _write(str(tmp_path), "video.mp4", b"\x00\x00\x00\x20ftyp")
with patch.object(opt, "_remux_clean") as remux:
result = opt.prepare_for_upload(mp4)
remux.assert_not_called()
assert result == (mp4, None)
@@ -0,0 +1,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."""
+128 -3
View File
@@ -601,7 +601,7 @@ class TestWaitForCompletionPollTolerance:
"""Tolerates up to MAX_CONSECUTIVE_POLL_FAILURES-1 consecutive failures."""
call_count = 0
async def mock_get_status(job_id):
async def mock_get_status(job_id, worker_url=None):
nonlocal call_count
call_count += 1
if call_count <= 2:
@@ -623,7 +623,7 @@ class TestWaitForCompletionPollTolerance:
@pytest.mark.asyncio
async def test_fails_after_max_consecutive_poll_failures(self, encoding_service):
"""Fails after MAX_CONSECUTIVE_POLL_FAILURES consecutive failures."""
async def always_fail(job_id):
async def always_fail(job_id, worker_url=None):
raise aiohttp.ClientConnectorError(
connection_key=MagicMock(), os_error=OSError("Connection refused")
)
@@ -640,7 +640,7 @@ class TestWaitForCompletionPollTolerance:
"""A successful poll resets the consecutive failure counter."""
call_count = 0
async def intermittent_failures(job_id):
async def intermittent_failures(job_id, worker_url=None):
nonlocal call_count
call_count += 1
# Fail for 2, succeed (running), fail for 2 more, succeed (complete)
@@ -752,3 +752,128 @@ class TestFormatException:
e = aiohttp.ClientConnectorError(MagicMock(), OSError())
# Type name should always appear
assert "ClientConnectorError" in _format_exception(e)
class TestWorkerUrlPinning:
"""Status polls must stay pinned to the worker that ACCEPTED the job.
Regression for incident 2026-06-16 (job d3af33ae): a blue-green deploy
swapped the primary pointer mid-render, and because status polls re-resolved
`active_url` on every call, they migrated from the worker actually encoding
the job (old primary) to the freshly-swapped new primary — which 404'd
"Encoding job ... not found" and failed the render after 5 polls, even though
the original worker finished the encode fine.
"""
@pytest.mark.asyncio
async def test_get_job_status_targets_pinned_url(self, encoding_service):
"""A pinned poll hits the given worker_url, not active_url, and disables
failover (a pinned poll must never re-resolve or spin up a fallback VM —
a fresh VM cannot have the in-flight job)."""
# active_url would resolve to worker-b, but the job lives on worker-a.
captured = {}
async def fake_request(**kwargs):
captured.update(kwargs)
return {"status": 200, "json": {"status": "running", "progress": 40}, "text": None}
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
result = await encoding_service.get_job_status("d3af33ae", worker_url="http://worker-a:8080")
assert result["status"] == "running"
assert captured["url"] == "http://worker-a:8080/status/d3af33ae"
assert captured["allow_failover"] is False
@pytest.mark.asyncio
async def test_get_job_status_without_pin_uses_active_url(self, encoding_service):
"""Regression: unpinned polls still resolve the current active_url."""
captured = {}
async def fake_request(**kwargs):
captured.update(kwargs)
return {"status": 200, "json": {"status": "running"}, "text": None}
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-b:8080"), \
patch.object(encoding_service, "_request_with_retry", side_effect=fake_request):
await encoding_service.get_job_status("d3af33ae")
assert captured["url"] == "http://worker-b:8080/status/d3af33ae"
# Unpinned keeps the existing failover/re-resolution behaviour.
assert captured.get("allow_failover", True) is True
@pytest.mark.asyncio
async def test_wait_for_completion_threads_pinned_url_into_polls(self, encoding_service):
"""wait_for_completion forwards its worker_url to every status poll."""
seen_urls = []
async def mock_get_status(job_id, worker_url=None):
seen_urls.append(worker_url)
return {"status": "complete", "output_files": ["a.mp4"]}
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
result = await encoding_service.wait_for_completion(
"d3af33ae", worker_url="http://worker-a:8080"
)
assert result["status"] == "complete"
assert seen_urls == ["http://worker-a:8080"]
@pytest.mark.asyncio
async def test_request_with_retry_no_failover_when_disabled(self, encoding_service):
"""With allow_failover=False, a connection error must NOT trigger the
fallback-VM warmup nor URL re-resolution — it just retries the same URL
and surfaces the failure to the caller's own poll-tolerance loop."""
encoding_service.set_worker_manager(MagicMock())
warmup = AsyncMock()
with patch.object(encoding_service, "_warmup_encoding_worker_fallback", warmup), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("aiohttp.ClientSession") as mock_session:
mock_session.side_effect = aiohttp.ClientConnectorError(
MagicMock(), OSError("Connection refused")
)
with pytest.raises(aiohttp.ClientConnectorError):
await encoding_service._request_with_retry(
method="GET",
url="http://worker-a:8080/status/j1",
headers={},
job_id="j1",
path=None,
allow_failover=False,
)
warmup.assert_not_called()
@pytest.mark.asyncio
async def test_render_video_keeps_polling_submission_worker_after_swap(self, encoding_service):
"""End-to-end: when active_url has swapped to a worker that 404s, the
render keeps polling the worker the job was submitted to and completes.
This FAILS before the fix (the poll follows active_url to worker-b and
gets "not found"), and PASSES after (the poll is pinned to worker-a)."""
encoding_service.set_worker_manager(MagicMock())
async def fake_submit(job_id, render_config):
return {"status": "accepted", "job_id": job_id}
async def fake_get_status(job_id, worker_url=None):
# worker-a owns the job; the post-swap active worker (worker-b, or an
# unpinned None) has never seen it.
if worker_url == "http://worker-a:8080":
return {"status": "complete", "output_files": ["4k.mp4"]}
raise RuntimeError(f"Encoding job {job_id} not found")
with patch.object(encoding_service, "_get_worker_url", return_value="http://worker-a:8080"), \
patch.object(encoding_service, "submit_render_video_job", side_effect=fake_submit), \
patch.object(encoding_service, "get_job_status", side_effect=fake_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
result = await encoding_service.render_video_on_gce("d3af33ae", {"foo": "bar"})
assert result["status"] == "complete"
assert result["output_files"] == ["4k.mp4"]
+77 -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,86 @@ 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 must map a real platform to an https URL."""
from backend.api.routes.file_upload import (
_DRM_DOWNLOADER_SUGGESTIONS,
_UNSUPPORTED_DRM_HOSTS,
)
known_platforms = set(_UNSUPPORTED_DRM_HOSTS.values()) | {"Amazon Music"}
for platform, url in _DRM_DOWNLOADER_SUGGESTIONS.items():
assert platform in known_platforms, f"{platform} is not a known DRM platform"
assert url.startswith("https://"), f"{platform} downloader must be https"
# Apple Music is the verified case driving this feature.
assert _DRM_DOWNLOADER_SUGGESTIONS.get("Apple Music") == "https://am-dl.pages.dev"
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()
+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
+120
View File
@@ -0,0 +1,120 @@
"""Tests for POST /api/catalog/match-judge."""
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from fastapi.testclient import TestClient
from backend.main import app
from backend.services.match_judge.verdict import MatchVerdict, KIND_COSMETIC, KIND_NONE
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def auth_headers():
return {"Authorization": "Bearer test-admin-token"}
@pytest.fixture(autouse=True)
def clear_rate_limits():
from backend.api.routes.catalog import _rate_limit_windows
_rate_limit_windows.clear()
yield
_rate_limit_windows.clear()
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_returns_verdict(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict(
kind=KIND_COSMETIC,
confident=True,
canonical_artist="Paramore",
canonical_title="Big Man, Little Dignity",
engine="catalog",
reason="casing",
)
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "paramore", "title": "big man, little dignity"},
headers=auth_headers,
)
assert resp.status_code == 200
data = resp.json()
assert data["kind"] == "cosmetic"
assert data["confident"] is True
assert data["canonical_artist"] == "Paramore"
assert data["canonical_title"] == "Big Man, Little Dignity"
assert data["engine"] == "catalog"
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_passes_audio_tier(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b", "audio_confidence_tier": 3},
headers=auth_headers,
)
# judge_match(artist, title, audio_tier=...) — tier forwarded
_, kwargs = mock_judge.call_args
assert kwargs.get("audio_tier") == 3 or mock_judge.call_args.args[2] == 3
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_defaults_to_full_stage(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict("none", True, "q", "b", engine="ai")
client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b"},
headers=auth_headers,
)
_, kwargs = mock_judge.call_args
assert kwargs.get("stage") == "full"
@patch("backend.api.routes.catalog.require_auth")
@patch("backend.services.match_judge.service.judge_match", new_callable=AsyncMock)
def test_match_judge_forwards_fast_stage(mock_judge, mock_auth, client, auth_headers):
mock_auth.return_value = MagicMock(user_email="t@example.com", token_id="t")
mock_judge.return_value = MatchVerdict(
KIND_NONE, False, "q", "b", engine="catalog", reason="needs ai", needs_ai=True
)
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b", "stage": "fast"},
headers=auth_headers,
)
assert resp.status_code == 200
assert resp.json()["needs_ai"] is True
_, kwargs = mock_judge.call_args
assert kwargs.get("stage") == "fast"
def test_match_judge_rejects_unknown_stage(client, auth_headers):
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "q", "title": "b", "stage": "turbo"},
headers=auth_headers,
)
assert resp.status_code == 422
def test_match_judge_validation_error(client, auth_headers):
resp = client.post(
"/api/catalog/match-judge",
json={"artist": "", "title": "Dreams"},
headers=auth_headers,
)
assert resp.status_code == 422
+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")
+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
+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:
+38
View File
@@ -365,6 +365,44 @@ class TestCompleteReviewZeroSegmentValidation:
assert response.status_code == 200
def test_existing_instrumental_defaults_selection_to_custom(self, _patched_client):
"""Jobs that supplied their own instrumental (tenant/existing_instrumental flow)
have no instrumental-selection UI step, so complete-review must default the
selection to 'custom' — otherwise the render defaults to 'clean' (a separated
stem that was never produced) and fails the prerequisite check."""
client, mock_jm = _patched_client
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
mock_jm.update_state_data.assert_any_call(
"job-zero-seg", "instrumental_selection", "custom"
)
def test_existing_instrumental_does_not_override_explicit_selection(self, _patched_client):
"""An explicit instrumental_selection in the request still wins over the default."""
client, mock_jm = _patched_client
job = self._make_job(state_data={'lyrics_metadata': {'segment_count': 5}})
job.existing_instrumental_gcs_path = "uploads/job-zero-seg/audio/existing_instrumental.mp3"
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
json={"instrumental_selection": "clean"},
)
assert response.status_code == 200
mock_jm.update_state_data.assert_any_call(
"job-zero-seg", "instrumental_selection", "clean"
)
class TestPreviewStyleLoading:
"""Tests for the unified style loader used in preview video generation.
+28 -1
View File
@@ -38,9 +38,36 @@ class TestStorageServiceInit:
assert service.bucket == mock_bucket
class TestStorageServiceCopy:
"""Test server-side copy (used to stage the tenant instrumental for the GCE encoder)."""
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_copy_blob(self, mock_settings, mock_client_class):
mock_settings.gcs_bucket_name = "test-bucket"
mock_src_blob = Mock()
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_src_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
result = service.copy_blob(
"uploads/job123/audio/existing_instrumental.mp3",
"jobs/job123/existing_instrumental.mp3",
)
mock_bucket.blob.assert_called_once_with("uploads/job123/audio/existing_instrumental.mp3")
mock_bucket.copy_blob.assert_called_once_with(
mock_src_blob, mock_bucket, "jobs/job123/existing_instrumental.mp3"
)
assert result == "jobs/job123/existing_instrumental.mp3"
class TestStorageServiceUpload:
"""Test upload operations."""
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_upload_file(self, mock_settings, mock_client_class):
+37
View File
@@ -56,6 +56,43 @@ def _make_job_mock(**kwargs):
return job
class TestSelectMixedAudioFiles:
"""Regression tests for _select_mixed_audio_files() in file_upload.py.
The existing-instrumental file shares the uploads/{job}/audio/ directory with the
mixed audio, so the 'audio/' prefix matches both. Before the fix, files[0] resolved to
'existing_instrumental.mp3' (it sorts first) and transcription ran on the instrumental.
"""
def _fn(self):
from backend.api.routes.file_upload import _select_mixed_audio_files
return _select_mixed_audio_files
def test_excludes_existing_instrumental(self):
fn = self._fn()
# Listing is sorted alphabetically by GCS, so the instrumental comes first.
files = [
"uploads/job123/audio/existing_instrumental.mp3",
"uploads/job123/audio/mixed.mp3",
]
result = fn(files)
assert result == ["uploads/job123/audio/mixed.mp3"]
assert result[0] == "uploads/job123/audio/mixed.mp3"
def test_plain_audio_only_unchanged(self):
fn = self._fn()
files = ["uploads/job123/audio/My Song.flac"]
assert fn(files) == files
def test_real_filenames_with_instrumental(self):
fn = self._fn()
files = [
"uploads/job123/audio/existing_instrumental.mp3",
"uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3",
]
assert fn(files) == ["uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3"]
class TestApplyTenantOverrides:
"""Tests for _apply_tenant_overrides() in file_upload.py."""
@@ -0,0 +1,72 @@
"""Test that _upload_results registers the standalone screen MOVs in file_urls.
This makes (Title).mov / (End).mov appear in the admin files manifest and verifiable
by the daily E2E. Regression: the screen MOVs were absent from Dropbox track folders.
"""
import os
import tempfile
import pytest
from backend.workers.video_worker import _upload_results
@pytest.mark.asyncio
async def test_upload_results_registers_screen_movs():
with tempfile.TemporaryDirectory() as temp_dir:
# Create local files the orchestrator would have downloaded into output_dir
title_mov = os.path.join(temp_dir, "Artist - Title (Title).mov")
end_mov = os.path.join(temp_dir, "Artist - Title (End).mov")
lossless = os.path.join(temp_dir, "Artist - Title (Final Karaoke Lossless 4k).mp4")
for p in (title_mov, end_mov, lossless):
with open(p, "wb") as f:
f.write(b"x")
from unittest.mock import MagicMock
job_manager = MagicMock()
storage = MagicMock()
storage.upload_file.side_effect = lambda local, gcs: f"gs://bucket/{gcs}"
result = {
"final_video": lossless,
"title_mov": title_mov,
"end_mov": end_mov,
}
await _upload_results("job-1", job_manager, storage, temp_dir, result)
# The screen MOVs are uploaded under finals/ and recorded in file_urls
registered = {
(c.args[1], c.args[2]) for c in job_manager.update_file_url.call_args_list
}
assert ("finals", "title_mov") in registered
assert ("finals", "end_mov") in registered
uploaded_gcs = {c.args[1] for c in storage.upload_file.call_args_list}
assert "jobs/job-1/finals/title_mov.mov" in uploaded_gcs
assert "jobs/job-1/finals/end_mov.mov" in uploaded_gcs
@pytest.mark.asyncio
async def test_upload_results_skips_missing_screen_movs():
"""Jobs without screen MOVs (legacy/None) must not error or register them."""
with tempfile.TemporaryDirectory() as temp_dir:
lossless = os.path.join(temp_dir, "Artist - Title (Final Karaoke Lossless 4k).mp4")
with open(lossless, "wb") as f:
f.write(b"x")
from unittest.mock import MagicMock
job_manager = MagicMock()
storage = MagicMock()
storage.upload_file.side_effect = lambda local, gcs: f"gs://bucket/{gcs}"
result = {"final_video": lossless, "title_mov": None} # end_mov absent entirely
await _upload_results("job-1", job_manager, storage, temp_dir, result)
registered = {
(c.args[1], c.args[2]) for c in job_manager.update_file_url.call_args_list
}
assert ("finals", "title_mov") not in registered
assert ("finals", "end_mov") not in registered
@@ -1058,6 +1058,52 @@ class TestVideoWorkerOrchestratorEncoding:
with pytest.raises(RuntimeError, match="stale"):
await orchestrator._download_gce_encoded_files(output)
@pytest.mark.asyncio
async def test_download_gce_includes_screen_movs(self):
"""Screen MOVs returned by the encoder are downloaded into output_dir.
Regression: the standalone (Title).mov / (End).mov stopped reaching the
Dropbox folder after #647/#650. They must be pulled back like other finals.
"""
with tempfile.TemporaryDirectory() as temp_dir:
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path=os.path.join(temp_dir, "title.png"),
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
output_dir=temp_dir,
)
mock_storage = MagicMock()
mock_storage.download_file = MagicMock()
orchestrator = VideoWorkerOrchestrator(config, storage=mock_storage)
from backend.services.encoding_interface import EncodingOutput
output = EncodingOutput(
success=True,
lossless_4k_mp4_path="jobs/test-job/finals/Test Artist - Test Title (Final Karaoke Lossless 4k).mp4",
title_mov_path="jobs/test-job/finals/Test Artist - Test Title (Title).mov",
end_mov_path="jobs/test-job/finals/Test Artist - Test Title (End).mov",
encoding_time_seconds=0.0,
encoding_backend="gce",
)
await orchestrator._download_gce_encoded_files(output)
downloaded = {os.path.basename(c.args[0]) for c in mock_storage.download_file.call_args_list}
assert "Test Artist - Test Title (Title).mov" in downloaded
assert "Test Artist - Test Title (End).mov" in downloaded
# Result points the screen MOVs at their local copies in output_dir
assert orchestrator.result.title_mov == os.path.join(
temp_dir, "Test Artist - Test Title (Title).mov"
)
assert orchestrator.result.end_mov == os.path.join(
temp_dir, "Test Artist - Test Title (End).mov"
)
class TestVideoWorkerOrchestratorOrganization:
"""Test organization stage."""
@@ -1405,6 +1451,36 @@ class TestCreateOrchestratorConfigFromJob:
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental User).mp3"
def test_create_config_includes_original_audio(self):
"""Config carries the original input audio so it can be staged into the
Dropbox folder. Regression: source audio stopped reaching organised outputs.
"""
job = MagicMock()
job.job_id = "test-123"
job.artist = "Test Artist"
job.title = "Test Title"
job.state_data = {"instrumental_selection": "clean"}
job.enable_cdg = False
job.enable_txt = False
job.enable_youtube_upload = False
job.is_private = False
job.brand_prefix = "NOMAD"
job.discord_webhook_url = None
job.youtube_description_template = None
job.dropbox_path = "/Karaoke"
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
# flacfetch (audio_search) download
job.audio_source_type = "audio_search"
job.input_media_gcs_path = "jobs/test-123/input/track.flac"
config = create_orchestrator_config_from_job(job=job, temp_dir="/tmp/test")
assert config.original_audio_gcs_path == "jobs/test-123/input/track.flac"
assert config.original_audio_filename == "Test Artist - Test Title (flacfetch).flac"
def test_create_config_passes_instrumental_selection(self):
"""Test that instrumental_selection is passed through to OrchestratorConfig.
@@ -1903,3 +1979,73 @@ class TestLrcHasLyricsContent:
lrc_file.write_text("[ti:Song Title]\n[ar:Artist Name]\n[re:MidiCo]\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is False
class TestStageOriginalAudio:
"""Original input audio is staged into output_dir before folder uploads.
Regression: the source audio ((flacfetch).flac / (uploaded).mp3) stopped
appearing in the Dropbox track folder after the move to the distributed
pipeline. It must be fetched from GCS into output_dir before upload.
"""
def _make(self, temp_dir, **overrides):
cfg = dict(
job_id="job-1",
artist="Test Artist",
title="Test Title",
title_video_path=os.path.join(temp_dir, "title.png"),
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
output_dir=temp_dir,
)
cfg.update(overrides)
config = OrchestratorConfig(**cfg)
storage = MagicMock()
return VideoWorkerOrchestrator(config, storage=storage), storage
def test_downloads_original_audio_into_output_dir(self):
with tempfile.TemporaryDirectory() as temp_dir:
orch, storage = self._make(
temp_dir,
original_audio_gcs_path="jobs/job-1/input/track.flac",
original_audio_filename="Test Artist - Test Title (flacfetch).flac",
)
orch._stage_original_audio_for_upload()
storage.download_file.assert_called_once()
args = storage.download_file.call_args.args
assert args[0] == "jobs/job-1/input/track.flac"
assert args[1] == os.path.join(temp_dir, "Test Artist - Test Title (flacfetch).flac")
def test_noop_when_no_original_audio_configured(self):
with tempfile.TemporaryDirectory() as temp_dir:
orch, storage = self._make(temp_dir)
orch._stage_original_audio_for_upload()
storage.download_file.assert_not_called()
def test_skips_when_already_present(self):
with tempfile.TemporaryDirectory() as temp_dir:
fname = "Test Artist - Test Title (uploaded).mp3"
# File already in output_dir (e.g. legacy/local run)
with open(os.path.join(temp_dir, fname), "wb") as f:
f.write(b"existing")
orch, storage = self._make(
temp_dir,
original_audio_gcs_path="jobs/job-1/input/song.mp3",
original_audio_filename=fname,
)
orch._stage_original_audio_for_upload()
storage.download_file.assert_not_called()
def test_download_failure_is_non_fatal(self):
with tempfile.TemporaryDirectory() as temp_dir:
orch, storage = self._make(
temp_dir,
original_audio_gcs_path="jobs/job-1/input/track.flac",
original_audio_filename="Test Artist - Test Title (flacfetch).flac",
)
storage.download_file.side_effect = Exception("gcs boom")
# Must not raise
orch._stage_original_audio_for_upload()
assert any("Original audio" in w for w in orch.result.distribution_warnings)
+2
View File
@@ -83,6 +83,8 @@
"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 from {downloader}, 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "خطأ في تحديد الصوت للمهمة {job_id}: {error}",
"searchAudioError": "خطأ في البحث عن الصوت: {error}",
"searchCreatedSuccessfully": "تم إنشاء المهمة. جاري البحث عن الصوت...",
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل..."
"autoDownloadStarted": "تم تحديد أفضل نتيجة تلقائيًا. جاري بدء التنزيل...",
"drmUrlUnsupported": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. حاول تنزيل الصوت باستخدام أداة خارجية أولاً، ثم قم برفع ملف الصوت هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية.",
"drmUrlUnsupportedWithLink": "روابط {platform} محمية بحقوق الطبع والنشر، لذا لا يمكننا تنزيلها مباشرة. يمكنك تنزيل المقطع الصوتي من {downloader}، ثم قم برفع ملف الصوت هنا. يمكنك أيضاً لصق رابط YouTube، أو استخدام البحث الصوتي للعثور على هذه الأغنية."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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, així que no els podem descarregar directament. Pots descarregar la pista des de {downloader} i, a continuació, pujar 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 z {downloader} a poté sem nahrát zvukový soubor. Můžeš také vložit odkaz na YouTube nebo použít Audio Search k vyhledání této písně."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 fra {downloader} og derefter uploade lydfilen her. Du kan også indsætte et YouTube-link eller bruge Audio Search til at finde denne sang."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 Track von {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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
"searchAudioError": "Σφάλμα κατά την αναζήτηση ήχου: {error}",
"searchCreatedSuccessfully": "Η εργασία δημιουργήθηκε. Αναζήτηση για ήχο...",
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά..."
"autoDownloadStarted": "Το καλύτερο αποτέλεσμα επιλέχθηκε αυτόματα. Η λήψη ξεκινά...",
"drmUrlUnsupported": "Οι σύνδεσμοι του {platform} προστατεύονται από αντιγραφή, οπότε δεν μπορούμε να τους κατεβάσουμε απευθείας. Δοκίμασε να κατεβάσεις τον ήχο με ένα εργαλείο τρίτου πρώτα, και μετά ανέβασε το αρχείο ήχου εδώ. Μπορείς επίσης να επικολλήσεις έναν σύνδεσμο YouTube, ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι.",
"drmUrlUnsupportedWithLink": "Οι σύνδεσμοι του {platform} προστατεύονται από αντιγραφή, οπότε δεν μπορούμε να τους κατεβάσουμε απευθείας. Μπορείς να κατεβάσεις το κομμάτι από το {downloader}, και μετά να ανεβάσεις το αρχείο ήχου εδώ. Μπορείς επίσης να επικολλήσεις έναν σύνδεσμο YouTube, ή να χρησιμοποιήσεις την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+2
View File
@@ -83,6 +83,8 @@
"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 from {downloader}, 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"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, así que no podemos descargarlos directamente. Puedes descargar la pista desde {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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 palvelusta {downloader} ja ladata äänitiedoston sitten tänne. Voit myös liittää YouTube-linkin tai etsiä tämän kappaleen Äänihaun avulla."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 par le droit d'auteur, nous ne pouvons donc pas les télécharger directement. Tu peux télécharger le morceau depuis {downloader}, puis téléverser 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "שגיאה בבחירת אודיו עבור המשימה {job_id}: {error}",
"searchAudioError": "שגיאה בחיפוש אודיו: {error}",
"searchCreatedSuccessfully": "המשימה נוצרה. מחפש אודיו...",
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה..."
"autoDownloadStarted": "התוצאה הטובה ביותר נבחרה אוטומטית. ההורדה מתחילה...",
"drmUrlUnsupported": "הקישורים של {platform} מוגנים מפני העתקה, ולכן איננו יכולים להוריד אותם ישירות. נסו להוריד את האודיו בעזרת כלי צד שלישי תחילה, ואז העלו את קובץ האודיו לכאן. תוכלו גם להדביק קישור ל-YouTube, או להשתמש בחיפוש אודיו כדי למצוא את השיר הזה.",
"drmUrlUnsupportedWithLink": "הקישורים של {platform} מוגנים מפני העתקה, ולכן איננו יכולים להוריד אותם ישירות. תוכלו להוריד את הרצועה מ-{downloader}, ואז להעלות את קובץ האודיו לכאן. תוכלו גם להדביק קישור ל-YouTube, או להשתמש בחיפוש אודיו כדי למצוא את השיר הזה."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "जॉब {job_id} के लिए ऑडियो चुनने में त्रुटि: {error}",
"searchAudioError": "ऑडियो खोजने में त्रुटि: {error}",
"searchCreatedSuccessfully": "जॉब बन गई। ऑडियो खोजा जा रहा है...",
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है..."
"autoDownloadStarted": "सबसे अच्छा रिज़ल्ट अपने आप चुन लिया गया। डाउनलोड शुरू हो रहा है...",
"drmUrlUnsupported": "{platform} लिंक्स कॉपी-प्रोटेक्टेड हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। पहले किसी थर्ड-पार्टी टूल से ऑडियो डाउनलोड करने की कोशिश करो, फिर ऑडियो फ़ाइल को यहाँ अपलोड करो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।",
"drmUrlUnsupportedWithLink": "{platform} लिंक्स कॉपी-प्रोटेक्टेड हैं, इसलिए हम उन्हें सीधे डाउनलोड नहीं कर सकते। तुम {downloader} से ट्रैक डाउनलोड कर सकते हो, फिर ऑडियो फ़ाइल को यहाँ अपलोड कर सकते हो। तुम YouTube लिंक भी पेस्ट कर सकते हो, या इस गाने को खोजने के लिए Audio Search का उपयोग कर सकते हो।"
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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. Možeš preuzeti pjesmu s {downloader}, a zatim ovdje prenijeti 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"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, így nem tudjuk őket közvetlenül letölteni. Letöltheted a számot a(z) {downloader} segítségével, majd feltöltheted ide a hangfájlt. Beilleszthetsz egy YouTube linket is, vagy használd az Audio Search funkciót a dal megtalálásához."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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, jadi kami tidak dapat mengunduhnya secara langsung. Anda dapat mengunduh lagu dari {downloader}, lalu mengunggah file audionya di sini. Anda juga dapat menempelkan tautan YouTube, atau menggunakan Pencarian Audio untuk menemukan lagu ini."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 la traccia da {downloader}, poi caricare 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
"searchAudioError": "オーディオの検索中にエラーが発生しました: {error}",
"searchCreatedSuccessfully": "ジョブが作成されました。オーディオを検索しています...",
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します..."
"autoDownloadStarted": "最適な結果が自動的に選択されました。ダウンロードを開始します...",
"drmUrlUnsupported": "{platform}のリンクはコピー保護されているため、直接ダウンロードできません。サードパーティのツールでオーディオをダウンロードしてから、ここにアップロードしてみてください。または、YouTubeのリンクを貼り付けるか、オーディオ検索を使ってこの曲を探すこともできます。",
"drmUrlUnsupportedWithLink": "{platform}のリンクはコピー保護されているため、直接ダウンロードできません。{downloader}からトラックをダウンロードし、そのオーディオファイルをここにアップロードすることができます。または、YouTubeのリンクを貼り付けるか、オーディオ検索を使ってこの曲を探すこともできます。"
},
"users": {
"disposableEmailBlocked": "使い捨てメールアドレスは許可されていません",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
"searchAudioError": "오디오 검색 중 오류 발생: {error}",
"searchCreatedSuccessfully": "작업이 생성되었습니다. 오디오를 검색하는 중...",
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다..."
"autoDownloadStarted": "가장 적합한 결과가 자동으로 선택되었습니다. 다운로드를 시작합니다...",
"drmUrlUnsupported": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. 먼저 타사 도구를 사용하여 오디오를 다운로드한 다음, 여기에 오디오 파일을 업로드해 보세요. YouTube 링크를 붙여넣거나 오디오 검색을 사용하여 이 노래를 찾을 수도 있습니다.",
"drmUrlUnsupportedWithLink": "{platform} 링크는 복사 방지가 되어 있어 직접 다운로드할 수 없습니다. {downloader}에서 트랙을 다운로드한 다음, 여기에 오디오 파일을 업로드할 수 있습니다. YouTube 링크를 붙여넣거나 오디오 검색을 사용하여 이 노래를 찾을 수도 있습니다."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 dari {downloader}, kemudian muat naik fail audio di sini. Anda juga boleh menampal pautan YouTube, atau menggunakan Carian Audio untuk mencari lagu ini."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 fra {downloader}, og deretter laste 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",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 via {downloader} en vervolgens het audiobestand hier uploaden. Je kunt ook een YouTube-link plakken, of Audio Search gebruiken om dit nummer te vinden."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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ą chronione przed kopiowaniem, więc nie możemy ich pobrać bezpośrednio. Możesz pobrać utwór z {downloader}, a następnie przesłać plik audio tutaj. Możesz też wkleić link do YouTube lub użyć wyszukiwania audio, aby znaleźć tę piosenkę."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 do {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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 de pe {downloader}, 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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "Ошибка при выборе аудио для задачи {job_id}: {error}",
"searchAudioError": "Ошибка при поиске аудио: {error}",
"searchCreatedSuccessfully": "Задача создана. Ищем аудио...",
"autoDownloadStarted": "Лучший результат выбран автоматически. Начинается скачивание..."
"autoDownloadStarted": "Лучший результат выбран автоматически. Начинается скачивание...",
"drmUrlUnsupported": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Попробуй сначала скачать аудио с помощью стороннего инструмента, а затем загрузи аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать Поиск аудио, чтобы найти эту песню.",
"drmUrlUnsupportedWithLink": "Ссылки {platform} защищены от копирования, поэтому мы не можем скачать их напрямую. Ты можешь скачать трек с {downloader}, а затем загрузить аудиофайл сюда. Ты также можешь вставить ссылку на YouTube или использовать Поиск аудио, чтобы найти эту песню."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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ť z {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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 spåret från {downloader} och sedan ladda 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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "เกิดข้อผิดพลาดในการเลือกเสียงสำหรับงาน {job_id}: {error}",
"searchAudioError": "เกิดข้อผิดพลาดในการค้นหาเสียง: {error}",
"searchCreatedSuccessfully": "สร้างงานแล้ว กำลังค้นหาเสียง...",
"autoDownloadStarted": "เลือกผลลัพธ์ที่ดีที่สุดโดยอัตโนมัติ กำลังเริ่มดาวน์โหลด..."
"autoDownloadStarted": "เลือกผลลัพธ์ที่ดีที่สุดโดยอัตโนมัติ กำลังเริ่มดาวน์โหลด...",
"drmUrlUnsupported": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง ลองดาวน์โหลดเสียงด้วยเครื่องมือของบุคคลที่สามก่อน แล้วจึงอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้อีกด้วย",
"drmUrlUnsupportedWithLink": "ลิงก์ของ {platform} มีการป้องกันการคัดลอก เราจึงไม่สามารถดาวน์โหลดได้โดยตรง คุณสามารถดาวน์โหลดแทร็กจาก {downloader} แล้วจึงอัปโหลดไฟล์เสียงที่นี่ คุณยังสามารถวางลิงก์ YouTube หรือใช้ Audio Search เพื่อค้นหาเพลงนี้ได้อีกด้วย"
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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 link ng {platform} ay copy-protected, kaya hindi namin ito direktang ma-download. Maaari mong i-download ang track mula sa {downloader}, 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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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ı kopya korumalı olduğu için onları doğrudan indiremiyoruz. Parçayı {downloader} üzerinden indirebilir, 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 Arama'yı kullanabilirsin."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "Помилка вибору аудіо для завдання {job_id}: {error}",
"searchAudioError": "Помилка пошуку аудіо: {error}",
"searchCreatedSuccessfully": "Завдання створено. Шукаємо аудіо...",
"autoDownloadStarted": "Найкращий результат вибрано автоматично. Починається завантаження..."
"autoDownloadStarted": "Найкращий результат вибрано автоматично. Починається завантаження...",
"drmUrlUnsupported": "Посилання {platform} захищені від копіювання, тому ми не можемо завантажити їх безпосередньо. Спробуй спочатку завантажити аудіо за допомогою стороннього інструменту, а потім завантаж аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню.",
"drmUrlUnsupportedWithLink": "Посилання {platform} захищені від копіювання, тому ми не можемо завантажити їх безпосередньо. Ти можеш завантажити трек з {downloader}, а потім завантажити аудіофайл сюди. Ти також можеш вставити посилання на YouTube або скористатися пошуком аудіо, щоб знайти цю пісню."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"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, vì vậy chúng tôi không thể tải chúng xuống trực tiếp. Bạn có thể tải bản nhạc từ {downloader}, 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."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
+3 -1
View File
@@ -92,7 +92,9 @@
"selectAudioError": "为任务 {job_id} 选择音频时出错:{error}",
"searchAudioError": "搜索音频时出错:{error}",
"searchCreatedSuccessfully": "任务已创建。正在搜索音频...",
"autoDownloadStarted": "已自动选择最佳结果。开始下载..."
"autoDownloadStarted": "已自动选择最佳结果。开始下载...",
"drmUrlUnsupported": "{platform} 链接受版权保护,因此我们无法直接下载。请先尝试使用第三方工具下载音频,然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或者使用音频搜索来查找这首歌。",
"drmUrlUnsupportedWithLink": "{platform} 链接受版权保护,因此我们无法直接下载。您可以从 {downloader} 下载该曲目,然后在此处上传音频文件。您也可以粘贴 YouTube 链接,或者使用音频搜索来查找这首歌。"
},
"users": {
"disposableEmailBlocked": "不允许使用一次性邮箱",
+4
View File
@@ -232,6 +232,10 @@ async def process_audio_download(job_id: str) -> bool:
'input_media_gcs_path': audio_gcs_path,
'filename': filename,
})
# Record the original input audio in file_urls too (the upload path does this
# in audio_worker), so it appears in the admin files manifest consistently
# across all source types and can be staged into the output folder.
job_manager.update_file_url(job_id, 'input', 'audio', audio_gcs_path)
# Download succeeded — clear any stale retry-pending marker and
# previous error so the UI stops showing a resolved failure.
+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()
+21
View File
@@ -107,6 +107,21 @@ async def _encode_via_gce(
instrumental_selection = job.state_data.get('instrumental_selection', 'clean')
existing_instrumental = getattr(job, 'existing_instrumental_gcs_path', None)
# Stage the user-provided instrumental into the encoder's input prefix (jobs/{job_id}/).
# It is uploaded under uploads/, which the GCE encoder does NOT pull via input_gcs_path;
# copying it here makes the encoder's recursive find_file("*existing_instrumental*")
# locate it regardless of the worker image version (older encoder images predate the
# encoding_config "existing_instrumental" download path). Without this, tenant /
# existing-instrumental jobs fail with "No instrumental audio found".
if existing_instrumental:
try:
ext = os.path.splitext(existing_instrumental)[1].lower() or ".mp3"
staged_path = f"jobs/{job_id}/existing_instrumental{ext}"
storage.copy_blob(existing_instrumental, staged_path)
job_log.info(f"Staged existing instrumental for encoder: {staged_path}")
except Exception as e:
job_log.warning(f"Failed to stage existing instrumental into jobs/ prefix: {e}")
encoding_config = {
"formats": ["mp4_4k_lossless", "mp4_4k_lossy", "mp4_720p"],
"base_name": base_name,
@@ -344,6 +359,8 @@ async def generate_video_orchestrated(job_id: str) -> bool:
'final_with_vocals_mp4': result.final_with_vocals_mp4,
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
'final_karaoke_txt_zip': result.final_karaoke_txt_zip,
'title_mov': result.title_mov,
'end_mov': result.end_mov,
})
# Store result metadata in job BEFORE transitioning to COMPLETE
@@ -1589,6 +1606,10 @@ async def _upload_results(
('final_with_vocals_mp4', 'finals', 'with_vocals_mp4'),
('final_karaoke_cdg_zip', 'packages', 'cdg_zip'),
('final_karaoke_txt_zip', 'packages', 'txt_zip'),
# Standalone screen videos — recorded so they appear in the admin files
# manifest and are verifiable (regression: missing from Dropbox folders)
('title_mov', 'finals', 'title_mov'),
('end_mov', 'finals', 'end_mov'),
]
for result_key, category, file_key in file_mappings:
@@ -28,6 +28,10 @@ from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.tracing import job_span, add_span_event
from backend.services.original_audio import (
original_audio_gcs_path,
original_audio_output_filename,
)
from karaoke_gen.utils import sanitize_filename
logger = logging.getLogger(__name__)
@@ -67,6 +71,11 @@ class OrchestratorConfig:
dropbox_path: Optional[str] = None
gdrive_folder_id: Optional[str] = None
# Original input audio to include in the uploaded folder (the archival master,
# e.g. "<artist> - <title> (flacfetch).flac"). GCS blob path + target filename.
original_audio_gcs_path: Optional[str] = None
original_audio_filename: Optional[str] = None
# Keep existing brand code (for re-processing)
keep_brand_code: Optional[str] = None
@@ -112,6 +121,11 @@ class OrchestratorResult:
final_karaoke_cdg_zip: Optional[str] = None
final_karaoke_txt_zip: Optional[str] = None
# Standalone 5-second screen videos (downloaded from GCE finals so they land in
# the Dropbox folder). Not used downstream — kept for archival/upload only.
title_mov: Optional[str] = None
end_mov: Optional[str] = None
# Organization
brand_code: Optional[str] = None
@@ -452,6 +466,27 @@ class VideoWorkerOrchestrator:
if self.config.countdown_padding_seconds:
self.job_log.info(f"Countdown padding: {self.config.countdown_padding_seconds}s - instrumental will be padded")
# The GCE encoder downloads its inputs from input_gcs_path (jobs/{job_id}/) and resolves
# the instrumental via find_file. For jobs that supply their own instrumental
# (existing_instrumental flow, e.g. tenant submissions), the file lives under
# uploads/{job_id}/audio/existing_instrumental.* — which is NOT under jobs/{job_id}/ and
# is NOT a name the encoder's 'custom' branch looks for. The encoder's 'custom' branch
# globs for "*custom_instrumental*.{flac,mp3}" / "*Instrumental Custom*", so copy the
# supplied instrumental into jobs/{job_id}/custom_instrumental.<ext> (server-side, from
# the authoritative GCS source — no dependency on local temp files). Without this,
# existing-instrumental jobs fail at the encoder with "No instrumental audio found".
if encoding_backend.name == "gce" and self.storage:
try:
srcs = self.storage.list_files(f"uploads/{self.config.job_id}/audio/existing_instrumental")
if srcs:
src = srcs[0]
ext = os.path.splitext(src)[1].lower() or ".mp3"
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
self.storage.copy_blob(src, dest)
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
except Exception as e:
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
# Run encoding
with job_span("encoding", self.config.job_id) as span:
add_span_event("encoding_started", {"backend": encoding_backend.name})
@@ -532,6 +567,9 @@ class VideoWorkerOrchestrator:
('lossy_4k_mp4_path', 'final_video_lossy'),
('lossy_720p_mp4_path', 'final_video_720p'),
('with_vocals_mp4_path', 'final_with_vocals_mp4'),
# Standalone screen videos — pulled back so they reach the Dropbox folder
('title_mov_path', 'title_mov'),
('end_mov_path', 'end_mov'),
]
downloaded_count = 0
@@ -602,6 +640,16 @@ class VideoWorkerOrchestrator:
self.job_log.info("Starting distribution stage")
self._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
# Stage the original input audio into output_dir before any folder upload
# (Dropbox/GDrive upload the whole directory). Only worth the GCS fetch when
# such an upload will actually happen.
will_upload_folder = (
(self.config.dropbox_path and self.config.brand_prefix)
or self.config.gdrive_folder_id
)
if will_upload_folder:
self._stage_original_audio_for_upload()
# YouTube upload
if self.config.enable_youtube_upload and self.config.youtube_credentials:
await self._upload_to_youtube()
@@ -738,6 +786,32 @@ class VideoWorkerOrchestrator:
f"YouTube upload skipped (quota exceeded) and failed to queue: {e}"
)
def _stage_original_audio_for_upload(self):
"""Copy the original input audio into output_dir so uploads include it.
The source audio (e.g. "<artist> - <title> (flacfetch).flac" /
"(uploaded).mp3") is the archival master used for separation/transcription.
The distributed pipeline otherwise leaves it in GCS only, so it stopped
appearing in the Dropbox track folder. Best-effort: never fail the pipeline.
"""
gcs_path = self.config.original_audio_gcs_path
filename = self.config.original_audio_filename
if not gcs_path or not filename:
return
dest = os.path.join(self.config.output_dir, filename)
if os.path.exists(dest):
self.job_log.info(f"Original audio already present, skipping: {filename}")
return
try:
self.job_log.info(f"Staging original audio for upload: {filename}")
self.storage.download_file(gcs_path, dest)
self.job_log.info(f"Staged original audio: {dest}")
except Exception as e:
self.job_log.warning(f"Failed to stage original audio ({filename}): {e}")
self.result.distribution_warnings.append(f"Original audio not included: {e}")
async def _upload_to_dropbox(self):
"""Upload files to Dropbox."""
self.job_log.info("Uploading to Dropbox")
@@ -974,6 +1048,10 @@ def create_orchestrator_config_from_job(
dropbox_path=dist.dropbox_path,
gdrive_folder_id=dist.gdrive_folder_id,
# Original input audio to include in the uploaded folder (archival master)
original_audio_gcs_path=original_audio_gcs_path(job),
original_audio_filename=original_audio_output_filename(job, base_name),
# Keep existing brand code
keep_brand_code=getattr(job, 'keep_brand_code', None),
+84
View File
@@ -831,6 +831,65 @@ Response:
When `has_community` is true, the frontend shows a dismissible green banner suggesting the user check existing versions before creating a new one.
#### Match Judge (artist/title formatting + match acceptance)
```http
POST /api/catalog/match-judge
Content-Type: application/json
{
"artist": "paramore",
"title": "big man, little dignity",
"audio_confidence_tier": 1,
"stage": "full"
}
```
Decides the official formatting for a typed artist/title and whether it matches a
real song. A deterministic normalizer + the catalog run first; a light Vertex
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.5-flash`) is consulted
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
optional) lets the judge tell whether weak audio results hint at a typo. The call
never blocks job creation — on timeout/error it returns a `none` verdict. Disable
the AI layer with `MATCH_JUDGE_ENABLED=false` (deterministic+catalog still run).
`stage` (optional, `"fast"` | `"full"`, default `"full"`) supports a two-call
pattern the frontend uses to keep the tidy off the critical path:
- `"fast"` — catalog-only pass (no AI, `audio_confidence_tier` ignored). The
client fires this on mount, in parallel with the audio search. Returns a
confident catalog verdict when it can, otherwise `needs_ai: true` (a marker
telling the client to follow up with a `"full"` call once the tier is known).
- `"full"` — the complete pipeline. Runs the AI judge when the catalog isn't
confident, **and** when a confident catalog match coincides with a weak audio
tier (`>= 3`) — a weak tier means the match may be a junk/typo'd entry, so the
AI verifies it and can override.
Response:
```json
{
"kind": "cosmetic",
"confident": true,
"canonical_artist": "Paramore",
"canonical_title": "Big Man, Little Dignity",
"alternatives": [],
"engine": "catalog",
"reason": "formatting differs from catalog",
"needs_ai": false
}
```
`kind` drives the Step 2 UI: `cosmetic` → silent tidy with a two-way toggle
("keep what I typed" ⇄ "use tidied version"); `content` (confident) → applied
with a "Corrected … · Undo" toggle, re-searching audio only when the original
results were weak; `ambiguous` (or unconfident `content`) → an ask-first "Did you
mean?" prompt; `none` → no change. `needs_ai` is only ever `true` on a `"fast"`
verdict that couldn't decide; it is always `false` on a `"full"` verdict.
Until the judge settles, the Step 2 audio-selection buttons are disabled with a
subtle "Checking song details…" indicator, so a user can never advance with
un-tidied metadata; a 12s timeout guarantees the gate releases.
### Audio Search
#### Search for Audio
@@ -2211,6 +2270,31 @@ Referred users with an active discount window (default 30 days) automatically re
After a credit purchase by a referred user, earnings are recorded automatically in the Stripe webhook handler. When a referrer's pending balance reaches $20 and they have a Stripe Connect account, a payout is triggered automatically.
## Bulk Mode
Submit up to 100 karaoke jobs at once (by text rows or by album lookup). All
routes require auth.
### Album lookup (MusicBrainz)
- `GET /api/bulk/album/artists?q=<name>` → `[{mbid,name,disambiguation,type,country}]`
- `GET /api/bulk/album/albums?artist_mbid=<mbid>` → `[{release_group_mbid,title,primary_type,secondary_types,first_release_date,is_studio}]` (studio albums first)
- `GET /api/bulk/album/tracklist?artist=<name>&release_group_mbid=<mbid>` (or `&release_mbid=<mbid>` for a specific edition; optional `&locale=<code>` biases representative-pressing choice) → `{release_mbid,canonical_release_mbid,selected_variant_mbid,title,date,tracks:[{position,title,recording_mbid,length_ms,is_extra,extra_reason,available,brands,versions:[{brand,url}]}],editions:[{release_mbid,title,status,date,country,track_count}],variants:[{representative_release_mbid,label,track_count,year,pressing_count,delta_vs_original}]}`. `variants` collapses the release-group's country pressings into distinct tracklists grouped by track count (label `Original`/`Reissue`, `Original` = earliest); load one via its `representative_release_mbid` as `release_mbid`. Each track is enriched with KaraokeNerds community-version availability — `available`/`brands` plus `versions` (per-version `{brand,url}` YouTube links for clickable preview); enrichment is best-effort and never fatal.
### Availability (text mode)
- `POST /api/bulk/availability` body `{tracks:[{artist,title}]}` (≤100) → `{results:[{artist,title,available,brands,brand_count,versions:[{brand,url}]}]}`. Backed by the existing KaraokeNerds community-version scraper (1h cache, bounded concurrency). `versions` carries per-version YouTube links for clickable preview.
### Submit
- `POST /api/bulk/submit` body `{songs:[{artist,title,display_artist?,display_title?}],settings:{auto_select_if_lossless,is_private,skip_audio_edit,skip_customization}}` → `{batch_id,job_ids,total}`.
- Credit gate: requires `credits >= len(songs)` (1/song minimum) before any job is created; admins bypass. Returns `402` with `{credits_available,credits_required}` if short (no jobs created). `422` for 0 or >100 songs.
- Creates one parked job per song (`auto_download=False`), stamps `state_data.batch_id` + `bulk_settings`, and dispatches the `bulk-search-job` Cloud Run Job which runs each search and either auto-selects a confident lossless match or parks the job in `AWAITING_AUDIO_SELECTION`.
### Progress
- `GET /api/bulk/{batch_id}` → `{batch_id,total,counts:{searching,awaiting_selection,processing,complete,failed},jobs:[{job_id,artist,title,status,auto_selected}]}`. Ownership-scoped (admins see any); `404` for another user's batch. Parked jobs are completed via the existing `/api/audio-search/{job_id}/select` flow.
## Webhooks
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
+11 -2
View File
@@ -1,6 +1,6 @@
# Disaster Recovery Runbook
**Last updated:** 2026-04-20
**Last updated:** 2026-06-18
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
**Implementation plan:** `docs/archive/2026-03-29-business-continuity-plan.md`
**External services reference:** `docs/archive/2026-03-29-external-services-config.md`
@@ -9,7 +9,7 @@
| Data | Backup Location | Recovery Method | RPO |
|------|----------------|-----------------|-----|
| Firestore | S3 `firestore/YYYY-MM-DD/` | Import to new GCP project | 24h |
| Firestore | S3 `firestore/YYYY-MM-DD/` | Import to new GCP project | 7 days off-site (S3); 24h local (GCS staging) |
| BigQuery (weekly) | S3 `bigquery/daily-refresh/` | Load Parquet files | 7 days |
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
@@ -343,6 +343,15 @@ export AWS_DEFAULT_REGION=us-east-1
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, and `bigquery/daily-refresh/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
| Prefix | S3 upload cadence | Monitor limit |
|--------|-------------------|---------------|
| `gcs/job-files/`, `secrets/` | nightly | 36h |
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
This monitor runs in GitHub, not GCP, so it survives a complete GCP project loss.
**Required GitHub secrets** (set via `gh secret set`):
+27
View File
@@ -6,6 +6,26 @@ Key insights for future AI agents working on this codebase.
---
## Bulk Mode (Jun 2026)
- **Auto-pick "tier 1" rule is duplicated** between `frontend/lib/audio-search-utils.ts`
(`getSearchConfidence`) and `backend/services/audio_search_service.py`
(`pick_auto_selection`). The backend port drives the `bulk_search_worker`
auto-select decision. If you change the rule, change BOTH — the parity is guarded
by `backend/tests/test_bulk_foundations.py`.
- **The duration-delta charge is replicated** in `bulk_search_worker._auto_select`
using the same primitives/state keys (`credits_charged`/`select_charge_applied`)
as `audio_search.select_audio_source`, rather than refactoring the proven money
path. Keep them in sync.
- **KaraokeNerds availability** reuses the existing `karaokenerds_service`
scraper via `check_community_versions_batch` (it has the `is_community` flag,
matching "community-*created* version"). We deliberately did NOT add a
karaoke-decide BigQuery endpoint — its catalog is search-based and lacks the
community distinction.
- **Parked bulk jobs are hidden from the main jobs list** (the dashboard filters
out `awaiting_audio_selection`). The bulk review queue renders them itself, and
the batch_id is persisted to `localStorage` so a returning user can finish them.
## AI Generation Patterns
### Auto-Correction Take 3: Suggestion Layer, Not Silent Application (Jun 2026)
@@ -72,6 +92,13 @@ When a metadata key is missing, don't set it to "now" and skip the action — th
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
### "Is It Busy?" Guards Must Fail SAFE, Not Fail Open (Jun 2026)
Both stop paths for the GCE encoder VMs guarded against killing a busy worker by checking `/health`'s `active_jobs` — but both defaulted to **0 (= idle)** when `/health` was unreachable or slow (CI drain: `... || echo "0"`; idle Cloud Function: `except: return 0`). A busy encoder runs a 4K ffmpeg on all 32 cores and shares uvicorn with the encode subprocess, so `/health` can miss its timeout *while the VM is hard at work*. Combined with blue/green deploy churn (every merge cycles the VMs) and the 5-min idle check, this stopped VMs **mid-render**, orphaning the in-memory job so backend polls got 404 → "lost contact with worker ... not found" (incident 2026-06-15; the burst was self-inflicted by rapid PR merges during the tenant E2E, 0 in the prior 48h). **Rule:** a guard that decides whether to destroy work must treat "couldn't confirm" as "assume busy / don't act," never as the permissive default. Retry the probe, and only act on a *confirmed* safe signal (here: a real `active_jobs == 0` from a 200 response), with a bounded timeout so a wedged worker can't block forever.
### In-Flight Status Polls Must Be Pinned to the Worker, Not the Floating Primary (Jun 2026)
The day after the drain fix above, the **same** "lost contact ... not found" error recurred (incident 2026-06-16, job d3af33ae) — but this time the VM was *never* stopped mid-render. `EncodingService.get_job_status()` re-resolved the worker URL on **every poll** via `_get_worker_url()` → `config.active_url`. A blue-green deploy swapped the Firestore `primary_vm` pointer at 04:33:46 (worker-a → worker-b); 7s later the in-flight render's polls started hitting worker-b, which had never received the job → 404 → 5 failures → render failed. Worker-a was alive and finished the encode the whole time; nobody was listening. The drain (which keeps the old VM *alive*) can't help — the job is orphaned at the **poll layer** the instant the pointer swaps, 47s before any VM stop. **Rule:** once a job is accepted by a specific worker, every subsequent poll for that job must target *that* worker until terminal — the poll follows the job, not the floating primary pointer. URL re-resolution is correct for *capacity fallback* (dead primary → start fallback → re-route a fresh submission) but wrong for an *in-flight poll* (a different/fresh VM can't have the job; re-routing only yields 404). Fix: capture the worker URL **after** submit (reflects a fallback re-route, precedes any later swap) and pass it as `worker_url=` through `wait_for_completion` → `get_job_status`, which then pins the request and sets `allow_failover=False`. v0.184.2.
### Cloud Run GPU: Let the Platform Scale, Not Your Code (Mar 2026)
**Don't use fire-and-forget + semaphore on Cloud Run.** We tried making the `/separate` endpoint return immediately (fire-and-forget background thread) with a `threading.Semaphore(1)` to serialize GPU work. Cloud Run couldn't see background threads as "busy", so it routed ALL requests to one instance where they queued behind the semaphore — causing 30-minute timeouts in production.
+3
View File
@@ -7,6 +7,9 @@
- **Web App**: https://gen.nomadkaraoke.com
- `/` - Landing page with pricing
- `/app` - Main app (upload audio, review lyrics, download videos)
- **Bulk Mode** (Jun 2026): submit up to 100 jobs at once by text or by album
(MusicBrainz lookup + KaraokeNerds availability); auto-picks confident
lossless audio, parks the rest in a review queue. See `docs/API.md` § Bulk Mode.
- `/admin` - Admin dashboard (user management, job monitoring)
- **Backend API**: https://api.nomadkaraoke.com - FastAPI on Cloud Run
- **CLI Tools**: `karaoke-gen` (local), `karaoke-gen-remote` (cloud)
+2
View File
@@ -58,6 +58,8 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
**Prevention:** The video worker now runs as a **Cloud Run Job** (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`), which runs to completion and is immune to Cloud Run Service deployment rollouts. This replaces the `BackgroundTask` pattern that was vulnerable to instance termination during deployments. Additionally, CI performs a graceful drain before restarting the GCE encoding worker, the encoding client retries for ~90s, and status polling tolerates up to 5 consecutive failures.
Since v0.184.2, in-flight status polls are also **pinned to the worker that accepted the job** (`get_job_status(..., worker_url=)`), so a blue-green deploy that swaps the `active_url` primary pointer mid-render no longer migrates the poll to a worker that never received the job. If you still see `lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`, confirm via step 2 above that the worker the job was submitted to (not necessarily the current primary) still has the job — a `not found` from the *current* primary while the job is alive on the old primary was the pre-v0.184.2 failure mode (incident 2026-06-16, job d3af33ae).
---
## CDG/TXT packages missing from completed job
@@ -0,0 +1,105 @@
# Artist/Title Matching, Suggestions & Auto-Correction Rework (Phase 1)
**Date:** 2026-06-15
**Worktree:** `karaoke-gen-submission-form-simplify`
**Branch:** `feat/sess-20260615-0101-submission-form-simplify`
**Status:** Design + plan — pending implementation
## Problem
On Step 2 ("Choose Audio") the wizard stacks two green "success" cards: the **"Song found in our database"** catalog panel and the **"Perfect match found"** audio card. User feedback: the first reads like "we already have this karaoke video," when its only real job is to nudge the user toward **official artist/title formatting** (a quality-bar concern for *published* tracks). It's confusing, and the underlying case-insensitive match is imperfect.
This phase reworks **only** the artist/title matching → suggestion → auto-correction behavior. The broader flow structure is deliberately left intact (see "Constraints from history"). The title-screen preview perf fix is tracked separately.
## Decisions (from 2026-06-15 brainstorm with Andrew)
1. **Invisible cosmetic tidy.** When formatting differs only cosmetically (casing, spacing, punctuation, diacritics, `&`/`feat.` conventions) and we're confident it's the same song, **silently apply** the official formatting. No green "database" card. Show only a faint, dismissible line: *"Tidied to **Paramore — Big Man, Little Dignity** · keep what I typed"*.
2. **Confident content correction → auto-apply + surface + smart re-search.** When the correction changes actual characters (e.g. `Yesteray → Yesterday`) and we're confident, apply it **and** surface it with one-tap Undo: *"Corrected to **Yesterday** — you typed 'Yesteray' · Undo"*. Because characters changed, the original audio search may be poor, so **re-run the audio search** — automatically **only when the original results were weak** (tier 3 / empty); otherwise offer a quiet "Search again" link.
3. **Ambiguous → ask first.** When the judge isn't confident which song is meant (multiple plausible candidates), show an ask-first prompt: *"Did you mean **X**? [Use this] [Keep mine]"* before changing anything.
4. **Three-layer engine, all in v1.** Deterministic rules → catalog canonical → light AI judge. **The AI judge fires only when the deterministic + catalog layers are not confident** (cheap; happy path never invokes it).
## Constraints from history (do NOT regress)
From `docs/archive/2026-02-28-ux-*`, `2026-03-02-decouple-search-from-job-creation.md`, `2026-03-08-step2-song-suggestions.plan.md`, `2026-03-08-fuzzy-did-you-mean.plan.md`, `docs/LESSONS-LEARNED.md`, PRs #444/#451/#480/#495/#512:
- **No Step-1 autocomplete.** It was added (PR #451) then removed (PR #512) because users didn't understand it. Suggestions belong on Step 2, in parallel with the audio search.
- **Cosmetic correction must NOT restart the audio search.** Already a documented decision — the existing catalog `onArtistTitleCorrection` updates artist/title without re-searching. Preserve this. (Content corrections that change characters MAY re-search — see decision 2.)
- **Deferred job creation (search-session pattern).** No job is created until the final confirm step. Don't move creation earlier. The tidied artist/title is passed at `create-from-search` time; the audio `search_session_id` is unaffected by a metadata tidy.
- **Preserve the fuzzy artist-tiebreaker lesson:** when title-matching returns multiple artists with the same song name, use the user's (possibly garbled) artist input as a tiebreaker. And the gating: fuzzy/"did you mean" only triggers when audio results are poor.
- **`display_artist`/`display_title`** stay distinct from matching `artist`/`title`; they're set at creation time. The tidy applies to the **matching** artist/title (what drives search, lyrics, and published metadata).
- **Public vs private brand rule, audio-before-customize ordering, combined review flow** — untouched by this phase.
## Architecture
Consolidate today's scattered client-side matching (case-insensitive exact match in `SongSuggestionPanel` + LCS fuzzy in `audio-search-utils.ts`) into **one backend "match judge" service**, called from Step 2 in parallel with the audio search (replacing the current `searchCatalogTracks` + client fuzzy effect). Rationale: testable, consistent canonical formatting, and the AI layer needs the backend's LLM clients/keys.
### Backend: `POST /api/catalog/match-judge`
Request: `{ artist, title, audio_confidence_tier?: 1|2|3 }`
(The frontend passes the audio search's computed confidence tier so the judge knows whether weak results suggest a typo.)
Pipeline (server-side):
1. **Deterministic normalize** (reuse/extend `karaoke_gen.utils.normalize_text`): trim, collapse whitespace, fix obvious casing (title-case with small-word handling), straighten quotes, standardize `feat.`/`ft.` → `(feat. …)` and `and`↔`&` per house style.
2. **Catalog lookup** (existing `search_tracks` via `catalog_proxy_service`). If a candidate matches the normalized input under a strict normalized-equality test → **confident cosmetic**: return the catalog's canonical `artist_name`/`track_name`.
3. **AI judge — only if (1)+(2) not confident.** Invoke a light model (see "Model") with the typed input, the top catalog candidates, and the audio tier. It returns a structured verdict.
Response:
```json
{
"kind": "cosmetic | content | ambiguous | none",
"confident": true,
"canonical_artist": "Paramore",
"canonical_title": "Big Man, Little Dignity",
"alternatives": [{"artist": "...", "title": "..."}],
"engine": "deterministic | catalog | ai",
"reason": "casing only"
}
```
- `kind=cosmetic` → frontend applies invisibly + faint line (no re-search).
- `kind=content` + `confident` → frontend auto-applies + Undo line; re-search if audio tier was weak.
- `kind=ambiguous` (or `content` not confident) → frontend shows ask-first "Did you mean?" with `alternatives`.
- `kind=none` → no suggestion (leave user input as typed).
**Resilience:** AI judge runs under a short timeout (~2–3s) and is fully optional — on timeout/error/unparseable output, fall back to deterministic+catalog result (or `kind=none`). Never block the audio search; never error the request. Mirror `auto_correct`'s greppable usage/cost logging (`match-judge usage/cost job/session=…`).
### Model (decided)
Reuse `auto_correct` dispatch (`claude*` → Anthropic, else Gemini via `genai.Client(vertexai=True, project=…, location="global").models.generate_content(model=…)`).
**Decision (Andrew, 2026-06-15):** default `MATCH_JUDGE_MODEL=gemini-3.5-flash` — the latest Vertex Gemini Flash (https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-5-flash). Passed bare to the genai Vertex client exactly like `auto_correct` passes `gemini-3.1-pro-preview`. No `ANTHROPIC_API_KEY` needed. Env-configurable, so if Vertex requires a version suffix it's a one-line env change (an invalid id surfaces as a loud error on first call). Add `gemini-3.5-flash` pricing to `pricing.py` for cost logging.
### Frontend (`AudioSourceStep.tsx`)
- Replace the parallel `searchCatalogTracks` + client fuzzy `useEffect` with a single `api.matchJudge(artist, title, tier)` call fired in parallel on mount (after the audio tier is known, or fired and reconciled when the tier resolves).
- **Remove** the green `SongSuggestionPanel`. Add a quiet `TidyNotice` (cosmetic) and reuse/restyle `DidYouMeanBanner` for the surfaced-content (Undo) and ambiguous (ask) cases.
- Wire cosmetic/confident-content application through the existing `onArtistTitleCorrection` (no restart). Add a `reSearch()` path (reuse `handleFuzzyAccept`'s restart logic) gated on weak prior results for content corrections.
- Keep the `confidence.tier` gating and artist-tiebreaker semantics (now enforced server-side, but the frontend still passes the tier).
## Out of scope (this phase)
- Title-screen preview perf (separate task: smaller canvas + low-res bg + preload at step 2 + spinner).
- Any change to step count / visibility / customize / job-creation timing.
- Auto-selecting audio on a Tier-1 match (possible later, separately).
## Testing strategy
Per `docs/TESTING.md`:
- **Backend unit:** deterministic normalizer rule table (casing, spacing, punctuation, feat./&, quotes); judge response parsing; confidence/kind classification; AI-failure fallback; "only call AI when not confident" gating.
- **Backend integration:** `/api/catalog/match-judge` happy/edge paths with catalog mocked and AI mocked.
- **Frontend unit (Jest):** TidyNotice rendering + Undo; content-correction auto-apply + smart re-search gating (weak vs ok results); ambiguous ask-first; preserve "no restart on cosmetic".
- **E2E (Playwright) + prod E2E:** end-to-end on a real song (cosmetic case), a typo case (content + re-search), and an ambiguous case.
## Telemetry
- Log judge decisions + engine used + latency + token cost (greppable, like `auto-correct usage/cost`).
- Count cosmetic / content / ambiguous / none and Undo clicks to measure real-world correction quality (informs whether thresholds need tuning).
## Open decisions
1. ~~Judge model default~~ — DECIDED: `gemini-3.5-flash` (Vertex), configurable via `MATCH_JUDGE_MODEL`.
2. Confidence thresholds for cosmetic vs content vs ambiguous (start conservative; tune from telemetry).
3. Whether to keep a tiny instant frontend normalizer for immediate display, or rely solely on the judge response (~sub-second). Lean: rely on judge for v1; add instant normalize later if the delay is noticeable.
## Rollout
- `MATCH_JUDGE_ENABLED` env flag (default on) so the AI layer can be disabled without a deploy; deterministic+catalog still function if AI is off.
- Bump `pyproject.toml` version. Ship behind normal CI; Andrew reviews locally (localhost:3000 → prod backend) before merge/deploy.
@@ -0,0 +1,98 @@
# White-Label Tenant Portals: Made Working End-to-End (Jun 2026)
## Context
The two B2B white-label tenant portals (`vocalstar.nomadkaraoke.com`, `singa.nomadkaraoke.com`)
had full data models, middleware, GCS config, themes, a simplified job form, a separate
Cloudflare deployment, and 280+ unit tests — and were documented as "production ready."
**But no tenant job had ever actually completed:** 0 of the 484 most recent prod jobs
carried a `tenant_id`. The feature looked done but was broken at every stage that had
never been exercised by a real end-to-end tenant job.
This session drove a real Vocal Star track (`Eddy Grant - I Don't Wanna Dance`, from their
bulk batch) through the full pipeline in production, fixing each blocker in turn, until a
tenant job completed: correct attribution → transcription → screens → review → render →
Dropbox delivery, with the locked theme and **no** YouTube / Google Drive.
## The seven blockers (each was the next never-exercised stage)
1. **Tenant attribution never happened (root cause).** The frontend API client never sent
the `X-Tenant-ID` header (`getTenantHeaders()` existed but was unwired). Tenant portals
call the shared `api.nomadkaraoke.com`, whose Host isn't the tenant subdomain, and the
`?tenant=` param is prod-disabled — so the backend never detected the tenant and every
sign-in/job silently became a consumer job. Fix: attach `X-Tenant-ID` from
`window.__TENANT_CONFIG__` in `lib/api.ts` (`getBaseHeaders`), incl. the magic-link
request. PR #824.
2. **Tenant config not authoritative.** Prod sets global `DEFAULT_DROPBOX_PATH` /
`DEFAULT_GDRIVE_FOLDER_ID` / `DEFAULT_BRAND_PREFIX`; `_apply_tenant_overrides` only
filled unset fields, so tenant jobs leaked into the shared consumer Dropbox folder and
uploaded to the global Google Drive. Fix: tenant config is authoritative, gated by
feature flags (gdrive/dropbox cleared when disabled). PR #824.
3. **Wrong file transcribed.** existing-instrumental jobs upload mixed + instrumental into
the same `uploads/{job}/audio/` dir; `uploads-complete` resolved the `audio` slot via
`files[0]`, which sorts to `existing_instrumental.mp3`. Transcription ran on the
instrumental. Fix: `_select_mixed_audio_files` excludes the instrumental. PR #825.
4. **AudioShake rejected the audio.** Vocal Star's MP3s begin with ~731 leading null bytes
before the first frame; ffmpeg tolerates it, AudioShake 400s ("Error fetching or
processing asset"). Consumer jobs never hit this (they transcribe re-encoded stems).
Fix: detect leading null padding on `.mp3/.aac` and losslessly remux (`ffmpeg -c copy`)
before upload. Verified against the live AudioShake API. PR #826.
5. **Theme incomplete.** The strict theme validator requires every field; the tenant
themes (created Jan 2026) were missing `extra_text_text_transform` (intro + end),
added to the schema later → "Title screen generation failed." Fix: added the field to
the live GCS themes and the setup scripts. PR #827.
6. **Theme assets not downloaded.** The setup scripts wrote full `gs://bucket/themes/.../assets/X`
URLs, but `theme_service._build_style_assets_mapping` only resolves bare basenames (the
consumer convention) → `style_assets` empty → assets never localized → encoder failed
with "Video background image not found". Fix: rewrote the live themes + setup scripts to
bare basenames. PR #827.
7. **Render prerequisites — "No instrumental selected".** existing-instrumental jobs have
no instrumental-selection UI step; the orchestrator defaults to `'clean'` (a stem never
produced) and `_validate_prerequisites` rejected the job. Fix: `complete-review`
defaults `instrumental_selection` to `'custom'` when `existing_instrumental_gcs_path`
is set. PR #827.
## Tenant config (final, both tenants)
- Locked theme (`vocalstar` / `singa`), no theme selection.
- `youtube_upload=false`, `gdrive_upload=false` (folder cleared), `dropbox_upload=true`.
- Dropbox: `/MediaUnsynced/Karaoke/Tracks-VocalStar`, `/MediaUnsynced/Karaoke/Tracks-Singa`.
- Jobs forced `is_private=true`; CDG + 4K enabled.
## Daily E2E
`scripts/e2e/tenant_e2e.py` + `.github/workflows/e2e-tenant-daily.yml` run a full job per
tenant daily (07:37 UTC, matrix vocalstar/singa): submit → approve review → render →
assert (completes, Dropbox link present, no YouTube, downloads available) → clean up the
job + uploads. Auth via WIF + `E2E_ADMIN_TOKEN`; test audio in `gs://.../e2e-tests/shared/`.
## Outcome
Both tenants pass the full prod E2E (PRs #824–#830): log in → submit (artist, title, mixed,
instrumental) → transcribe → review → render with the locked theme → encode → package →
Dropbox delivery, with **no YouTube, no Google Drive**, and all outputs (4K / 720p /
with-vocals MP4 + CDG + TXT) downloadable from the portal via `job.file_urls`.
The encoder blocker (bug #8) took three iterations: the staging had to land in the
**orchestrator** path (`video_worker_orchestrator._run_encoding`, not the legacy
`_encode_via_gce`) and use the filename the running encoder VM's `custom` branch globs for
(`custom_instrumental.<ext>`, since the live VM boots the 2026-01-23 image whose `custom`
branch predates `*existing_instrumental*` / `*Instrumental User*`). The instrumental is
server-side-copied from `uploads/{job}/audio/existing_instrumental.*` →
`jobs/{job}/custom_instrumental.<ext>`.
## Gotchas / lessons
- The tenant pipeline had never run end-to-end, so every stage hid a latent bug. "Has a
real job of this shape ever completed in prod?" is a better readiness question than test
count.
- Theme asset paths must be **bare basenames** (consumer convention), not `gs://` URLs.
- AudioShake needs clean audio at offset 0; user-provided files vary — remux defensively.
- Public tenant config API redacts `dropbox_path`/`gdrive_folder_id`/`brand_prefix`; read
the stored GCS config for the real values.
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff. Show more