Compare commits

...
62 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 b486fba790 fix: sanitize artist/title for CDG/TXT packaging (trailing period) (#661)
## Summary
- Fixes TXT packaging failure when song title ends with a period (e.g.
`Lofi Ver.`)
- Root cause: orchestrator's `sanitize_filename()` strips trailing
periods but CDG generator's internal sanitization does not, causing MP3
filename mismatch
- Now passes sanitized artist/title to CDG generator and reuses the
actual MP3 path for TXT packaging
- Adds 2 regression tests for the trailing-period filename scenario

## Details
Job `4117228f` (`Gió - JanK x Quanvrox「Lofi Ver.`) failed 5 times with
"TXT generation was enabled but failed" because:
1. Orchestrator sanitized title to `Lofi Ver` (no period)
2. CDG generator kept `Lofi Ver.` (with period) in ZIP filenames
3. TXT step looked for `...Lofi Ver (Karaoke).mp3` but file was `...Lofi
Ver. (Karaoke).mp3`

## Test plan
- [x] 67 orchestrator tests pass (including 2 new regression tests)
- [x] `test_cdg_packaging_uses_sanitized_artist_title` - verifies
sanitized values passed to CDG
- [x] `test_txt_uses_mp3_path_from_cdg_generation` - verifies TXT uses
actual CDG MP3 path
- [ ] Retry job 4117228f after deployment

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 01:27:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 04b5d16774 feat(i18n): add real Spanish and German translations (Gemini pipeline) (#660)
@coderabbitai ignore

## Summary
- Runs the two-pass Gemini 3.1 Pro translation pipeline on all English
strings
- **Frontend:** 1062/1062 keys translated for Spanish and German
- **Backend:** 186/186 keys translated for Spanish and German
- Uses karaoke-specific glossary (55 terms) for consistency
- 100% key coverage, valid JSON for all locales

## Sample translations
- "Create a Karaoke Video for Any Song" → "Crea un video de karaoke para
cualquier canción" (ES) / "Erstelle ein Karaoke-Video für jeden Song"
(DE)
- "Job not found" → "Trabajo no encontrado" (ES) / "Auftrag nicht
gefunden" (DE)

## Test plan
- [x] Build succeeds with real translations (45 pages generated)
- [ ] Post-deploy: visit /es/ and verify Spanish content
- [ ] Post-deploy: visit /de/ and verify German content
- [ ] Post-deploy: switch language via LanguageSwitcher

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 04:48:37 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 6ca0a58c14 feat(i18n): Phase 3 PR 4 — email localization, URL prefixes, user locale (#659)
@coderabbitai ignore

## Summary
- Final Phase 3 PR — localizes email subjects, adds locale prefix to all
frontend URLs in emails, persists user locale on login
- Adds `locale` parameter (default "en") to all 10 user-facing email
methods
- Job notification service looks up user locale from Firestore before
sending
- Stale review processor passes locale to reminder/expiry emails
- On magic link verification, user's locale is stored to Firestore for
async email use
- 11 new email subject translation keys in
`backend/translations/en.json`

## Test plan
- [x] 2897 backend tests pass (1 pre-existing flaky test)
- [x] 6 test files updated for locale-prefixed URL assertions
- [ ] Post-deploy: verify magic link email has /en/ prefix in verify URL
- [ ] Post-deploy: verify review reminder email has /en/ prefix in
review URL

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 04:08:29 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9e9c4582a6 feat(i18n): Phase 3 backend — i18n utility, 209 strings, all routes localized (#658)
@coderabbitai ignore

## Summary
- Backend i18n for karaoke-gen (Phase 3, PR 3 of 4)
- Adds `backend/i18n.py` utility with `t()`,
`get_locale_from_request()`, `get_locale_prefix()`
- **209 strings** extracted into `backend/translations/en.json` across
13 namespaces
- All 12 user-facing route files converted to use `t(locale,
"namespace.key")`
- Push notification titles/bodies localized
- `InsufficientCreditsError` handler localized
- User model gains `locale` field for async process locale preference
- 22 new i18n unit tests + 3 existing tests updated

## Changes by file
- **New:** `backend/i18n.py`, `backend/translations/{en,es,de}.json`,
`backend/tests/test_i18n.py`
- **Modified:** 12 route files (auth, jobs, users, review, audio_search,
file_upload, catalog, themes, tenant, push, rate_limits, admin)
- **Modified:** `backend/main.py` (exception handler),
`backend/services/push_notification_service.py`,
`backend/models/user.py`

## Test plan
- [x] 22 new i18n unit tests pass
- [x] Full backend test suite passes (2895+ tests)
- [x] Frontend tests unaffected (707 pass)
- [ ] Post-deploy: verify API returns English strings (Accept-Language:
en)
- [ ] Post-deploy: verify Accept-Language: es returns Spanish when
translations are ready

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 23:15:52 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 cba0e00bcc fix(i18n): add DefaultIntlProvider for non-locale routes (#657)
@coderabbitai ignore

## Summary
- Hotfix for #656 — shared components using `useTranslations()` crashed
on non-locale routes (`/app`, `/admin`) because they had no
`NextIntlClientProvider`
- Adds `DefaultIntlProvider` (client component) to root layout that
provides English translations as fallback
- The `[locale]/layout.tsx` overrides this for locale-prefixed routes

## Test plan
- [x] All 707 frontend tests pass
- [x] Static build generates all 45 pages
- [ ] Verify `/app` dashboard loads without errors
- [ ] Verify `/admin` pages load without errors
- [ ] Verify `/en/app` still works with locale-specific provider

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:16:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8c1dfe5460 feat(i18n): Phase 3 frontend — next-intl infrastructure + 1062 strings (en/es/de) (#656)
@coderabbitai ignore

## Summary
- Phase 3 of the i18n multilingual initiative — makes the karaoke-gen
frontend fully multilingual (English, Spanish, German)
- Installs `next-intl` with `[locale]` path-based routing,
LanguageSwitcher, and `Accept-Language` API header
- Extracts **1,062 strings** from ~70 components into `messages/en.json`
across 31 namespaces
- Wires `useTranslations()` into all user-facing components (landing,
dashboard, auth, job flow, lyrics review, instrumental review, audio
editor, etc.)
- Admin pages (`/admin/*`) stay outside locale routing — intentionally
excluded from i18n scope
- Static export generates `/en/`, `/es/`, `/de/` directories (45 total
pages) for Cloudflare Pages
- `es.json`/`de.json` are English placeholders — translation via Gemini
pipeline pending
- Translation pipeline (`scripts/translate.py`) and glossary (55
karaoke-specific terms) included

## Key architecture decisions
- Root layout keeps ThemeProvider/TenantProvider (needed by admin pages
outside `[locale]`)
- Only NextIntlClientProvider added to `[locale]/layout.tsx`
- `job-status.ts` labels converted to translation keys; consumers
translate via `useTranslations('jobStatus')`
- Jest mock loads actual `en.json` so existing tests validate i18n
wiring without assertion changes

## Test plan
- [x] All 707 frontend tests pass (39 suites)
- [x] Static build generates all 45 pages across 3 locales
- [x] Admin pages render at `/admin/` without locale prefix
- [x] CodeRabbit review: 4 issues fixed, 7 pre-existing noted
- [ ] Post-deploy: verify `/en/` landing page renders correctly
- [ ] Post-deploy: verify LanguageSwitcher redirects to `/es/` and
`/de/`
- [ ] Post-deploy: verify `/admin/` still works without locale context

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:50:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 105a5b28fd fix: default dashboard to all jobs, fix E2E completion detection (#655)
## Summary
- Default the dashboard status filter from "active" to "all" so
completed jobs remain visible (existing localStorage preferences
preserved)
- Add recovery logic to E2E happy path test: after 10 consecutive "card
unavailable" polls, automatically switch the filter dropdown to "All
statuses"
- Bump version to 0.157.4

**Root cause:** The daily E2E test (run #126) timed out at Step 9
because the "active" filter uses `hide_completed: true` at the API level
— when the job completed, the card vanished from the DOM and the test
retried for ~25 min until timeout. The generator itself was working
fine.

## Test plan
- [x] All 707 tests pass (`make test`)
- [x] CodeRabbit review clean (1 finding fixed)
- [ ] Next scheduled E2E run should pass with these changes

@coderabbitai ignore

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 11:41:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a0e6448e7b fix: make E2E job card polling resilient to transient DOM changes (#654)
## Summary
- E2E happy path test failed because the job card DOM element briefly
disappeared during a status transition (step 9/10 "Packaging files"),
causing an unhandled `TimeoutError` on `jobCard.textContent()`
- Wrapped all `textContent()` calls in polling loops with try/catch and
a 15s explicit timeout so transient DOM disappearances retry instead of
crashing the test
- Applied fix to both `happy-path-real-user.spec.ts` and
`demo-recording.spec.ts`

Fixes:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/23887007717

## Test plan
- [x] Verified TypeScript has no new errors (all existing errors are
pre-existing Playwright type issues)
- [ ] Next scheduled E2E run will validate the fix against production

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 03:11:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 fbe3edceec fix: video worker downloads PNG instead of MOV for screens (#650)
## Summary

Follow-up to #647. The video worker was hardcoded to download
`title.mov`/`end.mov` from GCS, but those no longer exist after the
screens_worker change. 404 error on all job retries.

- `video_worker.py`: download PNG (or MOV for legacy), validate with PNG
fallback
- `video_worker_orchestrator.py`: `_screen_ext()` helper for dynamic
file extension

## Test plan

- [x] All video unit tests pass
- [ ] Retry job f0d51a0a after deploy

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:39:57 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 ead074505b fix: skip files >3GB in divebar sync to prevent OOM kills (#653)
## Summary

- Skip files larger than 3GB in divebar file sync — the VM has 4GB RAM
and buffers files in memory, so a 4.3GB MKV was causing OOM kills every
run
- Sets `gcs_path = 'skipped:too_large'` so the file won't be retried
nightly (the `WHERE gcs_path IS NULL` query excludes it)
- Only 1 file currently affected: `IMBK-0068 - Zolas - Ancient Mars.mkv`
(4.3 GB)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:24:56 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7e93d62457 fix: thread-safe Drive service in divebar file sync (#651)
## Summary

- Use `threading.local()` for Drive API service — `googleapiclient` is
not thread-safe and sharing across `ThreadPoolExecutor` workers caused
SSL errors, bad file descriptors, and heap corruption (`free():
corrupted unsorted chunks`)
- This is why ~200 files were permanently stuck with `gcs_path=NULL` —
different files failed each run depending on thread timing

**Evidence from VM logs:**
```
ERROR Failed files/NOMAD-1346.zip: 'email'
ERROR Failed files/Shark Attack.zip: [Errno 9] Bad file descriptor
ERROR Failed files/KGAL-0004.zip: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC]
ERROR Failed files/LSWK-0024.zip: [SSL: WRONG_VERSION_NUMBER]
free(): corrupted unsorted chunks
```

## Test plan

- [x] Existing unit tests pass
- [ ] Next nightly file sync run should have 0 failures (was ~200/run)
- [ ] Monitor `gcs_path IS NULL` count — should drop to only genuinely
new files

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:04:54 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 1c846ebae7 fix: preserve gcs_path in divebar catalog sync (#649)
## Summary

- **index_builder.py**: replaced `WRITE_TRUNCATE` with staging table +
`MERGE` SQL to preserve `gcs_path` values during daily catalog index
updates
- **divebar_file_sync.py**: added `blob.exists()` check before
downloading from Drive — if a file is already in GCS, just updates
`gcs_path` in BigQuery without re-downloading
- Added unit tests verifying the MERGE approach preserves `gcs_path`
correctly

**Root cause**: The daily 2 AM index sync was atomically replacing the
entire `divebar_catalog` BigQuery table, wiping all `gcs_path` values.
The 3 AM file sync then saw all ~48K files as unsynced and re-downloaded
the entire ~779 GB catalog from Google Drive every night.

## Test plan

- [x] Unit tests for staging+MERGE behavior (5 tests pass)
- [ ] Verify staging table auto-creates on first run (BigQuery creates
on WRITE_TRUNCATE with schema)
- [ ] Monitor next nightly sync — file_sync should report "recovered
from GCS" instead of downloading
- [ ] Confirm gcs_path values persist across consecutive index runs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 22:31:42 +00:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 c02fdc8d9f Fix GCE cache invalidation and empty corrections handling (#648)
## Summary
- **GCE style asset disk cache** now validates file size against GCS on
cache hit, re-downloading when content has changed at the same URI.
Transient GCS errors gracefully fall back to cached version.
- **Review complete endpoint** no longer writes
`corrections_updated.json` when no corrections data is present (root
cause fix for KeyError in render workers).
- **Both GCE and Cloud Run render workers** validate
`corrections_updated.json` has a `corrections` key before processing,
falling back to base result gracefully (defensive fix).

## Test plan
- [x] Added `test_cache_hit_redownloads_on_size_mismatch` — verifies
stale cache replaced
- [x] Updated `test_cache_hit_skips_download` for size validation flow
- [x] Added `test_gce_worker_skips_empty_corrections` — verifies empty
dict doesn't crash
- [x] Added `TestCompleteReviewSkipsEmptyCorrections` — 4 tests covering
guard conditions
- [x] All 2875 tests pass (8 pre-existing emulator failures unrelated)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 18:03:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3bc1fcb250 fix: move screen video generation to GCE encoding worker (#647)
## Summary

- Screen MOV generation (4K H.264) was silently failing on Cloud Run
after right-sizing to 2Gi (PR #640), producing 36-byte empty shells that
broke all downstream encoding
- `screens_worker` now only generates PNG/JPG images (Pillow, no FFmpeg)
- GCE encoding worker generates MOV from PNG before encoding, with
proper `subprocess.run()` error handling
- Fixed `os.system()` in `video_generator.py` to use `subprocess.run()`
so failures are no longer silent

## Root Cause

PR #640 reduced Cloud Run from 8CPU/16Gi to 2CPU/2Gi. The
`VideoGenerator._create_video_from_image()` used `os.system(ffmpeg ...)`
which OOMs silently for 4K H.264 encoding, producing 36-byte empty MOV
shells. All jobs since March 31 are affected.

## Test plan

- [x] 2875 tests pass (8 pre-existing emulator failures unrelated)
- [x] CodeRabbit: no findings
- [ ] Re-run failed job f0d51a0a after deploy to verify fix
- [ ] Verify admin "Regen screens" button works (tested flow: deletes
old screens → worker generates PNG/JPG only → GCE generates MOV from
PNG)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 21:44:53 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 adae022fbf Fix encoding progress callback causing invalid state transition (#646)
## Summary
- Fix `encoding -> encoding` invalid state transition that caused job
7bbd0d9d to fail
- The GCE encoding `progress_callback` was using `transition_to_state()`
to update progress while already in ENCODING state, which the state
machine correctly rejects as a self-transition
- Changed to `update_job()` which updates progress/message without
validating state transitions

## Test plan
- [x] All 2875 backend tests pass (8 pre-existing emulator failures
unrelated to change)
- [x] State machine integration tests pass
- [x] Encoding interface contract tests pass

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 21:19:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9ccad7c6d3 feat: service health status modal with blue-green deploy details (#645)
## Summary
- Clickable footer opens a modal showing all service health, versions,
deploy times, and PR links
- Progressive disclosure: basic info for everyone, blue-green encoder
details for admins
- New aggregated `/api/health/system-status` endpoint (single fetch
instead of 4 separate calls)
- CI captures git SHA and PR info, passes to frontend and backend builds

## Changes
- **Backend**: New `/api/health/system-status` endpoint with optional
admin auth for blue-green Firestore config
- **Backend**: Build metadata env vars (COMMIT_SHA, PR_NUMBER, PR_TITLE,
STARTUP_TIME) in version module
- **Frontend**: New `SystemStatusModal` component with service cards and
expandable blue-green section
- **Frontend**: Footer version line is now clickable to open the modal
- **Frontend**: Build metadata env vars passed through next.config.mjs
- **CI**: Both frontend and backend deploy jobs capture and pass git SHA
+ PR info

## Testing
- [x] 3 unit tests for system-status endpoint (public, offline, admin
blue-green)
- [x] TypeScript compilation clean (no new errors)
- [x] CodeRabbit CLI reviewed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 15:42:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8e2a949a29 fix: complete blue-green deploy test payload and status check (#644)
## Summary
- Fix the deploy health check test payload and status value mismatches
that prevented blue-green swaps from ever completing
- Follow-up to #642 which fixed the error handling / rollback conditions

## Changes
- **Missing required fields**: `encode-preview` requires
`audio_gcs_path` and `output_gcs_path` but the health check only sent
`job_id`, `ass_gcs_path`, and `duration_seconds` (caused HTTP 422).
Added a 3-second test audio file and proper output path.
- **Status polling mismatch**: Polling checked for `"completed"` but the
GCE worker returns `"complete"` — would always time out even on success.
- **Submit response mismatch**: Validated against `"completed"` which is
never returned — endpoint returns `"accepted"`, `"cached"`, or
`"in_progress"`.

## Root Cause
The test payload was written based on the plan doc which had an
incomplete request schema. The `audio_gcs_path` and `output_gcs_path`
fields have been required since the endpoint was first created (PR #200,
Jan 2026). The status string mismatch (`"completed"` vs `"complete"`)
was likely a typo that was never caught because the request always
failed before reaching the polling stage.

## Testing
- Previous deploy (#642) confirmed the 422 error and verified rollback
now triggers correctly
- This fix addresses the payload so the encode test can actually succeed
and the swap can complete
- Real validation: next deploy after merge

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:07:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0464d3edb3 Fix render_video GCE endpoint import paths (#643)
@coderabbitai ignore

## Summary

- Fix broken import paths in GCE worker's `/render-video` endpoint that
caused `ImportError: No module named 'backend.output_generator'` in
production
- Fix incorrect API signatures for OutputGenerator, CountdownProcessor,
CorrectionResult, load_styles_from_gcs
- Update tests to mock correct module paths

## Root cause

The subagent that implemented Task 2 (PR #641) used invented module
paths (`backend.output_generator`,
`backend.services.countdown_processor`, etc.) instead of the actual
karaoke-gen wheel paths
(`karaoke_gen.lyrics_transcriber.output.generator`, etc.). The tests
also mocked the wrong paths, so they passed locally but the code failed
in production.

## Changes

- `backend/services/gce_encoding/main.py` — Rewrote `run_render_video()`
to use correct imports and API calls matching `render_video_worker.py`
- `tests/unit/test_gce_render_video_endpoint.py` — Rewrote
TestRunRenderVideo to mock correct module paths

## Test plan

- [ ] 18 unit tests pass (verified locally with
`GOOGLE_CLOUD_PROJECT=""` to simulate CI)
- [ ] E2E happy path test after merge validates full pipeline

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:01:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5dfaa3f73f fix: blue-green deploy health check and rollback conditions (#642)
## Summary
- Fix blue-green deploy workflow that has been silently failing since
v0.151.0 (March 25)
- Every deploy has fallen through to `ensure_latest_wheel()` hot-update
instead of tested blue-green swap

## Changes
- **Health check curl**: Replace `curl -sf` (which exits immediately on
HTTP errors before setting output) with `curl -s -o file -w
'%{http_code}'` to capture HTTP status without early exit
- **Status polling curl**: Remove `-f` flag and add fallback for failed
status checks
- **Rollback condition**: Change `passed == 'false'` to `passed !=
'true'` to catch unset/skipped cases (defense in depth)

## Root Cause
`curl -sf` with `-f` (fail silently) exits non-zero on HTTP errors.
Combined with GitHub Actions' `set -e`, the script exits before writing
`passed=false` to `$GITHUB_OUTPUT`. Both the rollback (`== 'false'`) and
swap (`== 'true'`) conditions evaluate false against the unset output,
creating a silent no-op.

## Testing
- [x] CI workflow syntax validated
- [x] CodeRabbit CLI review completed locally (no issues in changed
file)
- Real validation: next deploy will exercise the fixed workflow

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 13:46:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1cf6b62398 Route render_video to GCE encoding worker (#641)
@coderabbitai ignore

## Summary

- Route `render_video_worker` (OutputGenerator/ffmpeg lyrics rendering)
to the GCE encoding worker instead of running on Cloud Run
- Fixes OOM crashes after Cloud Run memory was right-sized to 2Gi
- Adds style asset disk cache on GCE worker to avoid repeated downloads
of the same default theme
- Preserves local fallback when GCE is disabled

## Changes

### GCE Worker (`backend/services/gce_encoding/main.py`)
- New `/render-video` endpoint with `RenderVideoRequest` model
- `run_render_video()` — downloads corrections/audio/styles from GCS,
runs OutputGenerator, uploads outputs
- `download_with_cache()` — SHA-256 keyed disk cache for style assets
(fonts, backgrounds)
- `metadata` field added to `JobStatus` model for countdown padding info

### EncodingService (`backend/services/encoding_service.py`)
- `submit_render_video_job()` — POST to `/render-video` with retry logic
- `render_video_on_gce()` — submit + wait convenience method

### render_video_worker (`backend/workers/render_video_worker.py`)
- Conditional GCE routing when `encoding_service.is_enabled`
- Cloud Run does zero downloads in GCE path — constructs GCS paths from
Firestore metadata
- Existing local path preserved unchanged as fallback

## Test plan

- [ ] 18 new unit tests covering cache, endpoint, service methods, and
routing logic (all pass)
- [ ] Full test suite: 1164 passed, 0 failures
- [ ] CodeRabbit review: 1 bug caught and fixed (missing metadata in
cached response)
- [ ] E2E happy path CI validates full pipeline after merge

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:58:00 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 82e9becc7c chore: right-size Cloud Run + fix divebar-sync auto-shutdown (#640)
## Summary
- Right-size karaoke-backend Cloud Run: concurrency 1→80, minScale 4→1,
CPU 8→2, memory 16Gi→2Gi, enable cpu-throttling, maxScale 50→20
- Fix divebar-sync VM: add missing `shutdown -h now` after file sync
completes (VM was staying on 24/7)

## Cost Impact
- Backend right-sizing: ~$1,800/mo savings
- Divebar-sync fix: ~$32/mo savings
- Part of broader GCP cost reduction
(docs/2026-03-31-cost-reduction-design.md)

## Context
The backend is an I/O-bound API orchestrator (Firestore queries + Cloud
Run job dispatch). Heavy processing was moved to Cloud Run Jobs and a
dedicated GCE encoding worker months ago, but the Cloud Run config was
never updated. Concurrency=1 forced one-request-per-instance, and
minScale=4 kept 4 instances of 8CPU/16Gi running 24/7.

Changes have already been applied live via `gcloud run services update`
and verified with health checks.

## Test plan
- [x] All 6 Cloud Run settings updated incrementally with health checks
between each
- [x] `curl https://api.nomadkaraoke.com/api/health` returns 200 after
all changes
- [x] Divebar-sync VM stopped and metadata updated with new startup
script
- [ ] Monitor billing data over next 24-48h to confirm cost reduction

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 10:00:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ca0d5507b2 Business continuity: DR backups, read-only SA, deny policies (#639)
## Summary

- Two-tier disaster recovery: GCP-native protections (PITR, versioning,
deny policies) + cross-cloud AWS S3 backups
- Nightly Cloud Function exports Firestore, BigQuery, and GCS job files
to AWS S3
- Read-only Claude SA (`claude-readonly`) and break-glass SA for
emergency access
- IAM deny policy blocking `buckets.delete` and `datasets.delete` for
all principals
- External backup freshness monitor (AWS Lambda alerts if backups go
stale >48h)

## Changes

**Infrastructure (Pulumi):**
- `modules/iam/claude_readonly_sa.py` — new read-only + break-glass SAs
- `modules/backup.py` — backup SA, staging bucket, Cloud Function, Cloud
Scheduler
- `modules/database.py` — enable Firestore PITR
- `modules/storage.py` — enable GCS versioning + soft delete lifecycle
- `modules/secrets.py` — add `discord-alert-webhook` secret
- `__main__.py` — wire new modules

**Backup Cloud Function:**
- `functions/backup_to_aws/` — Firestore export, BigQuery export
(weekly/monthly), GCS delta sync, S3 streaming upload, Discord alerts

**Documentation:**
- `docs/DISASTER-RECOVERY.md` — restore runbook for accidental deletion
+ catastrophic GCP loss
- `docs/archive/2026-03-27-business-continuity-design.md` — full design
spec
- `docs/archive/2026-03-29-business-continuity-plan.md` — implementation
plan
- `docs/archive/2026-03-29-external-services-config.md` —
OAuth/DNS/external service reference

## Already deployed

All infrastructure has been applied via `pulumi up`. First backup run
completed successfully (Firestore + job files in S3). Nightly backups
running at 1 AM ET.

## Test plan

- [x] Pulumi preview — 30 creates, 2 updates, 0 deletes
- [x] Pulumi up — all resources deployed
- [x] Manual backup function trigger — Firestore export (1.4 GB) landed
in S3
- [x] GCS job files sync — 161 files (2.9 GB) in S3
- [x] AWS Lambda freshness check — returned `ok` (3h age)
- [x] IAM deny policy verified active via `gcloud iam policies get`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 03:32:01 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 789bf80646 Skip welcome credit AI evaluation for test emails (#638)
## Summary
- E2E test accounts (`@inbox.testmail.app`) were triggering the
Gemini-based credit evaluation on every daily test run, wasting LLM
credits and sending unnecessary denial emails
- Skip both the pre-compute (at magic link send) and inline evaluation
(at verification) for test emails — they get auto-granted directly

## Changes
- `backend/api/routes/users.py`: Skip background pre-compute thread for
test emails
- `backend/services/user_service.py`: Skip AI evaluation in
`grant_welcome_credits_if_eligible()` for test emails, go straight to
granting
- `backend/tests/test_anti_abuse.py`: Add test verifying AI eval is
skipped for testmail addresses

## Testing
- [x] All 2872 unit tests pass (8 pre-existing emulator failures
unrelated)
- [x] New test `test_skips_evaluation_for_test_emails` verifies behavior

## Review
- [x] Local CodeRabbit review completed — no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 14:37:14 -04:00
Andrew Beveridge ☄️ c98da49da9 feat: add jobs search, status filter, and fix loading states (#637)
## Summary
- Add server-side text search to jobs list API (case-insensitive
substring match across artist, title, job_id)
- Replace eye icon toggle with status filter dropdown (All statuses,
Active, Failed, Completed, Cancelled, Awaiting review, Processing)
- Add debounced search input to Recent Jobs header
- Expand limit dropdown options (5, 10, 20, 50, 100, 1000)
- Fix loading state showing "No jobs yet" during cold starts (now shows
spinner)
- Fix API always fetching limit=100 regardless of dropdown selection

## Test plan
- [x] 8 unit tests for `_search_filter_jobs` (artist, title, job_id,
audio search fields, case insensitivity, None handling, empty string,
limit interaction)
- [x] Full backend test suite passes (2870 passed)
- [x] Frontend builds cleanly
- [ ] Manual: verify search filters jobs in real-time on dashboard
- [ ] Manual: verify status dropdown filters correctly
- [ ] Manual: verify loading spinner shows during cold starts instead of
"No jobs yet"

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-30 05:03:05 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 022b4e343a fix: backing vocals recommendation showing 0% with contradictory message (#636)
## Summary

- Fixed API defaulting `recommended_selection` to `with_backing` when no
analysis exists, creating contradictory "Significant backing vocals
(0%)" message — now defaults to `clean`
- Fixed analyzer returning `review_needed` (unknown to frontend) instead
of `with_backing` when backing vocals detected
- Fixed race condition where backing vocals analysis ran in
screens_worker before audio separation completed — moved to audio_worker

## Test plan

- [x] All 25 analyzer unit tests pass (3 updated to match new
`WITH_BACKING` return value)
- [x] All 21 frontend instrumental review component tests pass
- [x] Full test suite: 2863 passed (8 pre-existing emulator failures)
- [x] CodeRabbit: no findings
- [ ] Verify fix in production: create new job and check instrumental
review shows correct recommendation

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:39:59 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 16fcb77d0f fix: relevance filtering in correction_disabled path + guidance message (#635)
## Summary

Two fixes found during post-deploy testing of #632:

1. **Relevance filter bypassed when SKIP_CORRECTION=true** — The
controller's `create_uncorrected_result()` path builds CorrectionResult
directly without going through LyricsCorrector, so wrong-song references
were never filtered. Now applies `filter_irrelevant_sources()` in this
path too.

2. **Misleading "All lyrics matched" message** — When no reference
sources exist (all filtered or none found), the guidance panel showed
"All lyrics matched the reference — no corrections needed." Now shows
"No reference lyrics were found" with guidance to use the search panel.

## Testing

- 9/9 relevance tests passing
- 22/22 GuidancePanel tests passing (updated + new test for empty state)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 04:21:58 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 14a6b767ce fix: improve cancelled job UX and fix /dashboard redirects (#633)
## Summary
- Allow downloading files from cancelled jobs (backend no longer
requires job to be complete if the file exists in GCS)
- Hide cancelled jobs from default recent jobs view alongside completed
jobs; visible via "Show all jobs" toggle
- Fix stale `/dashboard` routes → `/app` (including impersonation
redirect that 404'd)
- Show accurate total job count and helpful empty state when jobs are
filtered out

## Test plan
- [x] Backend unit tests pass (2837 passed)
- [x] Frontend unit tests pass (717 passed, 39 suites)
- [ ] Verify cancelled job download works in prod after deploy
- [ ] Verify impersonation redirects to /app correctly
- [ ] Verify "Show all jobs" toggle shows/hides cancelled and completed
jobs
- [ ] Verify empty state message shows correct total and eye icon hint

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 20:49:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 591c050545 feat: Reference lyrics search with relevance filtering (#632)
## Summary

- Add relevance filtering to the correction pipeline — automatically
rejects wrong-song reference lyrics (below 30% word match threshold,
validated against 168 prod source pairs)
- New `POST /api/review/{job_id}/search-lyrics` endpoint lets users
search with alternate artist/title from the review UI, with force-add
override for edge cases
- Redesigned Add Reference Lyrics modal with Search (default) and Paste
tabs, plus inline empty state when no valid sources exist

## Changes

### Backend
- **Relevance filtering** (`correction/relevance.py`): Per-source
scoring based on anchor sequence word coverage. Integrated into
`LyricsCorrector.run()` after anchor finding — sources below threshold
removed before corrections computed
- **Search endpoint** (`routes/review.py`): Queries all providers
(Genius, Spotify, Musixmatch, LRCLIB) with user-supplied artist/title,
auto-filters results, returns added/rejected/not-found breakdown
- **Provider factory** (`operations.py`): `create_lyrics_providers()`
reads env vars, `search_lyrics_sources()` orchestrates
fetch+filter+correct
- **Force override**: `add-lyrics` and `search-lyrics` support `force`
flag to bypass threshold

### Frontend
- **Tabbed modal**: `AddLyricsModal` rewritten with Search (default) and
Paste tabs
- **SearchLyricsTab**: Artist/title inputs, provider search, rejected
source cards with force-add checkboxes
- **ReferenceEmptyState**: Inline search/paste UI when no valid
reference sources exist
- **API client**: New `searchLyrics()` method with
`SearchLyricsResponse` types

### Analysis
- Empirical threshold analysis script
(`scripts/analyze_reference_relevance.py`) + visual review tool
- 168 source pairs from 81 prod jobs: wrong-song max 3.5%, correct-song
min 26.8% → 30% threshold

## Testing
- 35 new backend tests (relevance scoring, filtering, corrector
integration, search operation, API endpoint)
- 717 existing frontend tests passing (no regressions)
- Edge case: all sources filtered out handled gracefully

## Review
- [x] Local CodeRabbit review completed (3 issues fixed: response
contract, force param coercion, null checks)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:25:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 5a5ee4a780 fix: validate Google OIDC tokens from Cloud Scheduler (#631)
## Summary
- All 4 Cloud Scheduler → backend jobs (stale review processor, stuck
job recovery, YouTube queue, disposable domain sync) were returning 401
because the auth system didn't validate Google OIDC JWT tokens
- Added OIDC token validation to `AuthService.validate_token_full()`
using `google.oauth2.id_token.verify_oauth2_token()`
- Only accepts tokens signed by Google from the configured backend
service account

## Changes
- `backend/services/auth_service.py` — New `_validate_oidc_token()`
method + integration into `validate_token_full()`
- `backend/config.py` — New `SCHEDULER_SERVICE_ACCOUNT` setting
(defaults to `karaoke-backend@nomadkaraoke.iam.gserviceaccount.com`)
- `backend/tests/test_auth_oidc.py` — 10 unit tests covering all code
paths
- `docs/LESSONS-LEARNED.md` — New lesson about Cloud Scheduler OIDC vs
admin token auth
- `pyproject.toml` — Version bump 0.153.6 → 0.153.7

## Testing
- [x] 10 new unit tests (valid token, wrong SA, expired, invalid
signature, network error, passthrough)
- [x] Full backend suite: 2837 passed
- [x] Full frontend suite: 717 passed

## Review
- [x] Local CodeRabbit review completed (no findings)
- [x] Docs reviewed and updated

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 20:00:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f6102e11ab fix: correct admin credits API path in e2e test (#630)
## Summary
- Follow-up to #629 — the admin credits endpoint is at
`/api/users/admin/credits` (users router prefix `/users`), not
`/api/admin/credits`
- One-line fix to the URL in the e2e test

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 12:59:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dba4ea1912 fix: grant credits via admin API when e2e test user gets 0 credits (#629)
## Summary
- Follow-up to #625 and #628 — after fixing the disposable email
allowlist and credit interstitial handling, the e2e test hits a third
issue: the credit evaluation system denies credits to testmail.app
users, leaving the guided flow inputs disabled
- Now detects 0 credits after signup and uses `E2E_ADMIN_TOKEN` to grant
1 credit via the admin API, then reloads the page

## Changes
- `frontend/e2e/production/happy-path-real-user.spec.ts`: After signup,
check credit balance and grant via admin API if 0

## Test plan
- [ ] E2E happy path test passes after merge (triggered manually)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 12:48:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dbadcc5c17 fix: handle credit interstitial in e2e happy path test (#628)
## Summary
- Follow-up to #625 — after fixing the disposable email allowlist, the
e2e test hit a second failure: the magic link verification page now
shows credit evaluation interstitials for new users instead of
"Successfully signed in!" (which is only for returning users)
- The test now handles all verification outcomes (credits_granted,
credits_denied, credits_pending, success) and clicks through credit
interstitials to reach /app

## Changes
- `frontend/e2e/production/happy-path-real-user.spec.ts`: Use
`Promise.race` to detect which verification state appears, handle credit
interstitials by clicking through

## Test plan
- [ ] E2E happy path test passes after deployment (triggered manually)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 12:38:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 257315d632 ci: use poetry.lock for GPU base image hash to avoid needless rebuilds (#627)
## Summary

- Use `poetry.lock` instead of `pyproject.toml` when computing the GPU
base image content hash
- Prevents expensive 15-20 min GPU base image rebuilds on version-only
bumps

## Problem

The GPU base image hash was computed from `cat Dockerfile.gpu-base
pyproject.toml | sha256sum`. Any change to `pyproject.toml` — including
version bumps that don't change dependencies — triggered a full GPU base
image rebuild. This adds ~15-20 min to every deploy that follows a
version bump.

## Fix

`poetry.lock` is the authoritative record of resolved dependencies. It
only changes when actual dependencies are added/removed/updated, not on
version bumps. The GPU base image installs deps via `pip install -e .`
which reads `pyproject.toml` at build time, but the Docker layer cache
handles that separately — the CI hash check just needs to know if deps
changed.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 11:30:50 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 92d1c9729d ci: auto-update lyrics-transcription-job on deploy (#626)
## Summary

- Add `lyrics-transcription-job` to the CI deploy step that updates
Cloud Run Jobs
- Previously only `video-encoding-job` and `audio-separation-job` were
updated, requiring manual `gcloud run jobs update` for lyrics

## Context

Discovered during the anchor IndexError fix (#623) — the fix was
deployed to the Cloud Run Service automatically but the Cloud Run Job
(where lyrics transcription actually runs) had to be updated manually.

## Changes

- `.github/workflows/ci.yml`: Add `gcloud run jobs update
lyrics-transcription-job` alongside the existing job updates

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 10:52:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 cd3076fc58 fix: allowlisted domains bypassed by external disposable email APIs (#625)
## Summary
- The disposable email detection had a bug where the Firestore
`allowlisted_domains` only protected against the Tier 1 static blocklist
check. External API checks (DeBounce, verifymail.io) at Tiers 3-4 ran
regardless and could override admin allowlist decisions.
- This broke the E2E happy path test starting March 21 when
`inbox.testmail.app` got flagged by DeBounce as disposable — the signup
step failed because "Check Your Email" never appeared.
- Adds a "Tier 1.5" check so allowlisted domains skip external API calls
entirely, plus a CI setup step to ensure the domain stays allowlisted.

## Changes
- `backend/services/email_validation_service.py`: Add allowlist check
before external API calls; include `allowlisted_domains` in cached
config
- `backend/tests/test_email_validation_service.py`: Regression test for
allowlisted domain bypass
- `.github/workflows/e2e-happy-path.yml`: CI setup step to ensure
`inbox.testmail.app` is allowlisted before test runs

## Test plan
- [x] All 53 email validation tests pass (52 existing + 1 new regression
test)
- [x] `inbox.testmail.app` added to production Firestore allowlist
- [ ] E2E happy path test passes after deployment

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 10:48:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 78e4cc7010 fix: bounds check ref_words in anchor gap extension (IndexError b7e8c96d) (#623)
## Summary

- Fix IndexError in `_extend_anchors_into_single_word_gaps` when
`ref_texts_clean` and `ref_words` have different word counts due to
`clean_text()` normalization
- Adds production fixture regression test from crashing job `b7e8c96d`
(Bằng Kiều - Dẫu có lỗi lầm)

## Root Cause

`ref_texts_clean` is built by joining words → `clean_text()` →
`split()`, which can produce a **different word count** than the raw
`ref_words` Word objects list. For Spotify in the crashing job:
`ref_texts_clean` had 599 words, `ref_words` had 528. Anchor
`reference_positions` computed against the 599-word list were used to
index the 528-word list.

## Changes

- `anchor_sequence.py`: Add `< len(ref_words[source])` bounds check in
both `_apply_forward_extension` and `_apply_backward_extension`
- `test_anchor_gap_extension_bounds.py`: 4 regression tests (production
fixture + synthetic bounds tests)
- `anchor_crash_b7e8c96d.json`: Sanitized production fixture (49
anchors, 526 words)
- `LESSONS-LEARNED.md`: Document text normalization word count mismatch
gotcha
- Version bump: 0.153.4 → 0.153.5

## Testing

- [x] 33 anchor gap extension tests pass (29 existing + 4 new)
- [x] Full unit suite: 1146 tests pass
- [ ] After deploy: retry job `b7e8c96d`

## Review

- [x] CodeRabbit CLI review completed locally (1 finding fixed:
sanitized copyrighted lyrics)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-28 14:23:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dd25a6110f docs: troubleshooting runbooks for job repair and Cloud Run Jobs (#622)
## Summary

- Surgical audio re-separation that preserves lyrics/review data (direct
Firestore + Cloud Run Jobs API)
- How to trigger Cloud Run Jobs directly, bypassing internal API
idempotency checks
- CI gap: `lyrics-transcription-job` image not updated on deploy (manual
workaround + permanent fix pointer)

Docs-only — no code changes, no version bump.

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 20:36:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 e3c55672e5 fix: bounds check in anchor sequence gap extension (#621)
## Summary

- Fix IndexError in `_extend_anchors_into_single_word_gaps` when
`gap_position >= len(all_words)`
- This crashes lyrics transcription for songs where the last anchor ends
at the transcription boundary
- Affected job: `b7e8c96d` (Bằng Kiều - Dẫu có lỗi lầm)

## Fix

Add `if gap_position >= len(all_words): continue` before accessing
`all_words[gap_position]`.

## Test plan

- [x] 2 new boundary regression tests in test_anchor_gap_extension.py
- [x] Full unit suite: 1142 passed (29 anchor gap tests)
- [ ] After deploy: retry job b7e8c96d

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 19:51:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 bcbbb7865f fix: prevent false 'No audio sources found' on search failure (#620)
## Summary

- Fix misleading "No audio sources found" message that appeared when
audio search failed (timeout, network error, 5xx) instead of showing an
error
- Replace scattered boolean/string state with explicit `SearchStatus`
state machine so the no-results message can only appear after a
confirmed successful search
- Add automatic retry (up to 3 attempts with backoff) for transient
failures

## Changes

- **State machine:** Replace `isSearching`, `error`, `isCreditError`
with single `SearchStatus` discriminated union (`searching | succeeded |
failed`)
- **Retry logic:** Auto-retry network errors, timeouts, and 5xx up to 3
times with 2s/4s backoff delays. 4xx errors (auth, credits) fail
immediately
- **Spinner feedback:** Show "Retry 1 of 2" / "Retry 2 of 2" during
retries
- **Fuzzy accept:** Route through `doSearch` via useEffect instead of
inline API call, so corrected searches also get retry protection
- **Tests:** 5 new tests covering the core bug fix, retry behavior, and
error classification
- **Docs:** Added lesson learned about state conflation pattern

## Testing

- [x] 20/20 unit tests pass (15 existing + 5 new)
- [x] 712/712 full suite tests pass
- [x] TypeScript compiles cleanly
- [x] Production flacfetch verified healthy (v0.19.5, all providers up)

## Review

- [x] Local CodeRabbit review completed (no findings)
- [x] Two-stage review (spec compliance + code quality) during
implementation

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:44:27 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8c7627b7ec fix: prevent video worker race condition and add encoding worker warmup (#619)
## Summary
- Fix race condition where Cloud Run Job `max_retries` + manual retry
launched concurrent video workers that corrupted each other's state
transitions (job 13b8adcf)
- Add encoding worker VM warmup to all paths that trigger video
encoding, not just the frontend happy path
- Defense in depth: frontend warmup → worker dispatch warmup → encoding
retry warmup

## Changes
- **job_health_service.py**: Remove `GENERATING_VIDEO`/`RENDERING_VIDEO`
from valid video_worker startup states — if a job is already in those
states, another worker is processing it
- **video_worker.py**: Make `_validate_prerequisites` a hard failure on
wrong status (was warn-and-continue)
- **worker_service.py**: Add `_warmup_encoding_worker()` called from
both `trigger_video_worker` and `trigger_render_video_worker`
- **encoding_service.py**: Add `_warmup_encoding_worker_fallback()`
called on first connection failure in retry loop
- **docs/LESSONS-LEARNED.md**: Document both findings

## Testing
- [x] 7 new unit tests covering race condition fix, warmup dispatch, and
fallback behavior
- [x] Full backend suite passes (2817 passed)
- [x] Full frontend suite passes (712 passed)

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

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:27:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0c996d1c8e fix: rename Stage 1 vocals before Stage 2 to avoid stem tag regex collision (#618)
## Summary

Follow-up to #617 — the stem tag parsing fix alone wasn't enough. The
audio-separator library's ensemble code uses
`re.search(r'_\(([^)]+)\)')` to classify intermediate stems, matching
the **first** `_(Tag)_` pattern. When Stage 2 receives Stage 1 output
like `Song_(Vocals)_preset_instrumental_clean.flac`, the regex matches
the Stage 1 tag instead of the Stage 2 tag, classifying ALL stems as
"Vocals" and producing only 1 output file instead of 2.

## Fix

Copy Stage 1 vocals to a clean filename (`Artist - Song (Vocals).flac`)
before passing to Stage 2, avoiding the regex collision.

## Test plan

- [x] Unit tests updated to verify clean filename is used for Stage 2
input
- [x] Full test suite: 1140 passed, 0 failed
- [ ] After deploy: trigger test job and verify backing vocals +
combined instrumental stems appear

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:18:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f58c74e67e fix: ensemble preset stem tag parsing — restore backing vocals separation (#617)
## Summary

- Fix stem filename parsing bug where preset name `instrumental_clean`
caused the Vocals file to be misclassified as instrumental, preventing
Stage 2 (backing vocals separation) from running
- All new GPU-processed jobs were only producing `instrumental_clean` —
no backing vocals, lead vocals, or combined instrumentals
- The instrumental review page showed "No backing vocals detected" for
all jobs

## Root Cause

Ensemble preset output filenames follow
`{base}_(StemTag)_preset_{name}.flac`. The old code did `"instrumental"
in basename` which matched the **preset name** `instrumental_clean` in
the Vocals file, so `result["vocals"]` was never set, and Stage 2 never
ran.

## Fix

Extract the stem tag from between `_(` and `)_` delimiters and match
only that, not the full filename.

## Test plan

- [x] 5 new regression tests for stem tag parsing (both stages)
- [x] 2 pre-existing tests fixed to use realistic ensemble filenames
- [x] Full unit suite: 1140 passed, 0 failed
- [x] CodeRabbit: no findings
- [ ] After deploy: trigger a test job and verify all stems appear on
instrumental review page

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 12:14:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ccc1b7c714 Fix lyrics upload race condition when artist/title changes mid-processing (#616)
## Summary

- Fix race condition in `upload_lyrics_results` where admin edits to job
artist/title during lyrics worker execution caused filename mismatch and
"No corrections JSON found" errors
- Scan lyrics directory by file suffix pattern instead of reconstructing
filenames from mutable Firestore metadata
- Remove unnecessary `get_job()` call and `sanitize_filename` import
from upload path

## Root Cause

Job `fbec37d6` failed because:
1. Lyrics worker started processing with artist = `zmcmillan08`
2. Admin updated artist to `Quay Money` mid-processing
3. `upload_lyrics_results` read the updated artist from Firestore and
looked for `Quay Money - ... (Lyrics Corrections).json`
4. File on disk was `zmcmillan08 - ... (Lyrics Corrections).json` → not
found → job failed

## Test plan

- [x] Updated 3 existing tests to validate directory-scanning behavior
- [x] Added new test: error path when no corrections file exists at all
- [x] All 68 worker tests pass
- [x] CodeRabbit review: no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 11:14:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 056ce3ce2d docs: GPU audio separation learnings and cleanup (#615)
## Summary
- Remove deprecated `AUDIO_SEPARATOR_API_URL` from DEVELOPMENT.md env
vars (no longer used — separation runs directly in Cloud Run Job)
- Add GPU-specific lessons to LESSONS-LEARNED.md:
  - Pin CUDA-specific PyTorch versions in Docker images
  - Ensemble presets require explicit `load_model()` before `separate()`
  - Validate with actual Docker builds, not just package combos

Docs-only, no version bump needed.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 01:32:35 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 dfcd79e5c7 fix: GPU app image — preserve pinned torch cu126 with --no-deps (#614)
## Summary
- Use `--no-deps` in app Dockerfile when building on GPU base image
(detected via `MODEL_DIR` env var)
- Without this, `pip install -e .` upgrades torch from pinned cu126 back
to cu130 (pyproject.toml has `torch>=2.7`) and reinstalls
audio-separator[cpu], breaking both CUDA and GPU ONNX Runtime

This is a follow-up to #613 — the GPU base image had the right packages,
but the app layer's `pip install -e .` undid the pinning.

## Test plan
- [ ] CI passes
- [ ] Deploy, trigger audio separation job
- [ ] Verify Job logs show CUDA available + successful separation

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:59:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 c4ea0e8fb4 fix: GPU audio separation — pin PyTorch cu126 + missing load_model() (#613)
## Summary
- Pin PyTorch to `cu126` in GPU Dockerfile — Cloud Run L4 GPUs have
driver 570 (CUDA 12.8 max), but `audio-separator[gpu]` pulls PyTorch
`cu130` which fails with "driver too old"
- Add missing `separator.load_model()` before `separator.separate()` for
ensemble presets in `audio_processor.py` — the Separator API requires
this even for presets
- Remove `AUDIO_SEPARATOR_API_URL` from Service env vars (cleanup — Job
has its own `MODEL_DIR`)

## Validation
Tested on GCE L4 GPU VM:
- `torch==2.6.0+cu126` + `audio-separator[gpu]` 0.44.1 → CUDA detected,
GPU acceleration enabled
- Full ensemble separation (`instrumental_clean` preset) completed in
**26.6s** on real audio
- Docker image build validation in progress on separate L4 VM

## Test plan
- [ ] CI passes (GPU image rebuilds due to Dockerfile change)
- [ ] Trigger audio separation job after deploy
- [ ] Verify Cloud Run Job logs show "CUDA is available" and "local GPU"
mode
- [ ] Verify stems are correct

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:18:32 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7424398fcf fix: use us-east4 region for audio separation job trigger (#612)
## Summary

The audio-separation-job moved to us-east4 (GPU), but the worker trigger
was still using the default us-central1 region. Added `location`
parameter to `_trigger_worker_cloud_run_job()` and passed `us-east4` for
the audio worker.

Also includes the FFmpeg apt fix from #611.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:36:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 41f296f70b fix: use apt FFmpeg in GPU Dockerfile (CI timeout fix) (#611)
## Summary

The johnvansickle.com static FFmpeg download times out in CI (curl exit
code 28). The audio worker only uses FFmpeg for format conversion and
padding, not encoding, so the Ubuntu apt package is sufficient.

Fixes the GPU base image build failure in the deploy-backend workflow.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 20:56:36 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 177e70efc5 fix: GPU Cloud Run Job infra fixes (zonal redundancy, deletion protection) (#610)
## Summary

Fixes for the GPU audio worker Cloud Run Job that were discovered during
Pulumi apply:

- `deletion_protection=False` — needed so Pulumi can replace the job
when changing regions
- `gpu_zonal_redundancy_disabled=True` — required for Cloud Run Jobs
with GPU (GCP capacity limitation)

Follow-up to #609 (GPU image CI) where the Pulumi apply failed.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:28:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 55dd7a30d0 ci: add GPU image build and audio worker deploy to workflow (#609)
## Summary

- Adds GPU base image build to the deploy-backend CI job (same
hash-check pattern as regular base image)
- Builds GPU app image (regular Dockerfile with GPU base as
`BASE_IMAGE`)
- Updates `audio-separation-job` in us-east4 with the GPU image on every
deploy
- Configures Docker auth for the us-east4 Artifact Registry

## Changes

- `.github/workflows/ci.yml` — GPU base image hash check + build, GPU
app image build, audio-separation-job update
- `backend/Dockerfile.gpu-base` — Added `BASE_CONTENT_HASH` label for
hash-based rebuild detection

## How it works

On merge to main, the deploy-backend job now:
1. Builds regular base + app images (unchanged)
2. Hashes `Dockerfile.gpu-base` + `pyproject.toml` → checks if GPU base
needs rebuild
3. If rebuild needed: builds GPU base image (CUDA + PyTorch + models,
~45 min timeout)
4. Builds GPU app image (regular Dockerfile with GPU base)
5. Updates `audio-separation-job` in us-east4 with the new GPU image

The first run will take longer (GPU base image bootstrap). Subsequent
runs skip the GPU base build unless `Dockerfile.gpu-base` or
`pyproject.toml` changes.

## Testing
- [x] YAML syntax verified
- [ ] First CI run will bootstrap the GPU base image (expect ~30-45 min)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 15:47:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 92ae3fb28f feat: run audio separation directly on GPU in audio worker (#608)
## Summary

- **Eliminates HTTP hop** between the audio worker Cloud Run Job and the
audio-separator Cloud Run Service by running the `Separator` class
directly with an L4 GPU attached
- **Adds GPU Docker image** (`karaoke-backend-gpu`) with CUDA 12.6,
PyTorch, and pre-baked ensemble preset models
- **Moves audio worker to us-east4** with L4 GPU, 4 CPU, 16Gi memory —
old separator service kept for rollback

## Changes

### Code
- `audio_processor.py` — Ensemble presets wired into local Separator
path (2-stage: `instrumental_clean` + `karaoke`)
- `audio_worker.py` — Dual-mode support: `MODEL_DIR` env var → local
GPU, `AUDIO_SEPARATOR_API_URL` → remote API
- `create_audio_processor()` — New `model_file_dir` parameter to enable
local GPU mode

### Infrastructure (Pulumi)
- `gpu_artifact_registry.py` — New Artifact Registry in us-east4 for GPU
images
- `cloud_run.py` — Audio worker job: GPU (nvidia-l4), us-east4, 16Gi,
`MODEL_DIR=/models`
- `__main__.py` — Wire in GPU registry + Cloud Build IAM

### Docker
- `Dockerfile.gpu-base` — CUDA 12.6 + Python 3.11 + audio-separator[gpu]
+ baked models
- `cloudbuild-gpu-base.yaml` — Cloud Build config (E2_HIGHCPU_32, 100GB
disk, 1h timeout)
- `download_models.py` — Bakes `instrumental_clean` + `karaoke` preset
models at build time

### Tests
- 8 new unit tests covering factory config, mode selection, and preset
wiring
- Updated existing test patch targets for module-level Separator import

## Testing
- [x] 22/22 unit tests pass (8 new + 14 existing)
- [x] Code review completed (subagent-driven + final review)
- [x] CodeRabbit CLI review completed locally
- [ ] GPU image build (requires `gcloud builds submit`)
- [ ] Production verification with `under_pressure_harmonies.flac`

## Rollback Plan
Set `AUDIO_SEPARATOR_API_URL` back on the audio worker job → falls
through to remote API path. Old separator service is still running
(scale-to-zero).

## Design & Plan
- Design spec:
`docs/archive/2026-03-26-direct-gpu-audio-separation-design.md`
- Implementation plan:
`docs/archive/2026-03-26-direct-gpu-audio-separation-plan.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 15:13:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2cc1061a9d Audio separator infra + docs (concurrency, Firestore, GCS) (#607)
## Summary

- Infrastructure for async audio separator: GCS output bucket, Firestore
index, IAM, env vars
- Set concurrency=1 (each GPU job gets own instance for proper
autoscaling)
- Updated all docs: Modal→Cloud Run GPU references, architecture design
spec, lessons learned
- Phase 2 noted: migrate separator to Cloud Run Jobs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:37:59 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 be19e6c7a0 Infra for async audio separator (concurrency, GCS, Firestore) (#606)
## Summary

- Update audio separator Cloud Run service:
`max_instance_request_concurrency` 1→50, `max_instances` 5→10
- Add `OUTPUT_BUCKET` and `GCP_PROJECT` env vars for the separator
service
- Create `nomadkaraoke-audio-separator-outputs` GCS bucket with 1-day
lifecycle policy
- Grant separator service account `roles/datastore.user` for Firestore
and `roles/storage.objectAdmin` for the output bucket
- Add Firestore composite index on `audio_separation_jobs` (status +
updated_at) for cleanup queries

Companion to nomadkaraoke/python-audio-separator#280. Deploy order: this
PR's infra first (`pulumi up`), then the separator service.

## Test plan

- [ ] `pulumi preview` shows expected resource changes
- [ ] `pulumi up` applies cleanly
- [ ] Verify GCS bucket created with lifecycle policy
- [ ] Verify Firestore index created
- [ ] Verify separator service updated with new concurrency/scaling
settings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 00:41:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8f8fc269e6 fix: retry returns to lyrics review when not completed (#605)
## Summary
- Fixed retry checkpoint detection skipping lyrics review when user
never completed it
- Previously, retry used `corrections.json` + `title.mov` as proxy for
"review done," but both are auto-generated artifacts that exist BEFORE
user review
- Now requires `instrumental_selection` in state_data (only set via
review submit endpoint) to confirm review was actually completed
- Jobs that failed before review completion now correctly return to
`awaiting_review` on retry

## Root Cause
Job `45f9bbc0` hit this: audio separation kept failing, but corrections
+ title screen existed from the lyrics/screens pipeline. Retry jumped to
`REVIEW_COMPLETE`, skipping review entirely. Admin had to manually
reset.

## Test plan
- [x] Updated existing render checkpoint test to require
`instrumental_selection`
- [x] Added regression test for the skip-review scenario
- [x] All 8 retry endpoint tests pass
- [x] Full backend suite passes (2583 passed)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 21:58:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ce4bde6a6d fix: update audio-separator to 0.44.1 (multipart fix) (#603)
## Summary
Update audio-separator from 0.44.0 to 0.44.1 to fix 400 Bad Request when
using `gcs_uri`.

v0.44.0 sent `x-www-form-urlencoded` when no file was uploaded (gcs_uri
mode), but FastAPI requires `multipart/form-data`. v0.44.1 fixes this.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 19:01:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 22a500d153 Pre-compute credit evaluation at magic link send time (#602)
## Summary
- Run AI credit evaluation in background thread when sending magic link
(new users only)
- Store result on magic link Firestore doc
- At verify time, use pre-computed result if available, fall back to
inline evaluation if not
- Most users will see instant verification instead of 20s wait

## Test plan
- [x] 53 anti-abuse + credit evaluation tests pass (3 new)
- [x] New test: pre-computed eval skips AI call
- [x] New test: verify passes pre-computed eval from magic link doc
- [x] New test: verify falls back to None when no pre-computed eval
- [ ] Manual test: sign up, verify welcome screen appears quickly

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 22:36:31 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7c39b2817f Fix Vertex AI region: use global for latest Gemini models (#600)
## Summary
- Preview Gemini models (gemini-3.1-pro-preview) require
`location="global"`, not `us-central1`
- This was causing 404 errors when the credit evaluation tried to call
Gemini for users with abuse signal correlations
- Bump version to 0.150.6

## Test plan
- [x] All 50 anti-abuse + credit evaluation tests pass
- [ ] Manual test: sign up with correlated fingerprint/IP, verify AI
evaluation runs successfully

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 17:20:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c47fe6518c fix: update audio separator URL from Modal to Cloud Run (#601)
## Summary
- The CI deploy script was still setting `AUDIO_SEPARATOR_API_URL` to
the old Modal endpoint
- Update to the Cloud Run GPU service URL
(`audio-separator-718638054799.us-east4.run.app`)
- This was the root cause of the 422 error when retrying job 45f9bbc0

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 16:18:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 046ca69a1c fix: pass GCS URI to audio separator, fix WIF for deploys (#599)
## Summary
- Fix 413 Request Entity Too Large for audio separation of large FLAC
files
- Fix Workload Identity Federation for python-audio-separator Cloud Run
deploys

## Changes
- **Infrastructure:** Grant `storage.objectViewer` to audio-separator SA
so it can read from the main GCS bucket
- **Infrastructure:** Add `python-audio-separator` repo to the WIF
binding (was missing, blocking all Cloud Run deploys)
- **Audio worker:** Set `input_gcs_uri` on the processor when the input
file is already in GCS
- **Audio processor:** Stage 1 passes `gcs_uri` to the separator API
instead of uploading file bytes
- **Dependency:** Update `audio-separator` to 0.44.0 (adds `gcs_uri`
support)
- **Version:** 0.151.0 → 0.152.0

## How it works
Before: `audio_worker → download from GCS → HTTP POST (file bytes) →
separator` (fails for >32MB)
After: `audio_worker → pass gs:// URI → separator downloads from GCS
directly` (no size limit)

Stage 2 (backing vocals) still uses file upload since the input is a
Stage 1 output that's already local.

## Test plan
- [x] 2 new unit tests: GCS URI passthrough + fallback to file upload
- [x] All 28 migration tests pass
- [x] Pulumi infra changes applied (GCS IAM + WIF binding)
- [x] Audio separator v0.44.0 deployed to Cloud Run and healthy
- [ ] Re-run failed job 45f9bbc0 to verify fix end-to-end

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 14:36:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 efb4aa8351 fix: add google-cloud-compute dependency for encoding worker VM management (#598)
## Summary

- Adds `google-cloud-compute` to pyproject.toml dependencies
- The backend needs this to call the Compute API (start/stop VMs) for
the blue-green encoding worker warmup
- Without it, the warmup/heartbeat endpoints return 500 with
`ImportError: cannot import name 'compute_v1' from 'google.cloud'`

## Test plan

- [x] Verified the import error in Cloud Run logs
- [ ] After merge, warmup endpoint should return 200

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 14:12:15 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d681e26b02 fix: encoding worker deploy failure should not block Docker deploy (#597)
## Summary

- The blue-green encoding worker health check failure was blocking the
entire CI job, preventing the Docker image from being built and deployed
to Cloud Run
- This meant the new backend code (with warmup/heartbeat endpoints) was
never deployed, causing 404s on the new routes
- Fix: add `continue-on-error: true` to health check and encode test
steps so the Docker deploy always proceeds
- The rollback step now checks step outputs instead of `failure()`
condition

## Root cause

The CI job runs encoding worker deploy → Docker build → Cloud Run deploy
sequentially. When the encoding worker health check failed (missing
`packaging` module), the job stopped before reaching the Docker build
step.

## Test plan

- [x] Encoding worker deploy failure no longer blocks Docker deploy
- [ ] Next CI run on main will deploy the backend with new routes

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 13:53:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2003d4acc8 fix: add packaging to encoding worker Packer image venv (#596)
## Summary

- Adds `packaging` to the pre-installed Python dependencies in the
Packer image venv
- The encoding worker imports `packaging.version.Version` but this
wasn't in the base image
- First blue-green deploy caught this via the health check — encoding
worker crashed on startup with `ModuleNotFoundError: No module named
'packaging'`
- Manually installed on both VMs as a temporary fix; this makes it
permanent for future image builds

## Test plan

- [x] Verified encoding worker starts after manual `pip install
packaging` on both VMs
- [ ] Next Packer image build will include this dependency

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 12:00:05 -04:00
258 changed files with 49541 additions and 3400 deletions

No files matched your search

+183 -23
View File
@@ -902,6 +902,22 @@ jobs:
# - / (main app)
# - /app/jobs/{id}/lyrics (lyrics review)
# - /app/jobs/{id}/instrumental (instrumental review)
- name: Capture build metadata
id: frontend-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install frontend dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
@@ -911,6 +927,10 @@ jobs:
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy consumer to Cloudflare Pages
@@ -929,6 +949,10 @@ jobs:
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_TENANT_PORTAL: "true"
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy tenant portal to Cloudflare Pages
@@ -959,6 +983,11 @@ jobs:
REPOSITORY: karaoke-repo
BASE_IMAGE_NAME: karaoke-backend-base
APP_IMAGE_NAME: karaoke-backend
# GPU image for audio worker (L4 in us-east4)
GPU_REGISTRY: us-east4-docker.pkg.dev
GPU_REPOSITORY: karaoke-backend-gpu
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
GPU_APP_IMAGE_NAME: karaoke-backend
steps:
- name: Check disk space (aggressive for Docker builds)
run: |
@@ -1003,6 +1032,23 @@ jobs:
echo "📋 Current version: $VERSION"
echo "🚀 Deploying on every push to main"
- name: Capture build metadata
id: build-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
# For squash-merge commits, PR number is in the commit message as (#NNN)
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Authenticate to Google Cloud (Workload Identity)
id: auth
uses: google-github-actions/auth@v2
@@ -1146,6 +1192,7 @@ jobs:
- name: Wait for service health
id: health
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
@@ -1174,29 +1221,43 @@ jobs:
- name: Deep health check - real encode test
if: steps.health.outputs.healthy == 'true'
id: encode-test
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
echo "Uploading test assets to GCS..."
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
"${DEPLOY_TEST_PATH}/test-preview.ass"
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
"${DEPLOY_TEST_PATH}/test-audio.flac"
echo "Submitting test encode to $SECONDARY_IP..."
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"job_id": "deploy-health-check",
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
"duration_seconds": 10
}')
-d "{
\"job_id\": \"deploy-health-check\",
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
}") || HTTP_CODE="000"
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
echo "::error::Encode request failed with HTTP $HTTP_CODE"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
echo "Encode response: $RESPONSE"
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; then
echo "::error::Encode test failed with status: $STATUS"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
@@ -1204,11 +1265,11 @@ jobs:
for i in $(seq 1 12); do
sleep 5
JOB_STATUS=$(curl -sf \
JOB_STATUS=$(curl -s \
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
echo "Encode status: $JOB_STATUS (attempt $i/12)"
if [ "$JOB_STATUS" = "completed" ]; then
if [ "$JOB_STATUS" = "complete" ]; then
echo "Encode test passed!"
echo "passed=true" >> $GITHUB_OUTPUT
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
@@ -1225,7 +1286,7 @@ jobs:
exit 1
- name: Rollback on failure
if: failure()
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
@@ -1317,7 +1378,9 @@ jobs:
--zone=us-central1-c --project=nomadkaraoke || true
- name: Configure Docker for Artifact Registry
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
run: |
gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
# ============================================
# Docker Build with BuildKit + Registry Cache
@@ -1436,6 +1499,88 @@ jobs:
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# GPU Image Build (for audio worker with L4 GPU)
# Same pattern as base image: hash check → rebuild if needed
# GPU image lives in us-east4 (co-located with GPU instances)
# ============================================
- name: Calculate GPU base image hash
id: gpu-base-hash
run: |
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
# Using poetry.lock instead of pyproject.toml so that version-only bumps
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
echo "📋 GPU base content hash: $CURRENT_HASH"
- name: Check if GPU base image exists and is current
id: check-gpu-base
run: |
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
EXISTING_HASH=""
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
TOKEN=$(gcloud auth print-access-token)
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
else
echo "⚠️ No existing GPU base image found in registry - will build"
fi
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
else
echo "✅ GPU base image is up to date"
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
fi
- name: Build and push GPU base image (if needed)
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
timeout-minutes: 45
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile.gpu-base
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
build-args: |
BUILD_DATE=${{ github.run_id }}
BUILD_ID=${{ github.sha }}
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
provenance: false
- name: Build and push GPU app image
timeout-minutes: 10
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
build-args: |
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# Deploy to Cloud Run
# ============================================
@@ -1454,33 +1599,48 @@ jobs:
--region us-central1 \
--platform managed \
--allow-unauthenticated \
--memory 16Gi \
--cpu 8 \
--memory 2Gi \
--cpu 2 \
--cpu-boost \
--no-cpu-throttling \
--cpu-throttling \
--execution-environment gen2 \
--timeout 1800 \
--concurrency 1 \
--max-instances 50 \
--min-instances 4 \
--concurrency 80 \
--max-instances 20 \
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
echo "📦 Updating Cloud Run Jobs..."
# Video encoding job - runs video worker to completion, immune to service deployments
# Video encoding job (CPU, us-central1)
gcloud run jobs update video-encoding-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Lyrics transcription job (CPU, us-central1)
gcloud run jobs update lyrics-transcription-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Audio separation job (GPU, us-east4) — uses GPU image
gcloud run jobs update audio-separation-job \
--image "$GPU_IMAGE" \
--region us-east4 \
--project ${{ env.PROJECT_ID }} \
--quiet
echo "✅ Cloud Run Jobs updated"
- name: Verify deployment and version
+10
View File
@@ -67,6 +67,16 @@ jobs:
working-directory: frontend
run: mkdir -p test-results
- name: Ensure testmail.app domain is allowlisted
run: |
# testmail.app is used for E2E testing but gets flagged as disposable
# by external APIs. Ensure it's in the allowlist before the test runs.
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: failed to allowlist domain (may already exist)"
- name: Refresh E2E session token (when use_test_token enabled)
id: refresh_token
if: inputs.use_test_token == true
+1
View File
@@ -232,3 +232,4 @@ flacfetch
# Test output directories
Rick Astley*/
.superpowers/
+1
View File
@@ -0,0 +1 @@
[{"name":"generate-buildid","duration":272,"timestamp":244518298649,"id":4,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"load-custom-routes","duration":314,"timestamp":244518299029,"id":5,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"create-dist-dir","duration":333,"timestamp":244518299363,"id":6,"parentId":1,"tags":{},"startTime":1775262331362,"traceId":"b3ef0d179e8acedf"},{"name":"clean","duration":358,"timestamp":244518300558,"id":7,"parentId":1,"tags":{},"startTime":1775262331363,"traceId":"b3ef0d179e8acedf"},{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
+1
View File
@@ -0,0 +1 @@
[{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
+2
View File
@@ -29,6 +29,8 @@ tmp/
# Google Cloud
.gcloud/
*.json
# Allow i18n translation files
!translations/*.json
# Testing
.pytest_cache/
+9 -1
View File
@@ -26,7 +26,15 @@ COPY backend /app/backend
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
COPY karaoke_gen /app/karaoke_gen
COPY pyproject.toml README.md LICENSE /app/
RUN pip install --no-cache-dir -e .
# GPU images (MODEL_DIR set in base): use --no-deps to preserve pinned torch cu126
# and audio-separator[gpu]. Without this, pip upgrades torch to cu130 (breaks CUDA
# on Cloud Run L4 drivers) and reinstalls audio-separator[cpu] (breaks GPU ONNX).
# CPU images: normal install resolves all deps from pyproject.toml.
RUN if [ -n "$MODEL_DIR" ]; then \
pip install --no-cache-dir --no-deps -e .; \
else \
pip install --no-cache-dir -e .; \
fi
# Set environment variables
ENV PYTHONUNBUFFERED=1
+136
View File
@@ -0,0 +1,136 @@
# GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models
# This image is rebuilt only when deps or models change (infrequently).
#
# Build with: gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
# Or manually: docker build -f backend/Dockerfile.gpu-base -t karaoke-backend-gpu-base .
#
# Layer caching strategy:
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
# 2. CUDA library path configuration
# 3. pyproject.toml + package stubs (changes with dep updates)
# 4. pip install karaoke-gen deps + audio-separator[gpu] (slow, cached unless pyproject.toml changes)
# 5. Source code copy (changes every rebuild, but AFTER deps are installed)
# 6. spaCy model download (cached unless pip install layer changes)
# 7. Pre-downloaded ensemble preset models (~1-1.5 GB, cached unless pip layer changes)
FROM nvidia/cuda:12.6.3-runtime-ubuntu22.04
# Prevent interactive prompts during package installation
ENV DEBIAN_FRONTEND=noninteractive
# Install Python 3.11 from deadsnakes PPA and system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
software-properties-common \
&& add-apt-repository -y ppa:deadsnakes/ppa \
&& apt-get update && apt-get install -y --no-install-recommends \
# Python 3.11
python3.11 \
python3.11-dev \
python3.11-venv \
# Audio libraries
libsndfile1 \
libsox-dev \
sox \
# Build tools
build-essential \
# Utilities
curl \
xz-utils \
&& rm -rf /var/lib/apt/lists/* \
&& python3.11 --version
# Install comprehensive font support for international lyrics and symbols
# Noto fonts provide full Unicode coverage including:
# - Latin, Greek, Cyrillic (core)
# - CJK: Chinese, Japanese, Korean (~150MB)
# - Arabic, Hebrew, Thai, Hindi, and other scripts (extra)
# - Color emoji (limited support in libass, but available)
# - Musical symbols (♪ ♫ etc.)
# Note: This adds ~200-300MB to the image but ensures all languages render correctly
RUN apt-get update && apt-get install -y --no-install-recommends \
fonts-noto-core \
fonts-noto-cjk \
fonts-noto-extra \
fonts-noto-color-emoji \
fontconfig \
&& fc-cache -f \
&& rm -rf /var/lib/apt/lists/*
# Install FFmpeg from Ubuntu package
# The audio worker only uses FFmpeg for format conversion and padding, not
# encoding-intensive tasks, so the Debian package is sufficient. The static
# build from johnvansickle.com is used for the encoding worker instead.
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
# Set Python 3.11 as default and install pip
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
&& update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 \
&& curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11 \
&& python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel
# Set up CUDA library paths so GPU-accelerated packages can find CUDA libs at runtime
RUN echo '/usr/local/cuda/lib64' >> /etc/ld.so.conf.d/cuda.conf && ldconfig
# Environment configuration for CUDA and Python
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \
PATH=/usr/local/cuda/bin:$PATH \
PYTHONUNBUFFERED=1 \
MODEL_DIR=/models
# Set working directory
WORKDIR /app
# Copy ONLY dependency specification files first (changes less often than source code)
COPY pyproject.toml README.md LICENSE /app/
# Create minimal package stubs so pip can resolve the editable install
# pip install -e . needs package directories to exist but doesn't validate content
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
# Install all karaoke-gen Python dependencies (the slow part)
# BuildKit cache mount preserves downloaded wheels across builds
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --upgrade pip && \
pip install -e .
# Install audio-separator with GPU support (PyTorch + CUDA + onnxruntime-gpu)
# This is separate from pip install -e . to keep layer caching granular
#
# IMPORTANT: Install PyTorch cu126 FIRST, then audio-separator[gpu].
# The default audio-separator[gpu] pulls PyTorch cu130, but Cloud Run L4 GPUs
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
RUN --mount=type=cache,target=/root/.cache/pip \
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
pip install "audio-separator[gpu]"
# Now copy actual source code (AFTER deps installed, so code changes don't
# invalidate the expensive pip install layer in registry cache)
COPY karaoke_gen /app/karaoke_gen
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
COPY backend /app/backend
# Download spaCy language model for lyrics transcription
# Must be done at build time, not runtime (Cloud Run network restrictions)
RUN python -m spacy download en_core_web_sm
# Create models directory and pre-download ensemble preset models
# Baking models into the image eliminates cold-start model download latency.
# Total model size: ~1-1.5 GB for instrumental_clean + karaoke presets.
RUN mkdir -p /models
COPY backend/scripts/download_models.py /tmp/download_models.py
RUN python /tmp/download_models.py /models && \
rm /tmp/download_models.py && \
ls -lh /models/
# Label with build info
ARG BUILD_DATE
ARG BUILD_ID
ARG BASE_CONTENT_HASH
LABEL org.opencontainers.image.created="${BUILD_DATE}"
LABEL org.opencontainers.image.revision="${BUILD_ID}"
LABEL org.opencontainers.image.title="karaoke-backend-gpu-base"
LABEL org.opencontainers.image.description="GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models for karaoke-backend audio worker"
LABEL base.content.hash="${BASE_CONTENT_HASH}"
+2 -1
View File
@@ -11,10 +11,11 @@ import logging
from datetime import datetime, timedelta, timezone
from typing import Tuple, List, Optional, Any, Dict
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.i18n import t, get_locale_from_request
from backend.services.auth_service import UserType, AuthResult
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
from backend.services.job_manager import JobManager
+15 -10
View File
@@ -53,6 +53,7 @@ from backend.exceptions import InsufficientCreditsError
from backend.services.tracing import add_span_attribute
from backend.services.firestore_service import FirestoreService
from pathlib import Path
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -309,17 +310,17 @@ def _validate_and_prepare_selection(
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
# Get search results from state_data
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(status_code=400, detail="No search results available")
raise HTTPException(status_code=400, detail=t("en", "audioSearch.noSearchResults"))
if selection_index < 0 or selection_index >= len(search_results):
raise HTTPException(
status_code=400,
detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}"
detail=t("en", "audioSearch.invalidSelectionIndex", selection_index=selection_index, max=len(search_results)-1)
)
selected = search_results[selection_index]
@@ -594,12 +595,14 @@ async def search_audio(
- Interactive mode (default): Returns results, user calls /select endpoint
- Auto mode (auto_download=True): Automatically selects and downloads best
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(
status_code=403,
detail="Audio search is not available for this portal"
detail=t(locale, "audioSearch.notEnabled")
)
try:
@@ -966,12 +969,14 @@ async def search_audio_standalone(
Credits are checked here (early feedback) but NOT deducted — deduction
happens when the job is created via create-from-search.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(
status_code=403,
detail="Audio search is not available for this portal"
detail=t(locale, "audioSearch.notEnabled")
)
try:
@@ -1098,14 +1103,14 @@ async def get_audio_search_results(
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
search_results = job.state_data.get('audio_search_results', [])
if not search_results:
raise HTTPException(
status_code=400,
detail="No search results available for this job"
detail=t("en", "audioSearch.noSearchResults")
)
return {
@@ -1136,7 +1141,7 @@ async def select_audio_source(
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
# Verify job is awaiting selection
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
+41 -35
View File
@@ -9,7 +9,7 @@ Provides endpoints for:
import logging
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, BackgroundTasks
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request
from pydantic import BaseModel
from backend.services.credential_manager import (
@@ -18,6 +18,7 @@ from backend.services.credential_manager import (
CredentialCheckResult,
)
from backend.config import get_settings
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/auth", tags=["auth"])
@@ -125,15 +126,16 @@ async def get_credentials_status():
@router.get("/status/{service}", response_model=CredentialStatusResponse)
async def get_service_credential_status(service: str):
async def get_service_credential_status(service: str, request: Request):
"""
Get the status of a specific service's OAuth credentials.
Args:
service: One of "youtube", "gdrive", "dropbox"
"""
locale = get_locale_from_request(request)
manager = get_credential_manager()
if service == "youtube":
result = manager.check_youtube_credentials()
elif service == "gdrive":
@@ -141,7 +143,7 @@ async def get_service_credential_status(service: str):
elif service == "dropbox":
result = manager.check_dropbox_credentials()
else:
raise HTTPException(status_code=400, detail=f"Unknown service: {service}")
raise HTTPException(status_code=400, detail=t(locale, "auth.unknownService", service=service))
return CredentialStatusResponse(
service=result.service,
@@ -153,42 +155,43 @@ async def get_service_credential_status(service: str):
@router.post("/validate", response_model=CredentialValidationResponse)
async def validate_credentials(request: CredentialValidationRequest):
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
"""
Validate that credentials are available for requested services.
Use this before submitting a job to ensure all required
credentials are valid.
"""
locale = get_locale_from_request(http_request)
manager = get_credential_manager()
invalid_services = []
if request.youtube:
result = manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append("youtube")
if request.gdrive:
result = manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append("gdrive")
if request.dropbox:
result = manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append("dropbox")
if invalid_services:
return CredentialValidationResponse(
valid=False,
invalid_services=invalid_services,
message=f"The following services need re-authorization: {', '.join(invalid_services)}"
message=t(locale, "auth.invalidCredentials", services=", ".join(invalid_services))
)
return CredentialValidationResponse(
valid=True,
invalid_services=[],
message="All requested credentials are valid"
message=t(locale, "auth.validCredentials")
)
@@ -197,40 +200,41 @@ async def validate_credentials(request: CredentialValidationRequest):
# ===========================================================================
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None):
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
"""
Start YouTube device authorization flow.
This initiates a device auth flow that allows authorization
from any device. The user must visit the verification URL
and enter the user code.
Client credentials are loaded from Secret Manager ('youtube-client-credentials')
unless explicitly provided in the request body.
After starting, poll /auth/youtube/device/{device_code} to
check for completion.
"""
locale = get_locale_from_request(http_request) if http_request else "en"
manager = get_credential_manager()
try:
device_info = manager.start_youtube_device_auth(
client_id=request.client_id if request else None,
client_secret=request.client_secret if request else None
)
return DeviceAuthStartResponse(
device_code=device_info.device_code,
user_code=device_info.user_code,
verification_url=device_info.verification_url,
expires_in=device_info.expires_in,
interval=device_info.interval,
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
instructions=t(locale, "auth.youtubeAuthInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
)
except Exception as e:
logger.error(f"Failed to start YouTube device auth: {e}")
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "auth.youtubeAuthStartFailed", error=str(e)))
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
@@ -259,35 +263,36 @@ async def poll_youtube_device_auth(device_code: str):
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None):
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
"""
Start Google Drive device authorization flow.
Client credentials are loaded from Secret Manager ('gdrive-client-credentials')
unless explicitly provided in the request body.
After starting, poll /auth/gdrive/device/{device_code} to check for completion.
"""
locale = get_locale_from_request(http_request) if http_request else "en"
manager = get_credential_manager()
try:
device_info = manager.start_gdrive_device_auth(
client_id=request.client_id if request else None,
client_secret=request.client_secret if request else None
)
return DeviceAuthStartResponse(
device_code=device_info.device_code,
user_code=device_info.user_code,
verification_url=device_info.verification_url,
expires_in=device_info.expires_in,
interval=device_info.interval,
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
instructions=t(locale, "auth.gdriveLinkInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
)
except Exception as e:
logger.error(f"Failed to start Google Drive device auth: {e}")
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "auth.gdriveAuthStartFailed", error=str(e)))
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
@@ -311,19 +316,20 @@ async def poll_gdrive_device_auth(device_code: str):
# ===========================================================================
@router.post("/test-alert")
async def test_credential_alert(background_tasks: BackgroundTasks):
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
"""
Test the credential alert mechanism.
Sends a test alert to Discord if configured.
"""
locale = get_locale_from_request(request)
settings = get_settings()
discord_url = settings.get_secret("discord-alert-webhook")
if not discord_url:
raise HTTPException(
status_code=400,
detail="Discord alert webhook not configured"
detail=t(locale, "auth.discordAlertNotConfigured")
)
manager = get_credential_manager()
+13 -6
View File
@@ -14,6 +14,7 @@ from pydantic import BaseModel, Field
from backend.api.dependencies import require_auth
from backend.services.auth_service import AuthResult
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -26,7 +27,7 @@ RATE_LIMIT_MAX_REQUESTS = 20
RATE_LIMIT_WINDOW_SECONDS = 60
def _check_rate_limit(user_email: str) -> None:
def _check_rate_limit(user_email: str, locale: str = "en") -> None:
"""Check per-user rate limit. Raises 429 if exceeded."""
now = time.monotonic()
window_start = now - RATE_LIMIT_WINDOW_SECONDS
@@ -37,12 +38,12 @@ def _check_rate_limit(user_email: str) -> None:
# Remove expired entries
timestamps = _rate_limit_windows[user_email]
_rate_limit_windows[user_email] = [t for t in timestamps if t > window_start]
_rate_limit_windows[user_email] = [ts for ts in timestamps if ts > window_start]
if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS:
raise HTTPException(
status_code=429,
detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.",
detail=t(locale, "catalog.rateLimitExceeded", max_requests=RATE_LIMIT_MAX_REQUESTS),
)
_rate_limit_windows[user_email].append(now)
@@ -107,6 +108,7 @@ class CommunityCheckResponse(BaseModel):
@router.get("/artists", response_model=list[ArtistResult])
async def search_artists(
request: Request,
q: str = Query(..., min_length=2, description="Artist name search query"),
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
auth_result: AuthResult = Depends(require_auth),
@@ -115,7 +117,8 @@ async def search_artists(
Search for artists by name. Returns canonical MusicBrainz/Spotify artist data
for autocomplete in job creation forms.
"""
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.catalog_proxy_service import search_artists
results = await search_artists(q, limit)
@@ -124,6 +127,7 @@ async def search_artists(
@router.get("/tracks", response_model=list[TrackResult])
async def search_tracks(
request: Request,
q: str = Query(..., min_length=2, description="Track name search query"),
artist: Optional[str] = Query(None, description="Filter by artist name"),
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
@@ -133,7 +137,8 @@ async def search_tracks(
Search for tracks by name, optionally filtered by artist.
Returns canonical Spotify track data for autocomplete in job creation forms.
"""
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.catalog_proxy_service import search_tracks
results = await search_tracks(q, artist, limit)
@@ -142,6 +147,7 @@ async def search_tracks(
@router.post("/community-check", response_model=CommunityCheckResponse)
async def check_community_versions(
request: Request,
body: CommunityCheckRequest,
auth_result: AuthResult = Depends(require_auth),
):
@@ -149,7 +155,8 @@ async def check_community_versions(
Check if a song already has community-approved karaoke versions on YouTube
via karaokenerds.com. Non-blocking — just informs the user.
"""
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.karaokenerds_service import check_community_versions
result = await check_community_versions(body.artist, body.title)
+35 -22
View File
@@ -45,6 +45,7 @@ from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
)
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -350,7 +351,8 @@ async def _trigger_audio_worker_only(job_id: str) -> None:
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
color_overrides: Optional[Dict[str, str]] = None
color_overrides: Optional[Dict[str, str]] = None,
locale: str = "en"
) -> Tuple[str, Dict[str, str], Optional[str]]:
"""
Prepare theme style files for a job.
@@ -359,6 +361,7 @@ def _prepare_theme_for_job(
job_id: The job ID
theme_id: Theme identifier
color_overrides: Optional color override dict
locale: Locale for error messages
Returns:
Tuple of (style_params_gcs_path, style_assets, youtube_description)
@@ -372,7 +375,7 @@ def _prepare_theme_for_job(
if not theme_service.theme_exists(theme_id):
raise HTTPException(
status_code=400,
detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes."
detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id)
)
# Convert dict to ColorOverrides model if provided
@@ -465,6 +468,8 @@ async def upload_and_create_job(
The style_params JSON can reference the uploaded images/fonts by their original
filenames, and the backend will update the paths to GCS locations.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
@@ -699,7 +704,7 @@ async def upload_and_create_job(
if effective_theme_id and not has_custom_style_files:
try:
theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, parsed_color_overrides or None
job_id, effective_theme_id, parsed_color_overrides or None, locale=locale
)
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
except HTTPException:
@@ -896,7 +901,7 @@ async def upload_and_create_job(
return {
"status": "success",
"job_id": job_id,
"message": "Files uploaded successfully. Processing started.",
"message": t(locale, "fileUpload.uploadSuccess"),
"filename": file.filename,
"style_assets_uploaded": list(style_assets.keys()) if style_assets else [],
"server_version": VERSION,
@@ -909,7 +914,7 @@ async def upload_and_create_job(
raise
except Exception as e:
logger.error(f"Error uploading files: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadError", error=str(e))) from e
# ============================================================================
@@ -1110,6 +1115,8 @@ async def create_job_with_upload_urls(
- Works with any HTTP client (no HTTP/2 required)
- Resumable uploads possible with GCS
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
@@ -1121,14 +1128,14 @@ async def create_job_with_upload_urls(
try:
# Validate files list
if not body.files:
raise HTTPException(status_code=400, detail="At least one file is required")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
# Check that audio file is included
audio_files = [f for f in body.files if f.file_type == 'audio']
if not audio_files:
raise HTTPException(status_code=400, detail="An audio file is required")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
if len(audio_files) > 1:
raise HTTPException(status_code=400, detail="Only one audio file is allowed")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.multipleAudioFilesNotAllowed"))
# Validate file types and extensions
for file_info in body.files:
@@ -1271,7 +1278,7 @@ async def create_job_with_upload_urls(
# If theme is set and no style_params uploaded, prepare theme style now
if effective_theme_id and not has_style_params_upload:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
update_data = {
@@ -1307,7 +1314,7 @@ async def create_job_with_upload_urls(
return CreateJobWithUploadUrlsResponse(
status="success",
job_id=job_id,
message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete",
message=t(locale, "fileUpload.urlCreationSuccess"),
upload_urls=upload_urls,
server_version=VERSION
)
@@ -1318,12 +1325,13 @@ async def create_job_with_upload_urls(
raise
except Exception as e:
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.urlCreationError", error=str(e))) from e
@router.post("/jobs/{job_id}/uploads-complete")
async def mark_uploads_complete(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
body: UploadsCompleteRequest,
auth_result: AuthResult = Depends(require_auth)
@@ -1342,22 +1350,23 @@ async def mark_uploads_complete(
- Update job with GCS paths
- Trigger audio and lyrics workers
"""
locale = get_locale_from_request(request)
try:
# Get job and verify it exists
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Verify job is in pending state
if job.status != JobStatus.PENDING:
raise HTTPException(
status_code=400,
detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads."
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Validate required files
if 'audio' not in body.uploaded_files:
raise HTTPException(status_code=400, detail="Audio file upload is required")
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
# Build GCS paths for uploaded files and validate they exist
update_data = {}
@@ -1495,7 +1504,7 @@ async def mark_uploads_complete(
return {
"status": "success",
"job_id": job_id,
"message": "Uploads validated. Processing started.",
"message": t(locale, "fileUpload.uploadsCompleteSuccess"),
"files_validated": body.uploaded_files,
"style_assets": list(style_assets.keys()) if style_assets else [],
"server_version": VERSION,
@@ -1506,7 +1515,7 @@ async def mark_uploads_complete(
raise
except Exception as e:
logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e)) from e
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadsCompleteError", error=str(e))) from e
# ============================================================================
@@ -1589,6 +1598,8 @@ async def create_job_from_url(
Note: YouTube rate limiting may cause occasional download failures.
The backend will retry automatically.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.youtube_url:
@@ -1744,7 +1755,7 @@ async def create_job_from_url(
# If theme is set, prepare theme style now
if effective_theme_id:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
update_data = {
@@ -1803,7 +1814,7 @@ async def create_job_from_url(
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
raise HTTPException(
status_code=500,
detail=f"YouTube download failed: {e}"
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
else:
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
@@ -1897,6 +1908,8 @@ async def create_finalise_only_job(
The endpoint returns signed URLs for uploading all the prep files.
"""
locale = get_locale_from_request(request)
# Check tenant feature flag - finalise-only requires file upload capability
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
@@ -2057,7 +2070,7 @@ async def create_finalise_only_job(
# If theme is set and no style_params uploaded, prepare theme style now
if effective_theme_id and not has_style_params_upload:
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, body.color_overrides
job_id, effective_theme_id, body.color_overrides, locale=locale
)
# Update job with theme style data
update_data = {
+141 -3
View File
@@ -5,10 +5,12 @@ import os
import logging
import subprocess
import platform
from fastapi import APIRouter
from typing import Dict, Any, Optional
from fastapi import APIRouter, Depends
from typing import Dict, Any, Optional, Tuple
from backend.version import VERSION
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
from backend.api.dependencies import optional_auth
from backend.services.auth_service import UserType
from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
@@ -308,6 +310,30 @@ async def flacfetch_health() -> Dict[str, Any]:
}
def check_audio_separator_status() -> Dict[str, Any]:
"""Check audio separator availability without calling the remote GPU service."""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
except Exception:
pkg_version = None
return {
"available": True,
"status": "ok",
"version": pkg_version,
}
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
@@ -341,6 +367,118 @@ async def audio_separator_health() -> Dict[str, Any]:
}
def _get_encoding_worker_manager():
"""Get the EncodingWorkerManager instance. Separated for testability."""
try:
encoding_service = get_encoding_service()
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
return encoding_service._worker_manager
except Exception:
pass
return None
@router.get("/health/system-status")
async def system_status(
auth: Optional[Tuple] = Depends(optional_auth),
) -> Dict[str, Any]:
"""
Aggregated system status for all services.
Returns basic info for everyone. Admin users get additional
blue-green deployment details for the encoder.
"""
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
# Fetch all health statuses concurrently
import asyncio
encoding_task = check_encoding_worker_status()
flacfetch_task = check_flacfetch_service_status()
encoding_status, flacfetch_status = await asyncio.gather(
encoding_task, flacfetch_task
)
separator_status = check_audio_separator_status()
# Build frontend service info (from env vars baked at build time — returned as-is)
frontend_svc = {
"status": "ok",
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
}
# Build backend service info
backend_svc = {
"status": "ok",
"version": VERSION,
"deployed_at": STARTUP_TIME,
}
if COMMIT_SHA:
backend_svc["commit_sha"] = COMMIT_SHA
if PR_NUMBER:
backend_svc["pr_number"] = PR_NUMBER
if PR_TITLE:
backend_svc["pr_title"] = PR_TITLE
# Build encoder service info
encoder_svc = {
"status": "ok" if encoding_status.get("available") else "offline",
"version": encoding_status.get("wheel_version"),
"active_jobs": encoding_status.get("active_jobs", 0),
}
# Build flacfetch service info
flacfetch_svc = {
"status": "ok" if flacfetch_status.get("available") else "offline",
"version": flacfetch_status.get("version"),
}
# Build separator service info
separator_svc = {
"status": "ok" if separator_status.get("available") else "offline",
"version": separator_status.get("version"),
}
# Admin-only: blue-green encoder details from Firestore
if is_admin:
manager = _get_encoding_worker_manager()
if manager:
try:
config = manager.get_config()
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
"primary_version": config.primary_version,
"primary_deployed_at": config.primary_deployed_at,
"secondary_vm": config.secondary_vm,
"secondary_ip": config.secondary_ip,
"secondary_version": config.secondary_version,
"secondary_deployed_at": config.secondary_deployed_at,
"last_swap_at": config.last_swap_at,
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
# Add error details for offline services
if not flacfetch_status.get("available"):
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
if not separator_status.get("available"):
separator_svc["admin_details"] = {"error": separator_status.get("error")}
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
return {
"services": {
"frontend": frontend_svc,
"backend": backend_svc,
"encoder": encoder_svc,
"flacfetch": flacfetch_svc,
"separator": separator_svc,
}
}
@router.get("/health/detailed")
async def detailed_health_check() -> Dict[str, Any]:
"""
+192 -108
View File
@@ -38,6 +38,7 @@ from backend.services.tracing import add_span_attribute
from backend.api.dependencies import require_admin, require_auth
from backend.services.auth_service import AuthResult
from backend.services.metrics import metrics
from backend.i18n import t, get_locale_from_request
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
@@ -84,6 +85,7 @@ async def create_job(
3. Both workers update job state as they progress
4. When both complete, job transitions to AWAITING_REVIEW
"""
locale = get_locale_from_request(http_request)
try:
# Determine job owner email:
# All authentication methods must provide a user_email for job ownership
@@ -95,7 +97,7 @@ async def create_job(
logger.error("Authentication succeeded but no user_email provided")
raise HTTPException(
status_code=500,
detail="Authentication error: no user identity available"
detail=t(locale, "jobs.authError")
)
# Admins can optionally create jobs on behalf of other users
@@ -114,7 +116,7 @@ async def create_job(
if not effective_theme_id:
raise HTTPException(
status_code=422,
detail="No default theme configured. Please contact support or specify a theme_id."
detail=t(locale, "jobs.noDefaultTheme")
)
logger.info(f"Applying default theme: {effective_theme_id}")
@@ -156,7 +158,7 @@ async def create_job(
return JobResponse(
status="success",
job_id=job.job_id,
message="Job created successfully. Processing started."
message=t(locale, "jobs.created")
)
except InsufficientCreditsError:
raise
@@ -172,16 +174,18 @@ async def create_job(
@router.get("/{job_id}", response_model=Job)
async def get_job(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> Job:
"""Get job status and details."""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership - users can only see their own jobs, admins can see all
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
# If job is complete, include download URLs
if job.status == JobStatus.COMPLETE:
@@ -236,6 +240,7 @@ class EditTrackResponse(BaseModel):
async def edit_completed_track(
job_id: str,
request: EditTrackRequest,
http_request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth),
):
@@ -249,30 +254,31 @@ async def edit_completed_track(
No additional credits are consumed — the original credit covers re-edits.
"""
locale = get_locale_from_request(http_request)
import re
from datetime import timezone
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to edit this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionEdit"))
# Only completed jobs can be edited
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
raise HTTPException(
status_code=400,
detail=f"Only completed jobs can be edited. Current status: {job.status}"
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Prevent editing if outputs already deleted (edit already in progress)
if job.outputs_deleted_at:
raise HTTPException(
status_code=400,
detail="This job is already being edited (outputs were already deleted)"
detail=t(locale, "jobs.alreadyBeingEdited")
)
user_email = auth_result.user_email or "unknown"
@@ -397,8 +403,7 @@ async def edit_completed_track(
if critical_failures:
raise HTTPException(
status_code=500,
detail=f"Cleanup failed for {', '.join(critical_failures)}. "
f"Job not modified. Please try again or contact support."
detail=t(locale, "jobs.cleanupFailed", services=", ".join(critical_failures))
)
# --- Phase 2: Update job record ---
@@ -504,7 +509,7 @@ async def edit_completed_track(
return EditTrackResponse(
status="success",
job_id=job_id,
message="Track reopened for editing. Previous outputs have been removed.",
message=t(locale, "jobs.reopened"),
review_url=f"/app/jobs#/{job_id}/review",
review_token=review_token,
metadata_updated=metadata_updated,
@@ -519,7 +524,7 @@ _SUMMARY_STATE_DATA_KEYS = {
'backing_vocals_analysis', 'visibility_change_in_progress',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
@@ -538,6 +543,21 @@ def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
return data
def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[str, Any]]:
"""Filter job dicts by case-insensitive substring match across key fields."""
if not search:
return jobs
term = search.lower()
results = []
for job in jobs:
searchable = " ".join(
str(job.get(f) or "") for f in ("job_id", "artist", "title", "audio_search_artist", "audio_search_title")
)
if term in searchable.lower():
results.append(job)
return results
@router.get("", response_model=None)
async def list_jobs(
request: Request,
@@ -550,6 +570,7 @@ async def list_jobs(
limit: int = 100,
fields: Optional[str] = None,
hide_completed: bool = False,
search: Optional[str] = None,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -568,6 +589,7 @@ async def list_jobs(
limit: Maximum number of jobs to return (default 100)
fields: Set to "summary" for reduced payload with only dashboard-required fields
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
search: Text search filter - matches against artist, title, audio_search_artist, audio_search_title, and job_id (case-insensitive substring). Only works with fields=summary.
Returns:
List of jobs matching filters, ordered by created_at descending.
@@ -581,17 +603,19 @@ async def list_jobs(
created_after_dt = None
created_before_dt = None
locale = get_locale_from_request(request)
if created_after:
try:
created_after_dt = datetime.fromisoformat(created_after.replace('Z', '+00:00'))
except ValueError as e:
raise HTTPException(status_code=400, detail=f"Invalid created_after format: {created_after}") from e
raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_after", value=created_after)) from e
if created_before:
try:
created_before_dt = datetime.fromisoformat(created_before.replace('Z', '+00:00'))
except ValueError as e:
raise HTTPException(status_code=400, detail=f"Invalid created_before format: {created_before}") from e
raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_before", value=created_before)) from e
# Determine user_email filter based on admin status
# Admins see all jobs, regular users only see their own
@@ -615,6 +639,8 @@ async def list_jobs(
# --- Summary mode: field-projected query returning dicts ---
if fields == "summary":
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
# When searching, fetch more results and filter in Python
fetch_limit = 1000 if search else limit
jobs_dicts = job_manager.list_jobs_summary(
status=status,
exclude_statuses=exclude_statuses,
@@ -624,13 +650,18 @@ async def list_jobs(
created_before=created_before_dt,
user_email=user_email_filter,
tenant_id=effective_tenant_id,
limit=limit,
limit=fetch_limit,
)
# Exclude test user jobs (Python-side, same as full mode)
if exclude_test and auth_result.is_admin:
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
# Apply search filter if provided
if search:
jobs_dicts = _search_filter_jobs(jobs_dicts, search)
jobs_dicts = jobs_dicts[:limit] # Apply original limit after filtering
# Safety-net pruning (in case Firestore returned extra nested keys)
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
@@ -659,24 +690,26 @@ async def list_jobs(
raise
except Exception as e:
logger.error(f"Error listing jobs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.listError", error=str(e)))
@router.delete("/{job_id}")
async def delete_job(
job_id: str,
request: Request,
delete_files: bool = True,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""Delete a job and optionally its output files."""
locale = get_locale_from_request(request)
try:
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership - users can only delete their own jobs
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to delete this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete"))
# Recycle any unreturned brand code before deleting the job record
state_data = job.state_data or {}
@@ -703,11 +736,12 @@ async def delete_job(
raise
except Exception as e:
logger.error(f"Error deleting job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.deleteError", job_id=job_id, error=str(e)))
@router.delete("")
async def bulk_delete_jobs(
request: Request,
environment: Optional[str] = None,
client_id: Optional[str] = None,
status: Optional[JobStatus] = None,
@@ -739,13 +773,15 @@ async def bulk_delete_jobs(
"""
from datetime import datetime
locale = get_locale_from_request(request)
# Require at least one filter to prevent accidental deletion of all jobs
if not any([environment, client_id, status, created_before]):
raise HTTPException(
status_code=400,
detail="At least one filter (environment, client_id, status, created_before) is required"
detail=t(locale, "jobs.deletionRequiresFilters")
)
# Require explicit confirmation
if not confirm:
# Return preview of what would be deleted
@@ -766,7 +802,7 @@ async def bulk_delete_jobs(
return {
"status": "preview",
"message": "Add &confirm=true to execute deletion",
"message": t(locale, "jobs.deletionPreview"),
"jobs_to_delete": len(jobs),
"sample_jobs": [
{
@@ -808,7 +844,7 @@ async def bulk_delete_jobs(
except Exception as e:
logger.error(f"Error bulk deleting jobs: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.bulkDeleteError", error=str(e)))
# ============================================================================
@@ -818,6 +854,7 @@ async def bulk_delete_jobs(
@router.get("/{job_id}/review-data")
async def get_review_data(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> Dict[str, Any]:
"""
@@ -826,18 +863,19 @@ async def get_review_data(
Returns corrections JSON URL and audio URL.
Frontend loads these to render the review UI.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not ready for review (current status: {job.status})"
detail=t(locale, "jobs.reviewNotReady", status=job.status)
)
# Get URLs from file_urls
@@ -856,13 +894,13 @@ async def get_review_data(
if not corrections_url:
raise HTTPException(
status_code=500,
detail="Corrections data not available"
detail=t(locale, "jobs.correctionsUnavailable")
)
if not audio_url:
raise HTTPException(
status_code=500,
detail="Audio not available for review"
detail=t(locale, "jobs.audioUnavailable")
)
# Generate signed URLs for direct access
@@ -882,6 +920,7 @@ async def get_review_data(
async def start_review(
job_id: str,
request: StartReviewRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -889,22 +928,23 @@ async def start_review(
This helps track that the user is actively working on the review.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
success = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_REVIEW,
message="User started reviewing lyrics"
)
if not success:
raise HTTPException(status_code=400, detail="Cannot start review")
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
return {"status": "success", "job_status": "in_review"}
@@ -913,6 +953,7 @@ async def start_review(
async def submit_corrections(
job_id: str,
submission: CorrectionsSubmission,
http_request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -924,18 +965,19 @@ async def submit_corrections(
Can be called multiple times to save progress.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.jobNotInReviewState", status=job.status)
)
try:
@@ -971,7 +1013,7 @@ async def submit_corrections(
return {
"status": "success",
"job_status": "in_review",
"message": "Corrections saved. Call /complete-review when done."
"message": t(locale, "jobs.correctionsProcessing")
}
except Exception as e:
@@ -983,6 +1025,7 @@ async def submit_corrections(
async def submit_edit_log(
job_id: str,
edit_log: Dict[str, Any],
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -993,12 +1036,13 @@ async def submit_edit_log(
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
session_id = edit_log.get("session_id", "unknown")
entries = edit_log.get("entries", [])
@@ -1025,13 +1069,14 @@ async def submit_edit_log(
except Exception as e:
logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.editLogSaveFailed", job_id=job_id, error=str(e)))
@router.post("/{job_id}/create-custom-instrumental")
async def create_custom_instrumental(
job_id: str,
request: CreateCustomInstrumentalRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -1040,17 +1085,18 @@ async def create_custom_instrumental(
Downloads the clean instrumental and backing vocals stems, applies mute
regions, combines them, uploads to GCS, and returns a signed URL for playback.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.jobNotInReviewState", status=job.status)
)
# Get stem paths from job
@@ -1061,7 +1107,7 @@ async def create_custom_instrumental(
if not clean_path or not backing_path:
raise HTTPException(
status_code=400,
detail="Job missing required stems (instrumental_clean and/or backing_vocals)"
detail=t(locale, "jobs.stemsMissing")
)
try:
@@ -1109,12 +1155,13 @@ async def create_custom_instrumental(
except Exception as e:
logger.error(f"Error creating custom instrumental for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.customInstrumentalFailed", job_id=job_id, error=str(e)))
@router.post("/{job_id}/upload-instrumental")
async def upload_custom_instrumental(
job_id: str,
request: Request,
file: UploadFile = File(...),
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -1125,17 +1172,18 @@ async def upload_custom_instrumental(
The file is stored to GCS and its path recorded in the job's stems metadata.
The user can then select 'custom' as their instrumental_selection when completing review.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.reviewNotInState", status=job.status)
)
# Determine extension from filename or content type
@@ -1178,11 +1226,9 @@ async def upload_custom_instrumental(
if diff > 0.5:
raise HTTPException(
status_code=400,
detail=(
f"Duration mismatch: uploaded file is {upload_duration:.1f}s "
f"but original audio is {original_duration:.1f}s. "
f"The instrumental must be exactly {original_duration:.1f}s (±0.5s)."
),
detail=t(locale, "jobs.durationMismatch",
upload_duration=f"{upload_duration:.1f}",
original_duration=f"{original_duration:.1f}"),
)
# Convert to FLAC for consistency with the rest of the pipeline
@@ -1201,7 +1247,7 @@ async def upload_custom_instrumental(
raise
except Exception as e:
logger.error(f"Job {job_id}: Error processing uploaded instrumental: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to process audio file: {str(e)}")
raise HTTPException(status_code=500, detail=t(locale, "jobs.audioProcessingFailed", error=str(e)))
finally:
if tmp_path and os.path.exists(tmp_path):
os.unlink(tmp_path)
@@ -1254,6 +1300,7 @@ async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageS
@router.post("/{job_id}/complete-review")
async def complete_review(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth),
body: Optional[CompleteReviewRequest] = None
@@ -1270,18 +1317,19 @@ async def complete_review(
3. Worker uses OutputGenerator to create with_vocals.mkv
4. Job transitions to INSTRUMENTAL_SELECTED then GENERATING_VIDEO
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t(locale, "jobs.reviewNotInState", status=job.status)
)
# Check for 0-segment lyrics — fail early with user-friendly message
@@ -1296,12 +1344,7 @@ async def complete_review(
if segment_count == 0 and len(corrected_segments) == 0:
raise HTTPException(
status_code=400,
detail=(
"Cannot complete review: no lyrics were detected in the audio. "
"This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). "
"You can go back and paste lyrics manually using 'Replace All', "
"or cancel this job and try again with an audio file that contains vocals."
)
detail=t(locale, "jobs.noLyricsDetected")
)
try:
@@ -1328,18 +1371,19 @@ async def complete_review(
return {
"status": "success",
"job_status": "review_complete",
"message": "Review complete. Video rendering started."
"message": t(locale, "jobs.reviewCompleteStartRendering")
}
except Exception as e:
logger.error(f"Error completing review for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.reviewCompleteError", job_id=job_id, error=str(e)))
@router.post("/{job_id}/select-instrumental")
async def select_instrumental(
job_id: str,
selection: InstrumentalSelection,
request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -1359,18 +1403,19 @@ async def select_instrumental(
Returns:
Status and confirmation of selection
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status != JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job not awaiting instrumental selection (current status: {job.status})"
detail=t(locale, "jobs.reviewNotInState", status=job.status)
)
try:
@@ -1396,17 +1441,18 @@ async def select_instrumental(
"status": "success",
"job_status": "instrumental_selected",
"selection": selection.selection,
"message": "Instrumental selected. Video generation started."
"message": t(locale, "jobs.instrumentalSelected")
}
except Exception as e:
logger.error(f"Error selecting instrumental for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t(locale, "jobs.instrumentalSelectionError", job_id=job_id, error=str(e)))
@router.get("/{job_id}/download-urls")
async def get_download_urls(
job_id: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -1415,26 +1461,21 @@ async def get_download_urls(
Returns a dictionary mapping file types to download URLs.
Uses the streaming download endpoint which proxies through the backend.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status != JobStatus.COMPLETE:
raise HTTPException(
status_code=400,
detail=f"Job not complete (current status: {job.status})"
)
file_urls = job.file_urls or {}
download_urls = {}
# Build download URLs using the streaming endpoint
base_url = f"/api/jobs/{job_id}/download"
for category, files in file_urls.items():
if isinstance(files, dict):
download_urls[category] = {}
@@ -1444,7 +1485,7 @@ async def get_download_urls(
elif isinstance(files, str) and files:
# For single-file categories, use the category name as the file_key
download_urls[category] = f"{base_url}/{category}/{category}"
return {
"job_id": job_id,
"artist": job.artist,
@@ -1471,6 +1512,7 @@ async def download_file(
job_id: str,
category: str,
file_key: str,
request: Request,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -1479,23 +1521,18 @@ async def download_file(
This endpoint proxies the file from GCS through the backend,
so no client-side authentication is required.
"""
locale = get_locale_from_request(request)
from fastapi.responses import StreamingResponse
import tempfile
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
if job.status != JobStatus.COMPLETE:
raise HTTPException(
status_code=400,
detail=f"Job not complete (current status: {job.status})"
)
file_urls = job.file_urls or {}
category_files = file_urls.get(category)
@@ -1587,6 +1624,7 @@ async def download_file(
async def cancel_job(
job_id: str,
request: CancelJobRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
"""
@@ -1594,13 +1632,14 @@ async def cancel_job(
Jobs can be cancelled at any stage before completion.
"""
locale = get_locale_from_request(http_request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to cancel this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
success = job_manager.cancel_job(job_id, reason=request.reason)
@@ -1617,6 +1656,7 @@ async def cancel_job(
@router.post("/{job_id}/retry")
async def retry_job(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> dict:
@@ -1632,20 +1672,21 @@ async def retry_job(
The retry logic determines the appropriate stage to resume from
based on what files/state already exist.
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to retry this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]:
raise HTTPException(
status_code=400,
detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})"
detail=t(locale, "jobs.notCompleted", status=job.status)
)
try:
# Determine retry point based on what's already complete
error_details = job.error_details or {}
@@ -1693,11 +1734,14 @@ async def retry_job(
"retry_stage": "video_generation"
}
# If we have corrections and screens but no video, retry render
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
# If we have corrections, screens, AND review was completed, retry render
# Review completion is proven by instrumental_selection in state_data
# (set only when user submits the review endpoint)
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title') and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
# Clear error state and reset worker progress for idempotency
job_manager.update_job(job_id, {
@@ -1717,16 +1761,48 @@ async def retry_job(
status_code=500,
detail="Failed to transition job status for retry"
)
# Trigger render video worker
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
return {
"status": "success",
"job_status": "review_complete",
"message": "Job retry started from render stage",
"retry_stage": "render_video"
}
# If we have corrections and screens but review was NOT completed,
# return to awaiting_review so the user can review lyrics
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
# Clear error state
job_manager.update_job(job_id, {
'error_message': None,
'error_details': None,
})
# Transition to AWAITING_REVIEW so user can review lyrics
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_REVIEW,
progress=55,
message=f"Ready for review. Please review lyrics and select your instrumental."
):
raise HTTPException(
status_code=500,
detail="Failed to transition job status for retry"
)
return {
"status": "success",
"job_status": "awaiting_review",
"message": "Job retry: returning to lyrics review (review was not completed before failure)",
"retry_stage": "awaiting_review"
}
# If we have stems and corrections, retry from screens generation
elif (file_urls.get('stems', {}).get('instrumental_clean') and
@@ -1859,6 +1935,7 @@ async def retry_job(
@router.get("/{job_id}/logs")
async def get_worker_logs(
job_id: str,
request: Request,
since_index: int = 0,
worker: Optional[str] = None,
auth_result: AuthResult = Depends(require_auth)
@@ -1885,13 +1962,14 @@ async def get_worker_logs(
"total_logs": 42
}
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# Check ownership - users can only see logs for their own jobs
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access logs for this job")
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
logs = job_manager.get_worker_logs(job_id, since_index=since_index, worker=worker)
total = job_manager.get_worker_logs_count(job_id)
@@ -1906,6 +1984,7 @@ async def get_worker_logs(
@router.post("/{job_id}/cleanup-distribution")
async def cleanup_distribution(
job_id: str,
request: Request,
delete_job: bool = True,
auth_result: AuthResult = Depends(require_admin)
) -> dict:
@@ -1925,9 +2004,10 @@ async def cleanup_distribution(
Returns:
Cleanup results for each service
"""
locale = get_locale_from_request(request)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
state_data = job.state_data or {}
results = {
@@ -2144,6 +2224,8 @@ async def create_job_from_search(
Credit deduction happens here (inside job_manager.create_job).
"""
locale = get_locale_from_request(request)
# Lazy imports from audio_search to avoid circular imports at module level
from backend.api.routes.audio_search import (
_validate_and_prepare_selection,
@@ -2154,7 +2236,7 @@ async def create_job_from_search(
try:
user_email = auth_result.user_email
if not user_email:
raise HTTPException(status_code=401, detail="Authentication required")
raise HTTPException(status_code=401, detail=t(locale, "jobs.authError"))
# Read the session non-destructively for validation.
# consume_search_session (atomic read+delete) is called later, just before job creation,
@@ -2281,7 +2363,7 @@ async def create_job_from_search(
from backend.api.routes.file_upload import _prepare_theme_for_job
try:
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
job_id, effective_theme_id, {}
job_id, effective_theme_id, {}, locale=locale
)
theme_update = {
'style_params_gcs_path': style_params_path,
@@ -2342,6 +2424,7 @@ async def create_job_from_search(
async def change_visibility(
job_id: str,
request: ChangeVisibilityRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth),
):
"""
@@ -2355,10 +2438,11 @@ async def change_visibility(
- Resets custom styling to default Nomad theme
- Regenerates screens, re-renders video, publishes publicly
"""
locale = get_locale_from_request(http_request)
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
user_email = auth_result.user_email or "unknown"
is_admin = auth_result.is_admin
+24 -12
View File
@@ -18,6 +18,7 @@ from backend.config import get_settings
from backend.api.dependencies import require_auth, require_admin
from backend.services.auth_service import AuthResult
from backend.services.push_notification_service import get_push_notification_service
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -127,18 +128,20 @@ async def subscribe_push(
1. Request body tenant_id field (explicit from frontend)
2. Tenant middleware (X-Tenant-ID header or subdomain detection)
"""
locale = get_locale_from_request(http_request)
settings = get_settings()
if not settings.enable_push_notifications:
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
# Validate keys
if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys:
raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)")
raise HTTPException(status_code=400, detail=t(locale, "push.missingEncryptionKeys"))
# Resolve tenant_id: prefer explicit from body, fall back to middleware
tenant_id = subscribe_request.tenant_id
@@ -154,17 +157,18 @@ async def subscribe_push(
)
if not success:
raise HTTPException(status_code=500, detail="Failed to save subscription")
raise HTTPException(status_code=500, detail=t(locale, "push.subscriptionSaveFailed"))
return SubscribeResponse(
status="success",
message="Push subscription registered successfully"
message=t(locale, "push.subscriptionRegistered")
)
@router.post("/unsubscribe", response_model=UnsubscribeResponse)
async def unsubscribe_push(
request: UnsubscribeRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -172,8 +176,10 @@ async def unsubscribe_push(
Requires authentication. Users can only remove their own subscriptions.
"""
locale = get_locale_from_request(http_request)
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
@@ -186,17 +192,18 @@ async def unsubscribe_push(
# Don't error if subscription wasn't found - might already be removed
return UnsubscribeResponse(
status="success",
message="Subscription removed (or was not found)"
message=t(locale, "push.subscriptionNotFound")
)
return UnsubscribeResponse(
status="success",
message="Push subscription removed successfully"
message=t(locale, "push.subscriptionRemoved")
)
@router.get("/subscriptions", response_model=SubscriptionsListResponse)
async def list_subscriptions(
request: Request,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -204,8 +211,10 @@ async def list_subscriptions(
Requires authentication.
"""
locale = get_locale_from_request(request)
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
@@ -220,6 +229,7 @@ async def list_subscriptions(
@router.post("/test", response_model=TestNotificationResponse)
async def send_test_notification(
request: TestNotificationRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_admin)
):
"""
@@ -227,12 +237,14 @@ async def send_test_notification(
Admin only. Useful for testing push notification setup.
"""
locale = get_locale_from_request(http_request)
settings = get_settings()
if not settings.enable_push_notifications:
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
if not auth_result.user_email:
raise HTTPException(status_code=401, detail="User email not available")
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
push_service = get_push_notification_service()
@@ -247,5 +259,5 @@ async def send_test_notification(
return TestNotificationResponse(
status="success",
sent_count=sent_count,
message=f"Test notification sent to {sent_count} device(s)"
message=t(locale, "push.testNotificationSent", sent_count=sent_count)
)
+22 -21
View File
@@ -10,12 +10,13 @@ import logging
from datetime import datetime
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult
from backend.services.email_validation_service import get_email_validation_service, EmailValidationService
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"])
@@ -106,13 +107,13 @@ async def add_disposable_domain(
domain = request.domain.lower().strip()
if not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Invalid domain format")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
email_validation.add_disposable_domain(domain, auth_result.user_email)
return SuccessResponse(
success=True,
message=f"Domain '{domain}' added to disposable domains blocklist"
message=t("en", "admin.domainAddedToBl", domain=domain)
)
@@ -126,11 +127,11 @@ async def remove_disposable_domain(
domain = domain.lower().strip()
if not email_validation.remove_disposable_domain(domain, auth_result.user_email):
raise HTTPException(status_code=404, detail="Domain not found in blocklist")
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInBl"))
return SuccessResponse(
success=True,
message=f"Domain '{domain}' removed from disposable domains blocklist"
message=t("en", "admin.domainRemovedFromBl", domain=domain)
)
@@ -143,9 +144,9 @@ async def add_allowlisted_domain(
email_validation = get_email_validation_service()
domain = request.domain.lower().strip()
if not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Invalid domain format")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist")
return SuccessResponse(success=True, message=t("en", "admin.domainAddedToAllowlist", domain=domain))
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
@@ -157,8 +158,8 @@ async def remove_allowlisted_domain(
email_validation = get_email_validation_service()
domain = domain.lower().strip()
if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email):
raise HTTPException(status_code=404, detail="Domain not found in allowlist")
return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist")
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInAllowlist"))
return SuccessResponse(success=True, message=t("en", "admin.domainRemovedFromAllowlist", domain=domain))
@router.post("/blocklists/sync", response_model=SuccessResponse)
@@ -181,7 +182,7 @@ async def trigger_sync(
return SuccessResponse(
success=True,
message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)"
message=t("en", "admin.syncComplete", external_count=result['external_count'], added=result['added'], removed=result['removed'])
)
@@ -195,13 +196,13 @@ async def add_blocked_email(
email = request.email.lower().strip()
if not email or "@" not in email:
raise HTTPException(status_code=400, detail="Invalid email format")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidEmailFormat"))
email_validation.add_blocked_email(email, auth_result.user_email)
return SuccessResponse(
success=True,
message=f"Email '{email}' added to blocked emails list"
message=t("en", "admin.emailAddedToBl", email=email)
)
@@ -215,11 +216,11 @@ async def remove_blocked_email(
email = email.lower().strip()
if not email_validation.remove_blocked_email(email, auth_result.user_email):
raise HTTPException(status_code=404, detail="Email not found in blocklist")
raise HTTPException(status_code=404, detail=t("en", "admin.emailNotFoundInBl"))
return SuccessResponse(
success=True,
message=f"Email '{email}' removed from blocked emails list"
message=t("en", "admin.emailRemovedFromBl", email=email)
)
@@ -233,13 +234,13 @@ async def add_blocked_ip(
ip_address = request.ip_address.strip()
if not ip_address:
raise HTTPException(status_code=400, detail="Invalid IP address")
raise HTTPException(status_code=400, detail=t("en", "admin.invalidIPAddress"))
email_validation.add_blocked_ip(ip_address, auth_result.user_email)
return SuccessResponse(
success=True,
message=f"IP '{ip_address}' added to blocked IPs list"
message=t("en", "admin.ipAddedToBl", ip_address=ip_address)
)
@@ -253,11 +254,11 @@ async def remove_blocked_ip(
ip_address = ip_address.strip()
if not email_validation.remove_blocked_ip(ip_address, auth_result.user_email):
raise HTTPException(status_code=404, detail="IP not found in blocklist")
raise HTTPException(status_code=404, detail=t("en", "admin.ipNotFoundInBl"))
return SuccessResponse(
success=True,
message=f"IP '{ip_address}' removed from blocked IPs list"
message=t("en", "admin.ipRemovedFromBl", ip_address=ip_address)
)
@@ -303,12 +304,12 @@ async def retry_youtube_upload(
if not queue_service.retry_upload(job_id):
raise HTTPException(
status_code=404,
detail=f"Upload not found or not in retryable state for job {job_id}"
detail=t("en", "admin.youtubeUploadNotFound", job_id=job_id)
)
return SuccessResponse(
success=True,
message=f"YouTube upload for job {job_id} queued for retry"
message=t("en", "admin.youtubeUploadQueuedForRetry", job_id=job_id)
)
@@ -341,5 +342,5 @@ async def trigger_youtube_queue_processing(
return SuccessResponse(
success=True,
message="YouTube queue processing started in background"
message=t("en", "admin.youtubeQueueProcessingStarted")
)
+201 -48
View File
@@ -19,7 +19,7 @@ import json
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, Set, Tuple
from typing import Dict, Any, List, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
@@ -36,6 +36,7 @@ from backend.services.encoding_service import get_encoding_service
from backend.api.dependencies import require_auth, require_review_auth
from backend.services.auth_service import UserType
from backend.config import get_settings
from backend.i18n import t, get_locale_from_request
# LyricsTranscriber imports for preview generation
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
@@ -113,12 +114,12 @@ async def get_correction_data(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not ready for review (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
# Check for updated corrections first (from previous review sessions where user edited lyrics)
@@ -139,7 +140,7 @@ async def get_correction_data(
if not storage.file_exists(corrections_gcs):
raise HTTPException(
status_code=404,
detail="Corrections data not found. Lyrics processing may not be complete."
detail=t("en", "review.correctionsNotFound")
)
# Download and return corrections data
@@ -224,7 +225,7 @@ async def get_correction_data(
except Exception as e:
logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error loading corrections: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
@router.get("/{job_id}/audio/{audio_hash}")
@@ -260,11 +261,11 @@ async def _stream_audio(job_id: str):
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise HTTPException(status_code=404, detail="Audio file not found")
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
try:
transcoding = AudioTranscodingService()
@@ -274,7 +275,7 @@ async def _stream_audio(job_id: str):
except Exception as e:
logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
@router.post("/{job_id}/complete")
@@ -298,12 +299,12 @@ async def complete_review(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
# === Require instrumental selection ===
@@ -311,7 +312,7 @@ async def complete_review(
if not instrumental_selection:
raise HTTPException(
status_code=400,
detail="instrumental_selection is required. Must be 'clean' or 'with_backing'."
detail=t("en", "review.instrumentalSelectionRequired")
)
valid_selections = ["clean", "with_backing"]
@@ -323,7 +324,7 @@ async def complete_review(
if instrumental_selection not in valid_selections:
raise HTTPException(
status_code=400,
detail=f"Invalid instrumental_selection. Must be one of: {valid_selections}"
detail=t("en", "review.invalidInstrumentalSelection", valid_selections=valid_selections)
)
try:
@@ -331,12 +332,16 @@ async def complete_review(
# (it's stored separately in state_data)
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Save updated corrections to GCS
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
# Only write corrections_updated.json if there's actual correction data.
# Writing an empty dict causes KeyError downstream when render workers
# try to access updated_data["corrections"].
if corrections_to_save and "corrections" in corrections_to_save:
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
else:
logger.info(f"Job {job_id}: No corrections data in request, skipping corrections_updated.json")
# === Store instrumental selection in state_data ===
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
@@ -380,7 +385,7 @@ async def complete_review(
raise
except Exception as e:
logger.error(f"Job {job_id}: Error completing review: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error completing review: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.reviewCompletedError", error=str(e)))
@router.post("/{job_id}/handlers")
@@ -396,7 +401,7 @@ async def update_handlers(
would require re-running correction.
"""
logger.info(f"Job {job_id}: Handler update requested (not implemented)")
return {"status": "success", "message": "Handler updates not yet implemented"}
return {"status": "success", "message": t("en", "review.handlersUpdateNotImplemented")}
@router.post("/{job_id}/add-lyrics")
@@ -416,19 +421,21 @@ async def add_lyrics(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Job must be in review state to add lyrics
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
source = data.get("source", "").strip()
lyrics_text = data.get("lyrics", "").strip()
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters")
raw_force = data.get("force", False)
force = raw_force if isinstance(raw_force, bool) else str(raw_force).lower() == "true"
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters (force={force})")
# Use tracing and job_log_context for full observability
with create_span("add-lyrics", {"job_id": job_id, "source": source, "lyrics_length": len(lyrics_text)}) as span:
@@ -465,7 +472,8 @@ async def add_lyrics(
source=source,
lyrics_text=lyrics_text,
cache_dir=cache_dir,
logger=logger
logger=logger,
force=force,
)
add_span_event("correction_complete", {
"new_segments": len(updated_result.corrected_segments) if updated_result.corrected_segments else 0,
@@ -494,11 +502,156 @@ async def add_lyrics(
# ValueError from CorrectionOperations (e.g., duplicate source name)
logger.warning(f"Job {job_id}: Invalid add lyrics request: {e}")
span.set_attribute("error", str(e))
raise HTTPException(status_code=400, detail=str(e))
raise HTTPException(status_code=400, detail=t("en", "review.lyricsAddInvalidRequest", error=str(e)))
except Exception as e:
logger.error(f"Job {job_id}: Failed to add lyrics: {e}", exc_info=True)
span.set_attribute("error", str(e))
raise HTTPException(status_code=500, detail=f"Failed to add lyrics: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.lyricsAddError", error=str(e)))
@router.post("/{job_id}/search-lyrics")
async def search_lyrics(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Search for lyrics using an alternate artist/title and rerun correction.
Queries all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB)
with the supplied artist and title, then runs the correction pipeline (which
includes the relevance filter). Sources that pass the filter are added to the
job's corrections.json and returned to the frontend.
Request body:
artist (str): Artist name to search.
title (str): Song title to search.
force_sources (list[str], optional): Provider names whose results should
bypass the relevance filter.
Response:
200 {"status": "success", "data": {...CorrectionData...}, "sources_added": [...],
"sources_rejected": {...}, "sources_not_found": [...]}
200 {"status": "no_results", "message": "...", "sources_rejected": {...},
"sources_not_found": [...]}
400 on invalid request / wrong job state
500 on internal error
"""
job_manager = JobManager()
storage = StorageService()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=t("en", "review.reviewNotReady", status=job.status)
)
artist = (data.get("artist") or "").strip()
title = (data.get("title") or "").strip()
force_sources: List[str] = data.get("force_sources") or []
if not artist or not title:
raise HTTPException(status_code=400, detail="artist and title are required")
logger.info(f"Job {job_id}: Searching lyrics for '{artist}' - '{title}' (force={force_sources})")
with create_span("search-lyrics", {"job_id": job_id, "artist": artist, "title": title}) as span:
with job_log_context(job_id, worker="search-lyrics"):
try:
with tempfile.TemporaryDirectory() as temp_dir:
# Download current corrections.json
with create_span("download-corrections") as download_span:
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
corrections_path = os.path.join(temp_dir, "corrections.json")
storage.download_file(corrections_gcs, corrections_path)
download_span.set_attribute("gcs_path", corrections_gcs)
with open(corrections_path, "r", encoding="utf-8") as f:
original_data = json.load(f)
correction_result = CorrectionResult.from_dict(original_data)
add_span_event("corrections_loaded", {
"segments": len(correction_result.corrected_segments) if correction_result.corrected_segments else 0,
"reference_sources": len(correction_result.reference_lyrics) if correction_result.reference_lyrics else 0,
})
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(cache_dir, exist_ok=True)
with create_span("correction-operations-search-lyrics") as correction_span:
correction_span.set_attribute("artist", artist)
correction_span.set_attribute("title", title)
search_result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist=artist,
title=title,
cache_dir=cache_dir,
force_sources=force_sources,
logger=logger,
)
sources_added = search_result["sources_added"]
sources_rejected = search_result["sources_rejected"]
sources_not_found = search_result["sources_not_found"]
updated_result = search_result["updated_result"]
if not sources_added or updated_result is None:
logger.info(
f"Job {job_id}: No valid lyrics found via search "
f"(rejected={list(sources_rejected.keys())}, not_found={sources_not_found})"
)
span.set_attribute("success", False)
return {
"status": "no_results",
"message": t("en", "review.lyricsSearchNoResults"),
"sources_added": [],
"sources_rejected": sources_rejected,
"sources_not_found": sources_not_found,
}
# Add audio hash / job metadata for the frontend
audio_hash = _get_audio_hash(job_id)
if not updated_result.metadata:
updated_result.metadata = {}
updated_result.metadata["audio_hash"] = audio_hash
updated_result.metadata["artist"] = job.artist
updated_result.metadata["title"] = job.title
# Upload updated corrections back to GCS
with create_span("upload-corrections") as upload_span:
updated_data = updated_result.to_dict()
storage.upload_json(corrections_gcs, updated_data)
upload_span.set_attribute("gcs_path", corrections_gcs)
logger.info(
f"Job {job_id}: Search complete — added={sources_added}, "
f"rejected={list(sources_rejected.keys())}, not_found={sources_not_found}"
)
span.set_attribute("success", True)
span.set_attribute("sources_added", len(sources_added))
return {
"status": "success",
"data": updated_data,
"sources_added": sources_added,
"sources_rejected": sources_rejected,
"sources_not_found": sources_not_found,
}
except HTTPException:
raise
except ValueError as e:
logger.warning(f"Job {job_id}: Invalid search lyrics request: {e}")
span.set_attribute("error", str(e))
raise HTTPException(status_code=400, detail=t("en", "review.lyricsSearchInvalidRequest", error=str(e)))
except Exception as e:
logger.error(f"Job {job_id}: Failed to search lyrics: {e}", exc_info=True)
span.set_attribute("error", str(e))
raise HTTPException(status_code=500, detail=t("en", "review.lyricsSearchError", error=str(e)))
@router.post("/{job_id}/preview-video")
@@ -523,13 +676,13 @@ async def generate_preview_video(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Job must be in review state to generate preview
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
detail=t("en", "review.reviewNotReady", status=job.status)
)
# Check if GCE preview encoding is enabled
@@ -703,7 +856,7 @@ async def generate_preview_video(
span.set_attribute("error", str(e))
raise HTTPException(
status_code=500,
detail=f"Failed to generate preview video: {e}"
detail=t("en", "review.previewVideoGenerationError", error=str(e))
) from e
@@ -724,7 +877,7 @@ async def get_preview_video(
# Try standard path
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
if not storage.file_exists(preview_gcs_path):
raise HTTPException(status_code=404, detail="Preview video not found")
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
try:
# Download to temp file and stream
@@ -749,7 +902,7 @@ async def get_preview_video(
except Exception as e:
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error streaming preview video: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
@router.post("/{job_id}/v1/annotations")
@@ -789,7 +942,7 @@ async def submit_annotation(
except Exception as e:
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=t("en", "review.annotationSaveError", error=str(e)))
@router.get("/{job_id}/v1/annotations/stats")
@@ -830,7 +983,7 @@ async def get_instrumental_analysis(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Get backing vocals analysis from state_data
backing_analysis = job.state_data.get('backing_vocals_analysis', {})
@@ -870,7 +1023,7 @@ async def get_instrumental_analysis(
"has_audible_content": backing_analysis.get('has_audible_content', False),
"total_duration_seconds": backing_analysis.get('total_duration_seconds', 0),
"audible_segments": backing_analysis.get('audible_segments', []),
"recommended_selection": backing_analysis.get('recommended_selection', 'with_backing'),
"recommended_selection": backing_analysis.get('recommended_selection', 'clean'),
"total_audible_duration_seconds": backing_analysis.get('total_audible_duration_seconds', 0),
"audible_percentage": backing_analysis.get('audible_percentage', 0),
"silence_threshold_db": backing_analysis.get('silence_threshold_db', -40),
@@ -898,7 +1051,7 @@ async def get_waveform_data(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
# Get backing vocals path
stems = job.file_urls.get('stems', {})
@@ -909,7 +1062,7 @@ async def get_waveform_data(
backing_vocals_path = job.input_media_gcs_path
if not backing_vocals_path:
raise HTTPException(status_code=404, detail="No audio available for waveform")
raise HTTPException(status_code=404, detail=t("en", "review.waveformNoAudio"))
try:
analysis_service = AudioAnalysisService()
@@ -927,7 +1080,7 @@ async def get_waveform_data(
}
except Exception as e:
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
raise HTTPException(status_code=500, detail=t("en", "review.waveformGenerationError", error=str(e)))
# ============================================
@@ -959,11 +1112,11 @@ async def save_review_session(
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
correction_data = data.get("correction_data")
if not correction_data:
raise HTTPException(status_code=400, detail="correction_data is required")
raise HTTPException(status_code=400, detail=t("en", "review.sessionSaveError"))
# Compute hash for deduplication
data_json = json.dumps(correction_data, sort_keys=True, default=str)
@@ -1132,7 +1285,7 @@ async def save_audio_edit_session(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
user_email = auth_info[0] if isinstance(auth_info, tuple) else ""
edit_data = data.get("edit_data", {})
@@ -1325,7 +1478,7 @@ async def get_input_audio_info(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if not job.input_media_gcs_path:
raise HTTPException(status_code=404, detail="No input audio available")
@@ -1432,7 +1585,7 @@ async def apply_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1529,7 +1682,7 @@ async def undo_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1576,7 +1729,7 @@ async def redo_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1632,7 +1785,7 @@ async def upload_audio_for_join(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
@@ -1725,7 +1878,7 @@ async def submit_audio_edit(
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
+2 -1
View File
@@ -12,6 +12,7 @@ from fastapi import APIRouter, Query, Request
from backend.models.tenant import TenantConfigResponse, TenantPublicConfig
from backend.services.tenant_service import get_tenant_service
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -115,6 +116,6 @@ async def get_tenant_asset(tenant_id: str, asset_name: str):
if not url:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Asset not found")
raise HTTPException(status_code=404, detail=t("en", "tenant.assetNotFound"))
return RedirectResponse(url=url)
+18 -13
View File
@@ -9,10 +9,11 @@ before job creation.
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Request
from backend.models.theme import ThemeDetailResponse, ThemesListResponse
from backend.services.theme_service import get_theme_service
from backend.i18n import t, get_locale_from_request
logger = logging.getLogger(__name__)
@@ -20,7 +21,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
@router.get("", response_model=ThemesListResponse)
async def list_themes() -> ThemesListResponse:
async def list_themes(request: Request) -> ThemesListResponse:
"""
List all available themes.
@@ -29,6 +30,7 @@ async def list_themes() -> ThemesListResponse:
This endpoint is public and does not require authentication.
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
themes = theme_service.list_themes()
@@ -37,12 +39,12 @@ async def list_themes() -> ThemesListResponse:
logger.error(f"Error listing themes: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load themes"
detail=t(locale, "themes.themesLoadError")
)
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
async def get_theme(theme_id: str) -> ThemeDetailResponse:
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
"""
Get detailed information about a specific theme.
@@ -58,6 +60,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
Raises:
404: Theme not found
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
theme = theme_service.get_theme(theme_id)
@@ -65,7 +68,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
if theme is None:
raise HTTPException(
status_code=404,
detail=f"Theme not found: {theme_id}"
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
)
return ThemeDetailResponse(theme=theme)
@@ -75,12 +78,12 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
logger.error(f"Error getting theme {theme_id}: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load theme"
detail=t(locale, "themes.themeLoadError")
)
@router.get("/{theme_id}/preview")
async def get_theme_preview(theme_id: str) -> dict:
async def get_theme_preview(theme_id: str, request: Request) -> dict:
"""
Get a signed URL for the theme's preview image.
@@ -96,20 +99,21 @@ async def get_theme_preview(theme_id: str) -> dict:
Raises:
404: Theme not found or no preview available
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
if not theme_service.theme_exists(theme_id):
raise HTTPException(
status_code=404,
detail=f"Theme not found: {theme_id}"
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
)
theme = theme_service.get_theme(theme_id)
if theme is None or theme.preview_url is None:
raise HTTPException(
status_code=404,
detail=f"No preview available for theme: {theme_id}"
detail=t(locale, "themes.previewNotAvailable", theme_id=theme_id)
)
return {"preview_url": theme.preview_url}
@@ -119,12 +123,12 @@ async def get_theme_preview(theme_id: str) -> dict:
logger.error(f"Error getting preview for theme {theme_id}: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load theme preview"
detail=t(locale, "themes.previewLoadError")
)
@router.get("/{theme_id}/youtube-description")
async def get_theme_youtube_description(theme_id: str) -> dict:
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
"""
Get the YouTube description template for a theme.
@@ -141,13 +145,14 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
Raises:
404: Theme not found
"""
locale = get_locale_from_request(request)
try:
theme_service = get_theme_service()
if not theme_service.theme_exists(theme_id):
raise HTTPException(
status_code=404,
detail=f"Theme not found: {theme_id}"
detail=t(locale, "themes.youtubeDescriptionNotFound", theme_id=theme_id)
)
description = theme_service.get_youtube_description(theme_id)
@@ -158,5 +163,5 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
logger.error(f"Error getting YouTube description for theme {theme_id}: {e}")
raise HTTPException(
status_code=500,
detail="Failed to load YouTube description"
detail=t(locale, "themes.youtubeDescriptionLoadError")
)
+108 -27
View File
@@ -10,6 +10,7 @@ Handles:
"""
import hashlib
import logging
import threading
from datetime import datetime
from typing import Optional, Tuple
@@ -34,6 +35,7 @@ def _mask_email(email: str) -> str:
from fastapi import APIRouter, HTTPException, Depends, Request, Header
from pydantic import BaseModel, EmailStr
from backend.i18n import t, get_locale_from_request
from backend.services.email_validation_service import get_email_validation_service
from backend.models.user import (
UserRole,
@@ -132,6 +134,32 @@ class LogoutResponse(BaseModel):
# Magic Link Authentication
# =============================================================================
def _precompute_credit_eval(token: str, email: str) -> None:
"""Run credit evaluation in background and store result on magic link doc.
Called in a background thread after sending a magic link for new users.
If the user clicks the link before this finishes, verify_magic_link falls
back to inline evaluation (same as before this optimization).
"""
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
from backend.services.user_service import get_user_service, MAGIC_LINKS_COLLECTION
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
user_service = get_user_service()
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
"credit_eval_decision": evaluation.decision,
"credit_eval_reasoning": evaluation.reasoning,
"credit_eval_error": evaluation.error,
})
logger.info(f"Pre-computed credit eval for {_mask_email(email)}: {evaluation.decision}")
except Exception:
logger.exception(f"Background credit eval failed for {_mask_email(email)} — verify will compute inline")
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
async def send_magic_link(
request: SendMagicLinkRequest,
@@ -155,18 +183,20 @@ async def send_magic_link(
# (done before email service check so we can reject without needing email config)
email_validation = get_email_validation_service()
locale = get_locale_from_request(http_request)
if email_validation.is_disposable_domain(email):
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
raise HTTPException(
status_code=422,
detail="disposable_email_not_allowed"
detail=t(locale, "users.disposableEmailBlocked")
)
if email_validation.is_email_blocked(email):
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
ip_address = get_client_ip(http_request)
@@ -174,7 +204,7 @@ async def send_magic_link(
logger.warning(f"Blocked IP signup attempt: {ip_address}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
# Per-IP and per-fingerprint signup rate limit (only for new users)
@@ -190,7 +220,7 @@ async def send_magic_link(
# Silent reject (anti-enumeration)
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
# Check if email service is configured
@@ -198,7 +228,7 @@ async def send_magic_link(
logger.error("Email service not configured - cannot send magic links")
raise HTTPException(
status_code=503,
detail="Email service is not available. Please contact support."
detail=t(locale, "users.emailServiceNotConfigured")
)
# Get tenant context from middleware
@@ -212,7 +242,7 @@ async def send_magic_link(
# Return success anyway to prevent email enumeration
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
# Get client info for security logging (ip_address already extracted above for blocklist check)
@@ -243,6 +273,7 @@ async def send_magic_link(
sender_email=sender_email,
tenant_frontend_url=tenant_frontend_url,
tenant_name=tenant_name,
locale=locale,
)
if not sent:
@@ -250,9 +281,21 @@ async def send_magic_link(
# Don't reveal failure to prevent email enumeration
# Still return success
# Pre-compute credit evaluation in background for new users.
# By the time they check their email and click the link, the decision
# will be ready and verification will be instant.
# Skip for test emails — they get auto-granted without evaluation.
if existing_user is None and not is_test_email(email):
thread = threading.Thread(
target=_precompute_credit_eval,
args=(magic_link.token, email),
daemon=True,
)
thread.start()
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
message=t(locale, "users.magicLinkSent")
)
@@ -269,9 +312,11 @@ async def verify_magic_link(
Returns a session token that should be stored and used for subsequent requests.
The session will be associated with the tenant from the magic link.
"""
locale = get_locale_from_request(http_request)
# Reject empty tokens early to avoid invalid Firestore document paths
if not token or not token.strip():
raise HTTPException(status_code=401, detail="Invalid token")
raise HTTPException(status_code=401, detail=t(locale, "users.invalidToken"))
# Get client info
ip_address = get_client_ip(http_request)
@@ -295,12 +340,23 @@ async def verify_magic_link(
success, user, message = user_service.verify_magic_link(token)
if not success or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message))
# Grant welcome credits on first verification (with AI abuse evaluation)
# Use pre-computed evaluation from magic link if available (computed at send time)
precomputed_eval = None
if magic_link_doc.exists:
precomputed_eval = {
k: magic_link_data.get(k)
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
if magic_link_data.get(k) is not None
} or None
credits_granted = 0
credit_status = "not_applicable" # returning user, not first login
granted, credit_status = user_service.grant_welcome_credits_if_eligible(user.email)
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
user.email, precomputed_eval=precomputed_eval,
)
if granted:
credits_granted = user_service.NEW_USER_FREE_CREDITS
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
@@ -309,6 +365,13 @@ async def verify_magic_link(
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Persist user's locale preference (from Accept-Language header)
if locale and locale != (user.locale or "en"):
try:
user_service.update_user(user.email, locale=locale)
except Exception:
pass # Non-critical — don't block login
# Create session with tenant context and device fingerprint from the magic link
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
session = user_service.create_session(
@@ -321,7 +384,7 @@ async def verify_magic_link(
# Send welcome email to first-time users
if is_first_login:
email_service.send_welcome_email(user.email, user.credits)
email_service.send_welcome_email(user.email, user.credits, locale=locale)
# Return user info with tenant_id
user_public = UserPublic(
@@ -347,7 +410,7 @@ async def verify_magic_link(
status="success",
session_token=session.token,
user=user_public,
message="Successfully signed in",
message=t(locale, "users.magicLinkSuccess"),
tenant_subdomain=tenant_subdomain,
credits_granted=credits_granted,
credit_status=credit_status,
@@ -356,21 +419,23 @@ async def verify_magic_link(
@router.post("/auth/logout", response_model=LogoutResponse)
async def logout(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
"""
Logout and invalidate the current session.
"""
locale = get_locale_from_request(request)
if not authorization:
return LogoutResponse(status="success", message="Already logged out")
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
# Extract token from "Bearer <token>"
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
user_service.revoke_session(token)
return LogoutResponse(status="success", message="Successfully logged out")
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
# =============================================================================
@@ -379,6 +444,7 @@ async def logout(
@router.get("/me", response_model=UserProfileResponse)
async def get_current_user(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
@@ -387,10 +453,11 @@ async def get_current_user(
Requires a valid session token or admin token.
"""
locale = get_locale_from_request(request)
from backend.services.auth_service import get_auth_service
if not authorization:
raise HTTPException(status_code=401, detail="Not authenticated")
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
# Extract token
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
@@ -421,7 +488,7 @@ async def get_current_user(
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
feedback_eligible = (
user.total_jobs_completed >= 2
@@ -1094,6 +1161,7 @@ async def stripe_webhook(
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
async def check_feedback_eligibility(
request: Request,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
):
@@ -1102,8 +1170,9 @@ async def check_feedback_eligibility(
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
"""
locale = get_locale_from_request(request)
if not authorization:
raise HTTPException(status_code=401, detail="Authentication required")
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
@@ -1118,7 +1187,7 @@ async def check_feedback_eligibility(
else:
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
@@ -1132,6 +1201,7 @@ async def check_feedback_eligibility(
@router.post("/feedback", response_model=UserFeedbackResponse)
async def submit_user_feedback(
http_request: Request,
request: UserFeedbackRequest,
authorization: Optional[str] = Header(None),
user_service: UserService = Depends(get_user_service),
@@ -1143,8 +1213,9 @@ async def submit_user_feedback(
not have already submitted feedback. At least one text field
must have >50 characters.
"""
locale = get_locale_from_request(http_request)
if not authorization:
raise HTTPException(status_code=401, detail="Authentication required")
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
@@ -1159,20 +1230,20 @@ async def submit_user_feedback(
else:
valid, user, message = user_service.validate_session(token)
if not valid or not user:
raise HTTPException(status_code=401, detail=message)
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
# Check eligibility: must have completed 2+ jobs
if user.total_jobs_completed < 2:
raise HTTPException(
status_code=400,
detail="You need to complete at least 2 karaoke videos before submitting feedback."
detail=t(locale, "users.feedbackNotEligible")
)
# Check if already submitted
if user.has_submitted_feedback:
raise HTTPException(
status_code=400,
detail="You have already submitted feedback. Thank you!"
detail=t(locale, "users.feedbackNotEligible")
)
# Validate: at least one text field has >50 characters
@@ -1445,12 +1516,14 @@ async def list_users(
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
async def get_user_detail(
email: str,
request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Get detailed user information including credit history and recent jobs (admin only).
"""
locale = get_locale_from_request(request)
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
from urllib.parse import unquote
@@ -1460,7 +1533,7 @@ async def get_user_detail(
user = user_service.get_user(email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
db = user_service.db
@@ -1577,18 +1650,20 @@ async def add_credits_to_user(
@router.post("/admin/users/{email}/disable")
async def disable_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Disable a user account (admin only).
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
success = user_service.disable_user(email, admin_email=admin_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} has been disabled"}
@@ -1596,18 +1671,20 @@ async def disable_user(
@router.post("/admin/users/{email}/enable")
async def enable_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Enable a user account (admin only).
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
success = user_service.enable_user(email, admin_email=admin_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} has been enabled"}
@@ -1615,6 +1692,7 @@ async def enable_user(
@router.delete("/admin/users/{email}")
async def delete_user(
email: str,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
@@ -1623,6 +1701,7 @@ async def delete_user(
Jobs are NOT deleted - they remain as historical records.
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
try:
@@ -1631,7 +1710,7 @@ async def delete_user(
raise HTTPException(status_code=400, detail=str(e))
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} has been deleted"}
@@ -1640,18 +1719,20 @@ async def delete_user(
async def set_user_role(
email: str,
role: UserRole,
request: Request,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Set a user's role (admin only).
"""
locale = get_locale_from_request(request)
admin_id = auth_data.user_email or "admin:unknown"
success = user_service.set_user_role(email, role, admin_email=admin_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
return {"status": "success", "message": f"User {email} role set to {role.value}"}
+35
View File
@@ -0,0 +1,35 @@
# Cloud Build config for GPU base image
#
# Builds the CUDA + PyTorch + models base image used by the audio worker.
# This image is large (~10GB) so builds take 15-30 minutes.
#
# Trigger manually:
# gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
#
# The app-layer Dockerfile uses this as its BASE_IMAGE for audio worker deploys.
steps:
- name: 'gcr.io/cloud-builders/docker'
args:
- 'build'
- '-f'
- 'backend/Dockerfile.gpu-base'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
- '--build-arg'
- 'BUILD_DATE=$_BUILD_DATE'
- '--build-arg'
- 'BUILD_ID=$BUILD_ID'
- '.'
images:
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
timeout: '3600s'
options:
machineType: 'E2_HIGHCPU_32'
diskSizeGb: 100
+4
View File
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
# Authentication
admin_tokens: Optional[str] = os.getenv("ADMIN_TOKENS") # Comma-separated list
scheduler_service_account: str = os.getenv(
"SCHEDULER_SERVICE_ACCOUNT",
"karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
)
# Application
environment: str = os.getenv("ENVIRONMENT", "development")
+99
View File
@@ -0,0 +1,99 @@
"""
Lightweight i18n utility for backend translations.
Usage:
from backend.i18n import t, get_locale_from_request, SUPPORTED_LOCALES
# In a route handler:
locale = get_locale_from_request(request)
message = t(locale, "auth.userNotFound")
message = t(locale, "jobs.notFound", job_id="abc123")
"""
import json
from functools import lru_cache
from pathlib import Path
from typing import Any
from starlette.requests import Request
SUPPORTED_LOCALES = ("en", "es", "de")
DEFAULT_LOCALE = "en"
TRANSLATIONS_DIR = Path(__file__).parent / "translations"
@lru_cache(maxsize=len(SUPPORTED_LOCALES))
def _load_translations(locale: str) -> dict[str, Any]:
"""Load and cache translation file for a locale."""
path = TRANSLATIONS_DIR / f"{locale}.json"
if not path.exists():
if locale != DEFAULT_LOCALE:
return _load_translations(DEFAULT_LOCALE)
return {}
with open(path, encoding="utf-8") as f:
result: dict[str, Any] = json.load(f)
return result
def t(locale: str, key: str, **kwargs: Any) -> str:
"""Get a translated string by dotted key path.
Args:
locale: Language code (en, es, de)
key: Dotted path like "auth.userNotFound" or "emails.magicLink.subject"
**kwargs: Interpolation variables (e.g., job_id="abc123")
Returns:
Translated string with variables interpolated, or the key itself if not found.
"""
if locale not in SUPPORTED_LOCALES:
locale = DEFAULT_LOCALE
translations = _load_translations(locale)
# Walk the dotted path
value: Any = translations
for part in key.split("."):
if isinstance(value, dict) and part in value:
value = value[part]
else:
# Key not found — fall back to English
if locale != DEFAULT_LOCALE:
return t(DEFAULT_LOCALE, key, **kwargs)
return key # Return the key itself as last resort
if not isinstance(value, str):
return key
result: str = value
# Interpolate variables
if kwargs:
try:
result = result.format(**kwargs)
except KeyError:
pass # Missing variable — return template as-is
return result
def get_locale_from_request(request: Request) -> str:
"""Extract locale from Accept-Language header.
Returns the first supported locale found, or DEFAULT_LOCALE.
"""
accept_lang = request.headers.get("accept-language", "")
# Simple parsing — Accept-Language can be "de", "de-DE", "en-US,en;q=0.9,de;q=0.8"
for part in accept_lang.split(","):
lang = part.split(";")[0].strip().split("-")[0].lower()
if lang in SUPPORTED_LOCALES:
return lang
return DEFAULT_LOCALE
def get_locale_prefix(locale: str) -> str:
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
if locale not in SUPPORTED_LOCALES:
locale = DEFAULT_LOCALE
return f"/{locale}"
+4 -2
View File
@@ -170,18 +170,20 @@ app.include_router(tenant.router) # Tenant/white-label configuration (no /api p
from fastapi import Request
from fastapi.responses import JSONResponse
from backend.exceptions import InsufficientCreditsError
from backend.i18n import t, get_locale_from_request
@app.exception_handler(InsufficientCreditsError)
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
"""Handle insufficient credits errors with 402 Payment Required status."""
locale = get_locale_from_request(request)
return JSONResponse(
status_code=402,
content={
"detail": exc.message,
"detail": t(locale, "errors.insufficientCredits"),
"credits_available": exc.credits_available,
"credits_required": exc.credits_required,
"buy_url": "/#pricing",
"buy_url": t(locale, "errors.insufficientCreditsBuyUrl"),
},
)
+8
View File
@@ -91,6 +91,9 @@ class User(BaseModel):
# Optional profile fields for future use
display_name: Optional[str] = None
# i18n locale preference (set from Accept-Language on login, used for emails/push)
locale: Optional[str] = None
# Push notification subscriptions (Web Push API)
# Users can subscribe from multiple devices/browsers
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
@@ -129,6 +132,11 @@ class MagicLinkToken(BaseModel):
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
credit_eval_reasoning: Optional[str] = None
credit_eval_error: Optional[str] = None
class Session(BaseModel):
"""
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""
Download ensemble preset models at Docker build time.
Bakes models into the image so they're available immediately at runtime,
avoiding cold-start model download latency in Cloud Run Jobs.
Usage: python backend/scripts/download_models.py /models
"""
import json
import sys
import logging
import importlib.resources as resources
from audio_separator.separator import Separator
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Presets to bake into the GPU image
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
def download_preset_models(model_dir: str) -> None:
"""Download all models for the configured presets individually.
Ensemble presets resolve to multiple model filenames. We must download
each model individually via load_model(model_filename) — calling
load_model() with no args on an ensemble preset doesn't trigger downloads.
"""
with resources.open_text("audio_separator", "ensemble_presets.json") as f:
presets = json.load(f)["presets"]
models_to_download = set()
for preset_name in PRESETS_TO_DOWNLOAD:
models_to_download.update(presets[preset_name]["models"])
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
for model in sorted(models_to_download):
logger.info(f" Downloading: {model}")
sep = Separator(model_file_dir=model_dir)
sep.load_model(model)
logger.info(f" Done: {model}")
if __name__ == "__main__":
model_dir = sys.argv[1] if len(sys.argv) > 1 else "/models"
download_preset_models(model_dir)
logger.info(f"All preset models downloaded to {model_dir}")
+61
View File
@@ -3,6 +3,7 @@ Authentication service for karaoke backend.
Provides token-based authentication with support for:
- Admin tokens (hardcoded in environment)
- Google OIDC tokens (from Cloud Scheduler / Cloud Tasks service accounts)
- Admin by email domain (@nomadkaraoke.com)
- User tokens (stored in Firestore auth_tokens collection)
- Session tokens (stored in Firestore sessions collection, from magic link auth)
@@ -19,6 +20,9 @@ from enum import Enum
from typing import Optional, Tuple, Dict, Any, List
from datetime import datetime
from google.auth.transport import requests as google_auth_requests
from google.oauth2 import id_token as google_id_token
from backend.services.firestore_service import FirestoreService
from backend.config import get_settings
from backend.models.user import UserRole
@@ -72,6 +76,7 @@ class AuthService:
self.firestore = FirestoreService()
self.settings = get_settings()
self._init_admin_tokens()
self._scheduler_service_account = self.settings.scheduler_service_account
def _init_admin_tokens(self):
"""Load admin tokens from environment variables."""
@@ -83,6 +88,56 @@ class AuthService:
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
else:
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
"""
Validate a Google OIDC token (from Cloud Scheduler or Cloud Tasks).
Returns AuthResult if token is a valid Google OIDC JWT from an allowed
service account, None if the token is not a JWT or validation fails.
"""
# Quick check: JWTs have 3 dot-separated parts
if token.count('.') != 2:
return None
try:
# Verify the token signature and claims with Google
# audience=None skips audience check — Cloud Scheduler sets audience
# to the endpoint URL, which varies per endpoint
claims = google_id_token.verify_oauth2_token(
token,
google_auth_requests.Request(),
audience=None,
)
token_email = claims.get("email", "")
# Only accept tokens from the configured service account
if token_email != self._scheduler_service_account:
logger.warning(
f"OIDC token from unexpected service account: {token_email} "
f"(expected {self._scheduler_service_account})"
)
return None
logger.info(f"OIDC token validated for service account: {token_email}")
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="OIDC service account access granted",
user_email=token_email,
is_admin=True,
)
except ValueError as e:
# verify_oauth2_token raises ValueError for invalid/expired tokens
logger.debug(f"OIDC token validation failed: {e}")
return None
except Exception as e:
# Network errors fetching Google certs, etc.
logger.warning(f"OIDC token verification error: {e}")
return None
def validate_token(self, token: str) -> Tuple[bool, UserType, int, str]:
"""
@@ -213,6 +268,12 @@ class AuthService:
is_admin=True
)
# Check for Google OIDC tokens (Cloud Scheduler / Cloud Tasks)
# Done before Firestore lookup to avoid wasting a read on JWT strings
oidc_result = self._validate_oidc_token(token)
if oidc_result is not None:
return oidc_result
# Check stored tokens in Firestore (auth_tokens collection)
token_data = self.firestore.get_token(token)
@@ -297,7 +297,7 @@ class CreditEvaluationService:
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location=self.settings.gcp_region,
location="global",
)
response = client.models.generate_content(
model=self.settings.credit_eval_model,
+56 -30
View File
@@ -19,6 +19,7 @@ from typing import Optional, List
from zoneinfo import ZoneInfo
from backend.config import get_settings
from backend.i18n import t, get_locale_prefix
from karaoke_gen.utils import sanitize_filename
@@ -249,6 +250,7 @@ class EmailService:
sender_email: Optional[str] = None,
tenant_frontend_url: Optional[str] = None,
tenant_name: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send a magic link email for authentication.
@@ -264,10 +266,10 @@ class EmailService:
True if email was sent successfully
"""
base_url = tenant_frontend_url or self.frontend_url
magic_link_url = f"{base_url}/auth/verify?token={token}"
magic_link_url = f"{base_url}{get_locale_prefix(locale)}/auth/verify?token={token}"
brand_name = tenant_name or "Nomad Karaoke"
subject = f"Sign in to {brand_name}"
subject = t(locale, "emails.magicLink.subject", brand_name=brand_name)
extra_styles = """
.warning {
@@ -322,7 +324,7 @@ If you didn't request this email, you can safely ignore it.
email, subject, html_content, text_content, from_email_override=sender_email
)
def send_credits_added(self, email: str, credits: int, total_credits: int) -> bool:
def send_credits_added(self, email: str, credits: int, total_credits: int, locale: str = "en") -> bool:
"""
Send notification when credits are added to account.
@@ -334,7 +336,7 @@ If you didn't request this email, you can safely ignore it.
Returns:
True if email was sent successfully
"""
subject = f"🎉 {credits} credits added to your Nomad Karaoke account"
subject = t(locale, "emails.creditsAdded.subject", credits=credits)
extra_styles = f"""
.credits-box {{
@@ -372,7 +374,7 @@ If you didn't request this email, you can safely ignore it.
</ul>
<p style="text-align: center;">
<a href="{self.frontend_url}" class="button">Create Karaoke Now</a>
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">Create Karaoke Now</a>
</p>
"""
@@ -385,7 +387,7 @@ Your new balance: {total_credits} credits
Each credit lets you create one professional karaoke video.
Start creating: {self.frontend_url}
Start creating: {self.frontend_url}{get_locale_prefix(locale)}
---
© {self._get_year()} Nomad Karaoke
@@ -393,7 +395,7 @@ Start creating: {self.frontend_url}
return self.provider.send_email(email, subject, html_content, text_content)
def send_welcome_email(self, email: str, credits: int = 0) -> bool:
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
"""
Send welcome email to new users.
@@ -404,7 +406,7 @@ Start creating: {self.frontend_url}
Returns:
True if email was sent successfully
"""
subject = "Welcome to Nomad Karaoke! 🎤"
subject = t(locale, "emails.welcome.subject")
extra_styles = """
.credits-box {
@@ -498,7 +500,7 @@ Start creating: {self.frontend_url}
</p>
<p style="text-align: center;">
<a href="{self.frontend_url}" class="button">Get Started</a>
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">Get Started</a>
</p>
"""
@@ -527,7 +529,7 @@ Here's how it works:
Complete 2 videos and earn 2 more free credits by sharing your feedback!
Get started: {self.frontend_url}
Get started: {self.frontend_url}{get_locale_prefix(locale)}
---
© {self._get_year()} Nomad Karaoke
@@ -870,6 +872,7 @@ Get started: {self.frontend_url}
title: Optional[str] = None,
brand_code: Optional[str] = None,
cc_admin: bool = True,
locale: str = "en",
) -> bool:
"""
Send job completion email with the rendered template content.
@@ -891,11 +894,11 @@ Get started: {self.frontend_url}
safe_artist = sanitize_filename(artist) if artist else None
safe_title = sanitize_filename(title) if title else None
if brand_code and safe_artist and safe_title:
subject = f"{brand_code}: {safe_artist} - {safe_title} (Your karaoke video is ready!)"
subject = t(locale, "emails.jobCompletion.subjectWithBrand", brand_code=brand_code, artist=safe_artist, title=safe_title)
elif safe_artist and safe_title:
subject = f"{safe_artist} - {safe_title} (Your karaoke video is ready!)"
subject = t(locale, "emails.jobCompletion.subject", artist=safe_artist, title=safe_title)
else:
subject = "Your karaoke video is ready!"
subject = t(locale, "emails.jobCompletion.subjectFallback")
extra_styles = """
.content {
@@ -927,6 +930,7 @@ Get started: {self.frontend_url}
action_type: str,
artist: Optional[str] = None,
title: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send action-needed reminder email.
@@ -942,13 +946,26 @@ Get started: {self.frontend_url}
True if email was sent successfully
"""
# Build subject based on action type
song_info = f" for {artist} - {title}" if artist and title else ""
if action_type == "lyrics":
subject = f"Action needed: Review lyrics{song_info}"
if artist and title:
subject = t(locale, "emails.actionReminder.lyricsSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.lyricsSubjectFallback")
elif action_type == "instrumental":
subject = f"Action needed: Select instrumental{song_info}"
if artist and title:
subject = t(locale, "emails.actionReminder.instrumentalSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.instrumentalSubjectFallback")
elif action_type == "audio_edit":
if artist and title:
subject = t(locale, "emails.actionReminder.audioEditSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.audioEditSubjectFallback")
else:
subject = f"Action needed{song_info}"
if artist and title:
subject = t(locale, "emails.actionReminder.audioEditSubject", artist=artist, title=title)
else:
subject = t(locale, "emails.actionReminder.audioEditSubjectFallback")
extra_styles = """
.alert {
@@ -987,6 +1004,7 @@ Get started: {self.frontend_url}
artist: Optional[str] = None,
title: Optional[str] = None,
job_id: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send 24h review reminder email with expiry warning.
@@ -1003,10 +1021,13 @@ Get started: {self.frontend_url}
Returns:
True if email was sent successfully
"""
song_info = f" — {artist} - {title}" if artist and title else ""
subject = f"Reminder: Your karaoke video is waiting for review{song_info}"
if artist and title:
subject = t(locale, "emails.reviewReminder.subject", artist=artist, title=title)
else:
subject = t(locale, "emails.reviewReminder.subjectFallback")
review_url = f"{self.frontend_url}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}/app"
locale_prefix = get_locale_prefix(locale)
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
extra_styles = """
.alert {
@@ -1084,6 +1105,7 @@ Get started: {self.frontend_url}
artist: Optional[str] = None,
title: Optional[str] = None,
credits_balance: int = 0,
locale: str = "en",
) -> bool:
"""
Send review expiry notification email.
@@ -1100,8 +1122,10 @@ Get started: {self.frontend_url}
Returns:
True if email was sent successfully
"""
song_info = f" — {artist} - {title}" if artist and title else ""
subject = f"Your karaoke video has expired{song_info}"
if artist and title:
subject = t(locale, "emails.reviewExpired.subject", artist=artist, title=title)
else:
subject = t(locale, "emails.reviewExpired.subjectFallback")
extra_styles = """
.info-box {
@@ -1146,7 +1170,7 @@ Get started: {self.frontend_url}
<p>You can create a new karaoke video anytime using your credits:</p>
<p style="text-align: center;">
<a href="{html.escape(self.frontend_url)}/app" class="create-btn">Create New Video</a>
<a href="{html.escape(self.frontend_url)}{get_locale_prefix(locale)}/app" class="create-btn">Create New Video</a>
</p>
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
@@ -1158,7 +1182,7 @@ Get started: {self.frontend_url}
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
f"Create a new video anytime: {self.frontend_url}/app\n\n"
f"Create a new video anytime: {self.frontend_url}{get_locale_prefix(locale)}/app\n\n"
"If you had any trouble or need help, just reply to this email."
)
@@ -1176,6 +1200,7 @@ Get started: {self.frontend_url}
artist: Optional[str] = None,
title: Optional[str] = None,
brand_code: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send follow-up email when a deferred YouTube upload completes.
@@ -1193,11 +1218,11 @@ Get started: {self.frontend_url}
safe_artist = sanitize_filename(artist) if artist else None
safe_title = sanitize_filename(title) if title else None
if brand_code and safe_artist and safe_title:
subject = f"{brand_code}: {safe_artist} - {safe_title} (YouTube upload ready!)"
subject = t(locale, "emails.youtubeUpload.subjectWithBrand", brand_code=brand_code, artist=safe_artist, title=safe_title)
elif safe_artist and safe_title:
subject = f"{safe_artist} - {safe_title} (YouTube upload ready!)"
subject = t(locale, "emails.youtubeUpload.subject", artist=safe_artist, title=safe_title)
else:
subject = "Your YouTube upload is ready!"
subject = t(locale, "emails.youtubeUpload.subjectFallback")
extra_styles = """
.content {
@@ -1226,6 +1251,7 @@ Get started: {self.frontend_url}
title: str,
job_id: str,
notes: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send order confirmation email to customer for made-for-you orders.
@@ -1240,7 +1266,7 @@ Get started: {self.frontend_url}
Returns:
True if email was sent successfully
"""
subject = f"Order Confirmed: {artist} - {title} | Nomad Karaoke"
subject = t(locale, "emails.madeForYouConfirmation.subject", artist=artist, title=title)
extra_styles = """
.order-details {
@@ -1662,14 +1688,14 @@ If the user looks legitimate, grant them credits from their admin page.
text_content=text_content,
)
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
def send_credit_denied_email(self, email: str, grant_type: str = "welcome", locale: str = "en") -> bool:
"""
Send a friendly-but-firm email when free credits are denied due to abuse signals.
CC'd to andrew@beveridge.uk so he can intervene if it's a false positive.
The tone invites the user to reply if it's a mistake.
"""
subject = "About your Nomad Karaoke free credits"
subject = t(locale, "emails.creditDenied.subject")
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
@@ -212,9 +212,11 @@ class EmailValidationService:
effective_domains = (external | manual) - allowlisted
else:
# Old data model (pre-migration): use disposable_domains + defaults
allowlisted = set()
effective_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
config = {
"disposable_domains": effective_domains,
"allowlisted_domains": allowlisted,
"blocked_emails": set(data.get("blocked_emails", [])),
"blocked_ips": set(data.get("blocked_ips", [])),
"verified_clean_domains": data.get("verified_clean_domains", {}),
@@ -222,6 +224,7 @@ class EmailValidationService:
else:
config = {
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
"allowlisted_domains": set(),
"blocked_emails": set(),
"blocked_ips": set(),
"verified_clean_domains": {},
@@ -267,6 +270,12 @@ class EmailValidationService:
if domain in config["disposable_domains"]:
return True
# Tier 1.5: Explicitly allowlisted domains skip external API checks.
# Without this, external APIs can override admin allowlist decisions
# (e.g. inbox.testmail.app is a legitimate testing domain we allow).
if domain in config.get("allowlisted_domains", set()):
return False
# Tier 2: Recently verified clean? Skip API calls
if self._is_domain_verified_clean(domain, config):
return False
+134
View File
@@ -115,6 +115,28 @@ class EncodingService:
"""Check if GCE preview encoding is enabled and configured."""
return self.settings.use_gce_preview_encoding and self.is_configured
def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
"""Safety net: try to start the encoding worker VM on first connection failure.
If the worker_manager is available, calls ensure_primary_running() so the VM
starts booting during the retry window. If worker_manager is not set (e.g. dev
mode with static URL), this is a no-op.
"""
if not self._worker_manager:
return
try:
result = self._worker_manager.ensure_primary_running()
if result["started"]:
logger.warning(
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
)
else:
logger.info(
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
)
except Exception as e:
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
async def _request_with_retry(
self,
method: str,
@@ -176,6 +198,8 @@ class EncodingService:
}
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
last_exception = e
if attempt == 0:
self._warmup_encoding_worker_fallback(job_id)
if attempt < MAX_RETRIES:
logger.warning(
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
@@ -560,6 +584,116 @@ class EncodingService:
timeout=timeout,
)
async def submit_render_video_job(
self,
job_id: str,
render_config: Dict[str, Any],
) -> Dict[str, Any]:
"""
Submit a render-video job to the GCE worker.
Args:
job_id: Unique job identifier
render_config: Configuration dict containing original_corrections_gcs_path,
audio_gcs_path, output_gcs_prefix, artist, title, and any other render params.
Returns:
Response from the encoding worker
Raises:
RuntimeError: If submission fails
"""
self._load_credentials()
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/render-video"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {"job_id": job_id, **render_config}
logger.info(f"[job:{job_id}] Submitting render-video job to GCE worker: {url}")
resp = await self._request_with_retry(
method="POST",
url=url,
headers=headers,
json_payload=payload,
timeout=30.0,
job_id=job_id,
)
if resp["status"] == 401:
raise RuntimeError("Invalid API key for encoding worker")
if resp["status"] == 409:
# Job already exists on worker — check if it already completed
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
try:
status = await self.get_job_status(job_id)
job_status = status.get("status", "unknown")
if job_status == "complete":
logger.info(f"[job:{job_id}] Render-video job already complete on GCE worker, returning cached result")
return {
"status": "cached",
"job_id": job_id,
"output_files": status.get("output_files"),
"metadata": status.get("metadata"),
}
elif job_status in ("pending", "running"):
logger.info(f"[job:{job_id}] Render-video job still in progress on GCE worker")
return {"status": "in_progress", "job_id": job_id}
else:
raise RuntimeError(f"Render-video job {job_id} already exists with status: {job_status}")
except RuntimeError as e:
if "not found" in str(e).lower():
raise RuntimeError(f"Render-video job {job_id} conflict: 409 but job not found on status check")
raise
if resp["status"] != 200:
raise RuntimeError(f"Failed to submit render-video job: {resp['status']} - {resp['text']}")
return resp["json"]
async def render_video_on_gce(
self,
job_id: str,
render_config: Dict[str, Any],
progress_callback=None,
) -> Dict[str, Any]:
"""
Submit render-video job and wait for completion.
This is a convenience method that combines submit + wait.
Args:
job_id: Unique job identifier
render_config: Configuration dict for the render-video worker endpoint
progress_callback: Optional callback for progress updates
Returns:
Final job status with output files and metadata
"""
# Submit the job
submit_result = await self.submit_render_video_job(job_id, render_config)
# If cached, return immediately — rendering already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
return {
"status": "complete",
"output_files": submit_result.get("output_files"),
"metadata": submit_result.get("metadata"),
}
# If in_progress, another request is rendering it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# Wait for completion
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
)
async def health_check(self) -> Dict[str, Any]:
"""
Check the health of the encoding worker.
+381 -1
View File
@@ -1,9 +1,11 @@
import asyncio
import glob as glob_module
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
@@ -59,12 +61,27 @@ class EncodePreviewRequest(BaseModel):
font_gcs_path: Optional[str] = None # gs://bucket/path/to/custom-font.ttf
class RenderVideoRequest(BaseModel):
job_id: str
original_corrections_gcs_path: str
updated_corrections_gcs_path: Optional[str] = None
audio_gcs_path: str
style_params_gcs_path: Optional[str] = None
style_assets: Optional[dict] = None
output_gcs_prefix: str
artist: str
title: str
subtitle_offset_ms: int = 0
video_resolution: str = "4k"
class JobStatus(BaseModel):
job_id: str
status: str # pending, running, complete, failed
progress: int # 0-100
error: Optional[str] = None
output_files: Optional[list[str]] = None
metadata: Optional[dict] = None
def download_from_gcs(gcs_uri: str, local_path: Path):
@@ -136,6 +153,59 @@ def upload_single_file_to_gcs(local_path: Path, gcs_uri: str):
logger.info(f"Uploaded: {local_path} -> {gcs_uri}")
# Style asset disk cache directory
# Persists across jobs to avoid re-downloading the same theme assets (fonts, backgrounds)
STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
the cached file size against the GCS object size (via a lightweight metadata
call). On size mismatch the stale entry is replaced.
When cache_dir is None, downloads directly (no caching).
"""
if cache_dir is None:
download_single_file_from_gcs(gcs_uri, local_path)
return
cache_dir.mkdir(parents=True, exist_ok=True)
cache_key = hashlib.sha256(gcs_uri.encode()).hexdigest()
cached_path = cache_dir / cache_key
if cached_path.exists():
# Validate cached file against GCS object size
try:
parts = gcs_uri.replace("gs://", "").split("/", 1)
bucket_name = parts[0]
blob_name = parts[1] if len(parts) > 1 else ""
blob = storage_client.bucket(bucket_name).blob(blob_name)
blob.reload() # Fetch metadata (lightweight HEAD request)
gcs_size = blob.size
cached_size = cached_path.stat().st_size
if gcs_size is not None and cached_size != gcs_size:
logger.warning(
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
)
cached_path.unlink()
else:
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
shutil.copy2(str(cached_path), str(local_path))
return
except Exception as e:
# On transient GCS errors, serve from cache rather than failing the job
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
shutil.copy2(str(cached_path), str(local_path))
return
logger.info(f"Cache miss for {gcs_uri}, downloading...")
download_single_file_from_gcs(gcs_uri, local_path)
# Store in cache
shutil.copy2(str(local_path), str(cached_path))
def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewRequest"):
# Run FFmpeg encoding for preview video (480x270, fast settings)
jobs[job_id]["status"] = "running"
@@ -239,6 +309,192 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
raise
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
to produce with_vocals.mkv and subtitle files, then uploads results.
Style assets use disk cache to avoid repeated downloads of the same theme.
This mirrors the logic in render_video_worker.py but runs on the GCE VM
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
"""
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 5
try:
# Import from installed karaoke-gen wheel
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.style_loader import load_styles_from_gcs
from karaoke_gen.utils import sanitize_filename
# 1. Download original corrections
corrections_path = work_dir / "corrections.json"
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
jobs[job_id]["progress"] = 15
with open(corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
base_result = CorrectionResult.from_dict(original_data)
# 2. Apply user corrections if available
if request.updated_corrections_gcs_path:
updated_path = work_dir / "corrections_updated.json"
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
if isinstance(updated_data, dict) and "corrections" in updated_data:
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
logger.info(f"[job:{job_id}] Applied user corrections")
else:
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
jobs[job_id]["progress"] = 25
# 3. Download audio
audio_path = work_dir / "audio.flac"
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
jobs[job_id]["progress"] = 35
# 4. Process countdown intro
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=str(audio_path),
)
audio_path = Path(audio_path_str)
jobs[job_id]["progress"] = 40
# 5. Download style assets (with disk cache for repeated themes)
def cached_download(gcs_path, local_path):
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=request.style_params_gcs_path,
style_assets=request.style_assets,
temp_dir=str(work_dir),
download_func=cached_download,
logger=logger,
)
# Register any downloaded fonts with fontconfig
for asset_key, gcs_path in (request.style_assets or {}).items():
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
fonts_dir = Path("/usr/local/share/fonts/custom")
fonts_dir.mkdir(parents=True, exist_ok=True)
font_filename = gcs_path.split("/")[-1]
font_dest = fonts_dir / font_filename
if not font_dest.exists():
ext = os.path.splitext(gcs_path)[1]
style_font = work_dir / "style" / f"{asset_key}{ext}"
if style_font.exists():
shutil.copy2(str(style_font), str(font_dest))
subprocess.run(["fc-cache", "-fv"], capture_output=True)
logger.info(f"Registered font: {font_filename}")
jobs[job_id]["progress"] = 50
# 6. Configure and run OutputGenerator
output_dir = work_dir / "output"
cache_dir = work_dir / "cache"
output_dir.mkdir(exist_ok=True)
cache_dir.mkdir(exist_ok=True)
config = OutputConfig(
output_dir=str(output_dir),
cache_dir=str(cache_dir),
output_styles_json=styles_path,
render_video=True,
generate_cdg=False,
generate_plain_text=True,
generate_lrc=True,
video_resolution=request.video_resolution,
subtitle_offset_ms=request.subtitle_offset_ms,
)
output_generator = OutputGenerator(config, logger)
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
jobs[job_id]["progress"] = 55
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={},
output_prefix=output_prefix,
audio_filepath=str(audio_path),
artist=request.artist,
title=request.title,
)
jobs[job_id]["progress"] = 85
# 7. Upload outputs to GCS
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
output_files = []
if outputs.video and os.path.exists(outputs.video):
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
output_files.append(gcs_path)
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
else:
raise RuntimeError("Video generation failed - no output file produced")
if outputs.ass and os.path.exists(outputs.ass):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
output_files.append(gcs_path)
if outputs.lrc and os.path.exists(outputs.lrc):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
output_files.append(gcs_path)
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
output_files.append(gcs_path)
jobs[job_id]["progress"] = 95
jobs[job_id]["output_files"] = output_files
jobs[job_id]["metadata"] = {
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
}
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
except ImportError as e:
error_msg = (
f"OutputGenerator not available: {e}. "
"The karaoke-gen wheel must be installed. "
"Check that ensure_latest_wheel() succeeded."
)
logger.error(error_msg)
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = error_msg
raise RuntimeError(error_msg) from e
except Exception as e:
logger.error(f"[job:{job_id}] Render video failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
raise
def ensure_latest_wheel():
'''Download and install latest karaoke-gen wheel from GCS.
@@ -307,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
return None
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
"""Generate a MOV video from a static PNG image using FFmpeg.
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
encoding requires more memory than the right-sized Cloud Run container
provides (2Gi). See PR #640 / #647.
Args:
png_path: Path to input PNG image
mov_path: Path for output MOV video
duration: Video duration in seconds (default 5)
Returns:
Path to generated MOV file
Raises:
RuntimeError: If FFmpeg fails
"""
command = [
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
"-loop", "1", "-framerate", "30", "-i", str(png_path),
"-f", "lavfi", "-i", "anullsrc",
"-c:v", "libx264", "-r", "30", "-t", str(duration),
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
"-c:a", "aac", "-shortest",
str(mov_path),
]
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
if not mov_path.exists() or mov_path.stat().st_size < 1024:
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
return mov_path
def run_encoding(job_id: str, work_dir: Path, config: dict):
'''Run encoding using LocalEncodingService (single source of truth).
@@ -336,10 +629,36 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.info(f"Encoding for: {base_name}")
# Find input files in work_dir
# Title/end screens are in screens/ subdirectory
# Title/end screens: look for MOV first, fall back to generating from PNG.
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
# Get intro/end video durations from style config (default 5s)
intro_duration = config.get("intro_video_duration", 5)
end_duration = config.get("end_video_duration", 5)
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
if not title_video or title_video.stat().st_size < 1024:
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
if title_png:
title_mov_path = title_png.parent / "title.mov"
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
elif title_video:
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
# Generate end MOV from PNG if missing or invalid
if not end_video or (end_video and end_video.stat().st_size < 1024):
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
if end_png:
end_mov_path = end_png.parent / "end.mov"
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
elif end_video:
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
# Karaoke video - search for With Vocals or main karaoke video
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
# old encoding outputs from finals/ directory when re-encoding after reset
@@ -584,6 +903,36 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
jobs[job_id]["error"] = str(e)
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
# Process a render-video job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
ensure_latest_wheel()
with tempfile.TemporaryDirectory() as temp_dir:
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run render-video in thread pool (CPU-bound)
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
run_render_video,
job_id,
work_dir,
request
)
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
logger.info(f"Render video job {job_id} complete")
except Exception as e:
logger.error(f"Render video job {job_id} failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
@app.post("/encode-preview")
async def submit_preview_encode_job(request: EncodePreviewRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit a preview encoding job
@@ -615,6 +964,37 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
return {"status": "accepted", "job_id": job_id}
@app.post("/render-video")
async def submit_render_video_job(request: RenderVideoRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit a render-video job
job_id = request.job_id
# If job already exists, return cached result or current status
if job_id in jobs:
existing_job = jobs[job_id]
if existing_job["status"] == "complete":
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files"), "metadata": existing_job.get("metadata")}
elif existing_job["status"] == "failed":
# Previous attempt failed, allow retry by replacing the job
pass
else:
# Job is still in progress
return {"status": "in_progress", "job_id": job_id}
jobs[job_id] = {
"job_id": job_id,
"status": "pending",
"progress": 0,
"error": None,
"output_files": None,
"metadata": None,
}
background_tasks.add_task(process_render_video_job, job_id, request)
return {"status": "accepted", "job_id": job_id}
@app.post("/encode")
async def submit_encode_job(request: EncodeRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit an encoding job
+4 -2
View File
@@ -213,8 +213,10 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
"video_worker": [
JobStatus.INSTRUMENTAL_SELECTED,
JobStatus.REVIEW_COMPLETE,
JobStatus.RENDERING_VIDEO,
JobStatus.GENERATING_VIDEO,
# Note: RENDERING_VIDEO and GENERATING_VIDEO are intentionally excluded.
# If the job is already in those states, another worker is actively processing it.
# Including them caused a race condition where Cloud Run Job retries + manual retries
# could launch concurrent workers that corrupt each other's state transitions.
],
"render_video_worker": [
JobStatus.REVIEW_COMPLETE,
+34 -9
View File
@@ -12,8 +12,10 @@ import logging
import os
from typing import Optional, Dict, Any
from backend.i18n import get_locale_prefix
from backend.services.email_service import get_email_service
from backend.services.template_service import get_template_service
from backend.services.user_service import get_user_service
logger = logging.getLogger(__name__)
@@ -51,19 +53,30 @@ class JobNotificationService:
self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
self.backend_url = os.getenv("BACKEND_URL", "https://api.nomadkaraoke.com")
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None) -> str:
def _get_user_locale(self, user_email: str) -> str:
"""Look up user's locale preference from Firestore, defaulting to 'en'."""
try:
user_service = get_user_service()
user = user_service.get_user(user_email)
if user and user.locale:
return user.locale
except Exception:
pass # Fall back to English
return "en"
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None, locale: str = "en") -> str:
"""Build the lyrics review URL for a job."""
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/review"
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/review"
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None) -> str:
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None, locale: str = "en") -> str:
"""Build the instrumental selection URL for a job."""
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/instrumental"
def _build_audio_edit_url(self, job_id: str) -> str:
def _build_audio_edit_url(self, job_id: str, locale: str = "en") -> str:
"""Build the audio edit URL for a job."""
return f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/audio-edit"
async def send_job_completion_email(
self,
@@ -105,6 +118,9 @@ class JobNotificationService:
return False
try:
# Get user locale for email
user_locale = self._get_user_locale(user_email)
# Render the completion message using template service
message_content = self.template_service.render_job_completion(
name=user_name,
@@ -126,6 +142,7 @@ class JobNotificationService:
title=title,
brand_code=brand_code,
cc_admin=True,
locale=user_locale,
)
if success:
@@ -171,6 +188,9 @@ class JobNotificationService:
return False
try:
# Get user locale for email
user_locale = self._get_user_locale(user_email)
message_content = self.template_service.render_youtube_upload_complete(
artist=artist,
title=title,
@@ -183,6 +203,7 @@ class JobNotificationService:
artist=artist,
title=title,
brand_code=brand_code,
locale=user_locale,
)
if success:
@@ -237,9 +258,12 @@ class JobNotificationService:
return False
try:
# Get user locale for email
user_locale = self._get_user_locale(user_email)
# Render the appropriate template
if action_type == "lyrics":
review_url = self._build_review_url(job_id, audio_hash, review_token)
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
artist=artist,
@@ -247,7 +271,7 @@ class JobNotificationService:
review_url=review_url,
)
elif action_type == "instrumental":
instrumental_url = self._build_instrumental_url(job_id, instrumental_token)
instrumental_url = self._build_instrumental_url(job_id, instrumental_token, locale=user_locale)
message_content = self.template_service.render_action_needed_instrumental(
name=user_name,
artist=artist,
@@ -255,7 +279,7 @@ class JobNotificationService:
instrumental_url=instrumental_url,
)
elif action_type == "audio_edit":
audio_edit_url = self._build_audio_edit_url(job_id)
audio_edit_url = self._build_audio_edit_url(job_id, locale=user_locale)
# Reuse the lyrics template but with the audio edit URL and different subject
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
@@ -274,6 +298,7 @@ class JobNotificationService:
action_type=action_type,
artist=artist,
title=title,
locale=user_locale,
)
if success:
@@ -12,6 +12,7 @@ from pywebpush import webpush, WebPushException
from backend.config import get_settings
from backend.models.user import User, PushSubscription
from backend.i18n import t
logger = logging.getLogger(__name__)
@@ -239,15 +240,16 @@ class PushNotificationService:
artist = job.get("artist", "Unknown Artist")
title = job.get("title", "Unknown Title")
tenant_id = job.get("tenant_id") or None
locale = job.get("locale", "en")
if action_type == "lyrics":
notif_title = "Review Lyrics"
notif_body = f'"{title}" by {artist} needs lyrics review'
notif_title = t(locale, "pushNotifications.reviewLyricsTitle")
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
url = f"/app/jobs#/{job_id}/review"
tag = f"lyrics-{job_id}"
else: # instrumental
notif_title = "Select Instrumental"
notif_body = f'"{title}" by {artist} needs instrumental selection'
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
url = f"/app/jobs#/{job_id}/instrumental"
tag = f"instrumental-{job_id}"
@@ -278,11 +280,12 @@ class PushNotificationService:
artist = job.get("artist", "Unknown Artist")
title = job.get("title", "Unknown Title")
tenant_id = job.get("tenant_id") or None
locale = job.get("locale", "en")
return await self.send_push(
user_email=user_email,
title="Video Ready!",
body=f'Your karaoke video for "{title}" by {artist} is ready to download',
title=t(locale, "pushNotifications.videoReadyTitle"),
body=t(locale, "pushNotifications.videoReadyBody", title=title, artist=artist),
url=f"/app/?job={job_id}",
tag=f"complete-{job_id}",
tenant_id=tenant_id,
+66 -36
View File
@@ -370,7 +370,11 @@ class UserService:
logger.exception("Error verifying magic link")
return False, None, "An error occurred during verification"
def grant_welcome_credits_if_eligible(self, email: str) -> Tuple[bool, str]:
def grant_welcome_credits_if_eligible(
self,
email: str,
precomputed_eval: Optional[dict] = None,
) -> Tuple[bool, str]:
"""
Grant welcome credits on first magic link verification.
@@ -381,6 +385,12 @@ class UserService:
check (survives credit_transactions list trimming). Falls back to
checking for welcome_credit transaction as secondary defense.
Args:
email: User's email address.
precomputed_eval: Optional pre-computed evaluation from magic link doc.
Keys: credit_eval_decision, credit_eval_reasoning, credit_eval_error.
If provided and has a decision, skips the AI call.
Returns:
Tuple of (credits_granted: bool, status: str).
status is one of: "granted", "denied", "already_granted", "not_found", "error"
@@ -400,50 +410,70 @@ class UserService:
if txn.reason == "welcome_credit":
return False, "already_granted"
# AI evaluation: check for abuse signals before granting
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
if evaluation.decision == "deny":
# Mark as evaluated but not granted so we don't re-evaluate
self.update_user(email, welcome_credits_granted=True)
logger.info(
f"Denied welcome credits to {email}: {evaluation.reasoning}"
# Skip AI evaluation for test emails (e.g. E2E test accounts)
# to avoid wasting LLM credits and sending unnecessary denial emails
from backend.utils.test_data import is_test_email
if not is_test_email(email):
# AI evaluation: check for abuse signals before granting
# Use pre-computed result from magic link if available
try:
from backend.services.credit_evaluation_service import (
get_credit_evaluation_service,
CreditEvaluation,
)
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(email, "welcome")
except Exception:
logger.exception(f"Failed to send credit denied email to {email}")
return False, "denied"
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
if precomputed_decision:
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
evaluation = CreditEvaluation(
decision=precomputed_decision,
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
confidence=1.0,
error=(precomputed_eval or {}).get("credit_eval_error"),
)
else:
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
if evaluation.decision == "pending_review":
# Don't mark welcome_credits_granted — allow retry after manual review
logger.info(
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
)
if evaluation.decision == "deny":
# Mark as evaluated but not granted so we don't re-evaluate
self.update_user(email, welcome_credits_granted=True)
logger.info(
f"Denied welcome credits to {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(email, "welcome")
except Exception:
logger.exception(f"Failed to send credit denied email to {email}")
return False, "denied"
if evaluation.decision == "pending_review":
# Don't mark welcome_credits_granted — allow retry after manual review
logger.info(
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
return False, "pending_review"
except Exception:
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
pass
return False, "pending_review"
except Exception:
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
pass
return False, "pending_review"
else:
logger.info(f"Skipping credit evaluation for test email {email}")
# Grant welcome credits
welcome_credit = self.NEW_USER_FREE_CREDITS
+33 -5
View File
@@ -383,14 +383,13 @@ class WorkerService:
"""
Trigger audio separation worker.
Always uses Cloud Run Jobs to avoid instance termination during long-running
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
instances mid-processing when no HTTP requests were active.
Uses Cloud Run Jobs with L4 GPU in us-east4 for direct audio separation.
"""
return await self._trigger_worker_cloud_run_job(
job_id=job_id,
cloud_run_job_name="audio-separation-job",
worker_module="audio_worker",
location="us-east4", # GPU job runs in us-east4 (L4 quota)
)
async def trigger_lyrics_worker(self, job_id: str) -> bool:
@@ -412,14 +411,40 @@ class WorkerService:
"""Trigger screen generation worker."""
return await self.trigger_worker("screens", job_id)
def _warmup_encoding_worker(self, job_id: str) -> None:
"""Fire-and-forget warmup of the encoding worker VM.
Called before dispatching video/render workers so the GCE encoding
VM starts booting while the worker downloads files and prepares.
Failures are logged but never block worker dispatch.
"""
try:
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
db = firestore.Client(project=self.settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=self.settings.google_cloud_project,
)
result = manager.ensure_primary_running()
if result["started"]:
logger.info(f"[job:{job_id}] Encoding worker warmup: started VM {result['vm_name']}")
else:
logger.info(f"[job:{job_id}] Encoding worker warmup: VM {result['vm_name']} already running")
except Exception as e:
logger.warning(f"[job:{job_id}] Encoding worker warmup failed (non-fatal): {e}")
async def trigger_video_worker(self, job_id: str) -> bool:
"""
Trigger video generation worker.
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
self._warmup_encoding_worker(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
return await self._trigger_cloud_run_job(job_id)
return await self.trigger_worker("video", job_id)
@@ -448,6 +473,7 @@ class WorkerService:
job_id: str,
cloud_run_job_name: str,
worker_module: str,
location: str | None = None,
) -> bool:
"""
Trigger a worker as a Cloud Run Job.
@@ -460,6 +486,7 @@ class WorkerService:
job_id: Job ID to process
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
worker_module: Worker module name (e.g., "lyrics_worker")
location: GCP region for the job (defaults to settings.gcp_region)
Returns:
True if job was triggered successfully, False otherwise
@@ -472,7 +499,7 @@ class WorkerService:
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
return False
location = self.settings.gcp_region
location = location or self.settings.gcp_region
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
# Create Cloud Run Jobs client
@@ -510,6 +537,7 @@ class WorkerService:
async def trigger_render_video_worker(self, job_id: str) -> bool:
"""Trigger render video worker (post-review)."""
self._warmup_encoding_worker(job_id)
return await self.trigger_worker("render-video", job_id)
async def schedule_idle_reminder(
+2 -2
View File
@@ -282,7 +282,7 @@ class TestSubmitFeedbackEmailIntegration:
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# Verify email notification was called with matching args
@@ -339,7 +339,7 @@ class TestSubmitFeedbackEmailIntegration:
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# User still gets credits even though email failed
+97
View File
@@ -130,6 +130,36 @@ class TestGrantWelcomeCredits:
assert update_args['credits'] == 1
assert update_args['welcome_credits_granted'] is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_uses_precomputed_eval_when_provided(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible uses pre-computed eval and skips AI call."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@example.com", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible(
"new@example.com",
precomputed_eval={
"credit_eval_decision": "grant",
"credit_eval_reasoning": "Pre-computed: clean user",
},
)
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_if_flag_already_set(self, mock_fs, mock_settings):
@@ -206,6 +236,30 @@ class TestGrantWelcomeCredits:
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_evaluation_for_test_emails(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible skips AI evaluation for @inbox.testmail.app emails."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="e2e.test@inbox.testmail.app", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible("e2e.test@inbox.testmail.app")
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
# =============================================================================
# Phase 2: Per-IP Signup Rate Limiting
@@ -565,6 +619,49 @@ class TestVerifyGrantsCredits:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_passes_precomputed_eval(self, mock_user_svc):
"""Verify endpoint passes pre-computed eval from magic link doc."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
# Add pre-computed eval to the magic link doc
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
mock_ml_doc.to_dict.return_value = {
'email': user.email,
'tenant_id': None,
'credit_eval_decision': 'grant',
'credit_eval_reasoning': 'Clean user',
}
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
# Verify precomputed_eval was passed through
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
assert call_kwargs[1]['precomputed_eval'] == {
'credit_eval_decision': 'grant',
'credit_eval_reasoning': 'Clean user',
}
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_falls_back_without_precomputed_eval(self, mock_user_svc):
"""Verify endpoint passes None when no pre-computed eval exists."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
assert call_kwargs[1]['precomputed_eval'] is None
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_returns_zero_credits_for_returning_user(self, mock_user_svc):
"""Returning user gets credits_granted=0."""
user = User(
+150
View File
@@ -0,0 +1,150 @@
"""
Tests for Google OIDC token validation in AuthService.
Cloud Scheduler and Cloud Tasks send OIDC JWTs signed by Google.
The auth service must validate these and grant admin access for
requests from the configured service account.
"""
import pytest
from unittest.mock import patch, MagicMock
from backend.services.auth_service import AuthService, AuthResult, UserType
@pytest.fixture
def auth_service():
"""Create an AuthService instance with mocked Firestore."""
with patch("backend.services.auth_service.FirestoreService"):
service = AuthService()
service._scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
return service
# A fake JWT-shaped token (3 dot-separated parts)
FAKE_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifQ.signature"
class TestOidcTokenValidation:
"""Tests for _validate_oidc_token."""
def test_non_jwt_returns_none(self, auth_service):
"""Non-JWT tokens (no dots) should return None immediately."""
result = auth_service._validate_oidc_token("simple-token-no-dots")
assert result is None
def test_two_dots_not_three_parts_returns_none(self, auth_service):
"""Tokens with wrong number of dots should return None."""
result = auth_service._validate_oidc_token("only.one.dot-but-not-jwt")
# This has 2 dots = 3 parts, so it will attempt OIDC validation
# but fail signature verification. That's fine — it returns None.
# A token with 1 dot should be skipped entirely.
result_one_dot = auth_service._validate_oidc_token("one.dot")
assert result_one_dot is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_valid_oidc_from_allowed_sa(self, mock_verify, auth_service):
"""Valid OIDC token from the configured service account grants admin."""
mock_verify.return_value = {
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
"email_verified": True,
"iss": "https://accounts.google.com",
"aud": "https://api.nomadkaraoke.com/api/internal/process-stale-reviews",
}
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is not None
assert result.is_valid is True
assert result.is_admin is True
assert result.user_type == UserType.ADMIN
assert result.remaining_uses == -1
assert result.user_email == "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_oidc_from_wrong_sa_returns_none(self, mock_verify, auth_service):
"""OIDC token from a different service account is rejected."""
mock_verify.return_value = {
"email": "attacker@evil-project.iam.gserviceaccount.com",
"email_verified": True,
"iss": "https://accounts.google.com",
}
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_expired_oidc_token_returns_none(self, mock_verify, auth_service):
"""Expired OIDC token raises ValueError and returns None."""
mock_verify.side_effect = ValueError("Token expired")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_invalid_signature_returns_none(self, mock_verify, auth_service):
"""Token with invalid signature raises ValueError and returns None."""
mock_verify.side_effect = ValueError("Could not verify token signature")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_network_error_returns_none(self, mock_verify, auth_service):
"""Network error fetching Google certs returns None gracefully."""
mock_verify.side_effect = Exception("Connection timeout")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
class TestValidateTokenFullOidc:
"""Tests that OIDC validation is properly integrated into validate_token_full."""
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_oidc_token_grants_admin_via_validate_token_full(self, mock_verify, auth_service):
"""OIDC token flows through validate_token_full and grants admin."""
mock_verify.return_value = {
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
"email_verified": True,
}
# Mock Firestore to not interfere
auth_service.firestore.get_token = MagicMock(return_value=None)
result = auth_service.validate_token_full(FAKE_JWT)
assert result.is_valid is True
assert result.is_admin is True
assert result.user_type == UserType.ADMIN
def test_admin_token_still_works(self, auth_service):
"""Admin tokens from env var still take priority over OIDC."""
auth_service.admin_tokens = ["test-admin-token"]
result = auth_service.validate_token_full("test-admin-token")
assert result.is_valid is True
assert result.is_admin is True
assert result.message == "Admin access granted"
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_failed_oidc_falls_through_to_firestore(self, mock_verify, auth_service):
"""If OIDC validation fails, token is still checked against Firestore."""
mock_verify.side_effect = ValueError("Invalid token")
# Firestore has a valid token
auth_service.firestore.get_token = MagicMock(return_value={
"type": "unlimited",
"active": True,
"max_uses": -1,
"user_email": "user@example.com",
})
result = auth_service.validate_token_full(FAKE_JWT)
assert result.is_valid is True
assert result.user_type == UserType.UNLIMITED
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
# Metadata and original_segments preserved
assert original_data['metadata']['preserved'] is True
assert original_data['original_segments'][0]['id'] == 1
class TestCompleteReviewSkipsEmptyCorrections:
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
Bug scenario: Completing review via admin API without corrections payload writes
an empty {} to corrections_updated.json. Downstream render workers then get
KeyError: 'corrections' when processing it.
"""
def test_no_corrections_key_skips_upload(self):
"""When updated_data has only instrumental_selection, no corrections file is written."""
# Simulate what the endpoint does with the corrections_to_save logic
updated_data = {"instrumental_selection": "clean"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# This is the guard we added
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write corrections_updated.json for empty payload"
def test_with_corrections_key_allows_upload(self):
"""When updated_data has corrections, the file should be written."""
updated_data = {
"corrections": [{"id": 1, "type": "edit"}],
"corrected_segments": [{"id": 1, "text": "fixed"}],
"instrumental_selection": "with_backing",
}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
should_write = corrections_to_save and "corrections" in corrections_to_save
assert should_write, "Should write corrections_updated.json when corrections present"
def test_empty_dict_payload_skips_upload(self):
"""When updated_data is effectively empty after removing instrumental_selection."""
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Has content but no "corrections" key
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write without corrections key"
def test_render_worker_handles_empty_corrections_gracefully(self):
"""Document that render workers skip empty corrections_updated.json.
Both GCE and Cloud Run workers now check for 'corrections' key
before passing to CorrectionOperations.update_correction_result_with_data().
"""
# Simulates what the workers do on download
empty_updated_data = {}
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
# Dict with irrelevant keys
bad_updated_data = {"some_key": "value"}
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
assert not has_valid_corrections, "Dict without corrections key should not be valid"
+3 -3
View File
@@ -59,8 +59,8 @@ class TestSendReviewReminder:
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
assert "gen.nomadkaraoke.com/en/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/en/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
def test_content_includes_expiry_warning(self):
"""Content should warn about 24h expiry."""
@@ -153,4 +153,4 @@ class TestSendReviewExpired:
credits_balance=2,
)
call_args = service.provider.send_email.call_args
assert "gen.nomadkaraoke.com/app" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/en/app" in call_args.kwargs["html_content"]
@@ -542,6 +542,41 @@ class TestExternalAPIChecks:
# No HTTP calls should have been made
mock_client.return_value.get.assert_not_called()
# =========================================================================
# Allowlisted domain bypass (Tier 1.5)
# =========================================================================
def test_allowlisted_domain_skips_external_api_checks(self, mock_db):
"""Allowlisted domains should skip external API checks entirely.
Regression test: inbox.testmail.app was getting flagged by DeBounce
even though it was in the allowlist, because external API calls ran
after the static blocklist check but before checking the allowlist.
"""
from backend.services.email_validation_service import EmailValidationService
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["yopmail.com"],
"manual_domains": ["inbox.testmail.app"], # auto-learned by DeBounce
"allowlisted_domains": ["inbox.testmail.app"], # but also allowlisted
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
service = EmailValidationService(db=mock_db)
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client:
result = service.is_disposable_domain("user@inbox.testmail.app")
assert result is False
# No HTTP calls should have been made — allowlist bypasses external APIs
mock_client.return_value.get.assert_not_called()
# =========================================================================
# DeBounce API
# =========================================================================
+31
View File
@@ -239,6 +239,37 @@ class TestRequestWithRetry:
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
class TestWarmupFallback:
"""Tests for _warmup_encoding_worker_fallback() in the retry loop."""
def test_warmup_fallback_called_on_first_connection_failure(self, encoding_service):
"""Warmup fallback is called when the first connection attempt fails."""
mock_manager = MagicMock()
mock_manager.ensure_primary_running.return_value = {
"started": True, "vm_name": "encoding-worker-b", "primary_url": "http://1.2.3.4:8080"
}
encoding_service._worker_manager = mock_manager
encoding_service._warmup_encoding_worker_fallback("test-job")
mock_manager.ensure_primary_running.assert_called_once()
def test_warmup_fallback_noop_without_worker_manager(self, encoding_service):
"""Warmup fallback is a no-op when worker_manager is not set (dev mode)."""
encoding_service._worker_manager = None
# Should not raise
encoding_service._warmup_encoding_worker_fallback("test-job")
def test_warmup_fallback_swallows_exceptions(self, encoding_service):
"""Warmup fallback never raises — failures are logged but non-fatal."""
mock_manager = MagicMock()
mock_manager.ensure_primary_running.side_effect = Exception("Compute API down")
encoding_service._worker_manager = mock_manager
# Should not raise
encoding_service._warmup_encoding_worker_fallback("test-job")
class TestWaitForCompletionPollTolerance:
"""Tests for wait_for_completion() transient failure tolerance."""
+117
View File
@@ -0,0 +1,117 @@
"""Tests for backend.i18n translation utility."""
import pytest
from unittest.mock import MagicMock
from backend.i18n import t, get_locale_from_request, get_locale_prefix, SUPPORTED_LOCALES, DEFAULT_LOCALE, _load_translations
class TestTranslationFunction:
"""Tests for t() function."""
def test_returns_english_string(self):
result = t("en", "jobs.notFound")
assert result == "Job not found"
def test_dotted_key_path(self):
result = t("en", "pushNotifications.reviewLyricsTitle")
assert result == "Review Lyrics"
def test_interpolation(self):
result = t("en", "jobs.notCompleted", status="downloading")
assert result == "Only completed jobs can be edited. Current status: downloading"
def test_multiple_interpolation_vars(self):
result = t("en", "jobs.durationMismatch", upload_duration="120", original_duration="180")
assert "120s" in result
assert "180s" in result
def test_spanish_returns_translated_string(self):
result = t("es", "jobs.notFound")
assert result == "Trabajo no encontrado"
def test_fallback_to_english_for_missing_key_in_other_locale(self):
# Key that exists in en.json but not in es.json should fall back to English
result = t("es", "nonexistent.key.path")
assert result == "nonexistent.key.path" # Falls all the way to key itself
def test_returns_key_for_nonexistent_key(self):
result = t("en", "nonexistent.key.path")
assert result == "nonexistent.key.path"
def test_unsupported_locale_falls_back_to_english(self):
result = t("fr", "jobs.notFound")
assert result == "Job not found"
def test_empty_locale_falls_back_to_english(self):
result = t("", "jobs.notFound")
assert result == "Job not found"
def test_missing_interpolation_var_returns_template(self):
# If kwargs are missing, return template string as-is
result = t("en", "jobs.notCompleted")
assert "{status}" in result
def test_all_supported_locales_load(self):
for locale in SUPPORTED_LOCALES:
translations = _load_translations(locale)
assert isinstance(translations, dict)
assert len(translations) > 0
class TestGetLocaleFromRequest:
"""Tests for get_locale_from_request()."""
def _make_request(self, accept_language: str = "") -> MagicMock:
request = MagicMock()
request.headers = {"accept-language": accept_language}
return request
def test_simple_locale(self):
request = self._make_request("de")
assert get_locale_from_request(request) == "de"
def test_locale_with_region(self):
request = self._make_request("es-MX")
assert get_locale_from_request(request) == "es"
def test_quality_weighted_list(self):
request = self._make_request("fr;q=0.9,de;q=0.8,en;q=0.7")
# fr is not supported, de is next
assert get_locale_from_request(request) == "de"
def test_complex_accept_language(self):
request = self._make_request("en-US,en;q=0.9,de;q=0.8")
assert get_locale_from_request(request) == "en"
def test_unsupported_locale_returns_default(self):
request = self._make_request("ja")
assert get_locale_from_request(request) == DEFAULT_LOCALE
def test_empty_header_returns_default(self):
request = self._make_request("")
assert get_locale_from_request(request) == DEFAULT_LOCALE
def test_missing_header_returns_default(self):
request = MagicMock()
request.headers = {}
assert get_locale_from_request(request) == DEFAULT_LOCALE
class TestGetLocalePrefix:
"""Tests for get_locale_prefix()."""
def test_english(self):
assert get_locale_prefix("en") == "/en"
def test_spanish(self):
assert get_locale_prefix("es") == "/es"
def test_german(self):
assert get_locale_prefix("de") == "/de"
def test_unsupported_returns_english(self):
assert get_locale_prefix("fr") == "/en"
def test_empty_returns_english(self):
assert get_locale_prefix("") == "/en"
+7
View File
@@ -285,6 +285,13 @@ class TestValidateWorkerCanRun:
assert error is not None
assert "video_worker called but job status is pending" in error
def test_video_worker_invalid_with_generating_video_status(self):
"""Test video worker rejects GENERATING_VIDEO to prevent concurrent worker races."""
job = create_test_job(status=JobStatus.GENERATING_VIDEO)
error = validate_worker_can_run("video_worker", job)
assert error is not None
assert "video_worker called but job status is generating_video" in error
def test_render_video_worker_valid_with_review_complete_status(self):
"""Test render video worker is valid with REVIEW_COMPLETE status."""
job = create_test_job(status=JobStatus.REVIEW_COMPLETE)
@@ -22,7 +22,7 @@ class TestURLBuilding:
url = service._build_review_url("job-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
def test_build_review_url_ignores_legacy_params(self):
"""Test review URL ignores legacy audio_hash and review_token params."""
@@ -33,7 +33,7 @@ class TestURLBuilding:
url = service._build_review_url("job-123", audio_hash="abc123", review_token="token456")
# URL should be the simple consolidated route
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
# No query params
assert "?" not in url
@@ -45,7 +45,7 @@ class TestURLBuilding:
# Note: job IDs with slashes would be unusual in real usage
url = service._build_review_url("abc-def-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs#/abc-def-123/review"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/abc-def-123/review"
def test_build_instrumental_url_basic(self):
"""Test basic instrumental URL building."""
@@ -54,7 +54,7 @@ class TestURLBuilding:
url = service._build_instrumental_url("job-123")
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
def test_build_instrumental_url_ignores_legacy_params(self):
"""Test instrumental URL ignores legacy instrumental_token param."""
@@ -65,7 +65,7 @@ class TestURLBuilding:
url = service._build_instrumental_url("job-123", instrumental_token="inst-token")
# URL should be the simple consolidated route
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
# No query params
assert "?" not in url
@@ -312,7 +312,7 @@ class TestActionReminderEmail:
# Verify the review URL was passed to template
call_kwargs = service.template_service.render_action_needed_lyrics.call_args.kwargs
review_url = call_kwargs.get('review_url')
assert review_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
assert review_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
@pytest.mark.asyncio
async def test_send_instrumental_reminder_includes_url(self):
@@ -334,7 +334,7 @@ class TestActionReminderEmail:
# Verify the instrumental URL was passed to template
call_kwargs = service.template_service.render_action_needed_instrumental.call_args.kwargs
instrumental_url = call_kwargs.get('instrumental_url')
assert instrumental_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
assert instrumental_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
class TestGetCompletionMessage:
+6 -2
View File
@@ -90,12 +90,16 @@ class TestExceptionHandlers:
credits_required=1,
)
response = await insufficient_credits_exception_handler(request=None, exc=exc)
from unittest.mock import MagicMock
mock_request = MagicMock()
mock_request.headers = {"accept-language": "en"}
response = await insufficient_credits_exception_handler(request=mock_request, exc=exc)
assert response.status_code == 402
import json
body = json.loads(response.body)
assert body["detail"] == "No credits remaining"
assert body["detail"] == "Insufficient credits for this operation"
assert body["credits_available"] == 0
assert body["credits_required"] == 1
assert body["buy_url"] == "/#pricing"
+125
View File
@@ -387,3 +387,128 @@ class TestScreensWorkerPrerequisites:
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
assert _validate_prerequisites(job) is False
# ==================== GCS URI Passthrough ====================
class TestGCSURIPassthrough:
"""
Test that Stage 1 uses gcs_uri when input_gcs_uri is set on the processor.
Fixes 413 Request Entity Too Large for large FLAC files.
"""
def test_stage1_uses_gcs_uri_when_set(self):
"""When input_gcs_uri is set, Stage 1 passes gcs_uri instead of file_path."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[],
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None
processor.job_id = "gcs-test-001"
processor.input_gcs_uri = "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
mock_client = Mock()
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
for name in ["gcs-test-001_mixed_vocals.flac", "gcs-test-001_mixed_instrumental.flac"]:
with open(os.path.join(stems_dir, name), "w") as f:
f.write("fake audio")
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [
os.path.join(stems_dir, "gcs-test-001_mixed_vocals.flac"),
os.path.join(stems_dir, "gcs-test-001_mixed_instrumental.flac"),
],
"files": {},
}
input_file = os.path.join(temp_dir, "song.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch.object(processor, '_normalize_audio_files'):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Verify gcs_uri was passed instead of file_path
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
assert call_kwargs["gcs_uri"] == "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
# Verify file_path was NOT passed as a positional arg
call_args = mock_client.separate_audio_and_wait.call_args[0]
assert len(call_args) == 0
def test_stage1_uses_file_upload_when_no_gcs_uri(self):
"""When input_gcs_uri is not set, Stage 1 uses file upload as before."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[],
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None
processor.job_id = "file-test-001"
# No input_gcs_uri set
mock_client = Mock()
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
for name in ["file-test-001_mixed_vocals.flac", "file-test-001_mixed_instrumental.flac"]:
with open(os.path.join(stems_dir, name), "w") as f:
f.write("fake audio")
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [
os.path.join(stems_dir, "file-test-001_mixed_vocals.flac"),
os.path.join(stems_dir, "file-test-001_mixed_instrumental.flac"),
],
"files": {},
}
input_file = os.path.join(temp_dir, "song.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch.object(processor, '_normalize_audio_files'):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Verify file_path was passed as positional arg (old behavior)
call_args = mock_client.separate_audio_and_wait.call_args[0]
assert call_args[0] == input_file
# Verify gcs_uri was NOT in kwargs
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
assert "gcs_uri" not in call_kwargs
+132 -7
View File
@@ -224,7 +224,38 @@ class TestRetryEndpoint:
assert has_video and has_instrumental_selection
def test_retry_checkpoint_detection_render_stage(self):
"""Test retry detects render stage checkpoint."""
"""Test retry detects render stage checkpoint when review was completed."""
job = Job(
job_id="test123",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
file_urls={
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
'screens': {'title': 'gs://bucket/path/title.mov'}
},
state_data={
'instrumental_selection': 'clean'
}
)
# This job has corrections, screens, AND completed review - should retry from render
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
has_screens = job.file_urls.get('screens', {}).get('title')
has_video = job.file_urls.get('videos', {}).get('with_vocals')
has_review = (job.state_data or {}).get('instrumental_selection')
assert has_corrections and has_screens and not has_video and has_review
def test_retry_checkpoint_returns_to_review_when_not_completed(self):
"""Test retry returns to awaiting_review when corrections and screens exist
but user never completed the review (no instrumental_selection).
Regression test: previously, retry would skip to REVIEW_COMPLETE based solely
on corrections.json + title.mov existing, but these are auto-generated artifacts
that exist BEFORE the user reviews anything.
"""
job = Job(
job_id="test123",
status=JobStatus.FAILED,
@@ -236,13 +267,15 @@ class TestRetryEndpoint:
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
'screens': {'title': 'gs://bucket/path/title.mov'}
}
# No state_data.instrumental_selection — review was never completed
)
# This job has corrections and screens - should retry from render
# Has corrections and screens but NO review completion
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
has_screens = job.file_urls.get('screens', {}).get('title')
has_video = job.file_urls.get('videos', {}).get('with_vocals')
assert has_corrections and has_screens and not has_video
has_review = (job.state_data or {}).get('instrumental_selection')
# Should match the "awaiting_review" checkpoint, NOT "render"
assert has_corrections and has_screens and not has_review
def test_retry_checkpoint_detection_from_beginning(self):
"""Test retry detects need to restart from beginning."""
@@ -525,14 +558,14 @@ class TestSummaryEndpoint:
assert list(result['file_urls'].keys()) == ['finals']
def test_hide_completed_statuses(self):
"""Verify _HIDE_COMPLETED_STATUSES only hides successful completions (not failed/cancelled)."""
"""Verify _HIDE_COMPLETED_STATUSES hides terminal statuses (not failed or active)."""
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
assert 'complete' in _HIDE_COMPLETED_STATUSES
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
# Failed/cancelled should NOT be hidden - users need to see these
assert 'cancelled' in _HIDE_COMPLETED_STATUSES
# Failed should NOT be hidden - users need to see these
assert 'failed' not in _HIDE_COMPLETED_STATUSES
assert 'cancelled' not in _HIDE_COMPLETED_STATUSES
# Active statuses should NOT be in the list
assert 'pending' not in _HIDE_COMPLETED_STATUSES
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
@@ -703,3 +736,95 @@ class TestContentDispositionHeader:
decoded = unquote(utf8_part)
assert decoded == "周杰倫 - 青花瓷.mp4"
class TestSearchFiltering:
"""Tests for the search parameter on list_jobs summary mode."""
def _make_job_dict(self, job_id="job1", artist="Queen", title="Bohemian Rhapsody",
audio_search_artist=None, audio_search_title=None, status="complete"):
return {
"job_id": job_id,
"artist": artist,
"title": title,
"audio_search_artist": audio_search_artist,
"audio_search_title": audio_search_title,
"status": status,
"user_email": "admin@nomadkaraoke.com",
}
def test_search_filters_by_artist(self):
"""Search 'queen' should match job with artist='Queen'."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
assert result[0]["job_id"] == "j1"
def test_search_filters_by_title(self):
"""Search 'california' should match job with title containing it."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "california")
assert len(result) == 1
assert result[0]["job_id"] == "j2"
def test_search_filters_by_job_id(self):
"""Search by partial job_id."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="abc-123-def"),
self._make_job_dict(job_id="xyz-789-ghi"),
]
result = _search_filter_jobs(jobs, "abc-123")
assert len(result) == 1
assert result[0]["job_id"] == "abc-123-def"
def test_search_filters_by_audio_search_fields(self):
"""Search should also check audio_search_artist and audio_search_title."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Display Name", title="Display Title",
audio_search_artist="Original Artist", audio_search_title="Original Song"),
]
result = _search_filter_jobs(jobs, "original artist")
assert len(result) == 1
def test_search_is_case_insensitive(self):
"""Search should be case-insensitive."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist="QUEEN", title="Bohemian Rhapsody")]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
def test_search_handles_none_fields(self):
"""Search should not crash on None artist/title fields."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist=None, title=None)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 0
def test_search_empty_string_returns_all(self):
"""Empty search string should return all jobs."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1"),
self._make_job_dict(job_id="j2"),
]
result = _search_filter_jobs(jobs, "")
assert len(result) == 2
def test_search_returns_all_matches_for_limit_slicing(self):
"""Search returns all matches — caller applies limit separately."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(job_id=f"j{i}", artist="Queen", title=f"Song {i}") for i in range(10)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 10 # All 10 match; limit slicing is caller's job
# Verify caller can slice: simulates jobs_dicts[:limit] in route handler
assert len(result[:3]) == 3
+551
View File
@@ -0,0 +1,551 @@
"""
Tests for the search-lyrics operation and API endpoint.
Covers:
- create_lyrics_providers() factory function
- CorrectionOperations.search_lyrics_sources() static method
- CorrectionOperations.add_lyrics_source() force parameter
- POST /{job_id}/search-lyrics API endpoint
"""
import pytest
import os
from unittest.mock import MagicMock, patch, call
from typing import Dict, Any, List
# ---------------------------------------------------------------------------
# Helpers / fixtures
# ---------------------------------------------------------------------------
def _make_lyrics_data(source: str = "TestSource", text: str = "Hello world\nTest line") -> "LyricsData":
"""Create a minimal LyricsData object for testing."""
from karaoke_gen.lyrics_transcriber.types import LyricsData, LyricsSegment, LyricsMetadata, Word
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
segments = []
for line in text.strip().splitlines():
words = [
Word(id=WordUtils.generate_id(), text=w, start_time=None, end_time=None)
for w in line.split()
]
segments.append(
LyricsSegment(
id=WordUtils.generate_id(),
text=line,
words=words,
start_time=None,
end_time=None,
)
)
return LyricsData(source=source, segments=segments, metadata=LyricsMetadata(source=source, track_name="Test Track", artist_names="Test Artist"))
def _make_correction_result(
reference_lyrics: Dict = None,
metadata: Dict = None,
) -> "CorrectionResult":
"""Create a minimal CorrectionResult for testing."""
from karaoke_gen.lyrics_transcriber.types import (
CorrectionResult, LyricsSegment, Word, LyricsData, LyricsMetadata
)
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
# A single transcription segment
word = Word(id=WordUtils.generate_id(), text="hello", start_time=0.0, end_time=0.5)
segment = LyricsSegment(id=WordUtils.generate_id(), text="hello", words=[word], start_time=0.0, end_time=0.5)
return CorrectionResult(
original_segments=[segment],
corrected_segments=[segment],
corrections=[],
corrections_made=0,
confidence=1.0,
reference_lyrics=reference_lyrics or {},
anchor_sequences=[],
gap_sequences=[],
resized_segments=None,
metadata=metadata or {"audio_hash": "testhash"},
correction_steps=[],
word_id_map={},
segment_id_map={},
)
# ---------------------------------------------------------------------------
# Tests: create_lyrics_providers factory
# ---------------------------------------------------------------------------
class TestCreateLyricsProviders:
"""Tests for the create_lyrics_providers() module-level factory."""
def test_returns_list(self):
"""Factory always returns a list."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {}, clear=False):
# Remove API keys so only LRCLIB is created
env_override = {
k: "" for k in ["GENIUS_API_KEY", "RAPIDAPI_KEY", "SPOTIFY_COOKIE_SP_DC"]
}
with patch.dict(os.environ, env_override):
providers = create_lyrics_providers(cache_dir="/tmp")
assert isinstance(providers, list)
def test_lrclib_always_included(self):
"""LRCLIBProvider is always included regardless of env vars."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "LRCLIB" in provider_names
def test_genius_included_when_genius_key_set(self):
"""GeniusProvider is included when GENIUS_API_KEY is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "fake-key", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
def test_genius_included_when_rapidapi_key_set(self):
"""GeniusProvider is included when RAPIDAPI_KEY is set (uses RapidAPI path)."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
def test_spotify_included_when_cookie_set(self):
"""SpotifyProvider is included when SPOTIFY_COOKIE_SP_DC is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": "fake-cookie"}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Spotify" in provider_names
def test_musixmatch_included_when_rapidapi_key_set(self):
"""MusixmatchProvider is included when RAPIDAPI_KEY is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Musixmatch" in provider_names
def test_genius_not_included_without_keys(self):
"""GeniusProvider is excluded when neither key is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" not in provider_names
def test_all_providers_when_all_keys_set(self):
"""All four providers are returned when all credentials are set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {
"GENIUS_API_KEY": "gk",
"RAPIDAPI_KEY": "rk",
"SPOTIFY_COOKIE_SP_DC": "sc",
}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
assert "Spotify" in provider_names
assert "Musixmatch" in provider_names
assert "LRCLIB" in provider_names
assert len(providers) == 4
# ---------------------------------------------------------------------------
# Tests: CorrectionOperations.search_lyrics_sources
# ---------------------------------------------------------------------------
class TestSearchLyricsSources:
"""Tests for CorrectionOperations.search_lyrics_sources()."""
def _mock_provider(self, name: str, lyrics_data=None):
"""Build a mock BaseLyricsProvider that returns lyrics_data."""
mock = MagicMock()
mock.get_name.return_value = name
mock.fetch_lyrics.return_value = lyrics_data
return mock
def test_returns_dict_with_expected_keys(self):
"""Return value always contains all four expected keys."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [] # No providers — simulates empty env
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "updated_result" in result
assert "sources_added" in result
assert "sources_rejected" in result
assert "sources_not_found" in result
def test_no_providers_returns_no_results(self):
"""When no providers are available, returns no results."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = []
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert result["updated_result"] is None
assert result["sources_added"] == []
def test_provider_not_found_appended_to_not_found(self):
"""Provider returning None is recorded in sources_not_found."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_provider = self._mock_provider("LRCLIB", lyrics_data=None)
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "LRCLIB" in result["sources_not_found"]
assert result["updated_result"] is None
def test_provider_exception_appended_to_not_found(self):
"""Provider raising an exception is recorded in sources_not_found."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_provider = self._mock_provider("Genius")
mock_provider.fetch_lyrics.side_effect = RuntimeError("network error")
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "Genius" in result["sources_not_found"]
def test_existing_source_skipped(self):
"""Provider whose name is already in reference_lyrics is skipped."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
existing_lyrics = {"Genius": _make_lyrics_data("Genius")}
correction_result = _make_correction_result(reference_lyrics=existing_lyrics)
mock_provider = self._mock_provider("Genius", lyrics_data=_make_lyrics_data("Genius"))
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
# fetch_lyrics should NOT have been called
mock_provider.fetch_lyrics.assert_not_called()
assert result["updated_result"] is None # Nothing new to add
def test_lyrics_found_runs_corrector(self):
"""When lyrics are found, LyricsCorrector.run is called."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
lyrics_data = _make_lyrics_data("LRCLIB")
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(metadata={"audio_hash": "testhash"})
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert mock_corrector.run.called
def test_force_sources_bypass_rejection(self):
"""Sources in force_sources are added even if the corrector rejects them."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
lyrics_data = _make_lyrics_data("Genius")
mock_provider = self._mock_provider("Genius", lyrics_data=lyrics_data)
# Corrector result that puts "Genius" in rejected_sources
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # Corrector filtered it out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"Genius": {"relevance": 0.0, "matched_words": 0, "total_words": 10,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
force_sources=["Genius"],
)
# The forced source should be in sources_added, not rejected
assert "Genius" in result["sources_added"]
assert "Genius" not in result["sources_rejected"]
# And it should have been re-added to reference_lyrics
assert "Genius" in result["updated_result"].reference_lyrics
def test_audio_hash_preserved(self):
"""The audio_hash from the original correction_result is preserved."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
original_hash = "original-audio-hash-abc"
correction_result = _make_correction_result(metadata={"audio_hash": original_hash})
lyrics_data = _make_lyrics_data("LRCLIB")
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(metadata={}) # metadata without audio_hash
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
if result["updated_result"] is not None:
assert result["updated_result"].metadata.get("audio_hash") == original_hash
# ---------------------------------------------------------------------------
# Tests: CorrectionOperations.add_lyrics_source force parameter
# ---------------------------------------------------------------------------
class TestAddLyricsSourceForce:
"""Tests for the force parameter added to add_lyrics_source."""
def test_force_false_does_not_override_rejection(self):
"""With force=False (default), rejected sources remain rejected."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # source was filtered out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=False,
)
# Source should NOT be in reference_lyrics when force=False
assert "custom" not in result.reference_lyrics
def test_force_true_adds_source_even_if_rejected(self):
"""With force=True, source is added back even if the corrector rejected it."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # source was filtered out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=True,
)
# Source SHOULD be in reference_lyrics when force=True
assert "custom" in result.reference_lyrics
def test_force_true_no_op_when_source_not_rejected(self):
"""With force=True but source wasn't rejected, nothing extra happens."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
# Source is accepted (not in rejected_sources)
mock_updated = _make_correction_result(
reference_lyrics={"custom": _make_lyrics_data("custom")},
metadata={"audio_hash": "testhash"},
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=True,
)
# Source remains in reference_lyrics normally
assert "custom" in result.reference_lyrics
# ---------------------------------------------------------------------------
# Tests: POST /{job_id}/search-lyrics API endpoint
# ---------------------------------------------------------------------------
class TestSearchLyricsEndpoint:
"""Tests for the POST /{job_id}/search-lyrics API endpoint."""
def test_endpoint_exists(self):
"""Verify the search-lyrics endpoint is registered in the router."""
from backend.api.routes.review import router
paths = [route.path for route in router.routes]
assert any("search-lyrics" in p for p in paths), f"search-lyrics not found in: {paths}"
def test_search_lyrics_requires_artist_and_title(self):
"""Document that the endpoint requires artist and title fields."""
valid_payload = {
"artist": "The Beatles",
"title": "Hey Jude",
}
assert "artist" in valid_payload
assert "title" in valid_payload
assert valid_payload["artist"].strip()
assert valid_payload["title"].strip()
def test_search_lyrics_accepts_force_sources(self):
"""Document that force_sources is an optional list of provider names."""
payload_with_force = {
"artist": "The Beatles",
"title": "Hey Jude",
"force_sources": ["Genius", "LRCLIB"],
}
assert isinstance(payload_with_force["force_sources"], list)
def test_success_response_format(self):
"""Document the expected success response format."""
example_success_response = {
"status": "success",
"data": {}, # CorrectionData dict
"sources_added": ["LRCLIB"],
"sources_rejected": {"Genius": {"relevance": 0.1}},
"sources_not_found": ["Spotify"],
}
assert example_success_response["status"] == "success"
assert "data" in example_success_response
assert "sources_added" in example_success_response
assert "sources_rejected" in example_success_response
assert "sources_not_found" in example_success_response
def test_no_results_response_format(self):
"""Document the expected no_results response format."""
example_no_results_response = {
"status": "no_results",
"message": "No matching lyrics found from any provider",
"sources_rejected": {},
"sources_not_found": ["Genius", "LRCLIB"],
}
assert example_no_results_response["status"] == "no_results"
assert "message" in example_no_results_response
assert "sources_rejected" in example_no_results_response
assert "sources_not_found" in example_no_results_response
def test_search_lyrics_uses_correction_operations(self):
"""Verify CorrectionOperations.search_lyrics_sources exists and is callable."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
assert hasattr(CorrectionOperations, "search_lyrics_sources")
method = getattr(CorrectionOperations, "search_lyrics_sources")
assert callable(method)
def test_add_lyrics_source_has_force_parameter(self):
"""Verify add_lyrics_source now accepts a force parameter."""
import inspect
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
sig = inspect.signature(CorrectionOperations.add_lyrics_source)
assert "force" in sig.parameters
# Default should be False
assert sig.parameters["force"].default is False
+46 -1
View File
@@ -336,9 +336,54 @@ class TestWorkerService:
assert "test123" in str(override_args)
class TestWorkerServiceWarmup:
"""Test encoding worker warmup in trigger methods."""
@pytest.mark.asyncio
async def test_trigger_video_worker_calls_warmup(self):
"""trigger_video_worker calls _warmup_encoding_worker before dispatching."""
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
await worker_service.trigger_video_worker("test-job")
mock_warmup.assert_called_once_with("test-job")
@pytest.mark.asyncio
async def test_trigger_render_video_worker_calls_warmup(self):
"""trigger_render_video_worker calls _warmup_encoding_worker before dispatching."""
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
await worker_service.trigger_render_video_worker("test-job")
mock_warmup.assert_called_once_with("test-job")
def test_warmup_swallows_exceptions(self):
"""Warmup failures are logged but never block worker dispatch."""
worker_service = get_worker_service()
with patch('backend.services.encoding_worker_manager.EncodingWorkerManager.ensure_primary_running',
side_effect=Exception("Compute API down")):
# Should not raise
worker_service._warmup_encoding_worker("test-job")
class TestWorkerServiceCloudTasks:
"""Test WorkerService Cloud Tasks integration."""
def test_should_use_cloud_tasks_default_false(self):
"""Test that Cloud Tasks is disabled by default."""
from backend.services.worker_service import WorkerService, reset_worker_service
+12 -12
View File
@@ -120,12 +120,12 @@ class TestProcessStaleReviews:
mock_job_manager.cancel_job.assert_called_once_with(
"job-123", reason="Review not completed within 48 hours"
)
mock_email_service.send_review_expired.assert_called_once_with(
to_email="user@test.com",
artist="Test Artist",
title="Test Song",
credits_balance=2,
)
call_kwargs = mock_email_service.send_review_expired.call_args.kwargs
assert call_kwargs["to_email"] == "user@test.com"
assert call_kwargs["artist"] == "Test Artist"
assert call_kwargs["title"] == "Test Song"
assert call_kwargs["credits_balance"] == 2
assert "locale" in call_kwargs # locale now passed from user profile
async def test_expires_job_over_48h_with_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should expire job >48h even if reminder was already sent (no duplicate reminder)."""
@@ -153,12 +153,12 @@ class TestProcessStaleReviews:
assert result["reminders_sent"] == 1
assert result["jobs_expired"] == 0
mock_email_service.send_review_reminder.assert_called_once_with(
to_email="user@test.com",
artist="Test Artist",
title="Test Song",
job_id="job-123",
)
call_kwargs = mock_email_service.send_review_reminder.call_args.kwargs
assert call_kwargs["to_email"] == "user@test.com"
assert call_kwargs["artist"] == "Test Artist"
assert call_kwargs["title"] == "Test Song"
assert call_kwargs["job_id"] == "job-123"
assert "locale" in call_kwargs
# Should update state_data with expiry_reminder_sent flag
mock_firestore.update_job.assert_called_once()
call_args = mock_firestore.update_job.call_args
@@ -0,0 +1,157 @@
"""Tests for the /api/health/system-status endpoint."""
import pytest
from unittest.mock import patch, MagicMock, AsyncMock
@pytest.fixture
def mock_encoding_status():
return {
"configured": True,
"enabled": True,
"available": True,
"status": "ok",
"active_jobs": 0,
"queue_length": 0,
"wheel_version": "0.155.3",
}
@pytest.fixture
def mock_flacfetch_status():
return {
"configured": True,
"available": True,
"status": "ok",
"version": "0.19.1",
}
@pytest.fixture
def mock_separator_status():
return {
"available": True,
"status": "ok",
"version": "0.4.3",
}
@pytest.fixture
def mock_encoding_worker_config():
"""Mock EncodingWorkerConfig dataclass."""
config = MagicMock()
config.primary_vm = "encoding-worker-b"
config.primary_ip = "34.10.189.118"
config.primary_version = "0.155.3"
config.primary_deployed_at = "2026-03-31T18:10:00Z"
config.secondary_vm = "encoding-worker-a"
config.secondary_ip = "34.57.78.246"
config.secondary_version = "0.155.2"
config.secondary_deployed_at = "2026-03-29T14:00:00Z"
config.last_swap_at = "2026-03-31T18:10:00Z"
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
return config
class TestSystemStatusPublic:
"""Tests for unauthenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_returns_all_services(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status
):
from backend.api.routes.health import system_status
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", "8e2a949a"), \
patch("backend.api.routes.health.PR_NUMBER", "644"), \
patch("backend.api.routes.health.PR_TITLE", "fix: blue-green deploy"), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert "services" in result
services = result["services"]
# All 5 services present
assert "frontend" in services
assert "backend" in services
assert "encoder" in services
assert "flacfetch" in services
assert "separator" in services
# Backend has build metadata
backend_svc = services["backend"]
assert backend_svc["version"] == "0.155.3"
assert backend_svc["commit_sha"] == "8e2a949a"
assert backend_svc["pr_number"] == "644"
# Encoder has status
assert services["encoder"]["status"] == "ok"
assert services["encoder"]["version"] == "0.155.3"
# No admin_details without auth
assert "admin_details" not in services["encoder"]
@pytest.mark.asyncio
async def test_offline_service(self, mock_flacfetch_status, mock_separator_status):
from backend.api.routes.health import system_status
offline_encoding = {
"configured": True,
"enabled": True,
"available": False,
"error": "Connection refused",
}
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=offline_encoding), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert result["services"]["encoder"]["status"] == "offline"
class TestSystemStatusAdmin:
"""Tests for admin-authenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_admin_gets_bluegreen_details(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
encoder = result["services"]["encoder"]
assert "admin_details" in encoder
admin = encoder["admin_details"]
assert admin["primary_vm"] == "encoding-worker-b"
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
+4 -4
View File
@@ -56,7 +56,7 @@ class TestSendMagicLinkTenantParams:
assert "Nomad Karaoke" in html_content
assert "Nomad Karaoke" in text_content
# Default URL should be used
assert f"{email_service.frontend_url}/auth/verify" in html_content
assert f"{email_service.frontend_url}/en/auth/verify" in html_content
def test_tenant_url_used_in_magic_link(self, email_service):
"""When tenant_frontend_url is provided, magic link points to tenant domain."""
@@ -70,8 +70,8 @@ class TestSendMagicLinkTenantParams:
html_content = call_args[0][2]
text_content = call_args[0][3]
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in html_content
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in text_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in html_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in text_content
# Should NOT contain default URL
assert "gen.nomadkaraoke.com" not in html_content
@@ -124,7 +124,7 @@ class TestSendMagicLinkTenantParams:
html_content = call_args[0][2]
assert subject == "Sign in to Vocal Star"
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=token123" in html_content
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=token123" in html_content
# Check sender email override was passed through
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
+109 -1
View File
@@ -621,6 +621,111 @@ class TestPackagingValidation:
assert orchestrator.result.final_karaoke_cdg_zip is None
class TestPackagingTrailingPeriodRegression:
"""Regression test for job 4117228f: title ending with period caused TXT failure.
Root cause: The orchestrator's sanitize_filename() strips trailing periods,
but the CDG generator's internal _sanitize_filename() did not, causing a
filename mismatch between the MP3 inside the CDG ZIP and what TXT expected.
Fix: Pass sanitized artist/title to CDG generator and use returned MP3 path.
"""
@pytest.mark.asyncio
async def test_cdg_packaging_uses_sanitized_artist_title(self):
"""Test that CDG packaging passes sanitized (not raw) artist/title."""
with tempfile.TemporaryDirectory() as temp_dir:
lrc_file = os.path.join(temp_dir, "test.lrc")
audio_file = os.path.join(temp_dir, "test.flac")
with open(lrc_file, "w") as f:
f.write("[00:00.00]Test lyrics")
with open(audio_file, "w") as f:
f.write("dummy audio")
# Title ends with period - this triggered the bug
config = OrchestratorConfig(
job_id="test-job",
artist="KARAOKE",
title="Song Title.", # Trailing period
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path=audio_file,
lrc_file_path=lrc_file,
output_dir=temp_dir,
enable_cdg=True,
cdg_styles={"background_color": "black"},
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
mock_service = MagicMock()
mock_service.create_cdg_package.return_value = (
f"{temp_dir}/cdg.zip",
f"{temp_dir}/test.mp3",
f"{temp_dir}/test.cdg",
)
mock_get.return_value = mock_service
await orchestrator._run_packaging()
call_kwargs = mock_service.create_cdg_package.call_args[1]
# Artist/title should be sanitized (trailing period stripped)
assert call_kwargs["artist"] == "KARAOKE"
assert call_kwargs["title"] == "Song Title" # No trailing period
@pytest.mark.asyncio
async def test_txt_uses_mp3_path_from_cdg_generation(self):
"""Test that TXT generation uses the actual MP3 path returned by CDG, not a constructed one."""
with tempfile.TemporaryDirectory() as temp_dir:
lrc_file = os.path.join(temp_dir, "test.lrc")
audio_file = os.path.join(temp_dir, "test.flac")
# Create a real MP3 file at the path CDG would return
mp3_from_cdg = os.path.join(temp_dir, "actual_cdg_output.mp3")
with open(lrc_file, "w") as f:
f.write("[00:00.00]Test lyrics")
with open(audio_file, "w") as f:
f.write("dummy audio")
with open(mp3_from_cdg, "w") as f:
f.write("dummy mp3")
config = OrchestratorConfig(
job_id="test-job",
artist="KARAOKE",
title="Song Title.", # Trailing period
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path=audio_file,
lrc_file_path=lrc_file,
output_dir=temp_dir,
enable_cdg=True,
enable_txt=True,
cdg_styles={"background_color": "black"},
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
mock_service = MagicMock()
# CDG returns a path that differs from constructed path
mock_service.create_cdg_package.return_value = (
f"{temp_dir}/cdg.zip",
mp3_from_cdg, # Actual MP3 path from CDG
f"{temp_dir}/test.cdg",
)
mock_service.create_txt_package.return_value = (
f"{temp_dir}/txt.zip",
f"{temp_dir}/test.txt",
)
mock_get.return_value = mock_service
await orchestrator._run_packaging()
# TXT should have been called with the actual CDG MP3 path
mock_service.create_txt_package.assert_called_once()
txt_call_kwargs = mock_service.create_txt_package.call_args[1]
assert txt_call_kwargs["mp3_file"] == mp3_from_cdg
class TestVideoWorkerOrchestratorEncoding:
"""Test encoding stage."""
@@ -1256,6 +1361,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'jobs/test-123/screens/title.png', 'end_png': 'jobs/test-123/screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1269,7 +1375,7 @@ class TestCreateOrchestratorConfigFromJob:
assert config.title == "Test Title"
assert config.enable_cdg is True
assert config.enable_youtube_upload is True
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).mov"
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).png"
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental Clean).flac"
def test_create_config_from_job_with_existing_instrumental(self):
@@ -1290,6 +1396,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = "gs://bucket/instrumental.mp3"
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1329,6 +1436,7 @@ class TestCreateOrchestratorConfigFromJob:
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'}}
config = create_orchestrator_config_from_job(
job=job,
+66 -51
View File
@@ -179,48 +179,48 @@ class TestLyricsWorker:
return storage
@pytest.mark.asyncio
async def test_upload_lyrics_results_requires_job(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results correctly fetches job for artist/title.
This test would have caught the UnboundLocalError bug where job was used
before being defined.
async def test_upload_lyrics_results_finds_corrections_by_scan(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results finds corrections JSON by scanning the directory.
The function scans for files ending in '(Lyrics Corrections).json' rather than
reconstructing filenames from job.artist/title, since those may change mid-processing
(e.g. admin updates artist name while lyrics worker is running).
"""
with patch('backend.workers.lyrics_worker.JobManager', return_value=mock_job_manager), \
patch('backend.workers.lyrics_worker.StorageService', return_value=mock_storage):
from backend.workers.lyrics_worker import upload_lyrics_results
with tempfile.TemporaryDirectory() as temp_dir:
# Create mock lyrics directory and files
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
# Create test LRC file
lrc_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Karaoke).lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test lyrics\n")
# Create corrections JSON
corrections_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Lyrics Corrections).json")
# Use a different artist than what's in the job to simulate mid-run rename
corrections_path = os.path.join(lyrics_dir, "OldArtist - Waterloo (Lyrics Corrections).json")
with open(corrections_path, 'w') as f:
json.dump({"lines": [], "corrections": []}, f)
transcription_result = {
"lrc_filepath": lrc_path,
"corrections_filepath": corrections_path
}
# This should NOT raise UnboundLocalError
await upload_lyrics_results(
"test123",
temp_dir,
transcription_result,
mock_storage,
"test123",
temp_dir,
transcription_result,
mock_storage,
mock_job_manager
)
# Verify job was fetched
mock_job_manager.get_job.assert_called_with("test123")
# Verify corrections file was found and uploaded as corrections.json
upload_calls = mock_storage.upload_file.call_args_list
corrections_uploads = [c for c in upload_calls if 'corrections.json' in str(c)]
assert len(corrections_uploads) == 1
@pytest.mark.asyncio
async def test_upload_lyrics_results_uploads_lrc_file(self, mock_job_manager, mock_storage, mock_job):
@@ -281,53 +281,68 @@ class TestLyricsWorker:
)
@pytest.mark.asyncio
async def test_upload_lyrics_results_uses_artist_title_from_job(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results correctly uses job.artist and job.title.
This test specifically validates the bug fix where job was not defined
when accessing job.artist and job.title for reference file lookups.
"""
async def test_upload_lyrics_results_raises_when_no_corrections(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results raises when no corrections file exists at all."""
from backend.workers.lyrics_worker import upload_lyrics_results
import json
with tempfile.TemporaryDirectory() as temp_dir:
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
# Create LRC file
lrc_path = os.path.join(lyrics_dir, "test.lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test\n")
# Create required corrections.json file
corrections_path = os.path.join(lyrics_dir, "corrections.json")
# No corrections file at all
transcription_result = {"lrc_filepath": lrc_path}
with pytest.raises(Exception, match="No corrections JSON found"):
await upload_lyrics_results(
"test123", temp_dir, transcription_result,
mock_storage, mock_job_manager
)
@pytest.mark.asyncio
async def test_upload_lyrics_results_finds_reference_and_uncorrected_by_scan(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results finds reference and uncorrected files by scanning.
Files are found by suffix pattern, not by reconstructing from job.artist/title,
so mid-processing artist name changes don't break the upload.
"""
from backend.workers.lyrics_worker import upload_lyrics_results
import json
with tempfile.TemporaryDirectory() as temp_dir:
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
lrc_path = os.path.join(lyrics_dir, "test.lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test\n")
corrections_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Corrections).json")
with open(corrections_path, 'w') as f:
json.dump({"corrected_segments": []}, f)
# Create a reference lyrics file using the job's artist/title
ref_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Genius).txt")
# Reference and uncorrected files with arbitrary artist name
ref_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Genius).txt")
with open(ref_path, 'w') as f:
f.write("Reference lyrics content\n")
# Create uncorrected transcription file using job's artist/title
uncorrected_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Uncorrected).txt")
uncorrected_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Uncorrected).txt")
with open(uncorrected_path, 'w') as f:
f.write("Uncorrected transcription\n")
transcription_result = {"lrc_filepath": lrc_path}
# This should NOT raise UnboundLocalError for 'job'
await upload_lyrics_results(
"test123", temp_dir, transcription_result,
mock_storage, mock_job_manager
)
# Verify job was fetched to get artist/title
mock_job_manager.get_job.assert_called_with("test123")
# Verify files were uploaded (the reference and uncorrected files exist)
# Verify files were uploaded: LRC + corrections + genius ref + uncorrected = 4
upload_calls = mock_storage.upload_file.call_args_list
assert len(upload_calls) >= 2 # LRC + at least one reference or uncorrected
assert len(upload_calls) == 4
@pytest.mark.asyncio
async def test_process_lyrics_transcription_marks_failed_on_error(self, mock_job_manager, mock_storage):
+238
View File
@@ -0,0 +1,238 @@
{
"auth": {
"unknownService": "Unbekannter Dienst: {service}",
"invalidCredentials": "Die folgenden Dienste müssen neu autorisiert werden: {services}",
"validCredentials": "Alle angeforderten Anmeldeinformationen sind gültig",
"youtubeAuthInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
"youtubeAuthStartFailed": "Starten der YouTube-Geräteauthentifizierung fehlgeschlagen: {error}",
"gdriveLinkInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
"gdriveAuthStartFailed": "Starten der Google Drive-Geräteauthentifizierung fehlgeschlagen: {error}",
"discordAlertNotConfigured": "Discord-Alert-Webhook nicht konfiguriert"
},
"jobs": {
"created": "Auftrag erfolgreich erstellt. Verarbeitung gestartet.",
"authError": "Authentifizierungsfehler: Keine Benutzeridentität verfügbar",
"noDefaultTheme": "Kein Standard-Theme konfiguriert. Bitte kontaktiere den Support oder gib eine theme_id an.",
"notFound": "Auftrag nicht gefunden",
"noPermissionAccess": "Du hast keine Berechtigung, auf diesen Auftrag zuzugreifen",
"noPermissionEdit": "Du hast keine Berechtigung, diesen Auftrag zu bearbeiten",
"noPermissionDelete": "Du hast keine Berechtigung, diesen Auftrag zu löschen",
"noPermissionModify": "Du hast keine Berechtigung, diesen Auftrag zu ändern",
"notCompleted": "Nur abgeschlossene Aufträge können bearbeitet werden. Aktueller Status: {status}",
"alreadyBeingEdited": "Dieser Auftrag wird bereits bearbeitet (Ausgaben wurden bereits gelöscht)",
"cleanupFailed": "Bereinigung für {services} fehlgeschlagen. Auftrag nicht geändert. Bitte versuche es erneut oder kontaktiere den Support.",
"reopened": "Track zur Bearbeitung wieder geöffnet. Vorherige Ausgaben wurden entfernt.",
"invalidDatetimeFormat": "Ungültiges {field}-Format: {value}",
"listError": "Fehler beim Auflisten der Aufträge: {error}",
"deleteError": "Fehler beim Löschen des Auftrags {job_id}: {error}",
"deletionPreview": "Füge &confirm=true hinzu, um die Löschung auszuführen",
"deletionRequiresFilters": "Mindestens ein Filter (environment, client_id, status, created_before) ist erforderlich",
"bulkDeleteError": "Fehler beim massenhaften Löschen von Aufträgen: {error}",
"reviewNotReady": "Auftrag nicht bereit zur Überprüfung (aktueller Status: {status})",
"correctionsUnavailable": "Korrekturdaten nicht verfügbar",
"audioUnavailable": "Audio nicht zur Überprüfung verfügbar",
"reviewCannotStart": "Überprüfung kann nicht gestartet werden",
"jobNotInReviewState": "Auftrag nicht im Überprüfungsstatus (aktueller Status: {status})",
"correctionsProcessing": "Korrekturen gespeichert. Rufe /complete-review auf, wenn du fertig bist.",
"editLogSaveFailed": "Fehler beim Speichern des Bearbeitungsprotokolls für Auftrag {job_id}: {error}",
"stemsMissing": "Dem Auftrag fehlen erforderliche Stems (instrumental_clean und/oder backing_vocals)",
"customInstrumentalFailed": "Fehler beim Erstellen des benutzerdefinierten Instrumentals für Auftrag {job_id}: {error}",
"audioProcessingFailed": "Fehler beim Verarbeiten der Audiodatei: {error}",
"durationMismatch": "Dauer stimmt nicht überein: Hochgeladene Datei ist {upload_duration}s lang, aber das Original-Audio ist {original_duration}s lang. Das Instrumental muss genau {original_duration}s (±0.5s) lang sein.",
"reviewNotInState": "Auftrag nicht im Überprüfungsstatus (aktueller Status: {status})",
"noLyricsDetected": "Überprüfung kann nicht abgeschlossen werden: Es wurde kein Text im Audio erkannt. Dies kann passieren, wenn das Eingabe-Audio keinen Gesang enthält (z. B. ein Karaoke-Track oder Instrumental). Du kannst zurückgehen und den Text manuell mit 'Alle ersetzen' einfügen oder diesen Auftrag abbrechen und es erneut mit einer Audiodatei versuchen, die Gesang enthält.",
"reviewCompleteStartRendering": "Überprüfung abgeschlossen. Rendern des Videos gestartet.",
"reviewCompleteError": "Fehler beim Abschließen der Überprüfung für Auftrag {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}"
},
"review": {
"jobNotFound": "Auftrag nicht gefunden",
"reviewNotReady": "Auftrag nicht bereit zur Überprüfung (aktueller Status: {status})",
"correctionsNotFound": "Korrekturdaten nicht gefunden. Die Textverarbeitung ist möglicherweise nicht abgeschlossen.",
"correctionsLoadFailed": "Fehler beim Laden der Korrekturen: {error}",
"audioNotFound": "Audiodatei nicht gefunden",
"audioServeError": "Fehler beim Bereitstellen von Audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
"reviewCompletedError": "Fehler beim Abschließen der Überprüfung: {error}",
"handlersUpdateNotImplemented": "Handler-Updates noch nicht implementiert",
"lyricsAddError": "Fehler beim Hinzufügen des Textes: {error}",
"lyricsAddInvalidRequest": "Ungültige Anfrage zum Hinzufügen von Text: {error}",
"lyricsSearchError": "Fehler bei der Textsuche: {error}",
"lyricsSearchInvalidRequest": "Ungültige Anfrage zur Textsuche: {error}",
"lyricsSearchNoResults": "Bei keinem Anbieter wurde ein passender Text gefunden",
"previewVideoGenerationError": "Fehler beim Generieren des Vorschau-Videos: {error}",
"previewVideoNotFound": "Vorschau-Video nicht gefunden",
"previewVideoStreamError": "Fehler beim Streamen des Vorschau-Videos: {error}",
"annotationSaveError": "Fehler beim Speichern der Anmerkungen: {error}",
"waveformGenerationError": "Fehler beim Generieren der Wellenform-Daten: {error}",
"waveformNoAudio": "Kein Audio für Wellenform verfügbar",
"sessionSaveError": "Korrekturdaten sind erforderlich"
},
"audioSearch": {
"notEnabled": "Die Audiosuche ist für diesen Mandanten nicht aktiviert",
"disabled": "Audiosuche ist nicht verfügbar",
"downloadError": "Download für Auftrag {job_id} fehlgeschlagen: {error}",
"jobNotFound": "Auftrag {job_id} nicht gefunden",
"noSearchResults": "Keine Suchergebnisse verfügbar",
"invalidSelectionIndex": "Ungültiger Auswahlindex {selection_index}. Gültiger Bereich: 0-{max}",
"selectionError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
"youtubeDownloadError": "YouTube-Download fehlgeschlagen: {error}",
"torrentDownloadError": "Download von {source} ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Keine source_id oder remote_search_id für {source}-Download verfügbar",
"remoteDownloadCompleteNoPath": "Remote-Download abgeschlossen, aber kein Dateipfad zurückgegeben",
"spotifyDownloadError": "Download von Spotify ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
"genericDownloadError": "Unbekannter Quellentyp: {source}, versuche generischen Download",
"jobNotFoundDuringDownload": "Auftrag {job_id} während des Hintergrund-Downloads nicht gefunden",
"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..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Wenn diese E-Mail-Adresse registriert ist, erhältst du in Kürze einen Anmeldelink.",
"emailServiceNotConfigured": "E-Mail-Dienst ist nicht verfügbar. Bitte kontaktiere den Support.",
"emailDomainNotAllowed": "E-Mail-Domain für diesen Mandanten nicht zulässig",
"invalidToken": "Ungültiges Token",
"verifyError": "Verifizierung fehlgeschlagen: {message}",
"magicLinkSuccess": "Erfolgreich angemeldet",
"logoutSuccess": "Erfolgreich abgemeldet",
"userNotFound": "Benutzer nicht gefunden",
"creditPackagesError": "Fehler beim Laden der Guthaben-Pakete: {error}",
"stripeSendError": "Fehler beim Senden des Stripe-Checkout-Links: {error}",
"stripeWebhookProcessingError": "Fehler bei der Verarbeitung des Stripe-Webhooks: {error}",
"feedbackSaveError": "Fehler beim Speichern des Feedbacks: {error}",
"feedbackNotEligible": "Benutzer nicht für Feedback berechtigt"
},
"fileUpload": {
"invalidTheme": "Theme nicht gefunden: {theme_id}. Verwende GET /api/themes, um verfügbare Themes aufzulisten.",
"uploadSuccess": "Datei erfolgreich hochgeladen. Verarbeitung gestartet.",
"uploadError": "Fehler beim Hochladen der Datei: {error}",
"urlDownloadError": "Fehler beim Herunterladen von der URL: {error}",
"invalidContentType": "Ungültiger Inhaltstyp: {content_type}",
"fileSizeError": "Datei ist zu groß: {size}. Maximum: {max_size}",
"invalidFileType": "Ungültiger Dateityp: {file_type}",
"multipleAudioFilesNotAllowed": "Es kann nur eine Audiodatei hochgeladen werden",
"noAudioFileProvided": "Keine Audiodatei bereitgestellt",
"urlCreationSuccess": "Auftrag erstellt. Upload-URLs generiert.",
"urlCreationError": "Fehler beim Erstellen des Auftrags mit Upload-URLs: {error}",
"uploadsCompleteSuccess": "Uploads abgeschlossen. Verarbeitung gestartet.",
"uploadsCompleteError": "Fehler beim Abschließen der Uploads: {error}",
"noUploadedFiles": "Keine hochgeladenen Dateien angegeben",
"styleUploadUrlsSuccess": "Style-Upload-URLs generiert.",
"styleUploadsCompleteSuccess": "Style-Dateien aktualisiert. Verarbeitung neu gestartet.",
"styleUploadsCompleteError": "Fehler beim Abschließen der Style-Uploads: {error}"
},
"catalog": {
"rateLimitExceeded": "Ratenlimit überschritten. Maximal {max_requests} Kataloganfragen pro Minute.",
"catalogSearchError": "Fehler bei der Katalogsuche: {error}",
"communityCheckError": "Fehler beim Überprüfen der Community-Versionen: {error}"
},
"themes": {
"themesLoadError": "Fehler beim Laden der Themes",
"themeNotFound": "Theme nicht gefunden: {theme_id}",
"themeLoadError": "Fehler beim Laden des Themes",
"previewNotAvailable": "Keine Vorschau für Theme verfügbar: {theme_id}",
"previewLoadError": "Fehler beim Laden der Theme-Vorschau",
"youtubeDescriptionNotFound": "Theme nicht gefunden: {theme_id}",
"youtubeDescriptionLoadError": "Fehler beim Laden der YouTube-Beschreibung"
},
"tenant": {
"assetNotFound": "Asset nicht gefunden"
},
"push": {
"disabled": "Push-Benachrichtigungen sind nicht aktiviert",
"userEmailNotAvailable": "Benutzer-E-Mail nicht verfügbar",
"missingEncryptionKeys": "Fehlende erforderliche Schlüssel (p256dh, auth)",
"subscriptionSaveFailed": "Fehler beim Speichern des Abonnements",
"subscriptionRegistered": "Push-Abonnement erfolgreich registriert",
"subscriptionNotFound": "Abonnement entfernt (oder wurde nicht gefunden)",
"subscriptionRemoved": "Push-Abonnement erfolgreich entfernt",
"testNotificationSent": "Testbenachrichtigung an {sent_count} Gerät(e) gesendet"
},
"pushNotifications": {
"reviewLyricsTitle": "Text überprüfen",
"reviewLyricsBody": "\"{title}\" von {artist} benötigt eine Textüberprüfung",
"selectInstrumentalTitle": "Instrumental auswählen",
"selectInstrumentalBody": "\"{title}\" von {artist} benötigt eine Instrumentalauswahl",
"videoReadyTitle": "Video fertig!",
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist bereit zum Herunterladen"
},
"admin": {
"invalidDomainFormat": "Ungültiges Domain-Format",
"domainAddedToBl": "Domain '{domain}' zur Sperrliste für Wegwerf-Domains hinzugefügt",
"domainNotFoundInBl": "Domain nicht in der Sperrliste gefunden",
"domainRemovedFromBl": "Domain '{domain}' aus der Sperrliste für Wegwerf-Domains entfernt",
"domainAddedToAllowlist": "Domain '{domain}' zur Erlaubnisliste hinzugefügt",
"domainNotFoundInAllowlist": "Domain nicht in der Erlaubnisliste gefunden",
"domainRemovedFromAllowlist": "Domain '{domain}' aus der Erlaubnisliste entfernt",
"syncComplete": "{external_count} externe Domains synchronisiert ({added} hinzugefügt, {removed} entfernt)",
"invalidEmailFormat": "Ungültiges E-Mail-Format",
"emailAddedToBl": "E-Mail '{email}' zur Liste blockierter E-Mails hinzugefügt",
"emailNotFoundInBl": "E-Mail nicht in der Sperrliste gefunden",
"emailRemovedFromBl": "E-Mail '{email}' aus der Liste blockierter E-Mails entfernt",
"invalidIPAddress": "Ungültige IP-Adresse",
"ipAddedToBl": "IP '{ip_address}' zur Liste blockierter IPs hinzugefügt",
"ipNotFoundInBl": "IP nicht in der Sperrliste gefunden",
"ipRemovedFromBl": "IP '{ip_address}' aus der Liste blockierter IPs entfernt",
"youtubeUploadNotFound": "Upload nicht gefunden oder nicht in einem wiederholbaren Status für Auftrag {job_id}",
"youtubeUploadQueuedForRetry": "YouTube-Upload für Auftrag {job_id} für erneuten Versuch in die Warteschlange eingereiht",
"youtubeQueueProcessingStarted": "Verarbeitung der YouTube-Warteschlange im Hintergrund gestartet"
},
"rateLimits": {
"configNotFound": "Ratenlimit-Konfiguration nicht gefunden: {config_id}",
"configUpdateError": "Fehler beim Aktualisieren der Ratenlimit-Konfiguration: {error}"
},
"errors": {
"insufficientCredits": "Unzureichendes Guthaben für diesen Vorgang",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Melde dich bei {brand_name} an"
},
"welcome": {
"subject": "Willkommen bei Nomad Karaoke!"
},
"creditsAdded": {
"subject": "{credits} Guthaben zu deinem Nomad Karaoke-Konto hinzugefügt"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Dein Karaoke-Video ist fertig!)",
"subject": "{artist} - {title} (Dein Karaoke-Video ist fertig!)",
"subjectFallback": "Dein Karaoke-Video ist fertig!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube-Upload bereit!)",
"subject": "{artist} - {title} (YouTube-Upload bereit!)",
"subjectFallback": "Dein YouTube-Upload ist bereit!"
},
"actionReminder": {
"lyricsSubject": "Aktion erforderlich: Text für {artist} - {title} überprüfen",
"lyricsSubjectFallback": "Aktion erforderlich: Text überprüfen",
"instrumentalSubject": "Aktion erforderlich: Instrumental für {artist} - {title} auswählen",
"instrumentalSubjectFallback": "Aktion erforderlich: Instrumental auswählen",
"audioEditSubject": "Aktion erforderlich für {artist} - {title}",
"audioEditSubjectFallback": "Aktion erforderlich"
},
"reviewReminder": {
"subject": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung — {artist} - {title}",
"subjectFallback": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung"
},
"reviewExpired": {
"subject": "Dein Karaoke-Video ist abgelaufen — {artist} - {title}",
"subjectFallback": "Dein Karaoke-Video ist abgelaufen"
},
"creditDenied": {
"subject": "Über dein kostenloses Nomad Karaoke-Guthaben"
},
"madeForYouConfirmation": {
"subject": "Bestellung bestätigt: {artist} - {title} | Nomad Karaoke"
}
}
}
+238
View File
@@ -0,0 +1,238 @@
{
"auth": {
"unknownService": "Unknown service: {service}",
"invalidCredentials": "The following services need re-authorization: {services}",
"validCredentials": "All requested credentials are valid",
"youtubeAuthInstructions": "Visit {verification_url} and enter code: {user_code}",
"youtubeAuthStartFailed": "Failed to start YouTube device auth: {error}",
"gdriveLinkInstructions": "Visit {verification_url} and enter code: {user_code}",
"gdriveAuthStartFailed": "Failed to start Google Drive device auth: {error}",
"discordAlertNotConfigured": "Discord alert webhook not configured"
},
"jobs": {
"created": "Job created successfully. Processing started.",
"authError": "Authentication error: no user identity available",
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
"notFound": "Job not found",
"noPermissionAccess": "You don't have permission to access this job",
"noPermissionEdit": "You don't have permission to edit this job",
"noPermissionDelete": "You don't have permission to delete this job",
"noPermissionModify": "You don't have permission to modify this job",
"notCompleted": "Only completed jobs can be edited. Current status: {status}",
"alreadyBeingEdited": "This job is already being edited (outputs were already deleted)",
"cleanupFailed": "Cleanup failed for {services}. Job not modified. Please try again or contact support.",
"reopened": "Track reopened for editing. Previous outputs have been removed.",
"invalidDatetimeFormat": "Invalid {field} format: {value}",
"listError": "Error listing jobs: {error}",
"deleteError": "Error deleting job {job_id}: {error}",
"deletionPreview": "Add &confirm=true to execute deletion",
"deletionRequiresFilters": "At least one filter (environment, client_id, status, created_before) is required",
"bulkDeleteError": "Error bulk deleting jobs: {error}",
"reviewNotReady": "Job not ready for review (current status: {status})",
"correctionsUnavailable": "Corrections data not available",
"audioUnavailable": "Audio not available for review",
"reviewCannotStart": "Cannot start review",
"jobNotInReviewState": "Job not in review state (current status: {status})",
"correctionsProcessing": "Corrections saved. Call /complete-review when done.",
"editLogSaveFailed": "Error saving edit log for job {job_id}: {error}",
"stemsMissing": "Job missing required stems (instrumental_clean and/or backing_vocals)",
"customInstrumentalFailed": "Error creating custom instrumental for job {job_id}: {error}",
"audioProcessingFailed": "Failed to process audio file: {error}",
"durationMismatch": "Duration mismatch: uploaded file is {upload_duration}s but original audio is {original_duration}s. The instrumental must be exactly {original_duration}s (±0.5s).",
"reviewNotInState": "Job not in review state (current status: {status})",
"noLyricsDetected": "Cannot complete review: no lyrics were detected in the audio. This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). You can go back and paste lyrics manually using 'Replace All', or cancel this job and try again with an audio file that contains vocals.",
"reviewCompleteStartRendering": "Review complete. Video rendering started.",
"reviewCompleteError": "Error completing review for job {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.",
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
"instrumentalSelected": "Instrumental selected. Video generation started.",
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
"downloadUrlsError": "Error getting download URLs: {error}"
},
"review": {
"jobNotFound": "Job not found",
"reviewNotReady": "Job not ready for review (current status: {status})",
"correctionsNotFound": "Corrections data not found. Lyrics processing may not be complete.",
"correctionsLoadFailed": "Error loading corrections: {error}",
"audioNotFound": "Audio file not found",
"audioServeError": "Error serving audio: {error}",
"instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.",
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
"reviewCompletedError": "Error completing review: {error}",
"handlersUpdateNotImplemented": "Handler updates not yet implemented",
"lyricsAddError": "Failed to add lyrics: {error}",
"lyricsAddInvalidRequest": "Invalid add lyrics request: {error}",
"lyricsSearchError": "Failed to search lyrics: {error}",
"lyricsSearchInvalidRequest": "Invalid search lyrics request: {error}",
"lyricsSearchNoResults": "No matching lyrics found from any provider",
"previewVideoGenerationError": "Failed to generate preview video: {error}",
"previewVideoNotFound": "Preview video not found",
"previewVideoStreamError": "Error streaming preview video: {error}",
"annotationSaveError": "Error saving annotations: {error}",
"waveformGenerationError": "Error generating waveform data: {error}",
"waveformNoAudio": "No audio available for waveform",
"sessionSaveError": "Correction data is required"
},
"audioSearch": {
"notEnabled": "Audio search is not enabled for this tenant",
"disabled": "Audio search is not available",
"downloadError": "Download failed for job {job_id}: {error}",
"jobNotFound": "Job {job_id} not found",
"noSearchResults": "No search results available",
"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}",
"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",
"spotifyDownloadError": "Cannot download from Spotify without remote flacfetch service. Configure FLACFETCH_API_URL.",
"genericDownloadError": "Unknown source type: {source}, attempting generic download",
"jobNotFoundDuringDownload": "Job {job_id} not found during background download",
"selectAudioError": "Error selecting audio for job {job_id}: {error}",
"searchAudioError": "Error searching audio: {error}",
"searchCreatedSuccessfully": "Job created. Searching for audio...",
"autoDownloadStarted": "Best result selected automatically. Download starting..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "If this email is registered, you will receive a sign-in link shortly.",
"emailServiceNotConfigured": "Email service is not available. Please contact support.",
"emailDomainNotAllowed": "Email domain not allowed for this tenant",
"invalidToken": "Invalid token",
"verifyError": "Verification failed: {message}",
"magicLinkSuccess": "Successfully signed in",
"logoutSuccess": "Successfully logged out",
"userNotFound": "User not found",
"creditPackagesError": "Error loading credit packages: {error}",
"stripeSendError": "Error sending Stripe checkout link: {error}",
"stripeWebhookProcessingError": "Error processing Stripe webhook: {error}",
"feedbackSaveError": "Error saving feedback: {error}",
"feedbackNotEligible": "User not eligible for feedback"
},
"fileUpload": {
"invalidTheme": "Theme not found: {theme_id}. Use GET /api/themes to list available themes.",
"uploadSuccess": "File uploaded successfully. Processing started.",
"uploadError": "Error uploading file: {error}",
"urlDownloadError": "Error downloading from URL: {error}",
"invalidContentType": "Invalid content type: {content_type}",
"fileSizeError": "File is too large: {size}. Maximum: {max_size}",
"invalidFileType": "Invalid file type: {file_type}",
"multipleAudioFilesNotAllowed": "Only one audio file can be uploaded",
"noAudioFileProvided": "No audio file provided",
"urlCreationSuccess": "Job created. Upload URLs generated.",
"urlCreationError": "Error creating job with upload URLs: {error}",
"uploadsCompleteSuccess": "Uploads complete. Processing started.",
"uploadsCompleteError": "Error completing uploads: {error}",
"noUploadedFiles": "No uploaded files specified",
"styleUploadUrlsSuccess": "Style upload URLs generated.",
"styleUploadsCompleteSuccess": "Style files updated. Processing restarted.",
"styleUploadsCompleteError": "Error completing style uploads: {error}"
},
"catalog": {
"rateLimitExceeded": "Rate limit exceeded. Maximum {max_requests} catalog requests per minute.",
"catalogSearchError": "Error searching catalog: {error}",
"communityCheckError": "Error checking community versions: {error}"
},
"themes": {
"themesLoadError": "Failed to load themes",
"themeNotFound": "Theme not found: {theme_id}",
"themeLoadError": "Failed to load theme",
"previewNotAvailable": "No preview available for theme: {theme_id}",
"previewLoadError": "Failed to load theme preview",
"youtubeDescriptionNotFound": "Theme not found: {theme_id}",
"youtubeDescriptionLoadError": "Failed to load YouTube description"
},
"tenant": {
"assetNotFound": "Asset not found"
},
"push": {
"disabled": "Push notifications are not enabled",
"userEmailNotAvailable": "User email not available",
"missingEncryptionKeys": "Missing required keys (p256dh, auth)",
"subscriptionSaveFailed": "Failed to save subscription",
"subscriptionRegistered": "Push subscription registered successfully",
"subscriptionNotFound": "Subscription removed (or was not found)",
"subscriptionRemoved": "Push subscription removed successfully",
"testNotificationSent": "Test notification sent to {sent_count} device(s)"
},
"pushNotifications": {
"reviewLyricsTitle": "Review Lyrics",
"reviewLyricsBody": "\"{title}\" by {artist} needs lyrics review",
"selectInstrumentalTitle": "Select Instrumental",
"selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection",
"videoReadyTitle": "Video Ready!",
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download"
},
"admin": {
"invalidDomainFormat": "Invalid domain format",
"domainAddedToBl": "Domain '{domain}' added to disposable domains blocklist",
"domainNotFoundInBl": "Domain not found in blocklist",
"domainRemovedFromBl": "Domain '{domain}' removed from disposable domains blocklist",
"domainAddedToAllowlist": "Domain '{domain}' added to allowlist",
"domainNotFoundInAllowlist": "Domain not found in allowlist",
"domainRemovedFromAllowlist": "Domain '{domain}' removed from allowlist",
"syncComplete": "Synced {external_count} external domains ({added} added, {removed} removed)",
"invalidEmailFormat": "Invalid email format",
"emailAddedToBl": "Email '{email}' added to blocked emails list",
"emailNotFoundInBl": "Email not found in blocklist",
"emailRemovedFromBl": "Email '{email}' removed from blocked emails list",
"invalidIPAddress": "Invalid IP address",
"ipAddedToBl": "IP '{ip_address}' added to blocked IPs list",
"ipNotFoundInBl": "IP not found in blocklist",
"ipRemovedFromBl": "IP '{ip_address}' removed from blocked IPs list",
"youtubeUploadNotFound": "Upload not found or not in retryable state for job {job_id}",
"youtubeUploadQueuedForRetry": "YouTube upload for job {job_id} queued for retry",
"youtubeQueueProcessingStarted": "YouTube queue processing started in background"
},
"rateLimits": {
"configNotFound": "Rate limit config not found: {config_id}",
"configUpdateError": "Error updating rate limit config: {error}"
},
"errors": {
"insufficientCredits": "Insufficient credits for this operation",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Sign in to {brand_name}"
},
"welcome": {
"subject": "Welcome to Nomad Karaoke!"
},
"creditsAdded": {
"subject": "{credits} credits added to your Nomad Karaoke account"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Your karaoke video is ready!)",
"subject": "{artist} - {title} (Your karaoke video is ready!)",
"subjectFallback": "Your karaoke video is ready!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube upload ready!)",
"subject": "{artist} - {title} (YouTube upload ready!)",
"subjectFallback": "Your YouTube upload is ready!"
},
"actionReminder": {
"lyricsSubject": "Action needed: Review lyrics for {artist} - {title}",
"lyricsSubjectFallback": "Action needed: Review lyrics",
"instrumentalSubject": "Action needed: Select instrumental for {artist} - {title}",
"instrumentalSubjectFallback": "Action needed: Select instrumental",
"audioEditSubject": "Action needed for {artist} - {title}",
"audioEditSubjectFallback": "Action needed"
},
"reviewReminder": {
"subject": "Reminder: Your karaoke video is waiting for review — {artist} - {title}",
"subjectFallback": "Reminder: Your karaoke video is waiting for review"
},
"reviewExpired": {
"subject": "Your karaoke video has expired — {artist} - {title}",
"subjectFallback": "Your karaoke video has expired"
},
"creditDenied": {
"subject": "About your Nomad Karaoke free credits"
},
"madeForYouConfirmation": {
"subject": "Order Confirmed: {artist} - {title} | Nomad Karaoke"
}
}
}
+238
View File
@@ -0,0 +1,238 @@
{
"auth": {
"unknownService": "Servicio desconocido: {service}",
"invalidCredentials": "Los siguientes servicios necesitan volver a autorizarse: {services}",
"validCredentials": "Todas las credenciales solicitadas son válidas",
"youtubeAuthInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
"youtubeAuthStartFailed": "Error al iniciar la autorización del dispositivo de YouTube: {error}",
"gdriveLinkInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
"gdriveAuthStartFailed": "Error al iniciar la autorización del dispositivo de Google Drive: {error}",
"discordAlertNotConfigured": "El webhook de alerta de Discord no está configurado"
},
"jobs": {
"created": "Trabajo creado con éxito. El procesamiento ha comenzado.",
"authError": "Error de autenticación: no hay identidad de usuario disponible",
"noDefaultTheme": "No hay un tema predeterminado configurado. Por favor, contacta a soporte o especifica un theme_id.",
"notFound": "Trabajo no encontrado",
"noPermissionAccess": "No tienes permiso para acceder a este trabajo",
"noPermissionEdit": "No tienes permiso para editar este trabajo",
"noPermissionDelete": "No tienes permiso para eliminar este trabajo",
"noPermissionModify": "No tienes permiso para modificar este trabajo",
"notCompleted": "Solo se pueden editar los trabajos completados. Estado actual: {status}",
"alreadyBeingEdited": "Este trabajo ya está siendo editado (los resultados ya fueron eliminados)",
"cleanupFailed": "La limpieza falló para {services}. El trabajo no fue modificado. Por favor, inténtalo de nuevo o contacta a soporte.",
"reopened": "Pista reabierta para edición. Los resultados anteriores han sido eliminados.",
"invalidDatetimeFormat": "Formato de {field} inválido: {value}",
"listError": "Error al listar los trabajos: {error}",
"deleteError": "Error al eliminar el trabajo {job_id}: {error}",
"deletionPreview": "Agrega &confirm=true para ejecutar la eliminación",
"deletionRequiresFilters": "Se requiere al menos un filtro (environment, client_id, status, created_before)",
"bulkDeleteError": "Error al eliminar trabajos en masa: {error}",
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
"correctionsUnavailable": "Datos de correcciones no disponibles",
"audioUnavailable": "Audio no disponible para revisión",
"reviewCannotStart": "No se puede iniciar la revisión",
"jobNotInReviewState": "El trabajo no está en estado de revisión (estado actual: {status})",
"correctionsProcessing": "Correcciones guardadas. Llama a /complete-review cuando termines.",
"editLogSaveFailed": "Error al guardar el registro de edición para el trabajo {job_id}: {error}",
"stemsMissing": "Al trabajo le faltan pistas de audio requeridas (instrumental_clean y/o backing_vocals)",
"customInstrumentalFailed": "Error al crear instrumental personalizado para el trabajo {job_id}: {error}",
"audioProcessingFailed": "Error al procesar el archivo de audio: {error}",
"durationMismatch": "Diferencia de duración: el archivo subido dura {upload_duration}s pero el audio original dura {original_duration}s. El instrumental debe durar exactamente {original_duration}s (±0.5s).",
"reviewNotInState": "El trabajo no está en estado de revisión (estado actual: {status})",
"noLyricsDetected": "No se puede completar la revisión: no se detectaron letras en el audio. Esto puede suceder cuando el audio de entrada no tiene voces (por ejemplo, una pista de karaoke o instrumental). Puedes regresar y pegar las letras manualmente usando 'Reemplazar todo', o cancelar este trabajo e intentarlo de nuevo con un archivo de audio que contenga voces.",
"reviewCompleteStartRendering": "Revisión completa. El renderizado de video ha comenzado.",
"reviewCompleteError": "Error al completar la revisión para el trabajo {job_id}: {error}",
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"instrumentalSelected": "Instrumental seleccionado. La generación de video ha comenzado.",
"instrumentalSelectionError": "Error al seleccionar instrumental para el trabajo {job_id}: {error}",
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
},
"review": {
"jobNotFound": "Trabajo no encontrado",
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
"correctionsNotFound": "Datos de correcciones no encontrados. El procesamiento de letras puede no estar completo.",
"correctionsLoadFailed": "Error al cargar las correcciones: {error}",
"audioNotFound": "Archivo de audio no encontrado",
"audioServeError": "Error al cargar el audio: {error}",
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"reviewCompletedError": "Error al completar la revisión: {error}",
"handlersUpdateNotImplemented": "Actualizaciones de manejadores aún no implementadas",
"lyricsAddError": "Error al agregar letras: {error}",
"lyricsAddInvalidRequest": "Solicitud para agregar letras inválida: {error}",
"lyricsSearchError": "Error al buscar letras: {error}",
"lyricsSearchInvalidRequest": "Solicitud para buscar letras inválida: {error}",
"lyricsSearchNoResults": "No se encontraron letras coincidentes en ningún proveedor",
"previewVideoGenerationError": "Error al generar el video de vista previa: {error}",
"previewVideoNotFound": "Video de vista previa no encontrado",
"previewVideoStreamError": "Error al transmitir el video de vista previa: {error}",
"annotationSaveError": "Error al guardar las anotaciones: {error}",
"waveformGenerationError": "Error al generar los datos de la forma de onda: {error}",
"waveformNoAudio": "No hay audio disponible para la forma de onda",
"sessionSaveError": "Se requieren datos de corrección"
},
"audioSearch": {
"notEnabled": "La búsqueda de audio no está habilitada para este inquilino",
"disabled": "La búsqueda de audio no está disponible",
"downloadError": "La descarga falló para el trabajo {job_id}: {error}",
"jobNotFound": "Trabajo {job_id} no encontrado",
"noSearchResults": "No hay resultados de búsqueda disponibles",
"invalidSelectionIndex": "Índice de selección inválido {selection_index}. Rango válido: 0-{max}",
"selectionError": "Error durante la selección de audio para el trabajo {job_id}: {error}",
"youtubeDownloadError": "La descarga de YouTube falló: {error}",
"torrentDownloadError": "No se puede descargar de {source} sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hay source_id o remote_search_id disponible para la descarga de {source}",
"remoteDownloadCompleteNoPath": "Descarga remota completada pero no se devolvió la ruta del archivo",
"spotifyDownloadError": "No se puede descargar de Spotify sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"genericDownloadError": "Tipo de fuente desconocido: {source}, intentando descarga genérica",
"jobNotFoundDuringDownload": "Trabajo {job_id} no encontrado durante la descarga en segundo plano",
"selectAudioError": "Error al seleccionar 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..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Si este correo electrónico está registrado, recibirás un enlace de inicio de sesión en breve.",
"emailServiceNotConfigured": "El servicio de correo electrónico no está disponible. Por favor, contacta a soporte.",
"emailDomainNotAllowed": "Dominio de correo electrónico no permitido para este inquilino",
"invalidToken": "Token inválido",
"verifyError": "La verificación falló: {message}",
"magicLinkSuccess": "Has iniciado sesión con éxito",
"logoutSuccess": "Has cerrado sesión con éxito",
"userNotFound": "Usuario no encontrado",
"creditPackagesError": "Error al cargar los paquetes de créditos: {error}",
"stripeSendError": "Error al enviar el enlace de pago de Stripe: {error}",
"stripeWebhookProcessingError": "Error al procesar el webhook de Stripe: {error}",
"feedbackSaveError": "Error al guardar los comentarios: {error}",
"feedbackNotEligible": "El usuario no es elegible para dejar comentarios"
},
"fileUpload": {
"invalidTheme": "Tema no encontrado: {theme_id}. Usa GET /api/themes para listar los temas disponibles.",
"uploadSuccess": "Archivo subido con éxito. El procesamiento ha comenzado.",
"uploadError": "Error al subir el archivo: {error}",
"urlDownloadError": "Error al descargar desde la URL: {error}",
"invalidContentType": "Tipo de contenido inválido: {content_type}",
"fileSizeError": "El archivo es demasiado grande: {size}. Máximo: {max_size}",
"invalidFileType": "Tipo de archivo inválido: {file_type}",
"multipleAudioFilesNotAllowed": "Solo se puede subir un archivo de audio",
"noAudioFileProvided": "No se proporcionó ningún archivo de audio",
"urlCreationSuccess": "Trabajo creado. URLs de subida generadas.",
"urlCreationError": "Error al crear el trabajo con URLs de subida: {error}",
"uploadsCompleteSuccess": "Subidas completadas. El procesamiento ha comenzado.",
"uploadsCompleteError": "Error al completar las subidas: {error}",
"noUploadedFiles": "No se especificaron archivos subidos",
"styleUploadUrlsSuccess": "URLs de subida de estilo generadas.",
"styleUploadsCompleteSuccess": "Archivos de estilo actualizados. El procesamiento se ha reiniciado.",
"styleUploadsCompleteError": "Error al completar las subidas de estilo: {error}"
},
"catalog": {
"rateLimitExceeded": "Límite de solicitudes excedido. Máximo {max_requests} solicitudes de catálogo por minuto.",
"catalogSearchError": "Error al buscar en el catálogo: {error}",
"communityCheckError": "Error al comprobar versiones de la comunidad: {error}"
},
"themes": {
"themesLoadError": "Error al cargar los temas",
"themeNotFound": "Tema no encontrado: {theme_id}",
"themeLoadError": "Error al cargar el tema",
"previewNotAvailable": "No hay vista previa disponible para el tema: {theme_id}",
"previewLoadError": "Error al cargar la vista previa del tema",
"youtubeDescriptionNotFound": "Tema no encontrado: {theme_id}",
"youtubeDescriptionLoadError": "Error al cargar la descripción de YouTube"
},
"tenant": {
"assetNotFound": "Activo no encontrado"
},
"push": {
"disabled": "Las notificaciones push no están habilitadas",
"userEmailNotAvailable": "El correo electrónico del usuario no está disponible",
"missingEncryptionKeys": "Faltan claves requeridas (p256dh, auth)",
"subscriptionSaveFailed": "Error al guardar la suscripción",
"subscriptionRegistered": "Suscripción push registrada con éxito",
"subscriptionNotFound": "Suscripción eliminada (o no fue encontrada)",
"subscriptionRemoved": "Suscripción push eliminada con éxito",
"testNotificationSent": "Notificación de prueba enviada a {sent_count} dispositivo(s)"
},
"pushNotifications": {
"reviewLyricsTitle": "Revisión de letras",
"reviewLyricsBody": "\"{title}\" de {artist} necesita revisión de letras",
"selectInstrumentalTitle": "Seleccionar instrumental",
"selectInstrumentalBody": "\"{title}\" de {artist} necesita selección de instrumental",
"videoReadyTitle": "¡Video listo!",
"videoReadyBody": "Tu video de karaoke para \"{title}\" de {artist} está listo para descargar"
},
"admin": {
"invalidDomainFormat": "Formato de dominio inválido",
"domainAddedToBl": "Dominio '{domain}' agregado a la lista de bloqueo de dominios desechables",
"domainNotFoundInBl": "Dominio no encontrado en la lista de bloqueo",
"domainRemovedFromBl": "Dominio '{domain}' eliminado de la lista de bloqueo de dominios desechables",
"domainAddedToAllowlist": "Dominio '{domain}' agregado a la lista de permitidos",
"domainNotFoundInAllowlist": "Dominio no encontrado en la lista de permitidos",
"domainRemovedFromAllowlist": "Dominio '{domain}' eliminado de la lista de permitidos",
"syncComplete": "Se sincronizaron {external_count} dominios externos ({added} agregados, {removed} eliminados)",
"invalidEmailFormat": "Formato de correo electrónico inválido",
"emailAddedToBl": "Correo electrónico '{email}' agregado a la lista de correos bloqueados",
"emailNotFoundInBl": "Correo electrónico no encontrado en la lista de bloqueo",
"emailRemovedFromBl": "Correo electrónico '{email}' eliminado de la lista de correos bloqueados",
"invalidIPAddress": "Dirección IP inválida",
"ipAddedToBl": "IP '{ip_address}' agregada a la lista de IPs bloqueadas",
"ipNotFoundInBl": "IP no encontrada en la lista de bloqueo",
"ipRemovedFromBl": "IP '{ip_address}' eliminada de la lista de IPs bloqueadas",
"youtubeUploadNotFound": "Subida no encontrada o no en estado de reintento para el trabajo {job_id}",
"youtubeUploadQueuedForRetry": "Subida a YouTube para el trabajo {job_id} en cola para reintento",
"youtubeQueueProcessingStarted": "Procesamiento de la cola de YouTube iniciado en segundo plano"
},
"rateLimits": {
"configNotFound": "Configuración de límite de solicitudes no encontrada: {config_id}",
"configUpdateError": "Error al actualizar la configuración de límite de solicitudes: {error}"
},
"errors": {
"insufficientCredits": "Créditos insuficientes para esta operación",
"insufficientCreditsBuyUrl": "/#pricing"
},
"emails": {
"magicLink": {
"subject": "Inicia sesión en {brand_name}"
},
"welcome": {
"subject": "¡Bienvenido a Nomad Karaoke!"
},
"creditsAdded": {
"subject": "{credits} créditos agregados a tu cuenta de Nomad Karaoke"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Tu video de karaoke está listo!)",
"subject": "{artist} - {title} (¡Tu video de karaoke está listo!)",
"subjectFallback": "¡Tu video de karaoke está listo!"
},
"youtubeUpload": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Subida a YouTube lista!)",
"subject": "{artist} - {title} (¡Subida a YouTube lista!)",
"subjectFallback": "¡Tu subida a YouTube está lista!"
},
"actionReminder": {
"lyricsSubject": "Acción necesaria: Revisar letras para {artist} - {title}",
"lyricsSubjectFallback": "Acción necesaria: Revisar letras",
"instrumentalSubject": "Acción necesaria: Seleccionar instrumental para {artist} - {title}",
"instrumentalSubjectFallback": "Acción necesaria: Seleccionar instrumental",
"audioEditSubject": "Acción necesaria para {artist} - {title}",
"audioEditSubjectFallback": "Acción necesaria"
},
"reviewReminder": {
"subject": "Recordatorio: Tu video de karaoke está esperando revisión — {artist} - {title}",
"subjectFallback": "Recordatorio: Tu video de karaoke está esperando revisión"
},
"reviewExpired": {
"subject": "Tu video de karaoke ha expirado — {artist} - {title}",
"subjectFallback": "Tu video de karaoke ha expirado"
},
"creditDenied": {
"subject": "Sobre tus créditos gratis de Nomad Karaoke"
},
"madeForYouConfirmation": {
"subject": "Pedido confirmado: {artist} - {title} | Nomad Karaoke"
}
}
}
+15
View File
@@ -25,3 +25,18 @@ def get_version() -> str:
VERSION = get_version()
# Build metadata — set by CI during deployment
COMMIT_SHA = os.environ.get("COMMIT_SHA", "")
PR_NUMBER = os.environ.get("PR_NUMBER", "")
PR_TITLE = os.environ.get("PR_TITLE", "")
STARTUP_TIME = None # Set on first import
def _get_startup_time() -> str:
"""Record when the backend process started (proxy for deploy time)."""
from datetime import datetime, timezone
return datetime.now(timezone.utc).isoformat()
STARTUP_TIME = _get_startup_time()
+57 -21
View File
@@ -2,11 +2,13 @@
Audio separation worker.
Handles the audio processing track of parallel processing:
1. Stage 1: Clean instrumental separation (Modal API, 3-5 min)
2. Stage 2: Backing vocals separation (Modal API, 2-3 min)
1. Stage 1: Clean instrumental separation (GPU, 3-5 min)
2. Stage 2: Backing vocals separation (GPU, 2-3 min)
3. Post-processing: Combine instrumentals, normalize
Re-uses karaoke_gen.audio_processor.AudioProcessor for remote GPU separation.
Supports two modes:
- Local GPU: Runs Separator directly with L4 GPU (MODEL_DIR env var)
- Remote API: Calls audio-separator Cloud Run Service (AUDIO_SEPARATOR_API_URL env var)
Observability:
- All operations wrapped in tracing spans for Cloud Trace visibility
@@ -200,6 +202,7 @@ async def download_from_url(url: str, temp_dir: str, artist: str, title: str, jo
def create_audio_processor(
temp_dir: str,
model_file_dir: Optional[str] = None,
clean_instrumental_model: Optional[str] = None,
backing_vocals_models: Optional[list] = None,
other_stems_models: Optional[list] = None,
@@ -207,15 +210,24 @@ def create_audio_processor(
karaoke_preset: Optional[str] = None,
) -> AudioProcessor:
"""
Create an AudioProcessor instance configured for remote API processing.
Create an AudioProcessor instance configured for audio processing.
Supports two modes:
- Local GPU mode: When model_file_dir is set, uses the local Separator class
with GPU models loaded from that directory. No remote API calls.
- Remote API mode (default): When model_file_dir is None, delegates separation
to a remote audio-separator API server.
Within each mode, separation can be configured via:
- Preset mode (default): Uses ensemble presets for higher quality separation.
Presets are resolved by the audio-separator API server.
Presets are resolved by the audio-separator API server (remote) or local
preset definitions (local GPU).
- Model mode (legacy): Uses explicit model filenames for per-job overrides.
Args:
temp_dir: Temporary directory for processing
model_file_dir: Directory containing local model files for GPU separation.
When set, enables local GPU mode. When None (default), uses remote API.
clean_instrumental_model: Model for clean instrumental (legacy, overrides preset)
backing_vocals_models: Models for backing vocals (legacy, overrides preset)
other_stems_models: Models for other stems (legacy, default empty)
@@ -241,7 +253,7 @@ def create_audio_processor(
logger=audio_logger,
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None, # No local models, using remote API
model_file_dir=model_file_dir,
lossless_output_format="FLAC",
clean_instrumental_model=effective_clean_model,
backing_vocals_models=effective_backing_models,
@@ -249,7 +261,7 @@ def create_audio_processor(
ffmpeg_base_command=ffmpeg_base_command,
)
# Set preset configuration (used by _process_audio_separation_remote)
# Set preset configuration (used by both remote and local paths)
processor.instrumental_preset = instrumental_preset or DEFAULT_INSTRUMENTAL_PRESET
processor.karaoke_preset = karaoke_preset or DEFAULT_KARAOKE_PRESET
@@ -265,8 +277,8 @@ async def process_audio_separation(job_id: str) -> bool:
Workflow:
1. Download audio from GCS
2. Stage 1: Separate with clean instrumental + other stems models (Modal API)
3. Stage 2: Separate vocals for backing vocals (Modal API)
2. Stage 1: Separate with clean instrumental + other stems models (GPU)
3. Stage 2: Separate vocals for backing vocals (GPU)
4. Post-process: Combine instrumentals, normalize audio
5. Upload all stems to GCS
6. Mark job as AUDIO_COMPLETE
@@ -326,13 +338,22 @@ async def process_audio_separation(job_id: str) -> bool:
job_log.info(f"Starting audio separation for {job.artist} - {job.title}")
logger.info(f"[job:{job_id}] Starting audio separation for {job.artist} - {job.title}")
# Ensure AUDIO_SEPARATOR_API_URL is set
# Determine separation mode: local GPU or remote API
api_url = os.environ.get("AUDIO_SEPARATOR_API_URL")
if not api_url:
raise Exception("AUDIO_SEPARATOR_API_URL environment variable not set. "
"Cannot perform audio separation without remote API access.")
job_log.info(f"Audio separator API: {api_url}")
add_span_attribute("audio_separator_api", api_url)
model_dir = os.environ.get("MODEL_DIR")
if api_url:
job_log.info(f"Audio separator mode: remote API at {api_url}")
add_span_attribute("audio_separator_mode", "remote")
add_span_attribute("audio_separator_api", api_url)
elif model_dir:
job_log.info(f"Audio separator mode: local GPU (models at {model_dir})")
add_span_attribute("audio_separator_mode", "local_gpu")
add_span_attribute("model_dir", model_dir)
else:
raise Exception(
"Audio separation not configured. Set either AUDIO_SEPARATOR_API_URL "
"(remote API) or MODEL_DIR (local GPU with baked-in models)."
)
# Download audio file from GCS or URL
with job_span("download-audio", job_id) as download_span:
@@ -371,9 +392,15 @@ async def process_audio_separation(job_id: str) -> bool:
clean_instrumental_model=job.clean_instrumental_model,
backing_vocals_models=job.backing_vocals_models,
other_stems_models=job.other_stems_models,
model_file_dir=model_dir,
)
audio_processor.job_id = job_id # Used as filename prefix (avoids artist/title encoding issues)
# Pass GCS URI so the separator can fetch directly from GCS (avoids 413 for large files)
if job.input_media_gcs_path:
audio_processor.input_gcs_uri = f"gs://{settings.gcs_bucket_name}/{job.input_media_gcs_path}"
job_log.info(f" GCS URI for separator: {audio_processor.input_gcs_uri}")
# Store effective model names in state_data for video_worker to use in file naming
# This ensures output filenames match local CLI behavior (e.g., "Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt")
effective_model_names = {
@@ -392,15 +419,15 @@ async def process_audio_separation(job_id: str) -> bool:
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
artist_title = f"{safe_artist} - {safe_title}"
# Run audio separation (calls Modal API internally)
# Run audio separation (local GPU or remote API)
# This returns a dict with paths to all separated stems
with job_span("modal-separation", job_id) as sep_span:
with job_span("audio-separation", job_id) as sep_span:
sep_start = time.time()
job_log.info("Starting audio separation (this may take 5-10 minutes)...")
job_log.info(" Stage 1: Clean instrumental separation (MDX models)")
job_log.info(" Stage 2: Backing vocals separation (Demucs model)")
add_span_event("separation_started")
logger.info(f"[job:{job_id}] Calling Modal API for audio separation")
logger.info(f"[job:{job_id}] Starting audio separation")
# Retry with exponential backoff. The audio-separator GPU service
# may be busy processing other jobs for 5-10+ minutes each, so we
@@ -408,7 +435,7 @@ async def process_audio_separation(job_id: str) -> bool:
max_retries = 5
for attempt in range(1, max_retries + 1):
try:
with metrics.time_external_api("modal", job_id):
with metrics.time_external_api("audio_separation", job_id):
separation_result = audio_processor.process_audio_separation(
audio_file=audio_path,
artist_title=artist_title,
@@ -455,7 +482,7 @@ async def process_audio_separation(job_id: str) -> bool:
# Store processing metadata for separation provenance
duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "separation", {
"provider": "modal",
"provider": "local_gpu" if model_dir else "remote_api",
"clean_model": effective_model_names['clean_instrumental_model'],
"backing_models": effective_model_names['backing_vocals_models'],
"other_models": effective_model_names['other_stems_models'],
@@ -464,6 +491,15 @@ async def process_audio_separation(job_id: str) -> bool:
})
job_manager.update_processing_metadata(job_id, "timing.audio_worker_seconds", round(duration, 1))
# Analyze backing vocals for instrumental selection recommendation
# This must run here (after stems are uploaded) rather than in screens_worker,
# because screens_worker triggers on lyrics completion and audio may not be done yet
from backend.workers.screens_worker import _analyze_backing_vocals
try:
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
except Exception as e:
logger.warning(f"[job:{job_id}] Backing vocals analysis failed (non-fatal): {e}")
# Mark audio processing complete
# This will check if lyrics are also complete and transition to next stage if so
job_manager.mark_audio_complete(job_id)
@@ -796,7 +832,7 @@ def main():
Environment Variables:
GOOGLE_CLOUD_PROJECT: GCP project ID (required)
GCS_BUCKET_NAME: Storage bucket name (required)
AUDIO_SEPARATOR_API_URL: Modal API URL (required)
AUDIO_SEPARATOR_API_URL: Remote API URL (or MODEL_DIR for local GPU)
"""
import argparse
import asyncio
+43 -44
View File
@@ -29,7 +29,6 @@ from typing import Optional, Dict, Any
from pathlib import Path
from backend.models.job import JobStatus
from karaoke_gen.utils import sanitize_filename
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
@@ -599,10 +598,7 @@ async def upload_lyrics_results(
job_log: Optional JobLogger for remote debugging
"""
logger.info(f"Job {job_id}: Uploading lyrics results to GCS")
# Get job object for artist/title
job = job_manager.get_job(job_id)
lyrics_dir = os.path.join(temp_dir, "lyrics")
# Upload LRC file (timed lyrics)
@@ -614,17 +610,21 @@ async def upload_lyrics_results(
# Upload corrections JSON (for review interface)
# LyricsProcessor saves it as "{artist} - {title} (Lyrics Corrections).json"
# Sanitize artist/title to prevent path injection and match LyricsProcessor's sanitization
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
corrections_filename = f"{safe_artist} - {safe_title} (Lyrics Corrections).json"
corrections_file = os.path.join(lyrics_dir, corrections_filename)
# Scan the directory instead of reconstructing the filename, because the artist/title
# in Firestore may have been updated (e.g. by admin) after LyricsProcessor generated the file.
corrections_file = None
if os.path.isdir(lyrics_dir):
for fname in os.listdir(lyrics_dir):
if fname.endswith("(Lyrics Corrections).json"):
corrections_file = os.path.join(lyrics_dir, fname)
break
# Fallback: check for generic corrections.json
if not corrections_file:
fallback = os.path.join(lyrics_dir, "corrections.json")
if os.path.exists(fallback):
corrections_file = fallback
# Also check for generic corrections.json (fallback)
if not os.path.exists(corrections_file):
corrections_file = os.path.join(lyrics_dir, "corrections.json")
if os.path.exists(corrections_file):
if corrections_file and os.path.exists(corrections_file):
# Always upload as corrections.json for consistent access
gcs_path = f"jobs/{job_id}/lyrics/corrections.json"
url = storage.upload_file(corrections_file, gcs_path)
@@ -660,33 +660,29 @@ async def upload_lyrics_results(
else:
# CRITICAL: corrections.json is required for the review UI
# If it's missing, the job cannot proceed to review
error_msg = f"No corrections JSON found at {corrections_file}. Transcription may have produced no lyrics."
error_msg = f"No corrections JSON found in {lyrics_dir}. Transcription may have produced no lyrics."
logger.error(f"Job {job_id}: {error_msg}")
raise Exception(error_msg)
# Upload ALL reference lyrics files (not just first) so they're available for distribution
# Note: Source names use .title() so "lrclib" -> "Lrclib", "genius" -> "Genius"
# Use sanitized artist/title to match LyricsProcessor's file naming
reference_files = [
(f"{safe_artist} - {safe_title} (Lyrics Genius).txt", "genius"),
(f"{safe_artist} - {safe_title} (Lyrics Spotify).txt", "spotify"),
(f"{safe_artist} - {safe_title} (Lyrics Musixmatch).txt", "musixmatch"),
(f"{safe_artist} - {safe_title} (Lyrics Lrclib).txt", "lrclib"),
]
# Scan directory for reference files instead of reconstructing filenames,
# since artist/title may have changed in Firestore after file generation.
source_keys = {"Genius": "genius", "Spotify": "spotify", "Musixmatch": "musixmatch", "Lrclib": "lrclib"}
found_references = []
for ref_filename, source_key in reference_files:
ref_path = os.path.join(lyrics_dir, ref_filename)
if os.path.exists(ref_path):
# Upload with original filename to preserve proper naming
gcs_path = f"jobs/{job_id}/lyrics/{ref_filename}"
url = storage.upload_file(ref_path, gcs_path)
# Track in job.files so video_worker can download for distribution
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
if job_log:
job_log.info(f"Found reference lyrics from {source_key}")
logger.info(f"Job {job_id}: Uploaded reference lyrics: {ref_filename}")
found_references.append(source_key)
if os.path.isdir(lyrics_dir):
for fname in os.listdir(lyrics_dir):
for source_label, source_key in source_keys.items():
if fname.endswith(f"(Lyrics {source_label}).txt"):
ref_path = os.path.join(lyrics_dir, fname)
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
url = storage.upload_file(ref_path, gcs_path)
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
if job_log:
job_log.info(f"Found reference lyrics from {source_key}")
logger.info(f"Job {job_id}: Uploaded reference lyrics: {fname}")
found_references.append(source_key)
break
if not found_references:
if job_log:
@@ -695,14 +691,17 @@ async def upload_lyrics_results(
else:
logger.info(f"Job {job_id}: Found {len(found_references)} reference lyrics sources: {found_references}")
# Upload uncorrected transcription if available (preserve original filename for distribution)
uncorrected_filename = f"{safe_artist} - {safe_title} (Lyrics Uncorrected).txt"
uncorrected_file = os.path.join(lyrics_dir, uncorrected_filename)
if os.path.exists(uncorrected_file):
gcs_path = f"jobs/{job_id}/lyrics/{uncorrected_filename}"
url = storage.upload_file(uncorrected_file, gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {uncorrected_filename}")
# Upload uncorrected transcription if available
# Scan directory instead of reconstructing filename (artist/title may have changed)
if os.path.isdir(lyrics_dir):
for fname in os.listdir(lyrics_dir):
if fname.endswith("(Lyrics Uncorrected).txt"):
uncorrected_file = os.path.join(lyrics_dir, fname)
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
url = storage.upload_file(uncorrected_file, gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {fname}")
break
logger.info(f"Job {job_id}: All lyrics results uploaded successfully")
+356 -211
View File
@@ -40,6 +40,7 @@ from backend.services.job_health_service import validate_worker_can_run
from backend.config import get_settings
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
from backend.services.encoding_service import get_encoding_service
# Import from lyrics_transcriber (submodule)
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
@@ -119,259 +120,403 @@ async def process_render_video(job_id: str) -> bool:
# This ensures logs from third-party libraries (lyrics_transcriber.output) are only
# captured by this job's handler, not handlers from other concurrent jobs
with job_logging_context(job_id):
# Transition to RENDERING_VIDEO
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=75,
message="Rendering karaoke video with corrected lyrics"
)
with tempfile.TemporaryDirectory() as temp_dir:
job_log.info(f"Created temp directory: {temp_dir}")
# Try updated corrections first (from human review), fall back to original
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
# Get GCS path from file_urls
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
if not corrections_url:
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
if not corrections_url:
# Try direct GCS paths
if storage.file_exists(corrections_gcs_updated):
corrections_gcs = corrections_gcs_updated
elif storage.file_exists(corrections_gcs_original):
corrections_gcs = corrections_gcs_original
else:
raise FileNotFoundError(f"No corrections file found for job {job_id}")
else:
# Extract GCS path from URL
corrections_gcs = _extract_gcs_path(corrections_url)
# 2. Load the ORIGINAL corrections (has full structure)
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
storage.download_file(original_corrections_gcs, original_corrections_path)
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Load base CorrectionResult from original data
base_result = CorrectionResult.from_dict(original_data)
# Check if GCE encoding is enabled
encoding_service = get_encoding_service()
use_gce = encoding_service.is_enabled
# 4. Apply user corrections if available (from review UI)
# Uses the same method as preview generation to ensure
# identical CorrectionResult construction (DRY).
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if use_gce:
# ============ GCE RENDER VIDEO PATH ============
job_log.info("GCE encoding enabled - delegating render_video to encoding worker")
logger.info(f"[job:{job_id}] Using GCE encoding worker for render_video")
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, applying via shared method")
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
else:
correction_result = base_result
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise FileNotFoundError(f"No input audio path for job {job_id}")
job_log.info(f"Downloading audio from {audio_gcs_path}")
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Process countdown intro if needed (for songs that start too quickly)
# This adds "3... 2... 1..." segment and pads audio with 3s silence
# Note: Countdown is deferred to this stage (not during lyrics transcription)
# so the review UI can show the original timing without the 3s shift
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=audio_path,
# Transition to RENDERING_VIDEO
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=75,
message="Rendering karaoke video on encoding worker"
)
if padding_added:
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
else:
job_log.info("No countdown needed - song starts after 3 seconds")
# Update lyrics_metadata with countdown info so video_worker knows to pad instrumental
# This is critical for audio sync - without this, instrumental won't match padded vocals
# Build render config from job metadata (no downloads needed on Cloud Run!)
bucket_name = settings.gcs_bucket_name
# Check for updated corrections
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
has_updated = storage.file_exists(updated_corrections_gcs)
render_config = {
"original_corrections_gcs_path": f"gs://{bucket_name}/jobs/{job_id}/lyrics/corrections.json",
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
"output_gcs_prefix": f"gs://{bucket_name}/jobs/{job_id}/",
"artist": job.artist,
"title": job.title,
"subtitle_offset_ms": getattr(job, 'subtitle_offset_ms', 0) or 0,
"video_resolution": "4k",
}
if has_updated:
render_config["updated_corrections_gcs_path"] = f"gs://{bucket_name}/{updated_corrections_gcs}"
if job.style_params_gcs_path:
render_config["style_params_gcs_path"] = f"gs://{bucket_name}/{job.style_params_gcs_path}" if not job.style_params_gcs_path.startswith("gs://") else job.style_params_gcs_path
if job.style_assets:
render_config["style_assets"] = {
k: f"gs://{bucket_name}/{v}" if not v.startswith("gs://") else v
for k, v in job.style_assets.items()
}
def progress_callback(progress: int):
scaled = 75 + int(progress * 0.07) # Map 0-100 to 75-82
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=scaled,
message=f"Rendering video ({progress}%)"
)
with job_span("gce-render-video", job_id) as render_span:
render_start = time.time()
result = await encoding_service.render_video_on_gce(
job_id, render_config, progress_callback=progress_callback
)
render_duration = time.time() - render_start
render_span.set_attribute("duration_seconds", render_duration)
job_log.info(f"GCE render_video complete in {render_duration:.1f}s")
logger.info(f"[job:{job_id}] GCE render_video complete in {render_duration:.1f}s")
# Parse response and update Firestore
output_files = result.get("output_files", [])
metadata = result.get("metadata", {})
# Update file URLs from GCE response
for gcs_path in output_files:
blob_path = gcs_path
if blob_path.startswith("gs://"):
blob_path = blob_path.split("/", 3)[3] if blob_path.count("/") >= 3 else blob_path
if "with_vocals.mkv" in blob_path:
job_manager.update_file_url(job_id, 'videos', 'with_vocals', blob_path)
elif "karaoke.ass" in blob_path:
job_manager.update_file_url(job_id, 'lyrics', 'ass', blob_path)
elif "karaoke.lrc" in blob_path:
job_manager.update_file_url(job_id, 'lyrics', 'lrc', blob_path)
elif "corrected.txt" in blob_path:
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', blob_path)
# Handle countdown padding metadata
padding_added = metadata.get("countdown_padding_added", False)
padding_seconds = metadata.get("countdown_padding_seconds", 0)
if padding_added:
existing_lyrics_metadata = job.state_data.get('lyrics_metadata', {})
existing_lyrics_metadata['has_countdown_padding'] = True
existing_lyrics_metadata['countdown_padding_seconds'] = padding_seconds
job_manager.update_state_data(job_id, 'lyrics_metadata', existing_lyrics_metadata)
job_log.info(f"Updated lyrics_metadata: has_countdown_padding=True, countdown_padding_seconds={padding_seconds}")
job_log.info(f"Countdown padding: {padding_seconds}s")
# 6. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=job_log,
)
# 7. Configure OutputGenerator
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
output_styles_json=styles_path,
render_video=True,
generate_cdg=False, # CDG optional, generated separately
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=subtitle_offset
)
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
output_generator = OutputGenerator(config, logger)
# 8. Generate outputs (video, LRC, ASS, etc.)
# Sanitize artist/title to handle Unicode characters (curly quotes, em dashes, etc.)
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={}, # Reference lyrics already in correction_result
output_prefix=output_prefix,
audio_filepath=audio_path,
artist=job.artist,
title=job.title
)
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
job_log.info(f"Video generated: {video_size} bytes")
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
video_url = storage.upload_file(outputs.video, video_gcs_path)
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
job_log.info(f"Uploaded with_vocals.mkv to GCS")
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
else:
job_log.error("Video generation failed - no output file produced!")
raise Exception("Video generation failed - no output file produced")
# 10. Upload LRC file
if outputs.lrc and os.path.exists(outputs.lrc):
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
job_log.info("Uploaded karaoke.lrc")
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
# 11. Upload ASS subtitle file
if outputs.ass and os.path.exists(outputs.ass):
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
job_log.info("Uploaded karaoke.ass")
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
# 12. Upload corrected text files
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# Store render timing in processing metadata
render_duration = time.time() - start_time
# Store render timing
job_manager.update_processing_metadata(job_id, "rendering", {
"render_duration_seconds": round(render_duration, 1),
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
"rendered_on": "gce",
})
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
# 13. Transition based on prep_only flag
# Note: Instrumental selection was already made during combined review
# (stored in state_data['instrumental_selection'])
# Transition state (same as local path)
if getattr(job, 'prep_only', False):
# Prep-only mode: stop here and mark as prep complete
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PREP_COMPLETE,
progress=100,
message="Prep phase complete - download outputs to continue locally"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY, GCE) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("prep_only", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
root_span.set_attribute("rendered_on", "gce")
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s gce=true prep_only=true")
else:
# Normal mode: instrumental was selected during combined review
# Transition directly to INSTRUMENTAL_SELECTED and trigger video worker
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=82,
message="Video rendered, starting final encoding"
message="Video rendered on encoding worker, starting final encoding"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
job_log.info("=== RENDER VIDEO WORKER COMPLETE (GCE) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
root_span.set_attribute("rendered_on", "gce")
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s gce=true")
# Trigger video worker for final encoding
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
job_log.info("Triggering video worker for final encoding...")
await worker_service.trigger_video_worker(job_id)
# Mark render progress as complete for idempotency
# This allows the worker to be re-triggered after admin reset
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
return True
else:
# ============ LOCAL RENDER VIDEO PATH ============
# Transition to RENDERING_VIDEO
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=75,
message="Rendering karaoke video with corrected lyrics"
)
with tempfile.TemporaryDirectory() as temp_dir:
job_log.info(f"Created temp directory: {temp_dir}")
# Try updated corrections first (from human review), fall back to original
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
# Get GCS path from file_urls
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
if not corrections_url:
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
if not corrections_url:
# Try direct GCS paths
if storage.file_exists(corrections_gcs_updated):
corrections_gcs = corrections_gcs_updated
elif storage.file_exists(corrections_gcs_original):
corrections_gcs = corrections_gcs_original
else:
raise FileNotFoundError(f"No corrections file found for job {job_id}")
else:
# Extract GCS path from URL
corrections_gcs = _extract_gcs_path(corrections_url)
# 2. Load the ORIGINAL corrections (has full structure)
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
storage.download_file(original_corrections_gcs, original_corrections_path)
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Load base CorrectionResult from original data
base_result = CorrectionResult.from_dict(original_data)
# 4. Apply user corrections if available (from review UI)
# Uses the same method as preview generation to ensure
# identical CorrectionResult construction (DRY).
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, applying via shared method")
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
if isinstance(updated_data, dict) and "corrections" in updated_data:
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
else:
job_log.warning("corrections_updated.json exists but has no 'corrections' key, using base result")
logger.warning(f"Job {job_id}: corrections_updated.json has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise FileNotFoundError(f"No input audio path for job {job_id}")
job_log.info(f"Downloading audio from {audio_gcs_path}")
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Process countdown intro if needed (for songs that start too quickly)
# This adds "3... 2... 1..." segment and pads audio with 3s silence
# Note: Countdown is deferred to this stage (not during lyrics transcription)
# so the review UI can show the original timing without the 3s shift
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=audio_path,
)
if padding_added:
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
else:
job_log.info("No countdown needed - song starts after 3 seconds")
# Update lyrics_metadata with countdown info so video_worker knows to pad instrumental
# This is critical for audio sync - without this, instrumental won't match padded vocals
if padding_added:
existing_lyrics_metadata = job.state_data.get('lyrics_metadata', {})
existing_lyrics_metadata['has_countdown_padding'] = True
existing_lyrics_metadata['countdown_padding_seconds'] = padding_seconds
job_manager.update_state_data(job_id, 'lyrics_metadata', existing_lyrics_metadata)
job_log.info(f"Updated lyrics_metadata: has_countdown_padding=True, countdown_padding_seconds={padding_seconds}")
# 6. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=job_log,
)
# 7. Configure OutputGenerator
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
output_styles_json=styles_path,
render_video=True,
generate_cdg=False, # CDG optional, generated separately
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=subtitle_offset
)
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
output_generator = OutputGenerator(config, logger)
# 8. Generate outputs (video, LRC, ASS, etc.)
# Sanitize artist/title to handle Unicode characters (curly quotes, em dashes, etc.)
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={}, # Reference lyrics already in correction_result
output_prefix=output_prefix,
audio_filepath=audio_path,
artist=job.artist,
title=job.title
)
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
job_log.info(f"Video generated: {video_size} bytes")
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
video_url = storage.upload_file(outputs.video, video_gcs_path)
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
job_log.info(f"Uploaded with_vocals.mkv to GCS")
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
else:
job_log.error("Video generation failed - no output file produced!")
raise Exception("Video generation failed - no output file produced")
# 10. Upload LRC file
if outputs.lrc and os.path.exists(outputs.lrc):
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
job_log.info("Uploaded karaoke.lrc")
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
# 11. Upload ASS subtitle file
if outputs.ass and os.path.exists(outputs.ass):
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
job_log.info("Uploaded karaoke.ass")
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
# 12. Upload corrected text files
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# Store render timing in processing metadata
render_duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "rendering", {
"render_duration_seconds": round(render_duration, 1),
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
})
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
# 13. Transition based on prep_only flag
# Note: Instrumental selection was already made during combined review
# (stored in state_data['instrumental_selection'])
if getattr(job, 'prep_only', False):
# Prep-only mode: stop here and mark as prep complete
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PREP_COMPLETE,
progress=100,
message="Prep phase complete - download outputs to continue locally"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("prep_only", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
else:
# Normal mode: instrumental was selected during combined review
# Transition directly to INSTRUMENTAL_SELECTED and trigger video worker
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=82,
message="Video rendered, starting final encoding"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
# Trigger video worker for final encoding
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
job_log.info("Triggering video worker for final encoding...")
await worker_service.trigger_video_worker(job_id)
# Mark render progress as complete for idempotency
# This allows the worker to be re-triggered after admin reset
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
return True
except Exception as e:
duration = time.time() - start_time
+37 -46
View File
@@ -178,11 +178,8 @@ async def generate_screens(job_id: str) -> bool:
# Apply countdown padding if needed
await _apply_countdown_padding_if_needed(job_id, job_manager, job)
# Analyze backing vocals for combined review
# This runs BEFORE review so user can select instrumental during lyrics review
with job_span("analyze-backing-vocals", job_id):
job_log.info("Analyzing backing vocals for instrumental selection...")
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
# Note: backing vocals analysis now runs in audio_worker after stems are uploaded,
# since screens_worker triggers on lyrics completion and audio may not be done yet.
# Transcode review audio to OGG Opus for fast browser playback
# This runs BEFORE review so all files are cached when the user opens the UI
@@ -388,7 +385,9 @@ async def _generate_title_screen(
logger.info(f"Job {job_id}: Title format - bg_image: {title_format.get('background_image')}, font: {title_format.get('font')}")
# Generate title screen (synchronous method)
# Generate title screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_title_video(
artist=job.artist,
title=job.title,
@@ -396,12 +395,13 @@ async def _generate_title_screen(
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_title_image=title_format.get('existing_image'),
intro_video_duration=intro_duration
intro_video_duration=0,
)
if os.path.exists(output_video_filepath):
logger.info(f"Job {job_id}: Title screen generated at {output_video_filepath}")
return output_video_filepath
output_png = f"{output_image_filepath_noext}.png"
if os.path.exists(output_png):
logger.info(f"Job {job_id}: Title screen image generated at {output_png}")
return output_png
else:
logger.error(f"Job {job_id}: Title screen generation returned no file")
return None
@@ -460,7 +460,9 @@ async def _generate_end_screen(
logger.info(f"Job {job_id}: End format - bg_image: {end_format.get('background_image')}, font: {end_format.get('font')}")
# Generate end screen (synchronous method)
# Generate end screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_end_video(
artist=job.artist,
title=job.title,
@@ -468,12 +470,13 @@ async def _generate_end_screen(
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_end_image=end_format.get('existing_image'),
end_video_duration=end_duration
end_video_duration=0,
)
if os.path.exists(output_video_filepath):
logger.info(f"Job {job_id}: End screen generated at {output_video_filepath}")
return output_video_filepath
output_png = f"{output_image_filepath_noext}.png"
if os.path.exists(output_png):
logger.info(f"Job {job_id}: End screen image generated at {output_png}")
return output_png
else:
logger.error(f"Job {job_id}: End screen generation returned no file")
return None
@@ -491,46 +494,34 @@ async def _upload_screens(
end_screen_path: str
) -> None:
"""
Upload title and end screens to GCS (video + images).
Upload title and end screen images to GCS.
Single Responsibility: Only handles uploads.
VideoGenerator creates .mov, .jpg, and .png files when configured with
output_png=True and output_jpg=True. We upload all three formats
for feature parity with the local CLI.
VideoGenerator creates .jpg and .png files when configured with
output_png=True and output_jpg=True. MOV video generation is handled
by the GCE encoding worker (not Cloud Run) to avoid OOM with 4K H.264.
Args:
job_id: Job ID
job_manager: Job manager instance
storage: Storage service instance
title_screen_path: Path to title screen video (.mov)
end_screen_path: Path to end screen video (.mov)
title_screen_path: Path to title screen image (.png)
end_screen_path: Path to end screen image (.png)
"""
# Upload title screen video
title_gcs_path = f"jobs/{job_id}/screens/title.mov"
title_url = storage.upload_file(title_screen_path, title_gcs_path)
job_manager.update_file_url(job_id, 'screens', 'title', title_url)
logger.info(f"Job {job_id}: Uploaded title screen video")
# Upload title screen images (.jpg and .png - created by VideoGenerator)
title_base = title_screen_path.replace('.mov', '')
for ext, key in [('.jpg', 'title_jpg'), ('.png', 'title_png')]:
# Upload title screen images (.png and .jpg)
title_base = title_screen_path.replace('.png', '')
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
image_path = f"{title_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/title{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', key, url)
logger.info(f"Job {job_id}: Uploaded title screen image ({ext})")
# Upload end screen video
end_gcs_path = f"jobs/{job_id}/screens/end.mov"
end_url = storage.upload_file(end_screen_path, end_gcs_path)
job_manager.update_file_url(job_id, 'screens', 'end', end_url)
logger.info(f"Job {job_id}: Uploaded end screen video")
# Upload end screen images (.jpg and .png - created by VideoGenerator)
end_base = end_screen_path.replace('.mov', '')
for ext, key in [('.jpg', 'end_jpg'), ('.png', 'end_png')]:
# Upload end screen images (.png and .jpg)
end_base = end_screen_path.replace('.png', '')
for ext, key in [('.png', 'end_png'), ('.jpg', 'end_jpg')]:
image_path = f"{end_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/end{ext}"
@@ -642,7 +633,7 @@ async def _analyze_backing_vocals(
job_manager.update_state_data(job_id, 'backing_vocals_analysis', {
'has_audible_content': None,
'analysis_error': str(e),
'recommended_selection': 'review_needed',
'recommended_selection': 'clean',
})
+22
View File
@@ -117,11 +117,21 @@ async def process_stale_reviews() -> Dict[str, Any]:
user_service = get_user_service()
credits_balance = user_service.check_credits(job.user_email)
# Look up user locale for email
user_locale = "en"
try:
user = user_service.get_user(job.user_email)
if user and user.locale:
user_locale = user.locale
except Exception:
pass
email_service.send_review_expired(
to_email=job.user_email,
artist=job.artist,
title=job.title,
credits_balance=credits_balance,
locale=user_locale,
)
except Exception as email_err:
logger.error(
@@ -143,11 +153,23 @@ async def process_stale_reviews() -> Dict[str, Any]:
# Send reminder email
if job.user_email:
try:
# Look up user locale for email
user_locale = "en"
try:
from backend.services.user_service import get_user_service
user_service = get_user_service()
user = user_service.get_user(job.user_email)
if user and user.locale:
user_locale = user.locale
except Exception:
pass
email_service.send_review_reminder(
to_email=job.user_email,
artist=job.artist,
title=job.title,
job_id=job.job_id,
locale=user_locale,
)
except Exception as email_err:
logger.error(
+28 -22
View File
@@ -121,13 +121,12 @@ async def _encode_via_gce(
def progress_callback(progress: int):
# Update job progress (encoding is 75-95% of total)
# Use update_job instead of transition_to_state since job is already in ENCODING state
scaled_progress = 75 + int(progress * 0.2) # Map 0-100 to 75-95
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.ENCODING,
progress=scaled_progress,
message=f"Encoding videos ({progress}%)"
)
job_manager.update_job(job_id, {
'progress': scaled_progress,
'message': f"Encoding videos ({progress}%)",
})
try:
# Submit and wait for encoding
@@ -1219,7 +1218,7 @@ def _validate_prerequisites(job) -> bool:
status_error = validate_worker_can_run("video_worker", job)
if status_error:
logger.warning(f"Job {job.job_id}: {status_error}")
# Continue anyway - this is a safety net warning, not a hard failure
return False
# Check instrumental selection
instrumental_selection = job.state_data.get('instrumental_selection')
@@ -1232,9 +1231,11 @@ def _validate_prerequisites(job) -> bool:
logger.error(f"Job {job.job_id}: Invalid instrumental selection: {instrumental_selection}")
return False
# Check screens exist
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
screens = job.file_urls.get('screens', {})
if not screens.get('title') or not screens.get('end'):
has_title = screens.get('title') or screens.get('title_png')
has_end = screens.get('end') or screens.get('end_png')
if not has_title or not has_end:
logger.error(f"Job {job.job_id}: Missing title or end screen")
return False
@@ -1288,19 +1289,24 @@ async def _setup_working_directory(
log_progress("Setting up working directory")
# Download title screen
log_progress("Downloading title screen...")
title_url = job.file_urls['screens']['title']
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
storage.download_file(title_url, title_path)
log_progress("Downloaded title screen")
# Download end screen
log_progress("Downloading end screen...")
end_url = job.file_urls['screens']['end']
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
storage.download_file(end_url, end_path)
log_progress("Downloaded end screen")
# Download title screen (PNG — MOV video is generated by the GCE encoding worker)
screens = job.file_urls.get('screens', {})
title_url = screens.get('title') or screens.get('title_png')
if title_url:
ext = os.path.splitext(title_url)[1] or '.png'
title_path = os.path.join(temp_dir, f"{base_name} (Title){ext}")
log_progress(f"Downloading title screen ({ext})...")
storage.download_file(title_url, title_path)
log_progress("Downloaded title screen")
# Download end screen (PNG — MOV video is generated by the GCE encoding worker)
end_url = screens.get('end') or screens.get('end_png')
if end_url:
ext = os.path.splitext(end_url)[1] or '.png'
end_path = os.path.join(temp_dir, f"{base_name} (End){ext}")
log_progress(f"Downloading end screen ({ext})...")
storage.download_file(end_url, end_path)
log_progress("Downloaded end screen")
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
+31 -7
View File
@@ -321,6 +321,9 @@ class VideoWorkerOrchestrator:
base_name = f"{safe_artist} - {safe_title}"
packaging_service = self._get_packaging_service()
# Track the actual MP3 path from CDG generation for use by TXT
cdg_mp3_path = None
# Generate CDG package
if self.config.enable_cdg:
if self.config.lrc_has_countdown_padding:
@@ -343,12 +346,15 @@ class VideoWorkerOrchestrator:
f"{base_name} (Karaoke).cdg"
)
# Pass sanitized artist/title to ensure filenames inside the ZIP
# match what we expect (the CDG generator has its own sanitization
# that may differ, e.g. not stripping trailing periods)
zip_file, mp3_file, cdg_file = packaging_service.create_cdg_package(
lrc_file=self.config.lrc_file_path,
audio_file=self.config.instrumental_audio_path,
output_zip_path=cdg_zip_path,
artist=self.config.artist,
title=self.config.title,
artist=safe_artist,
title=safe_title,
output_mp3_path=mp3_path,
output_cdg_path=cdg_path,
lrc_has_countdown_padding=self.config.lrc_has_countdown_padding,
@@ -356,6 +362,7 @@ class VideoWorkerOrchestrator:
)
self.result.final_karaoke_cdg_zip = zip_file
cdg_mp3_path = mp3_file
self.job_log.info(f"CDG package created: {zip_file}")
except Exception as e:
@@ -366,8 +373,9 @@ class VideoWorkerOrchestrator:
if self.config.enable_txt:
self.job_log.info("Generating TXT package")
try:
# TXT package needs MP3 file (from CDG generation or create it)
mp3_path = os.path.join(
# TXT package needs MP3 file from CDG generation.
# Prefer the actual path returned by CDG, fall back to constructed path.
mp3_path = cdg_mp3_path or os.path.join(
self.config.output_dir,
f"{base_name} (Karaoke).mp3"
)
@@ -836,6 +844,22 @@ class VideoWorkerOrchestrator:
# Never fail the pipeline for validation
def _screen_ext(job, screen_type: str) -> str:
"""Get the file extension for a screen (title/end) based on what's in GCS.
New jobs have only PNG (MOV is generated by GCE encoding worker).
Legacy jobs may still have MOV uploaded by the old screens_worker.
"""
screens = job.file_urls.get('screens', {})
# Check for MOV first (legacy), then fall back to PNG (new)
url = screens.get(screen_type) or screens.get(f'{screen_type}_png')
if url:
ext = os.path.splitext(url)[1]
if ext:
return ext
return '.png'
def create_orchestrator_config_from_job(
job,
temp_dir: str,
@@ -893,12 +917,12 @@ def create_orchestrator_config_from_job(
artist=job.artist,
title=job.title,
# Input files
title_video_path=os.path.join(temp_dir, f"{base_name} (Title).mov"),
# Input files — use actual extension from GCS (PNG for new jobs, MOV for legacy)
title_video_path=os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}"),
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
instrumental_audio_path=instrumental_path,
end_video_path=os.path.join(temp_dir, f"{base_name} (End).mov"),
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}"),
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
title_jpg_path=os.path.join(temp_dir, f"{base_name} (Title).jpg"),
+57
View File
@@ -141,6 +141,7 @@ GET /api/jobs?status=complete
GET /api/jobs?limit=10&offset=0
GET /api/jobs?exclude_test=false
GET /api/jobs?fields=summary&hide_completed=true
GET /api/jobs?fields=summary&search=bohemian
```
Query parameters:
@@ -149,6 +150,7 @@ Query parameters:
- `limit` / `offset` - Pagination
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
- `search` (string, optional) - Text search filter (summary mode only). Case-insensitive substring match against artist, title, audio_search_artist, audio_search_title, and job_id. When active, fetches up to 1000 results internally and filters in Python.
#### Delete Job
@@ -441,6 +443,61 @@ Content-Type: application/json
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
#### Add Reference Lyrics (Paste)
```http
POST /api/review/{job_id}/add-lyrics
Content-Type: application/json
{
"source": "manual",
"lyrics": "Full lyrics text...",
"force": false
}
```
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
Returns `{ "status": "success", "data": <CorrectionData> }`.
#### Search Reference Lyrics
```http
POST /api/review/{job_id}/search-lyrics
Content-Type: application/json
{
"artist": "Billie Eilish",
"title": "What Was I Made For",
"force_sources": []
}
```
Searches all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB) with the given artist/title. Results are filtered through the relevance threshold (30% word match minimum) — sources below are rejected as likely wrong-song matches. Sources in `force_sources` bypass the threshold.
**Success response** (at least one source passed):
```json
{
"status": "success",
"data": { "...CorrectionData..." },
"sources_added": ["genius", "lrclib"],
"sources_rejected": {
"spotify": { "relevance": 0.12, "matched_words": 18, "total_words": 150, "track_name": "...", "artist_names": "..." }
},
"sources_not_found": ["musixmatch"]
}
```
**No results response** (all filtered or nothing found):
```json
{
"status": "no_results",
"message": "No matching lyrics found from any provider",
"sources_rejected": { "genius": { "relevance": 0.05, "..." } },
"sources_not_found": ["lrclib", "musixmatch"]
}
```
#### Review Sessions
Server-side backup/restore of lyrics review editing sessions. Correction data is stored in GCS; metadata in Firestore subcollection `jobs/{job_id}/review_sessions/{session_id}`.
+32 -5
View File
@@ -67,11 +67,12 @@
• Instrumental track selection (clean vs with_backing)
• Single submit saves both lyrics + instrumental choice
▼
5. VIDEO RENDERING
5. VIDEO RENDERING (optionally via GCE for speed + memory)
• Merge corrections with original data
• Generate karaoke video with lyrics
• Generate karaoke video with lyrics (OutputGenerator + ffmpeg/libass)
• Style assets cached on GCE worker disk between jobs
▼
6. FINAL VIDEO (INSTRUMENTAL_SELECTED)
6. FINAL VIDEO (INSTRUMENTAL_SELECTED, via GCE)
• Remux with selected instrumental
• Concatenate: title + karaoke + end
• Encode to 4 formats
@@ -161,7 +162,7 @@ LyricsTranscriber LyricsTranscriber
| Service | Purpose | Required |
|---------|---------|----------|
| Cloud Run GPU (L4) | Audio stem separation (us-east4) | Yes |
| Cloud Run GPU Job (L4, us-east4) | Audio stem separation — `Separator` runs directly in the audio worker Job (no HTTP hop) | Yes |
| AudioShake | Lyrics transcription | Yes |
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Genius | Reference lyrics | Yes |
@@ -369,7 +370,7 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
│ │
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
│ audio-separation-job - 10-20 min (Cloud Run GPU) │
│ audio-separation-job - 10-20 min (L4 GPU, us-east4, direct) │
│ video-encoding-job - up to 60 min (optional) │
│ │
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
@@ -406,6 +407,32 @@ Screens and render workers run via internal HTTP endpoints with BackgroundTasks,
- If workers active, calls `wait_for_completion(timeout=600)` (10 min max)
- Logs which workers are still running for debugging
## Audio Separation Architecture
Audio stem separation runs **directly inside the audio worker Cloud Run Job** — the `Separator` class from `audio-separator` is imported and called in-process. There is no separate GPU microservice.
```text
┌──────────────────────────────────────────────────────────────────┐
│ audio-separation-job (Cloud Run Job, L4 GPU, us-east4) │
│ │
│ AudioWorker │
│ ├── download audio from GCS │
│ ├── create_audio_processor() ← Separator(model_file_dir=...) │
│ ├── Stage 1: instrumental_clean preset │
│ │ └── produces: vocals.flac, instrumental_clean.flac │
│ ├── Stage 2: karaoke preset │
│ │ └── produces: instrumental_with_backing.flac │
│ └── upload stems to GCS │
└──────────────────────────────────────────────────────────────────┘
```
**Key decisions:**
- **Direct GPU** — No HTTP hop to a separate service. Jobs can run up to 24h; no timeout concerns.
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
**Rollback**: The old audio-separator Cloud Run Service (HTTP endpoint) is kept for rollback but no longer receives traffic. It will be removed in a future phase.
## Multitenancy
The platform supports white-label B2B portals where business customers get their own branded karaoke generation experience.
-1
View File
@@ -170,7 +170,6 @@ The frontend's `detectTenantFromUrl()` checks for the `tenant` query param on lo
# Required
AUDIOSHAKE_API_TOKEN=...
GENIUS_ACCESS_TOKEN=...
AUDIO_SEPARATOR_API_URL=... # Modal API endpoint
# GCP (auto-configured in Cloud Run)
GOOGLE_CLOUD_PROJECT=...
+205
View File
@@ -0,0 +1,205 @@
# Disaster Recovery Runbook
**Last updated:** 2026-03-29
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
## Quick Reference
| Data | Backup Location | Recovery Method | RPO |
|------|----------------|-----------------|-----|
| Firestore | S3 `firestore/YYYY-MM-DD/` | Import to new GCP project | 24h |
| 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) |
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
| Secrets | AWS Secrets Manager | Decrypt with KMS, configure | On-change |
## Scenario 1: Accidental Data Deletion (GCP Still Available)
### Firestore Recovery
**Option A — PITR (fastest, within 7 days):**
```bash
gcloud firestore databases restore \
--source-database="(default)" \
--destination-database="(default)-restored" \
--snapshot-time="2026-03-28T12:00:00Z" \
--project=nomadkaraoke
```
**Option B — Import from S3 backup:**
```bash
# Download latest export from S3
aws s3 sync s3://nomadkaraoke-backup/firestore/LATEST_DATE/ /tmp/firestore-restore/ \
--profile nomadkaraoke-backup
# Upload to GCS
gsutil -m cp -r /tmp/firestore-restore/ gs://nomadkaraoke-backup-staging/firestore-import/
# Import
gcloud firestore import gs://nomadkaraoke-backup-staging/firestore-import/ --project=nomadkaraoke
```
### BigQuery Recovery
**Option A — Time Travel (within 7 days):**
```sql
-- Query historical data
SELECT * FROM `nomadkaraoke.karaoke_decide.TABLE_NAME`
FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR);
-- Restore to a new table
CREATE TABLE `nomadkaraoke.karaoke_decide.TABLE_NAME_restored` AS
SELECT * FROM `nomadkaraoke.karaoke_decide.TABLE_NAME`
FOR SYSTEM_TIME AS OF TIMESTAMP("2026-03-28 12:00:00 UTC");
```
**Option B — Load from S3 backup:**
```bash
# Download Parquet exports
aws s3 sync s3://nomadkaraoke-backup/bigquery/daily-refresh/LATEST_DATE/ /tmp/bq-restore/ \
--profile nomadkaraoke-backup
# Load each table
bq load --source_format=PARQUET \
nomadkaraoke:karaoke_decide.TABLE_NAME \
/tmp/bq-restore/TABLE_NAME/*.parquet
```
### GCS Recovery
**Option A — Object versioning (within 30 days):**
```bash
# List versions of a deleted/overwritten object
gsutil ls -a gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/
# Restore a specific version
gsutil cp gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac#VERSION \
gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac
```
**Option B — Restore from S3:**
```bash
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/jobs/JOB_ID/ /tmp/gcs-restore/ \
--profile nomadkaraoke-backup
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/
```
## Scenario 2: Complete GCP Project Loss
### Prerequisites
- AWS credentials from password manager
- AWS KMS key ARN from password manager
- All GitHub repos (code + IaC)
### Step-by-Step Recovery
**1. Create new GCP project**
```bash
gcloud projects create nomadkaraoke-v2 --name="Nomad Karaoke"
gcloud config set project nomadkaraoke-v2
gcloud services enable firestore.googleapis.com run.googleapis.com \
cloudfunctions.googleapis.com cloudscheduler.googleapis.com \
secretmanager.googleapis.com bigquery.googleapis.com \
cloudtasks.googleapis.com artifactregistry.googleapis.com
```
**2. Retrieve AWS credentials**
Get from password manager: AWS access key, secret key, KMS key ARN.
**3. Restore Firestore**
```bash
aws s3 sync s3://nomadkaraoke-backup/firestore/LATEST_DATE/ /tmp/firestore-restore/ \
--profile nomadkaraoke-backup
gsutil -m cp -r /tmp/firestore-restore/ gs://NEW_BUCKET/firestore-import/
gcloud firestore import gs://NEW_BUCKET/firestore-import/ --project=nomadkaraoke-v2
```
**4. Restore BigQuery**
```bash
# Create dataset
bq mk --dataset nomadkaraoke-v2:karaoke_decide
# Download and load each table
for prefix in daily-refresh musicbrainz; do
aws s3 sync s3://nomadkaraoke-backup/bigquery/$prefix/LATEST_DATE/ /tmp/bq-$prefix/ \
--profile nomadkaraoke-backup
for dir in /tmp/bq-$prefix/*/; do
table=$(basename $dir)
bq load --source_format=PARQUET nomadkaraoke-v2:karaoke_decide.$table "$dir*.parquet"
done
done
```
**Spotify tables (Glacier Deep Archive):** Retrieval takes 12-48 hours.
```bash
# Initiate restore (bulk = cheapest, ~$150 for 1TB)
aws s3api restore-object --bucket nomadkaraoke-backup \
--key "bigquery/spotify/TABLE/part-000.parquet" \
--restore-request '{"Days":7,"GlacierJobParameters":{"Tier":"Bulk"}}' \
--profile nomadkaraoke-backup
# Wait 12-48 hours, then download and load
```
**5. Restore GCS files**
```bash
# Create new bucket
gsutil mb -l US-CENTRAL1 gs://karaoke-gen-storage-nomadkaraoke-v2/
# Sync from S3
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/ /tmp/gcs-restore/ \
--profile nomadkaraoke-backup
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke-v2/
```
**6. Restore secrets**
```bash
# Retrieve all secrets from AWS Secrets Manager
aws secretsmanager get-secret-value --secret-id nomadkaraoke-gcp-secrets \
--profile nomadkaraoke-backup | jq -r '.SecretString' > /tmp/secrets.json
# Create each secret in new project
python3 -c "
import json
with open('/tmp/secrets.json') as f:
secrets = json.load(f)
for name, value in secrets.items():
print(f'echo -n \"{value}\" | gcloud secrets create {name} --data-file=- --project=nomadkaraoke-v2')
"
# Review and run the generated commands
rm /tmp/secrets.json
```
**7. Rebuild infrastructure**
```bash
cd karaoke-gen/infrastructure
# Update config.py with new project ID
pulumi config set gcp:project nomadkaraoke-v2
pulumi up
```
**8. Deploy services**
```bash
# Push to GitHub triggers CI/CD, or deploy manually:
gcloud run deploy karaoke-backend --source=. --project=nomadkaraoke-v2
```
**9. Update DNS (Cloudflare)**
Update DNS records to point to new Cloud Run URLs. See `docs/archive/2026-03-29-external-services-config.md`.
**10. Re-register OAuth apps**
Re-create OAuth apps at Spotify, Google, Dropbox with redirect URIs from `docs/archive/2026-03-29-external-services-config.md`.
## Cost Estimates for Recovery
| Action | Cost |
|--------|------|
| S3 Glacier Deep Archive retrieval (1 TB, bulk) | ~$150 |
| S3 Glacier Deep Archive retrieval (1 TB, standard) | ~$750 |
| S3 data transfer out to GCP | ~$0.09/GB |
| Full Spotify dataset retrieval + transfer (~1 TB) | ~$250 total |
+99
View File
@@ -8,6 +8,9 @@ Key insights for future AI agents working on this codebase.
## UX Patterns
### Don't Conflate "No Results" with "Not Yet Searched" (Mar 2026)
When a search component initializes `results = []`, any rendering condition like `results.length === 0 && !error` will match both "search returned empty" and "haven't searched yet" (or "search failed silently"). Use an explicit state machine with phases (`searching | succeeded | failed`) so that "no results" UI only appears after a confirmed successful search. This prevents misleading users when the real problem was a timeout, network error, or silent exception.
### Fixture-Driven UI Verification
For UI that renders differently based on data (e.g., audio search result tiers), fetch real production data as fixtures and build a Playwright review tool. The `npm run fixtures:review-ui` pattern (41 fixtures, console-based `next()` advancement) was far more effective than manual testing or screenshots — caught edge cases with non-Latin filenames, single-character filenames, and underscore-separated names that unit tests alone would have missed.
@@ -25,6 +28,7 @@ Three patterns from investigating production job failures where errors cascaded
1. **Validate every stage's outputs, not just some** — stage 1 of audio separation had validation for expected stems, stage 2 didn't. The missing validation let a transient Modal API failure propagate through 3 more functions before crashing with a confusing NoneType error.
2. **Block impossible downstream work early** — AudioShake returning 0 lyrics segments was treated as "success", letting the user submit an empty review that only failed at CDG generation. Validate at the boundary: if transcription returns 0 segments, fail with a user-friendly error, not 4 steps later.
3. **File handles in retry loops** — when wrapping HTTP calls with retry (e.g. tenacity), ensure file handles are re-opened on each attempt. A `with open()` wrapping a retried `requests.post(files=...)` exhausts the file handle on the first attempt; subsequent retries send empty data.
4. **Text normalization changes word counts** — `clean_text()` (strip punctuation, normalize whitespace) then `split()` can produce a different word count than the original Word objects list. In anchor sequence correction, `ref_texts_clean` had 599 words for Spotify but `ref_words` only had 528 Word objects. Anchor positions computed against the cleaned list were used to index the Word list, causing IndexError. Always bounds-check when indexing a different data structure than the one used to compute positions.
---
@@ -49,6 +53,38 @@ 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.
### 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.
**Fix: synchronous endpoint + `concurrency=1`.** Keep the HTTP request active during processing. Cloud Run sees the request as occupying the instance and scales to new GPU instances for concurrent jobs. This matches Modal's `.spawn()` pattern where each job gets its own container. The client POST timeout must match Cloud Run's request timeout (1800s).
**Rule of thumb**: If you need the platform's autoscaler to work for you, the request must stay active. Background threads are invisible to the platform.
### Direct GPU in Cloud Run Jobs > HTTP Microservice
When a Cloud Run Job needs GPU processing, attach the GPU directly to the Job instead of calling a separate GPU service over HTTP. Benefits:
- No HTTP timeout concerns (Jobs can run up to 24h)
- No connection management, retry logic, or polling
- Simpler architecture (1 hop instead of 3)
- Platform handles scaling naturally (each Job execution gets its own GPU)
The audio separator started as a separate Cloud Run Service called via HTTP from the audio worker Job. This required 1800s HTTP timeouts, complex retry logic, and caused a production outage when the fire-and-forget pattern interacted badly with Cloud Run's autoscaler. Moving the GPU work directly into the Job eliminated all of this complexity.
### GPU Docker Images: Pin CUDA-Specific Package Versions (Mar 2026)
**`pip install audio-separator[gpu]` pulls the latest PyTorch, which may require a newer CUDA than your runtime provides.** Cloud Run L4 GPUs have NVIDIA driver 570 (CUDA 12.8 max), but the default torch install gets `cu130` (requires CUDA 13.0), which fails silently — PyTorch reports "NVIDIA driver is too old" and falls back to CPU, then ONNX models fail to load.
**Fix:** Pin torch to a CUDA version your driver supports (`torch==2.6.0+cu126` from `--index-url https://download.pytorch.org/whl/cu126`), install it BEFORE `audio-separator[gpu]`, and protect it from being overwritten by later `pip install` commands (use `--no-deps` in the app layer).
**Validate with the actual Docker image, not just packages.** We proved the package combo worked interactively on a VM but missed that the app Dockerfile's `pip install -e .` (with `torch>=2.7` in pyproject.toml) upgraded torch back to cu130. The fastest debugging loop: spin up a GCE L4 VM (~$1/hr), build the Docker image locally, run separation inside the container with `--gpus all`, tear down.
### audio-separator Ensemble Presets Require Explicit load_model() (Mar 2026)
**Always call `separator.load_model()` before `separator.separate()`, even when using ensemble presets.** The Separator constructor with `ensemble_preset=` resolves the preset to model names but does NOT load them into memory. Calling `separate()` without `load_model()` fails with "Initialization failed or model not loaded."
Similarly, **baking models into Docker images requires downloading each model individually** — `Separator(ensemble_preset=...).load_model()` with no args doesn't trigger downloads. Use `sep.load_model(model_filename)` for each model file in the preset.
---
## Architecture Decisions
@@ -843,6 +879,12 @@ Add defensive type checking for all external service responses. Lists vs dicts,
### Thread All Encoding Outputs Through OrchestratorResult (Mar 2026)
The encoding pipeline (`LocalEncodingService`) created a `(With Vocals).mp4` file (3.4x smaller than the raw MKV), but `OrchestratorResult` had no field for it so it was silently dropped. Users got the 134MB raw MKV instead of the 39MB encoded MP4. **Pattern**: When adding output files to encoding, verify the full chain: `EncodingOutput` → `OrchestratorResult` → `_upload_results()` file_mappings → Firestore `file_urls`. Also beware of hardcoded file extensions — the temp directory saved `.mkv` files as `.mov`, causing Dropbox to receive mislabeled files.
### Cloud Run Job Retries Race With Manual Retries (Mar 2026)
Job 13b8adcf failed because Cloud Run Job `max_retries: 2` and a manual `/retry` call launched concurrent video workers. Worker A transitioned to `generating_video`, Worker B saw `generating_video` as valid (it was in the `validate_worker_can_run` allowlist), tried the same transition, failed, and marked the job `failed` — then Worker A tried `failed → encoding` and also failed. **Fix**: Remove in-progress states (`generating_video`, `rendering_video`) from the video_worker startup validation — if a job is already in those states, another worker is processing it. Also make `_validate_prerequisites` a hard failure, not just a warning.
### Encoding Worker Warmup Must Cover All Paths (Mar 2026)
The JIT startup design (frontend calls warmup on lyrics review page, VM boots during editing) only covered the happy path. Five of ten paths to encoding (retries, admin resets, pipeline chains, visibility changes) had no warmup — the encoding service retried blindly for ~90s against a TERMINATED VM. **Fix**: Call `ensure_primary_running()` at two layers: (1) in `trigger_video_worker`/`trigger_render_video_worker` for early start, and (2) as a fallback in `EncodingService._request_with_retry` on first connection failure. Defense in depth: frontend warmup → worker dispatch warmup → encoding retry warmup.
### Brand Code Allocation Must Be Atomic (Feb 2026)
Two concurrent jobs both got brand code `NOMADNP-0012` because `get_next_brand_code()` scanned Dropbox folders to find the next number — a classic TOCTOU race condition. Jobs processed 0.86s apart both saw the same state. **Fix**: `brand_code_service.py` uses Firestore transactions to atomically allocate codes. Counter doc per prefix (`NOMAD`, `NOMADNP`) with `next_number` and `recycled` pool. E2E cleanup recycles numbers via `recycle_brand_code()`.
@@ -987,3 +1029,60 @@ For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_d
**Key insight:** For abuse prevention, static lists give you a floor but not a ceiling. Real-time API verification services maintain much larger and more current databases. The tiered approach (free service first, paid service only for edge cases) keeps costs minimal while dramatically improving detection. In our test of 60 recent signups, the free DeBounce API caught 6 disposable accounts and verifymail.io caught 4 more that DeBounce missed.
### Lyrics Upload Race Condition: Admin Edits During Processing (Mar 2026)
**Problem:** When an admin updated a job's artist name while the lyrics worker was running, `upload_lyrics_results` reconstructed filenames from the updated Firestore values (`job.artist`, `job.title`), which no longer matched the files on disk generated with the original values. This caused "No corrections JSON found" errors even though the files existed.
**Fix:** Scan the lyrics directory for files by suffix pattern (e.g., `*(Lyrics Corrections).json`, `*(Lyrics Genius).txt`) instead of reconstructing filenames from Firestore job metadata. This decouples the upload from the current state of mutable job fields.
**Key insight:** Long-running workers should avoid re-reading mutable metadata to reconstruct local file paths. If a file was created earlier in the same pipeline, find it by pattern rather than reconstructing its name from state that may have changed. This is a variant of TOCTOU — the "check" (reading artist/title) and "use" (looking for the file) happen at different times, and the underlying data can change between them.
### Reference Lyrics Relevance Filtering: Data-Driven Thresholds (Mar 2026)
**Problem:** Lyrics providers often return wrong-song results for tracks with remixes, "feat." artists, or unusual naming. These irrelevant references pollute anchor/gap statistics and confuse correction tooling.
**Solution:** Added relevance filtering in `LyricsCorrector` — after anchor sequences are found, compute `(reference words in anchors) / (total reference words)` per source. Sources below 30% are rejected. The threshold was determined empirically by analyzing 168 source pairs across 81 production jobs: wrong-song sources maxed at 3.5%, correct-song sources started at 26.8%.
**Key insight:** Don't guess thresholds — measure them. A visual review tool showing side-by-side lyrics with match highlighting made it trivial to classify 168 pairs in minutes. The massive gap between wrong (0-3.5%) and correct (26.8%+) meant any threshold from 5-25% would work, but 30% provides safety margin. Always include a force-add override for edge cases where the transcription is bad (not the reference).
### Cloud Scheduler OIDC Tokens ≠ Admin Tokens (Mar 2026)
**Problem:** All 4 Cloud Scheduler → backend jobs (stale review processor, stuck job recovery, YouTube queue, disposable domain sync) were silently returning 401 since deployment. The auth system only validated admin tokens, Firestore tokens, and session tokens — it had no OIDC JWT validation. Cloud Scheduler sends a Google-signed OIDC JWT in the `Authorization: Bearer` header, which the auth service didn't recognize.
**Root cause:** A plan document incorrectly stated "The existing `require_admin` dependency handles OIDC via the Authorization header flow, so this works without changes." This was never verified, and the 401s went unnoticed because scheduler endpoints run in the background with no user-visible feedback.
**Fix:** Added OIDC token validation to `validate_token_full()` using `google.oauth2.id_token.verify_oauth2_token()`. Verifies the token is Google-signed and the `email` claim matches the configured backend service account.
**Key insight:** Background cron jobs need monitoring for auth failures — a 401 from a scheduler is silent by default. When adding new Cloud Scheduler endpoints, verify the auth flow end-to-end (check Cloud Logging for 200s after deployment). Don't assume OIDC "just works" with custom auth middleware — Cloud Tasks uses `X-Admin-Token` (custom header) for a reason, while Cloud Scheduler only sends OIDC.
### GCE Disk Cache Must Validate Content, Not Just URI (Mar 2026)
**Problem:** The GCE encoding worker's style asset disk cache (`/var/cache/karaoke-gen/styles/`) keyed on `SHA-256(GCS URI)`. When a file at a GCS path was replaced with different content (e.g., fixing corrupt 106-byte placeholder PNGs with correct 2.8MB files), the cache served the stale version indefinitely.
**Fix:** On cache hit, do a lightweight `blob.reload()` (HEAD request) to get the GCS object's current size. Compare with cached file size — re-download on mismatch. One metadata call per cache hit is a small price vs serving corrupt assets.
**Key insight:** Any local disk cache of remote objects needs a staleness check. URI-only cache keys assume content is immutable at that path — which is rarely guaranteed in GCS/S3. Size is the cheapest validation; for stronger guarantees, compare ETags or generation numbers.
### Don't Write Empty Sentinel Files to GCS (Mar 2026)
**Problem:** The review complete endpoint wrote `corrections_updated.json` to GCS even when no corrections were provided (e.g., admin API reset + complete without correction data). It wrote `{}` (empty dict). Downstream, render workers check `file_exists("corrections_updated.json")` — if present, they download and pass it to `CorrectionOperations.update_correction_result_with_data()` which does `updated_data["corrections"]`, causing `KeyError`.
**Fix:** (1) Root cause: Don't write `corrections_updated.json` unless the payload actually contains a `"corrections"` key. (2) Defensive: Both GCE and Cloud Run workers validate the downloaded JSON has the expected structure before processing, falling back to base result if not.
**Key insight:** When a file's existence is used as a boolean signal ("corrections were updated"), never write it with empty/invalid content. The existence check and content processing must agree on what constitutes a valid file. Apply defense in depth: fix the writer AND validate in readers.
### i18n: Keep Providers in Root Layout When Admin Pages Exist (Apr 2026)
**Problem:** The Phase 1/2 i18n pattern (public-website, karaoke-decide) stripped the root `app/layout.tsx` bare and moved all providers into `app/[locale]/layout.tsx`. This doesn't work for karaoke-gen because admin pages at `app/admin/` sit outside the `[locale]` route segment and need ThemeProvider/TenantProvider.
**Fix:** Keep shared providers (ThemeProvider, TenantProvider, ImpersonationBannerWrapper, ServiceWorkerRegistration, GoogleAnalytics) in root layout. Only add NextIntlClientProvider to `[locale]/layout.tsx`. Admin pages inherit root providers without locale context.
**Key insight:** When adding `[locale]` routing to a project with routes that should NOT be locale-prefixed (admin, API, etc.), don't blindly follow the "strip root layout" pattern. Keep shared providers in root so all route segments can access them.
### i18n: Mock next-intl in Jest by Loading en.json (Apr 2026)
**Problem:** Adding `useTranslations` to components caused 27 test suites to fail — Jest can't handle ESM exports from `next-intl`, and even after fixing that, tests that assert on English text (e.g., `screen.getByText("Review Lyrics")`) fail because the mock returns translation keys instead of English strings.
**Fix:** Mock `next-intl` in `jest.setup.js` with a function that loads the actual `messages/en.json` and resolves dotted key paths to real English strings. Tests see the same text users see, no test assertions need updating. The mock supports interpolation (`{count}`, ICU plurals).
**Key insight:** For i18n refactors, make the test mock return real translations, not keys. This lets existing tests validate that the i18n wiring produces correct output without changing every assertion. The mock is ~20 lines and eliminates hundreds of test updates.
+4 -4
View File
@@ -45,7 +45,7 @@ Input (audio + metadata)
v v
┌───────────────────┐ ┌───────────────────┐
│ Audio Separation │ │ Lyrics Processing │
│ (Modal GPU) │ │ (AudioShake API) │
│ (Cloud Run GPU L4)│ │ (AudioShake API) │
│ │ │ │
│ • Clean vocal │ │ • Fetch reference │
│ removal │ │ lyrics │
@@ -98,7 +98,7 @@ All code is open source (MIT license) because:
However, reliable fully-automated generation requires:
- **AudioShake API**: ~$0.50-1.00 per track for high-quality transcription
- **LLM tokens**: ~$0.50-1.00 for agentic correction workflow
- **GPU compute**: ~$0.20-0.50 for audio separation on Modal
- **GPU compute**: ~$0.10-0.30 for audio separation on Cloud Run GPU (L4)
- **Infrastructure**: Cloud Run, Firestore, GCS, etc.
**Cost per track: ~$2-3** for fully-automated processing, making a paid service necessary to sustain development.
@@ -130,7 +130,7 @@ Commercial producers pay for API access or custom integration to generate tracks
## Current State (December 2025)
### What Works
- Audio upload and separation (Modal API)
- Audio upload and separation (Cloud Run GPU)
- Lyrics transcription (AudioShake API)
- Agentic AI correction (Gemini 3 Flash via Vertex AI)
- Human lyrics review (React UI)
@@ -188,7 +188,7 @@ Commercial producers pay for API access or custom integration to generate tracks
- **Database**: Firestore
- **Storage**: Google Cloud Storage
- **Secrets**: Google Secret Manager
- **Audio Separation**: Modal (GPU compute)
- **Audio Separation**: Cloud Run GPU (L4, us-east4)
- **Lyrics Transcription**: AudioShake API
- **AI Correction**: Vertex AI (Gemini 3 Flash)
- **Payments**: Stripe
+4 -1
View File
@@ -36,6 +36,7 @@
| **Community version detection** | Working (via karaokenerds.com) |
| **Review session backup/restore** | Working (auto-save + restore UI) |
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
## Known Issues
@@ -98,6 +99,8 @@
- **Custom Instrumental Upload Fix** (2026-02-26): Fixed critical bug where uploaded custom instrumentals were ignored during encoding — GCE encoding worker and orchestrator had no `"custom"` case, falling back to clean instrumental instead. Upload endpoint now converts all formats to FLAC for pipeline consistency. Three fixes: (1) GCE encoding worker `find_file` now searches for `custom_instrumental*.flac` when selection is `"custom"`, (2) orchestrator config constructs correct `(Instrumental Custom).flac` path, (3) upload endpoint converts mp3/m4a/wav/etc. to FLAC before storing. Added 10 new regression tests for GCE resolution and orchestrator paths. See [API.md](API.md#upload-custom-instrumental).
- **Render Video GCE Routing** (2026-03-31): Routed the `render_video_worker` (OutputGenerator/ffmpeg lyrics rendering) to the GCE encoding worker instead of running on Cloud Run. Previously, render_video always ran on Cloud Run and OOM'd after memory was right-sized to 2Gi. Now when `USE_GCE_ENCODING=true`, Cloud Run constructs GCS paths from job metadata and delegates to the GCE worker's new `/render-video` endpoint. Style assets (fonts, backgrounds) are cached on the GCE worker's disk between jobs to avoid repeated downloads of the same default theme. Local fallback preserved when GCE is disabled. See [spec](superpowers/specs/2026-03-31-render-video-gce-routing-design.md).
- **Store Processing Metadata Permanently** (2026-03-10): Added `processing_metadata` field to the Job model — a top-level dict where each worker writes immutable provenance data during processing. Stores AudioShake task_id/asset_id (the original ask — these were previously lost after processing), worker timing, separation model names, ffprobe audio properties, correction stats, cache hit/miss data, video encoding details, and auth context at job creation. All metadata writes are non-fatal (wrapped in try/except). Includes `update_processing_metadata` helper on JobManager using Firestore dot-notation for atomic section updates. 23 tests covering model, helpers, all worker functions, and a SUMMARY_FIELD_PATHS regression guard. See [archive/2026-03-10-store-job-processing-metadata.md](archive/2026-03-10-store-job-processing-metadata.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#store-processing-metadata-when-you-have-it-mar-2026).
- **Custom Instrumental Upload** (2026-02-25): Added `POST /api/jobs/{job_id}/upload-instrumental` endpoint — was missing from backend, causing 404 in production when users tried to upload custom instrumental files during review. Validates uploaded audio duration matches original (±0.5s tolerance) using ffprobe on GCS signed URLs. Fixed frontend bug where "uploaded" selection type was sent to API instead of "custom" (the only value the backend accepts). Added 22 tests covering upload validation, duration checks, and frontend/backend contract. See [API.md](API.md#upload-custom-instrumental).
@@ -237,7 +240,7 @@
```
Upload Audio → Parallel Processing → Human Review → Video Generation → Download
│ │
(Modal + AudioShake) (LyricsTranscriber UI)
(Cloud Run GPU + AudioShake) (LyricsTranscriber UI)
```
## For AI Agents
+111
View File
@@ -252,3 +252,114 @@ doc = firestore.Client(project='nomadkaraoke').collection('config').document('en
print('primary:', doc.to_dict().get('primary'))
"
```
---
## Surgical job repair: re-run audio separation without losing lyrics/review
**When to use:** Jobs where audio separation failed or produced incomplete stems, but the user has already completed lyrics review. The admin `/restart` endpoint clears ALL state including lyrics — use direct Firestore updates instead.
**Approach:** Clear only audio-related state, trigger the Cloud Run GPU audio job, then advance the job to the correct next step.
```python
import os
os.environ["GOOGLE_CLOUD_PROJECT"] = "nomadkaraoke"
from google.cloud import firestore, run_v2
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from datetime import datetime, timezone
db = firestore.Client(project="nomadkaraoke")
job_id = "YOUR_JOB_ID"
# Step 1: Clear audio state only (preserves lyrics, review, instrumental selection)
job_ref = db.collection("jobs").document(job_id)
job_ref.update({
"status": "downloading", # Required: idempotency checks reject terminal states
"state_data.audio_progress": DELETE_FIELD,
"state_data.audio_complete": False,
"state_data.instrumental_options": DELETE_FIELD,
"state_data.backing_vocals_analysis": DELETE_FIELD,
"file_urls.stems": DELETE_FIELD,
"error_message": DELETE_FIELD,
"error_details": DELETE_FIELD,
"progress": 15,
"timeline": ArrayUnion([{
"status": "downloading",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": "Admin repair: re-running audio separation",
}]),
})
# Step 2: Trigger Cloud Run GPU audio job directly
# (bypasses internal HTTP endpoint which has idempotency checks)
client = run_v2.JobsClient()
client.run_job(request=run_v2.RunJobRequest(
name="projects/nomadkaraoke/locations/us-east4/jobs/audio-separation-job",
overrides=run_v2.RunJobRequest.Overrides(
container_overrides=[run_v2.RunJobRequest.Overrides.ContainerOverride(
args=["python", "-m", "backend.workers.audio_worker", "--job-id", job_id],
)]
)
))
# Step 3: After audio completes, advance the job based on its previous state:
# - If job was "failed" with lyrics: trigger screens worker → awaiting_review
# - If job was "instrumental_selected": set status back, trigger video worker
```
**Key gotchas:**
- Must set `status` to a non-terminal state (`"downloading"`) before triggering workers
- `mark_audio_complete()` only sets a flag — it does NOT trigger the next pipeline step
- After audio completes, you must manually trigger screens (for review path) or video (for post-review path)
- The admin `/restart` endpoint with `preserve_audio_stems=false` is the simpler option when lyrics don't need preserving
---
## Triggering Cloud Run Jobs directly (bypassing internal API)
**When to use:** The internal worker endpoints (`/api/internal/workers/audio`, etc.) have idempotency checks that reject jobs in terminal states (`failed`, `complete`, etc.). When repairing jobs, trigger Cloud Run Jobs directly via the API.
```python
from google.cloud import run_v2
client = run_v2.JobsClient()
client.run_job(request=run_v2.RunJobRequest(
name="projects/nomadkaraoke/locations/{REGION}/jobs/{JOB_NAME}",
overrides=run_v2.RunJobRequest.Overrides(
container_overrides=[run_v2.RunJobRequest.Overrides.ContainerOverride(
args=["python", "-m", "backend.workers.{MODULE}", "--job-id", "{JOB_ID}"],
)]
)
))
```
**Available Cloud Run Jobs:**
| Job Name | Region | Module | GPU |
|----------|--------|--------|-----|
| `audio-separation-job` | `us-east4` | `audio_worker` | L4 |
| `lyrics-transcription-job` | `us-central1` | `lyrics_worker` | No |
| `video-encoding-job` | `us-central1` | `video_worker` | No |
---
## CI does not update `lyrics-transcription-job` image
**Symptoms:** Deployed code fixes don't take effect for lyrics processing. The backend service shows the new version, but lyrics jobs still crash with the old bug.
**Cause:** The CI workflow (`.github/workflows/ci.yml`) updates `audio-separation-job` and `video-encoding-job` after deploy, but does NOT update `lyrics-transcription-job`. The job uses the `:latest` tag, but Cloud Run Jobs resolve the tag to a digest at update time — pushing a new `:latest` image doesn't automatically update running jobs.
**Manual fix after deploy:**
```bash
# Pin to the specific version tag (preferred)
gcloud run jobs update lyrics-transcription-job \
--image us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:vX.Y.Z \
--region us-central1 --project nomadkaraoke
# Or force re-resolve :latest
gcloud run jobs update lyrics-transcription-job \
--image us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:latest \
--region us-central1 --project nomadkaraoke
```
**Permanent fix:** Add `lyrics-transcription-job` update to CI deploy step in `.github/workflows/ci.yml` alongside the existing `video-encoding-job` and `audio-separation-job` updates (~line 1568).
@@ -0,0 +1,70 @@
# Audio Separator Cloud Run GPU Architecture
**Date:** 2026-03-25 (updated 2026-03-26)
**Status:** Implemented and deployed
**Repos:** python-audio-separator, karaoke-gen (infrastructure)
## Problem
The audio separator service had two issues:
1. **Client timeout**: The POST timeout (300s) was too short for ensemble presets on large WAV files (>5 min processing)
2. **No multi-instance scaling**: In-memory job status store and no concurrency protection prevented scaling
## Solution: Synchronous + Cloud Run Autoscaling (Modal Pattern)
The architecture mirrors how Modal handled this: **each separation request occupies one GPU instance** for its full duration, and the platform (Cloud Run) handles scaling to multiple instances for concurrent jobs.
### How it works
1. Client POSTs to `/separate` with `timeout=1800s`
2. Server downloads audio (from GCS URI or upload), runs separation synchronously
3. Server uploads output files to GCS, updates Firestore with status
4. Server returns completed result to client
5. Cloud Run sees the request as "active" for 3-5 minutes, so with `concurrency=1`, it scales to new instances for new requests
6. Up to 5 GPU instances run in parallel (Cloud Run GPU limit)
### Key infrastructure
| Component | Detail |
|-----------|--------|
| **Cloud Run GPU** | L4, us-east4, concurrency=1, max_instances=5 |
| **Firestore** | `audio_separation_jobs` collection — job status for observability |
| **GCS** | `nomadkaraoke-audio-separator-outputs` bucket — output files (1-day lifecycle) |
| **Client timeout** | 1800s POST timeout (matches Cloud Run request timeout) |
### Why synchronous, not fire-and-forget
We initially tried fire-and-forget (background threads + polling), but Cloud Run can't see background threads as "busy". With `concurrency=50` and fire-and-forget, all requests routed to one instance and queued behind a GPU semaphore — defeating the purpose of multi-instance scaling. Making the endpoint synchronous lets Cloud Run's autoscaler work naturally.
### Why no GPU semaphore
With `concurrency=1`, Cloud Run guarantees only one active request per instance. Each instance has its own GPU. No application-level serialization needed.
## Cross-repo changes
### python-audio-separator
- `deploy_cloudrun.py` — synchronous endpoint, Firestore status, GCS output upload
- `api_client.py` — 1800s POST timeout
- `job_store.py` — Firestore-backed job status store
- `output_store.py` — GCS output file management
- `Dockerfile.cloudrun` — google-cloud-firestore dependency
### karaoke-gen (infrastructure)
- `audio_separator_service.py` — concurrency=1, GCS bucket, Firestore IAM, env vars
- `database.py` — Firestore composite index for cleanup queries
## Phase 2: Migrate to Cloud Run Jobs
The current synchronous-service approach works but is not the ideal architecture. Cloud Run Jobs would be a natural fit — karaoke-gen already uses them for the audio worker itself. Benefits:
- No HTTP timeout concern (Jobs run up to 24h, no client connection needed)
- Native scaling (each execution gets its own container/GPU)
- Fire-and-forget + poll pattern (submit job, poll Firestore, download from GCS)
- Eliminates the `concurrency=1` workaround for autoscaling
The Firestore job store and GCS output store built in this session are the right foundations — they'd be reused directly by the Jobs-based approach.
## Lessons learned
1. **Cloud Run can't track background threads** — fire-and-forget makes the instance look idle, so the autoscaler doesn't scale. If you need the platform to scale for you, keep the request active.
2. **Match the platform's scaling model** — Modal's `.spawn()` gave each job its own container. Cloud Run's `concurrency=1` with synchronous processing achieves the same effect.
3. **The GPU semaphore was the wrong abstraction** — it serialized work on one instance instead of distributing across instances. Let the platform handle concurrency.
@@ -0,0 +1,123 @@
# Plan: Fix 413 Audio Separation Error via GCS Path Passthrough
**Created:** 2026-03-25
**Branch:** feat/sess-20260325-1130-fix-413-audio-sep
**Status:** Draft
## Overview
Audio separation fails with `413 Request Entity Too Large` when FLAC files exceed Cloud Run's 32MB request body limit. The current architecture uploads the entire audio file as a multipart POST body to the separator API. Since the file is **already in GCS** by the time the audio worker runs, we should pass the GCS path and let the separator download directly from GCS.
**Root cause:** `api_client.py:77,136` sends the file as `files={"file": (filename, open(file_path, "rb"))}` in a POST to `/separate`. Cloud Run rejects bodies > 32MB.
## Requirements
- [ ] Audio separation works for files of any size (no HTTP body limit)
- [ ] Backward compatible — file upload still works for non-GCS callers (CLI, tests)
- [ ] No data duplication — separator reads from the same GCS bucket, doesn't copy
- [ ] Stage 2 (backing vocals) still works — uses Stage 1 output which is local on the separator
## Technical Approach
**Change:** Add a `gcs_uri` parameter to the `/separate` endpoint. When provided, the separator downloads from GCS instead of expecting a file upload. The API client gains a new parameter for this.
Both services are in the same GCP project (`nomadkaraoke`), so the separator's service account just needs `roles/storage.objectViewer` on the `karaoke-gen-storage` bucket.
### Flow: Before
```
audio_worker → download from GCS → local file → HTTP POST (file bytes) → separator
```
### Flow: After
```
audio_worker → pass GCS path → separator downloads from GCS directly
```
Stage 2 (backing vocals) still uploads the local mixed_vocals file since it's a Stage 1 output that only exists on the separator's local disk. But Stage 2 files are small (vocals only), so no 413 risk.
## Implementation Steps
### Repo 1: python-audio-separator (separate worktree)
1. [ ] **Server: Add `gcs_uri` parameter to `/separate` endpoint** (`audio_separator/remote/deploy_cloudrun.py`)
- Add `gcs_uri: Optional[str] = Form(None)` parameter
- When provided, download from GCS instead of reading `file` upload
- Make `file` parameter optional (required only when `gcs_uri` not provided)
- Validate: exactly one of `file` or `gcs_uri` must be provided
2. [ ] **Server: Add GCS download helper** (`audio_separator/remote/deploy_cloudrun.py`)
- `download_from_gcs(gcs_uri: str, output_dir: str) -> tuple[bytes, str]`
- Parse `gs://bucket/path` or just `bucket/path` format
- Use `google-cloud-storage` (already a dependency for model download)
- Return `(audio_bytes, filename)`
3. [ ] **Client: Add `gcs_uri` parameter** (`audio_separator/remote/api_client.py`)
- Add `gcs_uri` param to `separate_audio()` and `separate_audio_and_wait()`
- When `gcs_uri` is provided, send it as form data instead of file upload
- When `gcs_uri` is provided, `file_path` becomes optional (not opened/sent)
4. [ ] **Tests: Add unit tests for GCS passthrough**
- Test server accepts `gcs_uri` parameter
- Test client sends `gcs_uri` instead of file when provided
- Test validation (can't provide both `file` and `gcs_uri`, must provide one)
5. [ ] **Bump version, push, publish**
### Repo 2: karaoke-gen (this worktree)
6. [ ] **Infrastructure: Grant GCS read access to separator SA** (`infrastructure/modules/audio_separator_service.py`)
- Add `roles/storage.objectViewer` on `karaoke-gen-storage` bucket to the `audio-separator` service account
7. [ ] **Audio worker: Pass GCS path to separator** (`karaoke_gen/audio_processor.py`)
- In `_process_audio_separation_remote()`, pass `gcs_uri` for Stage 1
- Construct URI: `gs://karaoke-gen-storage/{job.input_media_gcs_path}`
- Stage 2 continues using local file upload (the mixed_vocals file is on separator's disk, not in GCS)
8. [ ] **Update audio-separator dependency** (`pyproject.toml`)
- `poetry update audio-separator` after the new version is published
9. [ ] **Tests**
- Update existing audio processor tests to verify `gcs_uri` is passed
- Test that Stage 1 uses GCS path, Stage 2 uses file upload
## Files to Create/Modify
### python-audio-separator
| File | Action | Description |
|------|--------|-------------|
| `audio_separator/remote/deploy_cloudrun.py` | Modify | Add `gcs_uri` param to `/separate`, add GCS download helper |
| `audio_separator/remote/api_client.py` | Modify | Add `gcs_uri` param to client methods |
| `tests/unit/test_remote_api_client.py` | Modify | Add tests for GCS passthrough |
| `pyproject.toml` | Modify | Bump version |
### karaoke-gen
| File | Action | Description |
|------|--------|-------------|
| `infrastructure/modules/audio_separator_service.py` | Modify | Add GCS read permission |
| `karaoke_gen/audio_processor.py` | Modify | Pass `gcs_uri` in Stage 1 |
| `backend/workers/audio_worker.py` | Modify | Pass GCS path to audio processor |
| `pyproject.toml` | Modify | Update audio-separator dependency |
## Testing Strategy
- **Unit tests:** Mock GCS client in separator, verify download_from_gcs works
- **Unit tests:** Verify API client sends gcs_uri param correctly
- **Integration test:** Deploy separator locally, test with a real GCS file
- **Production test:** Re-run failed job `45f9bbc0` after deployment
## Open Questions
- [ ] Should we also upload Stage 2 input (mixed_vocals) to GCS and use gcs_uri? Not needed now — vocals-only files are small — but would be more consistent.
- [ ] Should the `gcs_uri` format be `gs://bucket/path` or just the blob path with a separate bucket param? Suggest `gs://` URI for clarity and flexibility.
## Rollback Plan
- Revert to file upload by not passing `gcs_uri` — the parameter is optional
- The separator still accepts file uploads as before (backward compatible)
- No infrastructure changes needed for rollback (extra IAM permission is harmless)
## Execution Order
1. Start with python-audio-separator (steps 1-5) — this is the dependency
2. Apply infra change (step 6) — can be done in parallel
3. Update karaoke-gen (steps 7-9) — depends on step 5
@@ -0,0 +1,53 @@
# Plan: Pre-compute Credit Evaluation at Magic Link Send Time
**Created:** 2026-03-25
**Branch:** feat/sess-20260324-2308-welcome-credit-abuse
**Status:** Draft
## Overview
Move the AI credit evaluation from verify-magic-link time to send-magic-link time. By the time the user clicks the link in their email (typically 10-20+ seconds later), the decision is already made and verification is instant. If they click very fast, fall back to computing inline (same experience as today).
## Requirements
- [ ] Run credit evaluation asynchronously after sending the magic link email
- [ ] Store the evaluation result on the magic link document in Firestore
- [ ] At verify time, read pre-computed result if available
- [ ] Fall back to inline evaluation if result isn't ready yet (preserves "preparing" UX)
- [ ] Only evaluate new users (existing users skip evaluation already)
- [ ] No change to the user-facing experience — just faster
## Technical Approach
**Key insight:** `send_magic_link` already has all the signals needed (email, IP, fingerprint) and already creates the user via `get_or_create_user()`. We just need to run the evaluation after sending the email and store the result.
**Threading:** Use `threading.Thread` to run evaluation in background so the magic link response returns immediately. FastAPI's async doesn't help here since the evaluation is sync (Firestore + Gemini calls).
**Storage:** Add `credit_eval_decision`, `credit_eval_reasoning`, and `credit_eval_error` fields to the magic link Firestore document. The verify endpoint already reads this document.
## Implementation Steps
1. [ ] Add evaluation result fields to magic link document schema
2. [ ] Create helper function that runs evaluation and writes result to magic link doc
3. [ ] Call helper in background thread from `send_magic_link` (new users only)
4. [ ] Update `verify_magic_link` to check for pre-computed result before calling evaluation
5. [ ] Update tests
6. [ ] Bump version
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/api/routes/users.py` | Modify | Trigger background eval in send_magic_link; read pre-computed result in verify_magic_link |
| `backend/services/user_service.py` | Modify | Add method to store eval result on magic link doc |
| `backend/models/user.py` | Modify | Add optional eval fields to MagicLinkToken model |
## Testing Strategy
- Update existing anti-abuse tests to verify pre-computation flow
- Test fallback path (no pre-computed result → inline evaluation)
- Test that send_magic_link still returns quickly (doesn't block on eval)
## Rollback Plan
The fallback path IS the current behavior. If pre-computation breaks, verify just runs evaluation inline as before.
@@ -0,0 +1,158 @@
# Direct GPU Audio Separation in Audio Worker
**Date:** 2026-03-26
**Status:** Approved, ready for implementation
**Repos:** karaoke-gen (primary), python-audio-separator (read-only reference)
**Branch:** feat/sess-20260326-1339-audio-sep-direct-gpu
## Problem
The audio worker Cloud Run Job calls a separate Cloud Run Service (audio-separator) over HTTP for GPU-accelerated stem separation. This architecture has proven fragile:
- 1800s HTTP timeout is the max Cloud Run allows; large files can exceed it
- Holding connections open for 5-10 minutes wastes resources
- `concurrency=1` forces a new $1/hr GPU instance per request
- Cold start delays add to the client's wait time
- A recent production outage (2026-03-25) was caused by the fire-and-forget/semaphore interaction with Cloud Run's autoscaler
## Solution
Run the `Separator` class directly inside the audio worker Cloud Run Job with an L4 GPU attached. This eliminates the HTTP hop entirely.
### Architecture Change
```
Current (3 hops):
karaoke-gen backend → Cloud Run Job (audio worker, CPU, us-central1)
→ HTTP POST → Cloud Run Service (separator, GPU, us-east4)
New (1 hop):
karaoke-gen backend → Cloud Run Job (audio worker, GPU, us-east4)
→ Separator class runs locally
```
## Decisions
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Docker image | Separate `karaoke-backend-gpu` image | Keeps regular backend lean; audio worker gets exactly what it needs |
| GPU region | us-east4 | L4 GPU quota already exists there; batch job tolerates cross-region latency |
| Model loading | Bake into image | Faster cold starts; model set rarely changes |
| Rollback strategy | Keep old service running | Phase 1 adds new path; old service removed in phase 2 |
| Code path | Reuse existing local Separator path | Already works; minimizes code changes and risk |
## Components
### 1. New Docker image: `karaoke-backend-gpu`
A GPU-capable base image for the audio worker. Based on `nvidia/cuda:12.6.3-runtime-ubuntu22.04`, includes everything from `karaoke-backend-base` plus GPU-specific dependencies.
**GPU dependencies (from audio-separator's Dockerfile.cloudrun):**
- PyTorch with CUDA support
- ONNX Runtime GPU (`onnxruntime-gpu`)
- `audio-separator[gpu]` package
- CUDA runtime libraries (already in base NVIDIA image)
**Baked-in models (~1.5GB total):**
- `instrumental_clean` preset models (Fv7z + Resurrection)
- `karaoke` preset models (3 karaoke models)
- Downloaded at build time via `scripts/download_preset_models.py` pattern from python-audio-separator
**Shared with karaoke-backend-base:**
- Python 3.11 (note: audio-separator uses 3.12; need to verify compatibility or align)
- FFmpeg (static build), sox, libsndfile
- Noto fonts (CJK, emoji, etc.)
- spaCy `en_core_web_sm` model
- All pip dependencies from karaoke-gen's pyproject.toml
**New files:**
- `backend/Dockerfile.gpu-base` — GPU base image definition
- `backend/cloudbuild-gpu-base.yaml` — Cloud Build config
- `backend/scripts/download_models.py` — Model download script for build time
**Artifact Registry:**
- New repo `karaoke-backend-gpu` in `us-east4` (co-located with GPU instances)
### 2. Infrastructure changes
All in `infrastructure/modules/cloud_run.py`:
**Audio worker Cloud Run Job modifications:**
- Move from `us-central1` to `us-east4` (GPU quota)
- Add L4 GPU: `nvidia.com/gpu: "1"`
- Increase resources: CPU 2→4, memory 4Gi→16Gi
- Change image to `us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend:latest`
- Remove `AUDIO_SEPARATOR_API_URL` env var (absence triggers local Separator path)
- Add `MODEL_DIR=/models` env var (tells Separator where baked-in models live)
**New resources in `infrastructure/`:**
- Artifact Registry repo for `karaoke-backend-gpu` in us-east4
- IAM for the existing audio-separator service account to pull from the new repo
### 3. Code changes
**`backend/workers/audio_worker.py`:**
- Remove the hard error when `AUDIO_SEPARATOR_API_URL` is not set (lines ~330-333)
- When `AUDIO_SEPARATOR_API_URL` is absent, configure `create_audio_processor()` with `model_file_dir` pointing to the baked-in models directory
**`backend/workers/audio_worker.py` — `create_audio_processor()`:**
- Accept optional `model_file_dir` parameter
- Pass `instrumental_preset` and `karaoke_preset` through to the processor (currently only used in remote path; the local path needs to use them too)
- When `model_file_dir` is set, the processor uses local `Separator`; when not set, it errors
**`karaoke_gen/audio_processor.py`:**
- In the local code path (lines ~200+), support `ensemble_preset` on the `Separator` constructor instead of only using explicit model lists
- The existing local path currently uses `self.clean_instrumental_model` / `self.backing_vocals_models` to call individual separation methods. With presets, we pass `ensemble_preset` to `Separator()` and call `separator.separate()` once — the preset handles model selection internally.
- Keep the file-lock mechanism (harmless in Cloud Run Jobs; one container = no contention)
### 4. What stays unchanged (phase 1)
- Audio-separator Cloud Run Service (kept for rollback)
- Firestore `audio_separation_jobs` collection and GCS output bucket
- Remote API code path in `audio_processor.py` (`_process_audio_separation_remote`)
- CI/CD for the existing `karaoke-backend` image
- All other Cloud Run Jobs (lyrics, video workers)
### 5. CI/CD
- Add a Cloud Build trigger for the GPU base image (triggered by changes to `backend/Dockerfile.gpu-base` or `pyproject.toml`)
- The existing app-layer build (`backend/Dockerfile`) works unchanged — just needs `BASE_IMAGE` build arg set to the GPU base for audio worker deploys
- GitHub Actions workflow addition: build and push the GPU image on merge to main
## Testing Strategy
**Unit tests:**
- Verify `create_audio_processor()` configures correctly with and without `AUDIO_SEPARATOR_API_URL`
- Verify `model_file_dir` is passed through when set
- Verify preset parameters reach the `Separator` constructor
**Local integration:**
- Build the GPU image locally (requires NVIDIA Docker runtime)
- Run a test separation with a sample audio file
**Production verification:**
- Submit a test job after deploy
- Verify all stems are generated: clean instrumental, vocals, lead vocals, backing vocals, combined instrumentals
- Compare output quality with a job processed through the old HTTP path
## Rollback Plan
If issues arise after deployment:
1. Add `AUDIO_SEPARATOR_API_URL` back to the audio worker job env vars
2. The code falls through to the remote API path
3. The old audio-separator service is still running (scale-to-zero, no cost)
No code changes needed for rollback — just an infra env var change via Pulumi.
## Phase 2 (follow-up PR)
After the direct GPU path is verified in production:
- Remove the audio-separator Cloud Run Service infrastructure
- Remove `AUDIO_SEPARATOR_API_URL` references from code
- Remove `_process_audio_separation_remote()` method
- Remove `AudioSeparatorAPIClient` import
- Clean up Firestore job store / GCS output bucket if no longer needed for observability
## Python Version
The audio-separator package requires Python >= 3.10. The GPU base image will use Python 3.11 (same as the existing karaoke-gen base) for consistency. The audio-separator's Dockerfile.cloudrun uses 3.12, but that's not a requirement — it was just the version chosen for that image.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,86 @@
# Audio Search Robustness — Design Spec
**Date:** 2026-03-27
**Status:** Approved
**Scope:** Frontend only — `AudioSourceStep.tsx`
## Problem
When an audio search fails silently (timeout, network error, edge case), the UI shows "No audio sources found" — implying the search succeeded with zero results. This misleads users into thinking the song isn't available when it actually is.
**Root cause:** The component uses `results.length === 0 && !error` to decide whether to show the "no results" message. But `results` initializes as `[]`, so any failure path that doesn't explicitly set the `error` string will render "No audio sources found."
## Design
### 1. Search State Machine
Replace `isSearching` (boolean), `error` (string), and `isCreditError` (boolean) with a single discriminated union:
```ts
type SearchStatus =
| { phase: 'idle' }
| { phase: 'searching'; attempt: number }
| { phase: 'succeeded' }
| { phase: 'failed'; reason: string; isCreditError: boolean; attempt: number }
```
Initial state: `{ phase: 'searching', attempt: 1 }` (search fires on mount).
**Rendering rules:**
| Condition | UI |
|---|---|
| `phase === 'searching'` | Spinner (with retry indicator if attempt > 1) |
| `phase === 'succeeded' && results.length > 0` | Tier-based result cards |
| `phase === 'succeeded' && results.length === 0` | NoResultsSection |
| `phase === 'failed' && isCreditError` | Credit error + Buy Credits button |
| `phase === 'failed' && !isCreditError` | Error banner + Retry button |
**Key guarantee:** `NoResultsSection` only renders when `phase === 'succeeded'` AND `results.length === 0`. No other path can reach it.
### 2. Retry Logic
Up to 3 automatic attempts (1 initial + 2 retries) with delays:
- Attempt 1: immediate
- Attempt 2: after 2s delay
- Attempt 3: after 4s delay
Only retry on transient failures:
- Network errors (TypeError from fetch, connection refused)
- Timeouts (AbortError from 45s timeout)
- Server errors (5xx status codes)
Do NOT retry on:
- 4xx errors (auth, credits, bad request)
Spinner shows retry progress: "Searching for audio sources... (retry 2 of 3)"
### 3. Error Classification
| Error Type | Detection | Message |
|---|---|---|
| Credit (402) | `ApiError` with status 402 | "You're out of credits..." + Buy Credits |
| Auth (401/403) | `ApiError` with status 401 or 403 | "Authentication required" |
| Server (5xx) | `ApiError` with status >= 500 | Auto-retry → "Our search service is temporarily unavailable. Please try again." |
| Timeout | `AbortError` or `err.name === 'AbortError'` | Auto-retry → "Search timed out. Please try again." |
| Network | Non-`ApiError` (TypeError, etc.) | Auto-retry → "Network error — check your connection and try again." |
All classified errors land in `{ phase: 'failed' }` — never a silent empty state.
### 4. Files Changed
Only `frontend/components/job/steps/AudioSourceStep.tsx`:
- Replace `isSearching`, `error`, `isCreditError` state variables with `searchStatus` state
- Rewrite `doSearch` to use state machine + retry with backoff
- Update all rendering conditionals to use `searchStatus.phase`
- Update spinner to show retry attempt count
No changes to: API client, backend, `NoResultsSection` component, result rendering, tier logic, fuzzy matching, catalog search.
### 5. Compatibility
- The `handleFuzzyAccept` function resets state and re-triggers search — will reset to `{ phase: 'searching', attempt: 1 }`
- Retry button in error banner resets to `{ phase: 'searching', attempt: 1 }` and calls `doSearch`
- External consumers (`onSearchCompleted`, `onSearchResultChosen`) are unaffected — they fire from the same success paths
@@ -0,0 +1,434 @@
# Audio Search Robustness Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Prevent the "No audio sources found" message from appearing when a search actually failed, by replacing scattered boolean/string state with an explicit state machine and adding automatic retries.
**Architecture:** Replace `isSearching` (boolean), `error` (string), and `isCreditError` (boolean) in `AudioSourceStep` with a single `searchStatus` discriminated union. Update `doSearch` to classify errors and auto-retry transient failures (up to 3 attempts with backoff). Update all rendering conditionals to key off `searchStatus.phase`.
**Tech Stack:** React (existing component), TypeScript
**Spec:** `docs/archive/2026-03-27-audio-search-robustness-design.md`
---
### Task 1: Add SearchStatus Type and Replace State Variables
**Files:**
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:110-114`
- [ ] **Step 1: Define the SearchStatus type**
Add immediately above the `AudioSourceStep` function (after the `PendingChoice` type around line 36):
```ts
type SearchStatus =
| { phase: 'idle' }
| { phase: 'searching'; attempt: number }
| { phase: 'succeeded' }
| { phase: 'failed'; reason: string; isCreditError: boolean; attempt: number }
const MAX_SEARCH_ATTEMPTS = 3
const RETRY_DELAYS = [0, 2000, 4000] // ms delay before each attempt
```
- [ ] **Step 2: Replace the three state variables**
Replace lines 110-114:
```ts
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [isSearching, setIsSearching] = useState(true)
const [error, setError] = useState("")
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
const [isCreditError, setIsCreditError] = useState(false)
```
With:
```ts
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [searchStatus, setSearchStatus] = useState<SearchStatus>({ phase: 'searching', attempt: 1 })
const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null)
```
- [ ] **Step 3: Add derived booleans for convenience**
Add after the `searchStatus` state declaration (these keep the rest of the file readable and limit the blast radius):
```ts
// Derived from searchStatus for rendering convenience
const isSearching = searchStatus.phase === 'searching'
const error = searchStatus.phase === 'failed' ? searchStatus.reason : ''
const isCreditError = searchStatus.phase === 'failed' && searchStatus.isCreditError
```
- [ ] **Step 4: Verify the file compiles**
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
This should succeed because the derived booleans preserve the same interface that the rendering code expects. If there are type errors, fix them before proceeding.
- [ ] **Step 5: Commit**
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "refactor: replace search booleans with SearchStatus state machine type"
```
---
### Task 2: Rewrite doSearch with State Machine and Retry Logic
**Files:**
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:140-165`
- [ ] **Step 1: Add a helper to classify whether an error is retryable**
Add immediately after the `RETRY_DELAYS` constant:
```ts
/** Returns true for transient errors that should be auto-retried */
function isRetryableError(err: unknown): boolean {
// Network errors (TypeError: Failed to fetch, connection refused, CORS)
if (!(err instanceof ApiError)) return true
// Server errors (5xx) are retryable
if (err.status >= 500) return true
// Everything else (4xx) is not
return false
}
```
- [ ] **Step 2: Replace the doSearch function**
Replace lines 140-165 (the entire `doSearch` useCallback) with:
```ts
// Search with automatic retry for transient failures
const doSearch = useCallback(async (attempt = 1): Promise<void> => {
setSearchStatus({ phase: 'searching', attempt })
// Delay before retry attempts
if (attempt > 1) {
await new Promise(r => setTimeout(r, RETRY_DELAYS[attempt - 1] ?? RETRY_DELAYS[RETRY_DELAYS.length - 1]))
}
try {
const response = await api.searchStandalone(artist, title)
onSearchCompleted(response.search_session_id)
setResults(response.results as ExtendedAudioSearchResult[])
setSearchStatus({ phase: 'succeeded' })
} catch (err) {
// Credit errors — never retry
if (err instanceof ApiError && err.status === 402) {
setSearchStatus({
phase: 'failed',
reason: "You're out of credits. Buy more to continue creating karaoke videos.",
isCreditError: true,
attempt,
})
return
}
// Retryable errors — try again if attempts remain
if (isRetryableError(err) && attempt < MAX_SEARCH_ATTEMPTS) {
return doSearch(attempt + 1)
}
// All retries exhausted or non-retryable error — show failure
let reason: string
if (err instanceof ApiError) {
reason = err.message
} else if (err instanceof DOMException && err.name === 'AbortError') {
reason = "Search timed out. Please try again."
} else {
reason = "Search failed due to a network error. Please try again."
}
setSearchStatus({ phase: 'failed', reason, isCreditError: false, attempt })
}
}, [artist, title, onSearchCompleted])
```
Note: the `finally { setIsSearching(false) }` is gone — the state machine handles it. Every path through `doSearch` now explicitly sets `searchStatus` to either `succeeded` or `failed`.
- [ ] **Step 3: Verify the file compiles**
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
- [ ] **Step 4: Commit**
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "feat: rewrite doSearch with state machine and auto-retry (up to 3 attempts)"
```
---
### Task 3: Update handleFuzzyAccept to Use State Machine
**Files:**
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:225-265` (the `handleFuzzyAccept` function)
The fuzzy accept has its own inline search call that bypasses `doSearch`. It needs to use the state machine too.
- [ ] **Step 1: Update handleFuzzyAccept state resets**
In the `handleFuzzyAccept` function, replace the state reset block (lines ~230-243):
```ts
setFuzzySuggestion(null)
setFuzzyAlternatives([])
setFuzzyDismissed(true)
setResults([])
setIsSearching(true)
setError("")
setCatalogResults([])
setCatalogDismissed(false)
setCommunityData(null)
setCommunityDismissed(false)
setShowOtherOptions(false)
searchTriggered.current = false
fuzzyTriggered.current = false
```
With:
```ts
setFuzzySuggestion(null)
setFuzzyAlternatives([])
setFuzzyDismissed(true)
setResults([])
setSearchStatus({ phase: 'searching', attempt: 1 })
setCatalogResults([])
setCatalogDismissed(false)
setCommunityData(null)
setCommunityDismissed(false)
setShowOtherOptions(false)
searchTriggered.current = false
fuzzyTriggered.current = false
```
- [ ] **Step 2: Update the inline search call's catch/finally**
In the same function, replace the `.catch` and `.finally` in the microtask (lines ~254-258):
```ts
.catch((err) => {
if (err instanceof ApiError) setError(err.message)
else setError("Search failed. Please try again.")
})
.finally(() => setIsSearching(false))
```
With:
```ts
.then(() => {
setSearchStatus({ phase: 'succeeded' })
})
.catch((err) => {
const reason = err instanceof ApiError
? err.message
: "Search failed. Please try again."
setSearchStatus({ phase: 'failed', reason, isCreditError: false, attempt: 1 })
})
```
Note: remove the `.finally(() => setIsSearching(false))` — the state machine handles it in both `.then` and `.catch`.
- [ ] **Step 3: Verify the file compiles**
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
- [ ] **Step 4: Commit**
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "refactor: update handleFuzzyAccept to use SearchStatus state machine"
```
---
### Task 4: Update the No-Results Guard and Retry Button
**Files:**
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:439-455` (error display), `529-531` (no-results)
- [ ] **Step 1: Update the no-results conditional**
The current line 529:
```tsx
{!isSearching && results.length === 0 && !error && (
<NoResultsSection />
)}
```
Replace with:
```tsx
{searchStatus.phase === 'succeeded' && results.length === 0 && (
<NoResultsSection />
)}
```
This is the **key safety change** — `NoResultsSection` now requires an explicit `succeeded` phase, not just the absence of an error string.
- [ ] **Step 2: Update the retry button in the error display**
In the error display section (around line 448), the retry button currently does:
```tsx
<button onClick={() => { searchTriggered.current = false; doSearch() }} ...>Retry</button>
```
This still works because `doSearch()` defaults to `attempt = 1`. No change needed here — the derived `error` and `isCreditError` booleans keep the error display working.
- [ ] **Step 3: Verify the file compiles**
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
- [ ] **Step 4: Commit**
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "fix: only show NoResultsSection when search explicitly succeeded with zero results"
```
---
### Task 5: Update Spinner to Show Retry Progress
**Files:**
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx:458-467` (loading state)
- [ ] **Step 1: Update the spinner section**
Replace the loading state block (lines 458-467):
```tsx
{isSearching && (
<div className="flex flex-col items-center justify-center py-12 gap-3">
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
<div className="text-center">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
This usually takes 15-30 seconds
</p>
</div>
</div>
)}
```
With:
```tsx
{searchStatus.phase === 'searching' && (
<div className="flex flex-col items-center justify-center py-12 gap-3">
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--brand-pink)' }} />
<div className="text-center">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Searching for audio sources...</p>
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
{searchStatus.attempt > 1
? `Retry ${searchStatus.attempt - 1} of ${MAX_SEARCH_ATTEMPTS - 1} — this usually takes 15-30 seconds`
: 'This usually takes 15-30 seconds'}
</p>
</div>
</div>
)}
```
- [ ] **Step 2: Verify the file compiles**
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
- [ ] **Step 3: Commit**
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "feat: show retry progress in search spinner"
```
---
### Task 6: Update Remaining Conditionals to Use searchStatus.phase
**Files:**
- Modify: `frontend/components/job/steps/AudioSourceStep.tsx`
The derived `isSearching` boolean handles most rendering conditions, but a few spots should use `searchStatus.phase` directly for clarity and safety.
- [ ] **Step 1: Update the fallback section conditional**
Line 534:
```tsx
{!isSearching && (confidence.tier !== 3 || results.length === 0) && (
```
Replace with:
```tsx
{searchStatus.phase !== 'searching' && searchStatus.phase !== 'idle' && (confidence.tier !== 3 || results.length === 0) && (
```
This prevents the fallback section (upload/YouTube URL) from showing during the `idle` phase. In practice `idle` is never reached since we initialize to `searching`, but it's defensive.
- [ ] **Step 2: Verify no other references to the old state setters remain**
Search for any remaining direct calls to `setIsSearching`, `setError`, or `setIsCreditError`:
Run: `grep -n 'setIsSearching\|setError\|setIsCreditError' frontend/components/job/steps/AudioSourceStep.tsx`
If any remain, replace them with appropriate `setSearchStatus` calls. (Tasks 1-3 should have caught them all.)
- [ ] **Step 3: Verify the file compiles**
Run: `cd frontend && npx next build --no-lint 2>&1 | tail -30`
- [ ] **Step 4: Commit**
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "refactor: use searchStatus.phase in remaining conditionals"
```
---
### Task 7: Manual Smoke Test
**Files:** None (testing only)
- [ ] **Step 1: Start the dev server**
Run: `cd frontend && npx next dev`
- [ ] **Step 2: Test the happy path**
Navigate to the Create Karaoke Video flow, enter an artist and title that has results (e.g., "Queen - Bohemian Rhapsody"). Verify:
- Spinner appears with "Searching for audio sources..."
- Results appear after search completes
- No flash of "No audio sources found" before results load
- [ ] **Step 3: Test no-results path**
Enter a made-up song (e.g., "Asdfghjkl - Zxcvbnm"). Verify:
- Spinner appears
- "No audio sources found" appears (correctly this time — search succeeded with 0 results)
- Upload/YouTube fallback options are available
- [ ] **Step 4: Test error path (simulate network failure)**
In browser DevTools, go to Network tab, set throttling to "Offline" after clicking to the Choose Audio step. Verify:
- Spinner shows retry progress ("Retry 1 of 2", "Retry 2 of 2")
- After all retries, an error banner appears — NOT "No audio sources found"
- Retry button is present and works when back online
- [ ] **Step 5: Commit any fixes from smoke test**
If anything needed fixing:
```bash
git add frontend/components/job/steps/AudioSourceStep.tsx
git commit -m "fix: address issues found during smoke test"
```
@@ -0,0 +1,312 @@
# Business Continuity & Disaster Recovery Design
**Date:** 2026-03-27
**Status:** Design approved, pending implementation
**Budget:** ~$50-100/month recurring (actual estimate: $20-40/month) + ~$900 one-time egress for Phase 3
**RPO:** 24 hours for Tier 1 (critical), 1 week for Tier 2 (high), N/A for Tier 3 (one-time)
**RTO:** Days (acceptable downtime while rebuilding from git/Pulumi + restoring data from backups)
## Risk Model
Ranked by priority:
1. **Errant Claude session** — AI agent with admin gcloud credentials accidentally deletes production data
2. **Google account termination** — GCP project suspended due to ToS concerns (Spotify dataset, YouTube cookies, torrent tracker integration)
3. **Accidental human error** — Destructive gcloud/bq command run by mistake
## Strategy: Two-Tier Protection
- **Tier A (GCP-native):** Fast recovery from mistakes — object versioning, PITR, deny policies, read-only SA
- **Tier B (Cross-cloud):** Catastrophic recovery — nightly exports to AWS S3 in a separate account
---
## 1. Data Classification
### Tier 1 — Critical (irreplaceable user-generated data)
| Data | Location | Size | Backup Freq | S3 Destination |
|------|----------|------|-------------|----------------|
| Firestore (all collections) | `nomadkaraoke` default DB | ~MBs | Nightly | Standard-IA |
| GCS job files | `karaoke-gen-storage-nomadkaraoke` | 249 GB | Nightly delta sync | Standard-IA |
| Secrets Manager | 48 secrets | Tiny | On-change + quarterly | AWS Secrets Manager |
| Stripe config | External service | N/A | Documented | AWS Secrets Manager |
**Firestore collections (gen):** `gen_users`, `jobs`, `jobs/{id}/logs`, `sessions`, `magic_links`, `user_feedback`, `beta_feedback`, `youtube_quota_pending`, `youtube_upload_queue`
**Firestore collections (decide):** `decide_users`, `lastfm_users`, `music_services`, `karaoke_songs`, `user_songs`, `user_artists`, `playlists`, `sync_jobs`, `sung_records`
### Tier 2 — High (expensive to recreate)
| Data | Location | Size | Backup Freq | S3 Destination |
|------|----------|------|-------------|----------------|
| BigQuery daily-refresh tables | `karaokenerds_raw`, `karaokenerds_community`, `divebar_catalog`, `kn_divebar_xref` | ~MBs | Weekly | Standard-IA |
| BigQuery MusicBrainz tables | `mb_artists`, `mb_recordings`, `mb_artist_tags`, `mb_recording_isrc`, `mbid_spotify_mapping`, `mb_artists_normalized`, `karaoke_recording_links` | ~5 GB | Monthly | Standard-IA |
| BigQuery MLHD+ | `mlhd_artist_similarity` | ~50 MB | One-time | Standard-IA |
| GCS MusicBrainz data | `nomadkaraoke-musicbrainz-data` | 17 GB | One-time | Glacier |
| GCS MLHD data | `nomadkaraoke-mlhd-data` | 252 GB | One-time | Glacier |
| GCS KN data | `nomadkaraoke-kn-data` | 44 MB | Weekly | Standard-IA |
### Tier 3 — Replaceable (can re-derive)
| Data | Location | Size | Backup Freq | S3 Destination |
|------|----------|------|-------------|----------------|
| BigQuery Spotify tables (13 tables) | `karaoke_decide` dataset | ~1 TB logical | One-time | Glacier Deep Archive |
| GCS raw archives | `nomadkaraoke-raw-archives` | 7.2 TB | One-time | Glacier Deep Archive |
### Not Backed Up
| Data | Reason |
|------|--------|
| GCS `nomad-usb-backup` (593 GB) | Already a backup itself |
| Artifact Registry (390 GB) | Rebuild from git |
| Cloud Run services | Code in GitHub, deploy via Pulumi |
| Cloud Scheduler / Cloud Tasks | Defined in Pulumi IaC |
| GCE VMs | Pulumi + Packer, recreatable |
| Firestore indexes | Defined in Pulumi |
| IAM / Service accounts | Defined in Pulumi |
| GCS `nomadkaraoke-audio-separator-models` | Empty bucket |
| GCS `karaoke-decide-data` | Empty bucket |
---
## 2. Prevention Layer: Read-Only Claude SA
### Service Account: `claude-readonly@nomadkaraoke.iam.gserviceaccount.com`
**Granted roles:**
| Role | Purpose |
|------|---------|
| `roles/viewer` | Project-wide read access |
| `roles/firestore.viewer` | Read Firestore documents |
| `roles/bigquery.dataViewer` | Query BigQuery tables |
| `roles/bigquery.jobUser` | Execute BigQuery queries |
| `roles/storage.objectViewer` | Read GCS objects |
| `roles/secretmanager.viewer` | List secrets (NOT access values) |
| `roles/run.viewer` | View Cloud Run services/logs |
| `roles/compute.viewer` | View GCE instances |
| `roles/logging.viewer` | Read Cloud Logging |
### Usage Pattern
- Default: `GOOGLE_APPLICATION_CREDENTIALS` points to read-only SA key
- Write access: User explicitly switches to admin credentials for specific tasks
- Alternative: Claude asks user to run write commands via `!` prefix
### IAM Deny Policies (apply to ALL principals except break-glass SA)
Protect against catastrophic deletes even with admin credentials:
```yaml
deniedPermissions:
- firestore.googleapis.com/databases.delete
- storage.googleapis.com/buckets.delete
- bigquery.googleapis.com/datasets.delete
- bigquery.googleapis.com/tables.delete # scoped to karaoke_decide dataset only
exceptionPrincipals:
- serviceAccount:break-glass@nomadkaraoke.iam.gserviceaccount.com
```
The `break-glass` SA key is stored offline (password manager / local encrypted file). For legitimate deletes, use the break-glass SA rather than removing the deny policy itself.
**Note:** `bigquery.tables.delete` is scoped to the `karaoke_decide` dataset only (not project-wide) to avoid blocking temp table cleanup by the backup pipeline or other automation.
---
## 3. GCP-Native Protections
| Protection | Resource | Config | Cost |
|------------|----------|--------|------|
| Object Versioning | `karaoke-gen-storage-nomadkaraoke` | Enable + lifecycle: delete old versions after 30 days | ~$5-10/month |
| Firestore PITR | Default database | Enable 7-day Point-in-Time Recovery | Free |
| BigQuery Time Travel | `karaoke_decide` dataset | Already enabled (7-day window) | Free |
| GCS Soft Delete | All critical buckets | 7-day soft delete retention | Minimal |
---
## 4. AWS Backup Infrastructure
### Account Setup
- New AWS account: dedicated to Nomad Karaoke backups
- Region: `us-east-1`
- IAM user for backup pipeline: write-only S3 access (no delete)
### S3 Bucket Structure
```
s3://nomadkaraoke-backup/
├── firestore/
│ └── YYYY-MM-DD/ # Nightly Firestore exports
├── bigquery/
│ ├── daily-refresh/ # KN, Divebar tables (weekly)
│ ├── musicbrainz/ # Monthly
│ ├── spotify/ # One-time, Glacier Deep Archive
│ └── mlhd/ # One-time
├── gcs/
│ ├── job-files/ # Mirror of karaoke-gen-storage
│ ├── kn-data/ # Weekly
│ └── musicbrainz-data/ # One-time
└── secrets/
└── YYYY-MM-DD.enc # Encrypted secrets snapshot
```
### S3 Lifecycle Policies
| Prefix | Storage Class | Retention |
|--------|---------------|-----------|
| `firestore/` | Standard-IA | Keep last 30 daily, delete older |
| `bigquery/daily-refresh/` | Standard-IA | Keep last 8 weekly |
| `bigquery/spotify/` | Glacier Deep Archive | Indefinite |
| `gcs/job-files/` | Standard-IA | Mirror (sync, no retention limit) |
| `secrets/` | Standard | Keep last 4 quarterly snapshots |
### Backup Pipeline
**Cloud Function `backup-to-aws`** (2nd gen, Python, 60-min timeout) triggered by Cloud Scheduler nightly at 1:00 AM ET.
Uses Python client libraries (NOT CLI tools — `gcloud`/`bq`/`gsutil` are not available in Cloud Functions):
1. **Firestore export** → `google.cloud.firestore_admin_v1` client to export to `gs://nomadkaraoke-backup-staging/firestore/YYYY-MM-DD/`
2. **BigQuery export** (weekly, based on day-of-week check) → `google.cloud.bigquery` client `extract_table()` to GCS staging as Parquet
3. **GCS sync** → `google.cloud.storage` client to copy new/changed job files to staging bucket
4. **AWS sync** → `boto3` to upload from GCS staging to S3
5. **Cleanup** → Remove GCS staging files after confirmed S3 upload
6. **Alert** → Discord webhook notification with backup summary + any failures
**Required IAM roles for backup function SA (`backup-to-aws@nomadkaraoke.iam.gserviceaccount.com`):**
- `roles/datastore.importExportAdmin` — Firestore export
- `roles/bigquery.dataViewer` + `roles/bigquery.jobUser` — BigQuery export
- `roles/storage.objectAdmin` on staging bucket — Write exports
- `roles/storage.objectViewer` on source buckets — Read job files
**Note:** For the 249 GB job-files bucket, delta sync may exceed Cloud Function timeout on first run. If needed, split into a separate Cloud Run job for the initial catchup, then use the Cloud Function for incremental deltas.
### Cost Estimate
**Recurring (monthly):**
| Component | Monthly Cost |
|-----------|-------------|
| S3 Glacier Deep Archive (7.5 TB) | ~$7 |
| S3 Standard-IA (~300 GB active) | ~$4 |
| GCP egress for nightly deltas | ~$5-15 |
| Cloud Function execution | ~$1 |
| GCS staging bucket | ~$2 |
| **Total recurring** | **~$20-40** |
**One-time (Phase 3 bulk transfer):**
| Component | Cost |
|-----------|------|
| GCP egress for ~7.5 TB to AWS | ~$900 |
| S3 Glacier Deep Archive retrieval (if ever needed) | ~$150 (bulk) to ~$750 (standard) |
---
## 5. Additional Single Points of Failure
Beyond GCP, these external dependencies should be documented/protected:
| Dependency | Risk | Mitigation |
|------------|------|------------|
| **GitHub** (all repos, IaC, CI/CD) | Org suspended/deleted | Keep local clones of all repos; consider periodic mirror to AWS CodeCommit |
| **Cloudflare** (DNS, Pages, Workers) | Account compromised/terminated | Export DNS zone records, document Pages/Worker config in this repo |
| **External OAuth apps** (Spotify, Google, Dropbox) | Losing Google account = losing OAuth app registrations | Document all OAuth redirect URIs, client IDs, app settings in encrypted backup |
| **Flacfetch VM data disk** | Chrome profile, cookies, tracker config | Document manual setup steps; cookies auto-refresh so only config matters |
## 6. Secrets Encryption & Key Management
Secrets backup files (`secrets/YYYY-MM-DD.enc`) are encrypted with an **AWS KMS key** (not GCP KMS — must survive GCP termination).
- AWS KMS key created in the backup AWS account
- Key ARN also stored in password manager as a failsafe
- The backup Cloud Function encrypts secrets client-side using `boto3` KMS before uploading to S3
**Critical:** AWS IAM credentials for the backup pipeline are stored in GCP Secret Manager for the Cloud Function to use, BUT must also be stored **outside GCP** (password manager) since they are needed to access backups if GCP is terminated.
## 7. Verification & Monitoring
| Check | Frequency | Method |
|-------|-----------|--------|
| Backup completed | Daily | Discord webhook alert from backup function |
| Backup freshness (external) | Daily | External cron (e.g., free-tier UptimeRobot or AWS Lambda) checks S3 last-modified; alerts if >48h stale |
| Backup integrity | Monthly | Script downloads random Firestore export, verifies doc count |
| S3 bucket growth | Weekly | CloudWatch alarm if bucket stops growing |
| Restore drill | Quarterly | Restore Firestore to test GCP project, verify data |
**Why external monitoring?** The backup pipeline runs on GCP. If GCP is terminated (Risk #2), backups stop silently. The external freshness check ensures you are alerted even if GCP is down.
## 8. High-Level Restore Procedure
For a catastrophic GCP termination, the restore flow would be:
1. **Create new GCP project** (or use a different cloud provider)
2. **Retrieve AWS credentials** from password manager
3. **Download Firestore export** from S3 → `firestore import` to new project
4. **Download BigQuery exports** from S3 → load Parquet files into new BigQuery (or equivalent)
5. **Sync GCS data** from S3 → new cloud storage
6. **Retrieve secrets** from AWS Secrets Manager → decrypt with AWS KMS → configure new project
7. **Run Pulumi** targeting new project to recreate all infrastructure
8. **Deploy services** from GitHub repos
9. **Update DNS** (Cloudflare) to point to new services
10. **Re-register OAuth apps** at Spotify, Google, etc. using documented config
---
## 9. Implementation Phases
### Phase 0: Audit (verify assumptions)
1. Run `pulumi stack export` and diff against actual GCP resources to catch any console-created resources not in IaC
2. Verify all Cloud Scheduler jobs are defined in Pulumi
3. Document Cloudflare configuration (DNS records, Pages projects, Worker scripts, custom domains)
4. Document external OAuth app registrations (Spotify, Google, Dropbox redirect URIs and client IDs)
### Phase 1: GCP-Native Protections (no AWS needed)
1. Create `claude-readonly` service account via Pulumi
2. Grant read-only roles
3. Create `break-glass` service account, store key in password manager
4. Create IAM deny policies for destructive operations (with break-glass exception)
5. Enable Firestore PITR
6. Enable GCS object versioning on `karaoke-gen-storage-nomadkaraoke`
7. Enable GCS soft delete on critical buckets
8. Generate `claude-readonly` SA key, store at `~/.config/gcloud/claude-readonly.json`
9. Configure direnv (`.envrc`) to set `GOOGLE_APPLICATION_CREDENTIALS` to read-only SA by default
### Phase 2: AWS Account & Bucket Setup
1. Create dedicated AWS account
2. Create S3 bucket with lifecycle policies
3. Enable S3 Object Lock (Governance mode) on backup bucket
4. Create write-only IAM user (`s3:PutObject` only, no delete)
5. Create AWS KMS key for secrets encryption
6. Create AWS Secrets Manager entries for external service config
7. Store AWS credentials in GCP Secret Manager (for backup function) AND in password manager (for catastrophic recovery)
### Phase 3: One-Time Bulk Exports (~$900 egress cost)
1. Export all BigQuery Spotify tables to GCS staging
2. Use GCP Storage Transfer Service (direct GCS→S3, no staging needed) for 7.2 TB raw archives to Glacier Deep Archive
3. Sync MusicBrainz and MLHD GCS buckets to S3 Glacier
4. Export and sync MLHD+ BigQuery table
5. Export all secrets, encrypt with AWS KMS, store in AWS Secrets Manager
6. Store KMS key ARN in password manager
### Phase 4: Automated Nightly Backups
1. Create GCS staging bucket (`nomadkaraoke-backup-staging`)
2. Create backup function SA with required roles (`datastore.importExportAdmin`, `bigquery.dataViewer`, `bigquery.jobUser`, `storage.objectAdmin` on staging, `storage.objectViewer` on sources)
3. Create 2nd-gen Cloud Function `backup-to-aws` (Python, 60-min timeout)
4. Create Cloud Scheduler trigger (1:00 AM ET daily)
5. Implement Firestore nightly export (via `firestore_admin_v1` Python client)
6. Implement BigQuery weekly export (via `bigquery` Python client, day-of-week check)
7. Implement BigQuery monthly export for MusicBrainz tables
8. Implement GCS job files delta sync (via `google.cloud.storage` + `boto3`)
9. Implement Discord webhook alerting on success/failure
10. Set up external backup freshness monitor (AWS Lambda or free-tier service, alerts if S3 not updated in 48h)
### Phase 5: Verification & Documentation
1. Run first full backup, verify all data landed in S3
2. Test Firestore restore to a test GCP project
3. Write detailed restore runbook (step-by-step for each data tier, including cost estimates for Glacier retrieval)
4. Set up CloudWatch monitoring on S3
5. Mirror GitHub repos to secondary git host (AWS CodeCommit or similar)
6. Schedule first quarterly restore drill
@@ -0,0 +1,60 @@
# Plan: Fix Ensemble Preset Stem Tag Parsing Bug
**Created:** 2026-03-27
**Branch:** feat/sess-20260326-2142-prod-broken-jobs
**Status:** Complete
## Overview
The ensemble preset stem filename parser in `audio_processor.py` uses naive substring matching (`"instrumental" in basename`) to classify output files as vocals vs instrumental. This breaks when the preset name itself contains the word "instrumental" (e.g., `instrumental_clean`), causing the Vocals file to be misclassified. Stage 2 (backing vocals separation) never runs, so users only get `instrumental_clean` — no backing vocals, no combined instrumentals, and the instrumental review page shows "No backing vocals detected."
## Requirements
- [x] Fix Stage 1 stem tag parsing to correctly identify Vocals vs Instrumental files regardless of preset name
- [x] Fix Stage 2 stem tag parsing with the same approach (same bug pattern)
- [ ] Add unit tests for stem tag parsing with various preset names
- [ ] Add regression test specifically for `instrumental_clean` preset name
- [ ] Verify upload function correctly handles the now-populated backing vocals data
## Technical Approach
**Root cause:** Output filenames follow the pattern `{base}_(StemTag)_preset_{name}.flac` where StemTag is `Vocals`, `Instrumental`, or `No Vocal`. The old code matched substrings against the entire filename, so preset name `instrumental_clean` caused the Vocals file to match `"instrumental" in basename`.
**Fix:** Extract the stem tag from between `_(` and `)_` delimiters and match only against that, not the full filename. This is already implemented — just needs tests and verification.
**Fallback:** If the stem tag extraction fails (no `_(...)_` pattern found), log a warning. This handles edge cases where the separator library changes its naming convention.
## Implementation Steps
1. [x] Fix stem tag parsing in Stage 1 (lines 308-331) — **already done**
2. [x] Fix stem tag parsing in Stage 2 (lines 364-380) — **already done**
3. [ ] Write unit tests for `process_audio_separation` ensemble path:
- Test Stage 1 correctly classifies files with `instrumental_clean` preset
- Test Stage 1 correctly classifies files with `karaoke` preset
- Test Stage 2 correctly classifies backing vocal files
- Test unrecognized stem tags produce warnings
- Test fallback when `_(...)_` pattern not present
4. [ ] Run existing tests to verify no regressions
5. [ ] Manual verification: check that a test job produces all stems (instrumental_clean, backing_vocals, lead_vocals, instrumental_with_backing)
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `karaoke_gen/audio_processor.py` | Modified | Fixed stem tag parsing in Stage 1 (L308-331) and Stage 2 (L364-380) |
| `tests/unit/test_audio_processor_local_gpu.py` | Modify | Add tests for ensemble stem tag parsing |
## Testing Strategy
- **Unit tests:** Mock the `Separator` to return filenames with various preset names, verify correct classification into vocals/instrumental/backing_vocals
- **Regression test:** Specifically test `instrumental_clean` preset to ensure it never regresses
- **Existing tests:** Run full test suite to verify no regressions
- **Manual:** After deploy, trigger a test job and verify all stems appear in GCS and on the instrumental review page
## Open Questions
None — root cause is confirmed and fix is verified.
## Rollback Plan
Revert the single commit. The old behavior (only instrumental_clean uploaded) would return as a known limitation. No data loss risk.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,82 @@
# External Services Configuration (DR Reference)
**Purpose:** If GCP or other services are terminated, this documents what needs to be re-created at the external service level. Actual secrets are in AWS Secrets Manager.
**Last verified:** 2026-03-29
## Cloudflare
- **Zone:** nomadkaraoke.com
- **DNS Records:**
- `api` → CNAME → `ghs.googlehosted.com` (proxied: false)
- `gen` → CNAME → Cloudflare Pages
- `decide` → CNAME → GitHub Pages
- `vocalstar` → CNAME → Cloudflare Pages (tenant portal)
- `singa` → CNAME → Cloudflare Pages (tenant portal)
- **Pages Projects:**
- `karaoke-gen` — gen.nomadkaraoke.com (consumer frontend)
- `karaoke-gen-tenant` — vocalstar/singa subdomains (B2B tenant portal)
- **Workers:**
- `karaoke-decide-api-proxy` — proxies decide.nomadkaraoke.com/api/* to Cloud Run
## Spotify Developer App
- **App name:** Nomad Karaoke Decide
- **Client ID:** stored in Secret Manager as `spotipy-client-id`
- **Client Secret:** stored in Secret Manager as `spotipy-client-secret`
- **Redirect URIs:**
- `https://decide.nomadkaraoke.com/api/services/spotify/callback`
- `http://localhost:8000/api/services/spotify/callback`
## Google (Flacfetch)
- **Account:** nomadflacfetch@gmail.com (no 2FA)
- **Used for:** YouTube cookies (refreshed every 8h), Spotify "Login with Google" (refreshed every 12h)
- **Managed by:** Flacfetch credential keeper systemd service on GCE VM
## Stripe
- **Webhook endpoint:** `https://api.nomadkaraoke.com/api/users/webhooks/stripe`
- **Events:** `checkout.session.completed`, `checkout.session.expired`, `payment_intent.payment_failed`
- **Keys:** `stripe-secret-key`, `stripe-webhook-secret` in Secret Manager
## SendGrid
- **Sender:** gen@nomadkaraoke.com
- **Used by:** karaoke-gen (job notifications, idle reminders), karaoke-decide (magic link auth)
- **Key:** `sendgrid-api-key` in Secret Manager
## AudioShake
- **Purpose:** Lyrics transcription API
- **Key:** `audioshake-api-key` in Secret Manager
## Genius
- **Purpose:** Reference lyrics lookup
- **Key:** `genius-api-key` in Secret Manager
## KaraokeNerds
- **Purpose:** Karaoke catalog API (daily sync)
- **Key:** `karaokenerds-api-key` in Secret Manager
## Dropbox
- **Purpose:** Karaoke file distribution (per-job upload)
- **Credentials:** `dropbox-oauth-credentials` in Secret Manager
## YouTube
- **Purpose:** Karaoke video upload + API quota tracking
- **Credentials:** `youtube-oauth-credentials`, `youtube-client-credentials`, `youtube-cookies` in Secret Manager
## Last.fm
- **Purpose:** User listening history for Decide recommendations
- **Keys:** `lastfm-api-key`, `lastfm-shared-secret` in Secret Manager
## Private Trackers (RED, OPS)
- **Purpose:** High-quality audio source downloads via Flacfetch
- **Keys:** `red-api-key`, `red-api-url`, `ops-api-key`, `ops-api-url` in Secret Manager
@@ -0,0 +1,66 @@
# Plan: Move Screen Video Generation to GCE Encoding Worker
**Created:** 2026-03-31
**Branch:** feat/sess-20260331-1619-investigate-render-failure
**Status:** Draft
## Overview
Screen video generation (title.mov, end.mov) currently runs FFmpeg in the Cloud Run API container via `VideoGenerator._create_video_from_image()`. After PR #640 right-sized Cloud Run to 2CPU/2Gi, the 4K H.264 encoding OOMs silently (producing 36-byte empty MOV shells). This breaks all downstream encoding since `encode_lossless_mp4` can't concatenate corrupt inputs.
Fix: Stop generating MOV in screens_worker. Generate them on the GCE encoding worker (which has adequate resources) just before the encoding step.
## Root Cause
- `VideoGenerator._create_video_from_image()` uses `os.system()` — silently swallows FFmpeg failures
- 4K H.264 encoding needs more than 2Gi RAM
- screens_worker checks `os.path.exists(output_video_filepath)` — the 36-byte shell passes this check
- All jobs since the Cloud Run right-sizing (March 31) are affected
## Implementation Steps
### 1. screens_worker.py — Stop generating MOV videos
**Changes:**
- In `_generate_title_screen`: pass `intro_video_duration=0` to skip MOV creation, return PNG path
- In `_generate_end_screen`: pass `end_video_duration=0` to skip MOV creation, return PNG path
- In `_upload_screens`: only upload PNG and JPG (remove MOV upload logic)
- Update function return types/docstrings to reflect image-only output
**Why duration=0 works:** `VideoGenerator._save_output_files` already has `if duration > 0:` guard around `_create_video_from_image`.
### 2. gce_encoding/main.py — Generate MOV from PNG before encoding
**Changes in `run_encoding()`:**
- After `find_file` for title/end videos, check if they're missing or invalid (< 1KB)
- If missing/invalid, look for corresponding PNG: `screens/title.png`, `screens/end.png`
- Generate MOV from PNG using `subprocess.run()` with proper error handling
- Use same FFmpeg command as `_create_video_from_image` but with error checking
- Log clearly when generating MOV from PNG vs using existing MOV
**Backwards compatible:** Old jobs with valid MOVs still work. New jobs with only PNGs get MOVs generated on GCE.
### 3. Fix `_create_video_from_image` error handling (defensive)
**Changes in `karaoke_gen/video_generator.py`:**
- Replace `os.system()` with `subprocess.run(check=True)`
- Log stderr on failure
- This protects the local CLI path too
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/workers/screens_worker.py` | Modify | Stop generating MOV, return/upload images only |
| `backend/services/gce_encoding/main.py` | Modify | Generate MOV from PNG in `run_encoding()` |
| `karaoke_gen/video_generator.py` | Modify | Replace `os.system()` with `subprocess.run()` |
## Testing Strategy
- Unit tests for GCE worker MOV generation helper
- Verify existing encoding tests still pass
- Manually re-run job f0d51a0a after deploy to confirm fix
## Rollback Plan
Revert the 3 files. The old behavior (generating MOV in Cloud Run) would still fail with 2Gi, but increasing memory to 4Gi would restore it.
+215
View File
@@ -0,0 +1,215 @@
# Plan: Karaoke-Gen i18n Multilingual (Phase 3)
**Created:** 2026-04-03
**Branch:** `feat/sess-20260403-1115-i18n-multilingual`
**Worktree:** `/Users/andrew/Projects/nomadkaraoke/karaoke-gen-i18n-multilingual`
**Status:** Draft
## Context
This is Phase 3 of the i18n multilingual initiative. Phases 1+2 shipped successfully for public-website (205 strings) and karaoke-decide (811 frontend + 47 backend strings). The patterns are proven — we're replicating them in karaoke-gen, the most complex project (many frontend surfaces + multi-layered backend).
## Scope Decisions
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Admin pages (`/admin/*`) | **Exclude** from i18n | Internal-only, ~30% more strings for zero user impact. Can add later. |
| Tenant default locale | **Out of scope** | Orthogonal to user locale; user's localStorage/browser detection suffices |
| Hash routing compatibility | **No conflict** | Hash (`#/jobId/review`) is client-side only, preserved across locale changes |
| Providers in root layout | **Keep in root** | Unlike Phase 1/2, karaoke-gen has admin pages outside `[locale]` that need ThemeProvider/TenantProvider. Only NextIntlClientProvider moves to `[locale]/layout.tsx`. |
## Architecture: Frontend Key Difference from Phase 1/2
karaoke-gen has admin pages at `app/admin/` that must NOT be under `[locale]` routing. So:
- **Root `app/layout.tsx`**: Keeps `<html>`, `<body>`, ThemeProvider, TenantProvider, ImpersonationBannerWrapper, ServiceWorkerRegistration, GoogleAnalytics. Remove hardcoded `lang="en"`.
- **`app/[locale]/layout.tsx`**: Adds NextIntlClientProvider + inline `<script>` to set `document.documentElement.lang`. Uses `generateStaticParams` for locale pre-rendering.
- **`app/admin/layout.tsx`**: Unchanged — inherits root providers, no locale context needed.
## PR Breakdown (4 PRs)
### PR 1: Frontend Infrastructure + Page Migration (~250 strings)
**Goal:** Set up next-intl, `[locale]` routing, move all user-facing pages under locale prefix.
**Create:**
- `frontend/i18n/routing.ts` — locale config, `createNavigation`
- `frontend/i18n/request.ts` — message loading for next-intl
- `frontend/messages/en.json` — all user-facing strings (namespaced: `common`, `landing`, `dashboard`, `auth`, `payment`, `jobFlow`, `lyricsReview`, `instrumentalReview`, `audioEditor`, `audioSearch`, `credits`, `feedback`, `push`, `status`)
- `frontend/app/[locale]/layout.tsx` — NextIntlClientProvider, `generateStaticParams`, lang script
- `frontend/app/[locale]/page.tsx` — landing page (moved from `app/page.tsx`)
- `frontend/app/[locale]/app/page.tsx` — dashboard
- `frontend/app/[locale]/app/jobs/[[...slug]]/page.tsx` — job router
- `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx` — job client component
- `frontend/app/[locale]/auth/verify/page.tsx` — magic link verify
- `frontend/app/[locale]/payment/success/page.tsx` — payment success
- `frontend/app/[locale]/order/success/page.tsx` — order success
- `frontend/components/LanguageSwitcher.tsx` — dropdown in header
- `frontend/scripts/translate.py` — copy from karaoke-decide
- `frontend/scripts/glossary.json` — extended with karaoke-gen terms
**Modify:**
- `frontend/app/layout.tsx` — remove `lang="en"` from `<html>`, keep all providers
- `frontend/app/page.tsx` — replace with client-side locale redirect (localStorage > navigator.language > 'en')
- `frontend/next.config.mjs` — wrap with `createNextIntlPlugin` from `next-intl/plugin`
- `frontend/package.json` — add `next-intl`
- `frontend/lib/api.ts` — add `Accept-Language` header via `getLocaleFromPath()`
- `frontend/components/app-header.tsx` — add LanguageSwitcher
**String extraction in this PR:** Extract ALL user-facing strings from ALL components (landing, dashboard, job flow, lyrics review, instrumental review, audio editor, audio search, credits, feedback, push, auth, status, common). Write the complete `en.json` upfront so PR 2 is just wiring `useTranslations()` into components.
**Why extract all strings in PR 1?** The en.json file defines the complete translation surface. Having it complete lets us run translate.py once to generate es.json/de.json, and subsequent PRs just add `useTranslations()` calls without needing to re-translate.
### PR 2: Component i18n Wiring (~50 components)
**Goal:** Wire `useTranslations()` into all user-facing components.
**Components to convert (by area):**
*Job creation (~14 files):*
- `components/job/GuidedJobFlow.tsx`, `TenantJobFlow.tsx`
- `components/job/steps/SongInfoStep.tsx`, `AudioSourceStep.tsx`, `CustomizeStep.tsx`, `VisibilityStep.tsx`
- `components/job/JobCard.tsx`, `JobActions.tsx`, `OutputLinks.tsx`, `JobSubmission.tsx`
- `components/job/ThemeSelector.tsx`, `TitleCardPreview.tsx`, `EditTrackModal.tsx`, `CommunityVersionBanner.tsx`
*Lyrics review (~20 files):*
- `components/lyrics-review/Header.tsx`, `LyricsAnalyzer.tsx`, `GuidancePanel.tsx`, `TranscriptionView.tsx`
- `components/lyrics-review/EditActionBar.tsx`, `EditFeedbackBar.tsx`, `EditWordList.tsx`
- `components/lyrics-review/ModeSelector.tsx`, `ReferenceView.tsx`, `ReferenceEmptyState.tsx`
- `components/lyrics-review/SessionRestoreDialog.tsx`, `PreviewVideoSection.tsx`, `GapNavigator.tsx`
- `components/lyrics-review/modals/*.tsx` (8 files)
- `components/lyrics-review/synchronizer/*.tsx` (4 files)
*Instrumental review (~7 files):*
- `components/instrumental-review/InstrumentalSelector.tsx`, `InstrumentalSelectorEmbedded.tsx`
- `components/instrumental-review/InstrumentalGuidancePanel.tsx`, `SelectionOptions.tsx`
- `components/instrumental-review/StemComparison.tsx`, `CustomUpload.tsx`, `MuteRegionEditor.tsx`
*Other (~10 files):*
- `components/audio-editor/AudioEditor.tsx`, `AudioEditRestoreDialog.tsx`
- `components/audio-search/AudioSearchDialog.tsx`
- `components/credits/BuyCreditsDialog.tsx`
- `components/feedback/FeedbackDialog.tsx`
- `components/auth/AuthDialog.tsx`, `AuthStatus.tsx`
- `components/push-notification-prompt.tsx`, `push-settings.tsx`
- `components/TenantLandingPage.tsx`, `WarmingUpLoader.tsx`, `status-badge.tsx`
**Pattern:** Each component gets `const t = useTranslations('namespace')` and replaces hardcoded strings with `t('key')`.
### PR 3: Backend i18n Infrastructure + Route Localization (~150-200 strings)
**Goal:** Add `backend/i18n.py`, translation files, convert all route files.
**Create:**
- `backend/i18n.py` — `t(locale, key, **kwargs)`, `get_locale_from_request(request)`, `get_locale_prefix(locale)` (copy from karaoke-decide)
- `backend/translations/en.json` — all backend strings
- `backend/translations/es.json`, `de.json` — via translate.py
**Modify:**
- `backend/models/user.py` — add `locale: Optional[str] = None` to User model
- `backend/services/user_service.py` — persist locale on create/update
- All user-facing route files (10 files): `auth.py`, `jobs.py`, `review.py`, `audio_search.py`, `users.py`, `push.py`, `file_upload.py`, `catalog.py`, `themes.py`, `tenant.py`
- `backend/main.py` — localize `InsufficientCreditsError` handler
**Pattern:**
```python
from backend.i18n import t, get_locale_from_request
locale = get_locale_from_request(request)
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
```
### PR 4: Email + Push Notification Localization (~50-80 strings)
**Goal:** Localize all 5 email types and 3 push notification types.
**Modify:**
- `backend/services/email_service.py` — pass locale to all email methods, use `t()` for subjects/headings/buttons
- `backend/services/template_service.py` — locale-aware GCS template paths (`templates/{locale}/...`)
- `backend/services/job_notification_service.py` — fetch user locale, pass to email service; localize URL prefixes
- `backend/services/push_notification_service.py` — locale-aware notification titles/bodies
**Add to translations:** `emails.*` and `push.*` namespaces in backend translation files.
## Implementation Order
```
PR 1 (Frontend Infra) ──→ PR 2 (Component Wiring)
│
└──→ PR 3 (Backend Infra) ──→ PR 4 (Emails + Push)
```
PRs 2 and 3 can be developed in parallel after PR 1 lands.
## Key Technical Details
### Accept-Language Header (frontend → backend)
```typescript
// frontend/lib/api.ts
function getLocaleFromPath(): string {
if (typeof window === 'undefined') return 'en';
const match = window.location.pathname.match(/^\/(en|es|de)\//);
return match ? match[1] : 'en';
}
```
Added to `getAuthHeaders()` so every API call includes locale.
### User Locale Persistence
- **Frontend:** `localStorage.setItem('locale', newLocale)` on language switch
- **Backend:** `User.locale` field in Firestore (`gen_users` collection), set on magic link verify from `Accept-Language`, updated on explicit language change
- **Emails/push:** Read `User.locale` from Firestore, fallback to `'en'`
### Static Export with Locale Routing
`generateStaticParams` on `[locale]/layout.tsx` returns `[{locale:'en'},{locale:'es'},{locale:'de'}]`. Combined with `output: 'export'` and `trailingSlash: true`, Next.js generates `/en/`, `/es/`, `/de/` directories — compatible with Cloudflare Pages.
### Backend-Generated URLs
All backend URLs that point to frontend must include locale prefix:
```python
f"{frontend_url}/{get_locale_prefix(user_locale)}/app/jobs#{job_id}/review"
```
## Testing Strategy
### Unit Tests
- **Backend:** Test `i18n.py` — `t()` function with valid/invalid keys, interpolation, fallback to English, unsupported locale handling
- **Backend:** Test locale extraction from `Accept-Language` header
- **Frontend:** Jest tests for `getLocaleFromPath()` helper
### Integration Tests
- **Backend:** Verify routes return localized error messages when `Accept-Language: es` is sent
- **Backend:** Verify emails are sent with correct locale strings
### E2E Tests (Playwright)
- **Production E2E:** Navigate to `/es/` and `/de/`, verify page renders in correct language
- **Production E2E:** Switch language via LanguageSwitcher, verify localStorage persistence and page reload
- **Production E2E:** Verify root `/` redirects to correct locale based on browser language
### Manual Verification
Convert to automated E2E tests per TESTING.md guidelines:
- Verify static export generates all 3 locale directories
- Verify admin pages still work at `/admin/` (no locale prefix)
- Verify tenant subdomains work with locale routing
## Estimated String Counts
| Area | Strings | PR |
|------|---------|-----|
| Frontend: landing, dashboard, auth, payment | ~100 | 1 |
| Frontend: common (buttons, errors, loading) | ~50 | 1 |
| Frontend: job flow | ~80 | 1 (extracted), 2 (wired) |
| Frontend: lyrics review | ~120 | 1 (extracted), 2 (wired) |
| Frontend: instrumental review | ~40 | 1 (extracted), 2 (wired) |
| Frontend: other components | ~60 | 1 (extracted), 2 (wired) |
| **Frontend total** | **~450-550** | |
| Backend: route messages | ~150-200 | 3 |
| Backend: emails + push | ~50-80 | 4 |
| **Backend total** | **~200-280** | |
| **Grand total** | **~650-830** | |
## Open Questions
- [ ] Should we store locale preference in a cookie too (for pre-auth pages where we don't have a user document)?
- [ ] The landing page (`app/page.tsx`) currently has a lot of marketing content — confirm it should be fully translated vs. just the chrome
- [ ] Any karaoke-gen-specific glossary terms beyond what's in karaoke-decide's glossary? (e.g., "stem separation", "instrumental track", "lyrics review")
## Rollback Plan
Each PR is independently revertable:
- PR 1: Revert moves pages back to non-locale paths. Admin pages unaffected.
- PR 3: Revert removes `i18n.py` and translation files. Routes return English strings.
- Cloudflare Pages: Previous deployment is one click to restore.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,165 @@
# Reference Lyrics Search & Relevance Filtering
## Problem
When a track has a remix, "feat." artist, or unusual naming, the automatic lyrics search during job processing often returns irrelevant results (wrong song entirely) or nothing useful. Users must then manually Google lyrics, copy/paste into the "Add Reference Lyrics" modal — introducing formatting errors and friction. Additionally, irrelevant reference lyrics that do get through skew anchor/gap statistics and confuse correction tooling.
## Solution
Three interconnected improvements:
1. **Relevance filtering in the correction pipeline** — automatically reject reference lyrics that don't match the transcription
2. **Search with alternate artist/title** — let users retry the lyrics search with adjusted metadata from the review UI
3. **Better empty state** — when no valid references exist, show the search/paste UI inline in the Reference panel
## Design
### 1. Relevance Filtering in the Correction Pipeline
**Location:** Inside `LyricsCorrector`, after anchor sequences are found but before corrections are applied.
**Per-source relevance score:**
```
relevance = (reference words appearing in anchor sequences) / (total words in reference source)
```
Sources below `MIN_REFERENCE_RELEVANCE` (default TBD — see Section 5) are removed from `reference_lyrics` and excluded from gap/correction processing.
**Applies to all code paths:**
- Initial job processing — irrelevant sources filtered before corrections saved to GCS
- Add lyrics (paste) — pasted text subject to same threshold
- Search lyrics (new endpoint) — results filtered automatically
**Edge case:** If all sources are filtered out, the job proceeds with zero reference sources. The transcription stands as-is with no corrections. The frontend shows the empty state (Section 4).
**Metadata:** Filtered-out sources are logged in correction metadata (source name + score) for debugging but not stored in `reference_lyrics`.
**Override:** The `search-lyrics` endpoint and `add-lyrics` endpoint accept a `force: true` flag to bypass the threshold for user-selected sources. This handles cases where the transcription is poor and a low match % doesn't mean wrong song.
### 2. New Backend Endpoint — Search Lyrics
**Endpoint:** `POST /api/review/{job_id}/search-lyrics`
**Request:**
```json
{
"artist": "Billie Eilish",
"title": "What Was I Made For",
"force_sources": []
}
```
- `artist` and `title`: Used for the lyrics search across all providers
- `force_sources`: Optional list of source names to add regardless of threshold (for the override flow)
**Behavior:**
1. Download current `corrections.json` from GCS
2. Create all standard lyrics providers (Genius, Spotify, Musixmatch, LRCLIB) with provided artist/title
3. Fetch lyrics from all providers
4. Run through the correction pipeline with relevance filtering
5. Sources passing threshold are added to `reference_lyrics`, corrections recomputed
6. Sources in `force_sources` bypass the threshold
7. Upload updated `corrections.json` to GCS
**Response — success (at least one source passed or force-added):**
```json
{
"status": "success",
"data": { "...full CorrectionData..." },
"sources_added": ["genius", "lrclib"],
"sources_rejected": {
"spotify": {"relevance": 0.12, "track_name": "What Was I Made For", "artist": "Billie Eilish"},
"musixmatch": {"relevance": 0.08, "track_name": "What Was I Made For", "artist": "Billie Eilish"}
}
}
```
**Response — no valid results:**
```json
{
"status": "no_results",
"message": "No lyrics sources passed the relevance threshold",
"sources_rejected": {
"genius": {"relevance": 0.15, "track_name": "What Was I Made For", "artist": "Billie Eilish"},
"spotify": {"relevance": 0.09, "track_name": "What Was I Made For", "artist": "Billie Eilish"}
},
"sources_not_found": ["lrclib", "musixmatch"]
}
```
### 3. Frontend — Add Reference Lyrics Modal Redesign
The modal gets two tabs: **Search** (default) and **Paste**.
#### Search Tab
- Two input fields pre-populated from job metadata: **Artist** and **Title**
- Helpful tip: "Try removing 'feat.', 'remix', or other extras from the title"
- "Search All Providers" button
- **Loading state:** Spinner with "Searching providers..."
- **Success (sources passed threshold):** Modal closes, new sources appear in Reference Lyrics panel
- **No results state:** Modal stays open, shows rejected sources as selectable cards:
- Each card shows: provider name, match %, track name/artist found
- Checkbox on each to select for force-add
- Providers that returned nothing shown grayed out (no checkbox)
- Explanation: "These sources were found but had low word match with your transcription. This could mean wrong song — or the transcription may just be inaccurate."
- "Add Selected" button (disabled until something checked) to force-add
- "Search Again" button to retry with adjusted terms
- Suggestion to try different terms or switch to Paste tab
#### Paste Tab
Identical to current modal: Source Name input + Lyrics textarea. No changes to the paste flow — still calls existing `add-lyrics` endpoint, still subject to relevance filtering. If pasted lyrics fail the threshold, the user gets a similar rejection message with option to force-add.
### 4. Empty State — Reference Panel Inline UI
When no valid reference sources exist after job processing (all filtered or none found), the Reference Lyrics panel shows:
1. **Explanation banner:** "No valid reference lyrics found" with context about why (remixes, feat., live versions)
2. **Inline Search/Paste tabbed UI** — same as the modal content but embedded directly in the panel. No "+ New" button click needed.
3. Artist/Title fields pre-populated from job metadata
Once a valid source is added (via search or paste), the panel switches back to the normal view: source buttons + lyrics display + "+ New" button for the modal.
### 5. Empirical Threshold Analysis
**Goal:** Determine the right `MIN_REFERENCE_RELEVANCE` value from real data.
**Method:**
1. Pull ~30 prod jobs from Firestore that have correction data with reference lyrics
2. Bias sampling toward jobs with mixed results (at least one source with low match %) — pure high-match jobs aren't useful for threshold tuning
3. For each job × source, compute: `(reference words in anchor sequences) / (total reference words)`
4. Generate a report with: job ID, source name, match %, first ~2 lines of transcription and reference (for quick visual comparison)
5. User visually classifies each source as "correct song" or "wrong song"
6. Find the threshold that best separates the two groups
**Output:** A concrete `MIN_REFERENCE_RELEVANCE` value backed by data. Stored as a constant in the corrector module, easily tunable later.
**Timing:** Research step early in implementation, before filtering logic is finalized.
## API Changes Summary
| Endpoint | Change |
|----------|--------|
| `POST /api/review/{job_id}/search-lyrics` | **New** — search with alternate artist/title |
| `POST /api/review/{job_id}/add-lyrics` | **Modified** — add `force` flag for threshold bypass |
## Files Likely Modified
### Backend
- `karaoke_gen/lyrics_transcriber/correction/corrector.py` — relevance filtering after anchor finding
- `karaoke_gen/lyrics_transcriber/correction/anchor_sequence.py` — expose per-source word match stats
- `backend/api/routes/review.py` — new `search-lyrics` endpoint, `force` flag on `add-lyrics`
- `karaoke_gen/lyrics_transcriber/correction/operations.py` — new operation for search-and-add flow
### Frontend
- `frontend/components/lyrics-review/modals/AddLyricsModal.tsx` — tabbed redesign with Search/Paste
- `frontend/components/lyrics-review/ReferenceView.tsx` — empty state inline UI
- `frontend/lib/api.ts` — new `searchLyrics()` method
- `frontend/lib/lyrics-review/types.ts` — types for search response
## Out of Scope
- Changing which providers are used during initial job processing
- Provider-specific configuration (API keys, rate limits)
- Lyrics quality beyond relevance (e.g., formatting, completeness)
@@ -0,0 +1,135 @@
# Route render_video to GCE Encoding Worker
**Date:** 2026-03-31
**Status:** Approved
**Branch:** feat/sess-20260331-1123-video-render-routing
## Problem
The `render_video_worker` runs OutputGenerator (ffmpeg/libass video rendering) on Cloud Run. After right-sizing Cloud Run to 2Gi memory, this OOMs. The GCE encoding worker handles final encoding (`/encode`) and preview encoding (`/encode-preview`), but render_video was never routed there — it was an intentional scope limitation from the original Jan 2026 PR #164, since render_video_worker predated the GCE encoding worker.
This also explains why karaoke jobs are slower than expected: the most resource-intensive rendering step runs on a constrained Cloud Run instance instead of the dedicated high-performance GCE VM.
## Solution
Add a `/render-video` endpoint to the GCE encoding worker and route render_video through `EncodingService`, following the same pattern as `/encode` and `/encode-preview`.
## Architecture
### GCE Worker: New `/render-video` endpoint
**Request model** (`RenderVideoRequest`):
| Field | Type | Description |
|-------|------|-------------|
| `job_id` | str | Job identifier |
| `original_corrections_gcs_path` | str | `gs://` path to corrections.json |
| `updated_corrections_gcs_path` | str (optional) | `gs://` path to corrections_updated.json |
| `audio_gcs_path` | str | `gs://` path to input audio |
| `style_params_gcs_path` | str (optional) | `gs://` path to style_params.json |
| `style_assets` | dict (optional) | Map of asset key → GCS path |
| `output_gcs_prefix` | str | `gs://` prefix for outputs (e.g. `gs://bucket/jobs/{id}/`) |
| `artist` | str | Artist name |
| `title` | str | Song title |
| `subtitle_offset_ms` | int | Subtitle timing offset (default 0) |
| `video_resolution` | str | Resolution (default "4k") |
**Processing** (`run_render_video()`):
1. `ensure_latest_wheel()` — hot code updates, same as `/encode`
2. Download inputs from GCS (with disk cache for style assets)
3. Load `CorrectionResult` from original corrections
4. Apply user corrections if `updated_corrections_gcs_path` provided (via `CorrectionOperations.update_correction_result_with_data`)
5. Run `CountdownProcessor` on correction result + audio
6. Load styles via `load_styles_from_gcs`
7. Configure and run `OutputGenerator.generate_outputs()`
8. Upload outputs to GCS:
- `{output_gcs_prefix}videos/with_vocals.mkv`
- `{output_gcs_prefix}lyrics/karaoke.ass`
- `{output_gcs_prefix}lyrics/karaoke.lrc`
- `{output_gcs_prefix}lyrics/corrected.txt`
9. Return output file paths + countdown metadata in job status
**Response:** Standard `JobStatus` model, with `output_files` listing GCS blob paths and `metadata` containing:
- `countdown_padding_added` (bool)
- `countdown_padding_seconds` (float)
- `render_duration_seconds` (float)
### Style Asset Disk Cache
To avoid repeated GCS downloads of the same default theme assets across jobs:
- **Location:** `/var/cache/karaoke-gen/{fonts,backgrounds,styles}/`
- **Cache key:** SHA-256 hash of the GCS path (deterministic, changes when asset path changes)
- **Lookup:** Before downloading, check if cached file exists; skip GCS download on hit
- **Scope:** Fonts, background images, style_params.json
- **No TTL needed:** GCS paths are versioned by theme ID — when a theme's assets change, the path changes, so the cache key changes naturally
- **Startup:** Create cache directories on worker boot
This is a simple wrapper around `download_single_file_from_gcs` — a `download_with_cache(gcs_uri, local_path, cache_dir)` helper that checks the cache first.
### EncodingService: New methods
```python
async def submit_render_video_job(self, job_id, render_config) -> dict:
"""POST to /render-video, with retry logic."""
async def render_video_on_gce(self, job_id, render_config, progress_callback=None) -> dict:
"""Submit + wait convenience method (like encode_videos)."""
```
Uses the same `_request_with_retry`, `wait_for_completion`, retry/backoff, and poll failure tolerance as existing methods.
### render_video_worker: Conditional routing
```python
encoding_service = get_encoding_service()
if encoding_service.is_enabled:
# GCE path: build config from job data, delegate to GCE
render_config = RenderVideoConfig(
original_corrections_gcs_path=f"gs://{bucket}/jobs/{job_id}/lyrics/corrections.json",
updated_corrections_gcs_path=..., # if exists
audio_gcs_path=f"gs://{bucket}/{job.input_media_gcs_path}",
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
output_gcs_prefix=f"gs://{bucket}/jobs/{job_id}/",
artist=job.artist,
title=job.title,
subtitle_offset_ms=job.subtitle_offset_ms or 0,
video_resolution="4k",
)
result = await encoding_service.render_video_on_gce(job_id, render_config)
# Parse result: update file_urls, lyrics_metadata from response
else:
# Local fallback: existing OutputGenerator code (unchanged)
```
Cloud Run does zero downloads in the GCE path — it just reads job metadata from Firestore and constructs GCS paths.
### Configuration
No new env vars. Reuses `USE_GCE_ENCODING` — render_video is video work that follows the same routing decision.
## What doesn't change
- The job pipeline flow (states, transitions, triggering video_worker after)
- The local fallback path (existing code stays as-is for when GCE is disabled)
- OutputGenerator itself (same library, same wheel, same output)
- The GCE encoding worker's existing `/encode` and `/encode-preview` endpoints
## Risk: Code path divergence
Per LESSONS-LEARNED.md ("Alternative Code Paths Must Implement All Features"), both paths must produce identical output. This is inherently guaranteed because:
- Both use the same `OutputGenerator` from the karaoke-gen wheel
- Both use the same `load_styles_from_gcs` for style loading
- Both use the same `CorrectionOperations` for applying user corrections
- The GCE worker runs `ensure_latest_wheel()` to stay current
The only divergence risk is in the orchestration layer (Firestore updates, file URL construction), which stays on Cloud Run in both paths.
## Testing
- Unit tests for the new EncodingService methods (mock HTTP)
- Unit tests for render_video_worker GCE routing logic (mock encoding_service)
- Integration test: GCE worker `/render-video` endpoint with test fixtures
- E2E: existing happy-path CI test validates the full pipeline
@@ -0,0 +1,213 @@
# Service Health Status Modal — Design Spec
## Overview
Replace the static footer version/status line with a clickable element that opens a modal showing detailed system status. Non-admin users see service health, versions, and deploy info. Admin users additionally see blue-green encoder deployment details. Each service links to the PR that produced its current version.
## Footer Changes
The existing footer line (`Frontend: v0.155.3 | Backend: v0.155.3 | ● Encoder: v0.155.3 | ...`) becomes a single clickable element. On hover: `cursor: pointer`, slight opacity change. No other visual changes to the footer layout.
Clicking anywhere on the version/status line opens the modal.
## Modal — Public View (everyone)
### Layout
- Standard modal: dark backdrop (click to dismiss), X close button, title "System Status"
- Responsive card grid: 2 columns on desktop, 1 column on mobile
- 5 service cards: **Frontend**, **Backend**, **Encoder**, **Flacfetch**, **Separator**
### Card Contents
Each card shows:
| Element | Example |
|---------|---------|
| Status indicator | Green dot (●) + "Healthy" or red dot (○) + "Offline" |
| Version | `v0.155.3` |
| Deploy time | "Deployed 2 hours ago" (relative) |
| Latest change | `#644 — fix blue-green deploy` (clickable link to GitHub PR) |
The "Latest change" line links to the GitHub PR that produced the currently deployed version. If unavailable, this line is omitted.
## Modal — Admin View (additional detail)
When the user has an admin token (stored in localStorage from login), the modal request includes it and the response includes extra data.
### Encoder Blue-Green Section
Inside the Encoder card, below the standard info, an expandable section labeled "Blue-Green Deployment" shows:
- **Two side-by-side mini-cards**: Primary (green-tinted border) and Secondary (muted/grey)
- Each mini-card shows:
- VM name (e.g., `encoding-worker-b`)
- Version (e.g., `v0.155.3`)
- Role label: "PRIMARY" (green) or "SECONDARY (stopped)" (muted)
- **Deploy status line**: "Last swap: 2 hours ago" or "⚠ Deploy in progress..." (amber)
- **Active jobs**: count on primary, if > 0
### Admin Detail on Other Cards
For Backend, Flacfetch, and Separator cards, admin view additionally shows:
- Error message if status is offline (from the health check error field)
No extra admin detail needed for Frontend (it's a static site).
## New Backend Endpoint
### `GET /api/health/system-status`
Single endpoint that aggregates all service health data. Avoids the current pattern of 4 separate fetches.
**Authentication**: Optional `X-Admin-Token` header. If valid admin token, response includes `admin_details`. If omitted or invalid, those fields are absent.
**Response (public fields)**:
```json
{
"services": {
"frontend": {
"status": "ok",
"version": "0.155.3",
"deployed_at": "2026-03-31T18:10:00Z",
"commit_sha": "8e2a949a",
"pr_number": 644,
"pr_title": "fix: complete blue-green deploy test payload and status check"
},
"backend": {
"status": "ok",
"version": "0.155.3",
"deployed_at": "2026-03-31T18:10:00Z",
"commit_sha": "8e2a949a",
"pr_number": 644,
"pr_title": "fix: complete blue-green deploy test payload and status check"
},
"encoder": {
"status": "ok",
"version": "0.155.3",
"deployed_at": "2026-03-31T18:10:00Z",
"active_jobs": 0
},
"flacfetch": {
"status": "ok",
"version": "0.19.1"
},
"separator": {
"status": "ok",
"version": "0.4.3"
}
}
}
```
**Additional fields when admin token is valid**:
```json
{
"services": {
"encoder": {
"admin_details": {
"primary_vm": "encoding-worker-b",
"primary_ip": "34.10.189.118",
"primary_version": "0.155.3",
"primary_deployed_at": "2026-03-31T18:10:00Z",
"secondary_vm": "encoding-worker-a",
"secondary_ip": "34.57.78.246",
"secondary_version": "0.155.2",
"secondary_deployed_at": "2026-03-29T14:00:00Z",
"last_swap_at": "2026-03-31T18:10:00Z",
"deploy_in_progress": false,
"active_jobs": 0,
"queue_length": 0
}
},
"flacfetch": {
"admin_details": {
"error": null
}
},
"separator": {
"admin_details": {
"error": null
}
}
}
}
```
## Build Metadata — Git SHA and PR Info
Currently no git metadata is baked into builds. We need to add this.
### CI Changes (`.github/workflows/ci.yml`)
Add a step early in the deploy job that captures git info:
```yaml
- name: Capture build metadata
id: build-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
# For merge commits, extract PR number from commit message
PR_NUM=$(git log -1 --format=%s | grep -oP '#\K[0-9]+' | head -1)
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
```
### Where metadata is stored
| Service | Storage mechanism |
|---------|------------------|
| **Frontend** | New env vars `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE`, `NEXT_PUBLIC_BUILD_TIME` set in CI before `npm run build`. Baked into the static bundle at build time via `next.config.mjs`. The `deployed_at` for frontend is the build timestamp (close enough to deploy time for Cloudflare Pages). |
| **Backend** | New env vars `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` set on the Cloud Run service. Read at runtime in `backend/version.py`. |
| **Encoder** | Written to GCS version manifest alongside the existing `version.txt`. The GCE worker reads it on startup and includes in `/health` response. |
| **Flacfetch / Separator** | These are separate repos with their own CI. PR info can be added later — for now, omit the "Latest change" line for these services. |
### GitHub PR Link Format
The frontend constructs the PR link as:
```
https://github.com/nomadkaraoke/karaoke-gen/pull/{pr_number}
```
Displayed as: `#{pr_number} — {pr_title}` (truncated to ~60 chars if needed).
## Frontend Components
### New files
- `frontend/components/system-status-modal.tsx` — the modal component
### Modified files
- `frontend/components/version-footer.tsx` — make status line clickable, add modal toggle state
- `frontend/lib/api.ts` — add `SystemStatus` types and `getSystemStatus()` method
- `frontend/next.config.mjs` — pass through new `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE` env vars
### Modified backend files
- `backend/api/routes/health.py` — new `/api/health/system-status` endpoint
- `backend/version.py` — read `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` env vars
- `.github/workflows/ci.yml` — capture build metadata, pass to builds/deploys
### Data Flow
1. User clicks footer → modal opens, state set to loading
2. Modal calls `GET /api/health/system-status` (with admin token header if available in localStorage)
3. Endpoint aggregates: existing health checks + Firestore blue-green config + build metadata env vars
4. Frontend renders cards from response
5. No auto-refresh — data is fresh on each open
## Styling
- Follow existing project design patterns (Tailwind, CSS variables for theming)
- Modal uses the same dark theme as the rest of the app
- Cards use `var(--card-border)`, `var(--card-bg)` etc. for consistency
- Green: `text-green-500` for healthy, red: `text-red-500` for offline
- Blue-green section uses amber accent (`text-amber-500`, `border-amber-500/30`) to distinguish it as an operational detail
## Out of Scope
- Auto-refresh / polling in the modal (can be added later)
- Flacfetch and Separator PR info (separate repos, separate CI)
- Historical deploy data or deploy log
- Notifications or alerts for status changes
+39 -186
View File
@@ -2,7 +2,7 @@
* Unit tests for job-status.ts utility functions
*/
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, getDisplayJobs, JobStep } from '../lib/job-status';
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, JobStep } from '../lib/job-status';
import type { Job } from '../lib/api';
// Helper to create a minimal Job object for testing
@@ -24,7 +24,7 @@ describe('getJobStep', () => {
const result = getJobStep(job);
expect(result.step).toBe(1);
expect(result.total).toBe(10);
expect(result.label).toBe('Setting up');
expect(result.label).toBe('settingUp');
expect(result.isBlocking).toBe(false);
expect(result.color).toBe('text-muted-foreground');
});
@@ -35,7 +35,7 @@ describe('getJobStep', () => {
const job = createJob('searching_audio');
const result = getJobStep(job);
expect(result.step).toBe(2);
expect(result.label).toBe('Searching for audio');
expect(result.label).toBe('searchingForAudio');
expect(result.isBlocking).toBe(false);
});
@@ -43,7 +43,7 @@ describe('getJobStep', () => {
const job = createJob('awaiting_audio_selection');
const result = getJobStep(job);
expect(result.step).toBe(2);
expect(result.label).toBe('Select audio source');
expect(result.label).toBe('selectAudioSource');
expect(result.isBlocking).toBe(true);
expect(result.color).toBe('text-amber-400');
});
@@ -54,21 +54,21 @@ describe('getJobStep', () => {
const job = createJob('downloading_audio');
const result = getJobStep(job);
expect(result.step).toBe(3);
expect(result.label).toBe('Downloading audio');
expect(result.label).toBe('downloadingAudio');
});
it('returns step 3 for downloading status without worker progress', () => {
const job = createJob('downloading');
const result = getJobStep(job);
expect(result.step).toBe(3);
expect(result.label).toBe('Downloading');
expect(result.label).toBe('downloading');
});
it('returns step 3 for downloading with empty state_data', () => {
const job = createJob('downloading', {});
const result = getJobStep(job);
expect(result.step).toBe(3);
expect(result.label).toBe('Downloading');
expect(result.label).toBe('downloading');
});
});
@@ -101,7 +101,7 @@ describe('getJobStep', () => {
});
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toMatch(/Audio.*\+.*Transcribing|Transcribing.*\+.*Audio/);
expect(result.label).toMatch(/audio.*\+.*transcribing|transcribing.*\+.*audio/);
});
it('shows only active worker when one is complete', () => {
@@ -112,7 +112,7 @@ describe('getJobStep', () => {
});
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toBe('Transcribing');
expect(result.label).toBe('transcribing');
});
it('shows processing complete when both workers done', () => {
@@ -124,7 +124,7 @@ describe('getJobStep', () => {
});
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toBe('Processing complete');
expect(result.label).toBe('processingComplete');
});
it('returns step 3 when state_data has no stage info', () => {
@@ -135,7 +135,7 @@ describe('getJobStep', () => {
});
const result = getJobStep(job);
expect(result.step).toBe(3);
expect(result.label).toBe('Downloading');
expect(result.label).toBe('downloading');
});
});
@@ -144,28 +144,28 @@ describe('getJobStep', () => {
const job = createJob('separating_stage1');
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toBe('Separating audio (1/2)');
expect(result.label).toBe('separatingAudio1');
});
it('returns step 4 for separating_stage2', () => {
const job = createJob('separating_stage2');
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toBe('Separating audio (2/2)');
expect(result.label).toBe('separatingAudio2');
});
it('returns step 4 for transcribing', () => {
const job = createJob('transcribing');
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toBe('Transcribing lyrics');
expect(result.label).toBe('transcribingLyrics');
});
it('returns step 4 for correcting', () => {
const job = createJob('correcting');
const result = getJobStep(job);
expect(result.step).toBe(4);
expect(result.label).toBe('Correcting lyrics');
expect(result.label).toBe('correctingLyrics');
});
it('shows combined progress when both audio and lyrics are in progress', () => {
@@ -176,7 +176,7 @@ describe('getJobStep', () => {
const result = getJobStep(job);
expect(result.step).toBe(4);
// Should show combined label
expect(result.label).toMatch(/Audio|Transcribing/);
expect(result.label).toMatch(/audio|transcribing/);
});
it('shows combined status when audio done but lyrics in progress', () => {
@@ -195,14 +195,14 @@ describe('getJobStep', () => {
const job = createJob('generating_screens');
const result = getJobStep(job);
expect(result.step).toBe(5);
expect(result.label).toBe('Generating screens');
expect(result.label).toBe('generatingScreens');
});
it('returns step 5 for applying_padding', () => {
const job = createJob('applying_padding');
const result = getJobStep(job);
expect(result.step).toBe(5);
expect(result.label).toBe('Syncing countdown');
expect(result.label).toBe('syncingCountdown');
});
});
@@ -211,7 +211,7 @@ describe('getJobStep', () => {
const job = createJob('awaiting_review');
const result = getJobStep(job);
expect(result.step).toBe(6);
expect(result.label).toBe('Review lyrics');
expect(result.label).toBe('reviewLyrics');
expect(result.isBlocking).toBe(true);
expect(result.color).toBe('text-amber-400');
});
@@ -220,7 +220,7 @@ describe('getJobStep', () => {
const job = createJob('in_review');
const result = getJobStep(job);
expect(result.step).toBe(6);
expect(result.label).toBe('In review');
expect(result.label).toBe('inReview');
expect(result.isBlocking).toBe(true);
});
});
@@ -230,14 +230,14 @@ describe('getJobStep', () => {
const job = createJob('review_complete');
const result = getJobStep(job);
expect(result.step).toBe(7);
expect(result.label).toBe('Starting render');
expect(result.label).toBe('startingRender');
});
it('returns step 7 for rendering_video', () => {
const job = createJob('rendering_video');
const result = getJobStep(job);
expect(result.step).toBe(7);
expect(result.label).toBe('Rendering video');
expect(result.label).toBe('renderingVideo');
});
});
@@ -246,7 +246,7 @@ describe('getJobStep', () => {
const job = createJob('awaiting_instrumental_selection');
const result = getJobStep(job);
expect(result.step).toBe(8);
expect(result.label).toBe('Select instrumental');
expect(result.label).toBe('selectInstrumental');
expect(result.isBlocking).toBe(true);
expect(result.color).toBe('text-amber-400');
});
@@ -257,28 +257,28 @@ describe('getJobStep', () => {
const job = createJob('instrumental_selected');
const result = getJobStep(job);
expect(result.step).toBe(9);
expect(result.label).toBe('Starting final encode');
expect(result.label).toBe('startingFinalEncode');
});
it('returns step 9 for generating_video', () => {
const job = createJob('generating_video');
const result = getJobStep(job);
expect(result.step).toBe(9);
expect(result.label).toBe('Generating final video');
expect(result.label).toBe('generatingFinalVideo');
});
it('returns step 9 for encoding', () => {
const job = createJob('encoding');
const result = getJobStep(job);
expect(result.step).toBe(9);
expect(result.label).toBe('Encoding video');
expect(result.label).toBe('encodingVideo');
});
it('returns step 9 for packaging', () => {
const job = createJob('packaging');
const result = getJobStep(job);
expect(result.step).toBe(9);
expect(result.label).toBe('Packaging files');
expect(result.label).toBe('packagingFiles');
});
});
@@ -287,7 +287,7 @@ describe('getJobStep', () => {
const job = createJob('uploading');
const result = getJobStep(job);
expect(result.step).toBe(10);
expect(result.label).toBe('Uploading');
expect(result.label).toBe('uploading');
expect(result.color).toBe('text-green-400');
});
@@ -295,14 +295,14 @@ describe('getJobStep', () => {
const job = createJob('notifying');
const result = getJobStep(job);
expect(result.step).toBe(10);
expect(result.label).toBe('Sending notifications');
expect(result.label).toBe('sendingNotifications');
});
it('returns step 10 for complete', () => {
const job = createJob('complete');
const result = getJobStep(job);
expect(result.step).toBe(10);
expect(result.label).toBe('Complete');
expect(result.label).toBe('complete');
expect(result.color).toBe('text-green-400');
});
@@ -310,7 +310,7 @@ describe('getJobStep', () => {
const job = createJob('prep_complete');
const result = getJobStep(job);
expect(result.step).toBe(10);
expect(result.label).toBe('Prep complete');
expect(result.label).toBe('prepComplete');
});
});
@@ -319,7 +319,7 @@ describe('getJobStep', () => {
const job = createJob('failed');
const result = getJobStep(job);
expect(result.step).toBe(0);
expect(result.label).toBe('Failed');
expect(result.label).toBe('failed');
expect(result.color).toBe('text-red-400');
});
@@ -327,7 +327,7 @@ describe('getJobStep', () => {
const job = createJob('cancelled');
const result = getJobStep(job);
expect(result.step).toBe(0);
expect(result.label).toBe('Cancelled');
expect(result.label).toBe('cancelled');
expect(result.color).toBe('text-muted-foreground');
});
});
@@ -372,19 +372,19 @@ describe('getJobStep', () => {
describe('formatStepIndicator', () => {
it('formats active step correctly', () => {
expect(formatStepIndicator(4, 10, 'Processing')).toBe('[4/10] Processing');
expect(formatStepIndicator(4, 10, 'processing')).toBe('[4/10] processing');
});
it('omits step number for terminal states (step 0)', () => {
expect(formatStepIndicator(0, 10, 'Failed')).toBe('Failed');
expect(formatStepIndicator(0, 10, 'failed')).toBe('failed');
});
it('formats first step correctly', () => {
expect(formatStepIndicator(1, 10, 'Setting up')).toBe('[1/10] Setting up');
expect(formatStepIndicator(1, 10, 'settingUp')).toBe('[1/10] settingUp');
});
it('formats last step correctly', () => {
expect(formatStepIndicator(10, 10, 'Complete')).toBe('[10/10] Complete');
expect(formatStepIndicator(10, 10, 'complete')).toBe('[10/10] complete');
});
});
@@ -556,152 +556,5 @@ describe('sortJobsByDate', () => {
});
});
describe('getDisplayJobs', () => {
// Helper: create jobs sorted by date (newest first)
function createDateSortedJobs(jobSpecs: Array<{ status: string; date: string }>): Job[] {
return jobSpecs
.map((spec, i) => ({
job_id: `job-${i}`,
status: spec.status,
progress: spec.status === 'complete' ? 100 : 0,
created_at: spec.date,
updated_at: spec.date,
}))
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
}
it('returns all jobs when fewer than display limit', () => {
const jobs = createDateSortedJobs([
{ status: 'complete', date: '2024-01-01T10:00:00Z' },
{ status: 'complete', date: '2024-01-01T11:00:00Z' },
{ status: 'complete', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(3);
expect(totalFetched).toBe(3);
});
it('returns empty array for empty input', () => {
const { displayedJobs, totalFetched } = getDisplayJobs([], 5);
expect(displayedJobs).toHaveLength(0);
expect(totalFetched).toBe(0);
});
it('limits to displayLimit', () => {
const jobs = createDateSortedJobs(
Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
expect(displayedJobs).toHaveLength(5);
expect(totalFetched).toBe(10);
});
it('returns all jobs when displayLimit is -1 (All mode)', () => {
const jobs = createDateSortedJobs(
Array.from({ length: 22 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1);
expect(displayedJobs).toHaveLength(22);
expect(totalFetched).toBe(22);
});
it('preserves date sort order from input', () => {
const jobs = createDateSortedJobs([
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
{ status: 'failed', date: '2024-01-04T12:00:00Z' },
{ status: 'awaiting_review', date: '2024-01-02T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, 10);
// Should be newest first
expect(displayedJobs[0].created_at).toBe('2024-01-05T12:00:00Z');
expect(displayedJobs[1].created_at).toBe('2024-01-04T12:00:00Z');
expect(displayedJobs[2].created_at).toBe('2024-01-03T12:00:00Z');
expect(displayedJobs[3].created_at).toBe('2024-01-02T12:00:00Z');
});
describe('hideCompleted filter', () => {
it('filters out only complete and prep_complete when hideCompleted is true (keeps failed)', () => {
const jobs = createDateSortedJobs([
{ status: 'awaiting_review', date: '2024-01-05T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
{ status: 'failed', date: '2024-01-02T12:00:00Z' },
{ status: 'prep_complete', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1, true);
expect(totalFetched).toBe(5);
expect(displayedJobs).toHaveLength(3); // blocking + processing + failed
expect(displayedJobs.some(j => j.status === 'failed')).toBe(true);
expect(displayedJobs.some(j => j.status === 'complete')).toBe(false);
expect(displayedJobs.some(j => j.status === 'prep_complete')).toBe(false);
});
it('respects display limit after filtering', () => {
const jobs = createDateSortedJobs([
{ status: 'rendering_video', date: '2024-01-10T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-09T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-08T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-07T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-06T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
...Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T10:00:00Z` })),
]);
const { displayedJobs } = getDisplayJobs(jobs, 5, true);
// 7 non-complete jobs after filtering, but limit is 5
expect(displayedJobs).toHaveLength(5);
});
it('returns empty when all jobs are complete and hideCompleted is true', () => {
const jobs = createDateSortedJobs(
Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
);
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5, true);
expect(displayedJobs).toHaveLength(0);
expect(totalFetched).toBe(10);
});
it('does not filter when hideCompleted is false', () => {
const jobs = createDateSortedJobs([
{ status: 'awaiting_review', date: '2024-01-04T12:00:00Z' },
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, -1, false);
expect(displayedJobs).toHaveLength(4);
});
it('defaults to showing all when hideCompleted is omitted', () => {
const jobs = createDateSortedJobs([
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
]);
const { displayedJobs } = getDisplayJobs(jobs, -1);
expect(displayedJobs).toHaveLength(2);
});
});
it('core bug fix: recently failed job appears at top of list', () => {
// The original bug: a newly failed job was invisible because priority sorting
// put all 45 complete jobs above it, and the limit of 10 truncated it.
// With date-based sorting, the newest job (failed) appears first.
const jobs = sortJobsByDate([
{ job_id: 'new-failed', status: 'failed', progress: 0, created_at: '2024-01-10T15:00:00Z', updated_at: '2024-01-10T15:00:00Z' },
...Array.from({ length: 45 }, (_, i) => ({
job_id: `complete-${i}`,
status: 'complete',
progress: 100,
created_at: `2024-01-${String(10 - Math.floor(i / 5)).padStart(2, '0')}T${String(12 - (i % 5)).padStart(2, '0')}:00:00Z`,
updated_at: '2024-01-01T00:00:00Z',
})),
]);
const { displayedJobs } = getDisplayJobs(jobs, 10);
// The failed job should be first (newest)
expect(displayedJobs[0].job_id).toBe('new-failed');
expect(displayedJobs[0].status).toBe('failed');
expect(displayedJobs).toHaveLength(10);
});
});
// Note: getDisplayJobs was removed — filtering is now handled server-side
// via the status and search query parameters on GET /api/jobs
@@ -0,0 +1,446 @@
"use client"
import { useEffect, useState, useCallback } from "react"
import { useAuth } from "@/lib/auth"
import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/api"
import { Spinner } from "@/components/ui/spinner"
import { Button } from "@/components/ui/button"
import { ArrowLeft, AlertCircle } from "lucide-react"
import Link from "next/link"
import { LyricsAnalyzer } from "@/components/lyrics-review"
import { InstrumentalSelector } from "@/components/instrumental-review"
import { AudioEditor } from "@/components/audio-editor/AudioEditor"
import { ThemeToggle } from "@/components/ThemeToggle"
import type { CorrectionData } from "@/lib/lyrics-review/types"
import { isLocalMode, createLocalModeJob } from "@/lib/local-mode"
type RouteType = "review" | "instrumental" | "audio-edit" | "unknown"
type AccessState =
| { status: "loading" }
| { status: "not_authenticated" }
| { status: "not_authorized"; reason: string }
| { status: "job_not_found" }
| { status: "wrong_state"; currentState: string; expectedStates: string[] }
| { status: "invalid_route" }
| { status: "authorized"; job: Job; routeType: RouteType }
| { status: "local_mode"; job: Job; routeType: RouteType }
// Parse route from window.location.pathname (used for local mode with path-based routing)
// For static exports, useParams() returns empty - we must parse the URL directly
function parseRouteFromPathname(pathname: string): { jobId: string | null; routeType: RouteType } {
if (!pathname) {
return { jobId: null, routeType: "unknown" }
}
// Expected format: /app/jobs/{jobId}/{action}
// e.g., /app/jobs/local/review or /app/jobs/local/instrumental
const match = pathname.match(/^\/app\/jobs\/([^/]+)\/(review|instrumental|audio-edit)\/?$/)
if (match) {
const [, jobId, action] = match
return { jobId, routeType: action as RouteType }
}
return { jobId: null, routeType: "unknown" }
}
// Parse route from URL hash (used for cloud mode)
// Expected format: #/{jobId}/review or #/{jobId}/instrumental
function parseRouteFromHash(hash: string): { jobId: string | null; routeType: RouteType } {
if (!hash || hash.length <= 1) {
return { jobId: null, routeType: "unknown" }
}
// Remove the leading '#' and parse
const hashPath = hash.substring(1)
// Support BOTH review and instrumental routes
const match = hashPath.match(/^\/?([^/]+)\/(review|instrumental|audio-edit)\/?$/)
if (match) {
const [, jobId, action] = match
return { jobId, routeType: action as RouteType }
}
return { jobId: null, routeType: "unknown" }
}
function getExpectedStates(routeType: RouteType): string[] {
switch (routeType) {
case "review":
return ["awaiting_review", "in_review"]
case "instrumental":
return ["awaiting_review", "in_review"] // Same states for now
case "audio-edit":
return ["awaiting_audio_edit", "in_audio_edit"]
default:
return []
}
}
export function JobRouterClient() {
// For static exports, useParams() returns empty object
// We need to parse the URL path directly instead
const [pathname, setPathname] = useState(() =>
typeof window !== 'undefined' ? window.location.pathname : ''
)
// Track hash for re-renders when hash changes (cloud mode)
const [hash, setHash] = useState(() =>
typeof window !== 'undefined' ? window.location.hash : ''
)
// Listen for hash changes
useEffect(() => {
const handleHashChange = () => {
setHash(window.location.hash)
}
window.addEventListener('hashchange', handleHashChange)
return () => window.removeEventListener('hashchange', handleHashChange)
}, [])
// Update pathname on mount (needed for SSR hydration)
useEffect(() => {
setPathname(window.location.pathname)
}, [])
// Determine routing mode and parse route
// - Local mode: Use path-based routing parsed from window.location.pathname
// - Cloud mode: Use hash-based routing (e.g., /app/jobs/#/{jobId}/review)
const inLocalMode = isLocalMode()
const { jobId, routeType } = inLocalMode
? parseRouteFromPathname(pathname)
: parseRouteFromHash(hash)
const { user, isLoading: authLoading, hasHydrated } = useAuth()
const [accessState, setAccessState] = useState<AccessState>({ status: "loading" })
useEffect(() => {
async function checkAccess() {
// Handle local mode (skip all auth checks)
if (inLocalMode) {
// In local mode, always use review (combined lyrics + instrumental)
const localRouteType: RouteType = routeType === "unknown" ? "review" : routeType
// Create mock job for local mode
const localJob = createLocalModeJob({ routeType: localRouteType }) as Job
setAccessState({ status: "local_mode", job: localJob, routeType: localRouteType })
return
}
// Cloud mode: Check hash-based route
if (!jobId || routeType === "unknown") {
setAccessState({ status: "invalid_route" })
return
}
// Wait for auth to finish loading and hydration to complete
// This prevents a flash of "Sign in required" before auth state is restored from localStorage
if (authLoading || !hasHydrated) return
// Must be authenticated
if (!user) {
setAccessState({ status: "not_authenticated" })
return
}
try {
// Fetch job details
const job = await api.getJob(jobId)
// Check ownership: user must own the job or be admin
const isOwner = job.user_email === user.email
const isAdmin = user.role === "admin"
if (!isOwner && !isAdmin) {
setAccessState({
status: "not_authorized",
reason: "You don't have permission to access this job"
})
return
}
// Check job is in correct state
const expectedStates = getExpectedStates(routeType)
if (!expectedStates.includes(job.status)) {
setAccessState({
status: "wrong_state",
currentState: job.status,
expectedStates
})
return
}
// All checks passed
setAccessState({ status: "authorized", job, routeType })
} catch (error: unknown) {
// Job not found or API error
if (error && typeof error === "object" && "status" in error && error.status === 404) {
setAccessState({ status: "job_not_found" })
} else {
setAccessState({
status: "not_authorized",
reason: "Failed to load job details"
})
}
}
}
checkAccess()
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated])
// Loading state
if (accessState.status === "loading") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<Spinner className="w-8 h-8 mx-auto mb-4" />
<p className="text-muted-foreground">Loading...</p>
</div>
</div>
)
}
// Invalid route
if (accessState.status === "invalid_route") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Page not found</h1>
<p className="text-muted-foreground mb-4">
The page you&apos;re looking for doesn&apos;t exist.
</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Not authenticated
if (accessState.status === "not_authenticated") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-amber-500" />
<h1 className="text-xl font-semibold mb-2">Sign in required</h1>
<p className="text-muted-foreground mb-4">
You need to sign in to access this page.
</p>
<Button asChild>
<Link href="/app">Sign in</Link>
</Button>
</div>
</div>
)
}
// Not authorized
if (accessState.status === "not_authorized") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Access denied</h1>
<p className="text-muted-foreground mb-4">{accessState.reason}</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Job not found
if (accessState.status === "job_not_found") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Job not found</h1>
<p className="text-muted-foreground mb-4">
The job you&apos;re looking for doesn&apos;t exist or has been deleted.
</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Wrong state
if (accessState.status === "wrong_state") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-amber-500" />
<h1 className="text-xl font-semibold mb-2">Not available</h1>
<p className="text-muted-foreground mb-4">
This job is currently in &quot;{accessState.currentState}&quot; state and is not ready for review.
</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Authorized or local mode - render the appropriate UI
const { job } = accessState
// Get route type from access state (which validated and stored it during checkAccess)
const currentRouteType = accessState.status === "authorized" || accessState.status === "local_mode"
? accessState.routeType
: "review" // Fallback (shouldn't happen since we return early for other statuses)
if (currentRouteType === "audio-edit") {
return <AudioEditor job={job} />
}
if (currentRouteType === "instrumental") {
return <InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
}
return <LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
}
// Lyrics Review Component Wrapper
function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
const [correctionData, setCorrectionData] = useState<CorrectionData | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// Create the API client for this job
const apiClient = createLyricsReviewApiClient(job.job_id)
// Load correction data
useEffect(() => {
async function loadData() {
try {
setIsLoading(true)
setError(null)
const data = await lyricsReviewApi.getCorrectionData(job.job_id)
setCorrectionData(data)
} catch (err) {
console.error("Failed to load correction data:", err)
setError(err instanceof Error ? err.message : "Failed to load lyrics data")
} finally {
setIsLoading(false)
}
}
loadData()
}, [job.job_id])
// File load handler (opens file picker for local file)
const handleFileLoad = useCallback(() => {
// For now, this is a no-op since we load from API
// Could be extended to allow loading from local files
console.log("File load requested")
}, [])
// Metadata handler
const handleShowMetadata = useCallback(() => {
// Could show a modal with job metadata
console.log("Show metadata requested", job)
}, [job])
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<Spinner className="w-8 h-8 mx-auto mb-4" />
<p className="text-muted-foreground">Loading lyrics data...</p>
</div>
</div>
)
}
if (error || !correctionData) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Failed to load lyrics</h1>
<p className="text-muted-foreground mb-4">
{error || "Could not load lyrics data for this job."}
</p>
{!isLocalMode && (
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
)}
</div>
</div>
)
}
return (
<div className="min-h-screen bg-background">
{/* App Header - matches old frontend's AppHeader */}
<header className="border-b bg-card/80 backdrop-blur-sm sticky top-0 z-50 px-4 py-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{!isLocalMode && (
<Button variant="ghost" size="sm" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back
</Link>
</Button>
)}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/nomad-karaoke-logo.svg"
alt="Nomad Karaoke"
style={{ height: 40 }}
/>
<h1 className="text-lg font-bold">Lyrics Transcription Review</h1>
</div>
<ThemeToggle />
</div>
</header>
<main className="px-4 py-2">
<LyricsAnalyzer
data={correctionData}
onFileLoad={handleFileLoad}
onShowMetadata={handleShowMetadata}
apiClient={apiClient}
isReadOnly={false}
audioHash={correctionData.metadata?.audio_hash || job.audio_hash || job.job_id}
isLocalMode={isLocalMode}
jobId={job.job_id}
hasExistingInstrumental={!!job.existing_instrumental_gcs_path}
/>
</main>
</div>
)
}
// Instrumental Review Component Wrapper
// The InstrumentalSelector component handles its own data fetching and submission
// It uses the appropriate API based on isLocalMode
function InstrumentalReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
return (
<InstrumentalSelector job={job} isLocalMode={isLocalMode} />
)
}
@@ -0,0 +1,16 @@
import { JobRouterClient } from "./client"
// Required for static export with catch-all routes
// Returns params array for paths to pre-render at build time
export async function generateStaticParams(): Promise<{ slug?: string[] }[]> {
return [
{ slug: undefined }, // /app/jobs/
// Local mode paths - pre-rendered for karaoke-gen CLI local review
{ slug: ['local', 'review'] }, // /app/jobs/local/review
{ slug: ['local', 'instrumental'] }, // /app/jobs/local/instrumental
]
}
export default function JobsPage() {
return <JobRouterClient />
}
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff. Show more