Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 5.5 bdca8f5542 fix(gemini): pin vertexai=False on the agentic ChatGoogleGenerativeAI model
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:47:28 -04:00
Andrew BeveridgeandClaude Opus 5.5 b9f9c90c6d fix(gemini): pin vertexai=False on the Developer API client
google-genai selects Vertex AI when GOOGLE_GENAI_USE_VERTEXAI is set and
vertexai is omitted, even with an api_key. Pin it explicitly.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:26:57 -04:00
Andrew BeveridgeandClaude Opus 5.5 b8c6c6d796 fix(gemini): address review — classifier and degradation hardening
- Classifier follows only explicit __cause__ chains (no implicit
  __context__), and per-day quotas count as exhausted even with a retry
  delay.
- credit eval: classify only the Gemini call, not Firestore errors.
- Quota alert I/O runs on a daemon thread (never blocks the event loop) and
  re-arms if the Discord send fails.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:26:57 -04:00
Andrew BeveridgeandClaude Opus 5.5 50b3b7db8e chore(gemini): move every Gemini call from Vertex AI to the Gemini Developer API
Eliminates AI spend in the nomadkaraoke GCP project: all Gemini calls now use
the Gemini Developer API with the gemini-api-key secret instead of Vertex AI.

- backend/services/gemini_client.py: get_genai_client(timeout_ms) (key from
  GEMINI_API_KEY env, else Secret Manager via settings.get_secret),
  is_quota_or_billing_error(), note_gemini_failure() which logs and sends a
  Discord ops alert at most once per 6h (Firestore-throttled across
  instances via new ops_alerts.send_throttled_ops_alert).
- Migrated callers: auto-correct (quota -> non-retryable, compare mode keeps
  Opus), credit eval (pending_review), lyrics translation (no retry, render
  without translation), parse-titles / match-judge / free-text / tenant bulk
  (existing non-LLM fallbacks), custom lyrics (clean 503 + 5-min timeout),
  error-monitor LLM (no retry; alerts sent without AI summary), agentic
  LangChain provider (gemini/ via ChatGoogleGenerativeAI with api key, no
  project).
- frontend/scripts/translate.py + gemini_client.py: env key else gcloud
  secrets access (in-process only); exit 2 with a clear message on
  quota/credit/key errors.
- Per-minute 429 rate limits stay transient/retryable.
- CI: GEMINI_API_KEY=gemini-api-key:latest in backend --set-secrets.
- Pulumi: GEMINI_API_KEY secret env on lyrics-transcription, video-encoding
  and error-monitor jobs (already applied); drop roles/aiplatform.user from
  karaoke-backend (to be applied after deploy).
- Version 0.261.1 -> 0.262.0; docs updated.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:26:57 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 49464e8fcc chore(cost): GCP cost cuts round 2 (v0.261.4) (#1107)
Round 2 of the GCP cost cuts, approved by Andrew. Target: the whole
project under $300/mo; the current run-rate is about $400.

## Changes
- **karaoke-backend min-instances 1 → 0** (`ci.yml`), about $24/mo. The
backend Cloud Run service isn't defined in Pulumi, so the CI flag is the
only place this is set. Andrew accepts a ~15s cold start. The 60s
`/api/health` uptime check and the `*/10` schedulers keep an instance
warm most of the time. With `--cpu-throttling` (request-based billing),
a warm instance above the minimum costs nothing while idle.
- **audio-separator Cloud Run GPU service shut down** (us-east4), about
$22/mo. It is now behind the Pulumi flag `audioSeparatorServiceEnabled`,
off by default. The service, SA, IAM bindings, output bucket and AR repo
were already removed with a targeted `pulumi up`; the bucket needed the
break-glass SA. `audio-separation-job` is untouched; it uses
`karaoke-backend-gpu/karaoke-backend`. The separator health check no
longer depends on `AUDIO_SEPARATOR_API_URL`, which also fixes a status
card that always showed "offline". The CLI now logs a clear hint when
the remote API fails. Companion PR:
nomadkaraoke/python-audio-separator#309 makes its Cloud Run deploy
manual-only.
- **backup-to-aws no longer copies job files to S3**, about $15/mo
egress. Job files now rely on GCS versioning plus soft-delete.
Firestore, secrets, BigQuery, kn-data and git-bundle backups are
unchanged. The freshness monitor no longer checks `gcs/job-files/`, and
DISASTER-RECOVERY.md is updated.
- **Artifact Registry cleanup policies**, about $8–10/mo. Per package:
keep the 10 most recent versions plus anything tagged `latest`,
`content-` or `cache`; delete all other versions older than 7d. Until
now, tagged per-commit images were never deleted. Dropped the CI
fallback that copied the GPU base once from us-east4, and deleted the
legacy 13 GB us-east4 GPU base package.
- Docs: GCP-COST-OPTIMIZATION.md (new section, including how to redeploy
the separator on demand), ARCHITECTURE.md, DISASTER-RECOVERY.md.

Changes made outside Pulumi (gcf-artifacts cleanup policy, destroying
superseded secret versions) are recorded in GCP-COST-OPTIMIZATION.md.

## Tests
- `backend/tests/test_system_status_endpoint.py` (new separator status
tests)
- `infrastructure/functions/backup_to_aws` (49 tests, including a new
one that checks job files aren't synced)
- `tests/unit/test_audio_remote.py`, `test_audio_processor_local_gpu.py`

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

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

## Summary by CodeRabbit

* **Service Availability**
* The hosted audio-separation service is no longer available. Audio
separation can run locally; users relying on the hosted service will
need another deployment.
* **Backup and Recovery**
* New job files are no longer copied to off-site S3 backups. S3 recovery
is limited to files backed up through September 30, 2026; newer outputs
may need to be regenerated.
* **System Status**
* Audio-separator health status now reports the locally installed
package version without checking a remote service.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:22:49 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 e4dc50d9e3 fix(ci): sanitize PR title in deploy env vars (v0.261.3) (#1109)
The v0.261.2 main deploy (run 36945703908) failed at **Deploy to Cloud
Run (candidate revision)** with:

`argument --set-env-vars: Bad syntax for dict arg`

The #1106 PR title contained a comma, and `PR_TITLE` is spliced into the
comma-delimited `--set-env-vars`. The bug was already there and that
title was the first to trigger it. Its Cloud Build step succeeded.

Fix: in both build-meta steps, commas become `;`, and newlines and
shell-active characters (`\" \` $ \\`) are removed. Version bumped to
0.261.3.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 20:50:43 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 dd795c66a0 ci(cost): build backend images in Cloud Build, run deploy-backend on ubuntu-latest (#1106)
## Summary
Retires the self-hosted `gha-build-*` runner VMs (e2-standard-8,
`docker-build` label, ~$21/mo). `deploy-backend` now runs on free
`ubuntu-latest`; the Docker images are built by **Cloud Build in
us-central1**.

## Why not build on the hosted runner? (egress math)
The app images are built `FROM` bases in us-central1 Artifact Registry,
and the app layer has a `RUN pip install`, so the full base must be
pulled each deploy:
- CPU base `karaoke-backend-base`: **4.22 GB** compressed
- GPU base `karaoke-backend-gpu-base`: **13.1 GB** compressed
- ~120 main deploys/month (119 in Sept, 11 so far today)

On a GitHub-hosted runner that is GCP internet egress: 17.3 GB × 120 ×
$0.12/GB ≈ **$250/mo** (CPU-only would still be ≈ $61/mo). Both are
worse than the $21 VM.

Cloud Build in us-central1 pulls same-region (free). Build-minutes on
the default-pool e2-standard-2 machine are in the **2,500 min/month free
tier** ($0.006/min after that). A test build of the real images (CPU and
GPU in parallel) took **6m55s**, about the same as today's ~7.3 min of
sequential builds on the VM. That's ~840 min/mo, so the expected cost is
~$0 (worst case ~$5/mo).

## Changes
- `infrastructure/cloudbuild/backend-images.yaml` +
`build-backend-images.sh`: buildx (docker-container) builds with the
**same tags and registry caches** as before. CPU and GPU build as
parallel steps, and each build gets a fresh metadata-server token.
- `ci.yml` `deploy-backend`: `runs-on: ubuntu-latest`. It keeps the hash
checks (manifest + ~10 KB config blob only) and submits `gcloud builds
submit --async`, then streams the logs and checks the status.
- Base rebuilds (≈ monthly) use e2-highcpu-8 with 300 GB disk and a 2 h
timeout.
- A Cloud Build still running when the job is cancelled or fails is
cancelled. CI concurrency cancels superseded deploys, and an orphaned
build would otherwise still push `:latest`.
- Removed the disk-space step, the local base pull, and the one-time
us-east4→us-central1 GPU-base copy. The copy finished 2026-09-26, and on
a hosted runner it would stream 13 GB through egress.
- `build-runner-images.yml`: `variants=all` no longer bakes the unused
`build` family. It can still be built with an explicit `variants=build`.
- Docs: EPHEMERAL-GHA-RUNNERS, SELF-HOSTED-RUNNERS,
GCP-COST-OPTIMIZATION.

No Pulumi or IAM changes were needed. `github-actions-deployer` already
has `cloudbuild.builds.editor`, `storage.admin` and
`iam.serviceAccountUser`, and the default Cloud Build SA (compute
default) already has `artifactregistry.writer` on both repos.

## Rollback (one commit)
`git revert <squash-merge sha of this PR>` and push to main. That
restores `runs-on: [self-hosted, linux, gcp, docker-build]` and the old
in-job buildx steps. Nothing outside the repo was changed: the
runner-manager `build` family is untouched, and the `gha-runner-build`
GCE images (20260812, 20260901) are kept so the dispatcher can still
launch `gha-build-*` VMs. If the build image has been pruned by then,
re-bake it with Actions → Build GHA Runner Images → `variants=build`
(only `variants=all` no longer includes it).

## Testing
- I ran the real CPU and GPU builds from this branch's config in Cloud
Build us-central1, with `cbtest-*` tags and no cache writes. Both
succeeded in 6m55s, and the us-east4 push uploaded only the app layers.
- `actionlint` and `shellcheck` report no new findings.
- Full verification is the first main deploy after merge.

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

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

## Summary by CodeRabbit

* **Improvements**
* Backend image builds now run through a managed build service in the
central US region, with CPU and GPU images published as part of the
deployment workflow.
* The default “all variants” selection now excludes the build variant;
explicitly requested variants remain available.
* **Documentation**
* Updated runner and cost documentation to reflect the current build and
deployment setup.
* **Maintenance**
  * Updated the package version to 0.261.2.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 20:22:59 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 17d60c58a0 fix(cost): low Gemini thinking for simple callers + dedupe proactive auto-correct (#1105)
## Summary
GCP cost cut: Vertex Gemini 3.8 Flash is now the largest variable cost
(~$85-90/mo), mostly thinking tokens.

### 1. `thinking_level="low"` for simple extraction/classification
callers
| Caller | Model setting | Before | After |
|---|---|---|---|
| `match_judge/ai.py`, `match_judge/free_text.py` | `match_judge_model`
| default (high/dynamic) | low |
| `tenant_bulk/analyze.py` (filename pairing) | `match_judge_model` |
default | low |
| `parse_titles/ai.py` | `parse_titles_model` | default | low |
| `credit_evaluation_service.py` (grant/deny) | `credit_eval_model` |
default | low |
| `frontend/scripts/translate.py` | n/a | medium | low |

**Unchanged on purpose:** auto-correct (quality eval), custom lyrics,
lyrics translation, and agentic correction (`agentic_ai_model` is
dormant because `SKIP_CORRECTION=true`; its router makes no LLM call).

Timeouts: low thinking only makes these calls faster, so the existing
deadlines (`match_judge_timeout_ms` 12s, `parse_titles_timeout_ms` 20s)
need no change.

**Live check (Vertex, ADC):** 8 match-judge cases plus a 4-file
parse-titles batch, default vs low. Same canonical artist/title on every
case and identical parses. One verdict changed: `beatles/hey jude` went
from content to cosmetic, and cosmetic is the correct label for a
casing/"The" fix. Thinking tokens dropped from 1519 to 167, and max
latency from 5.5s to 2.7s.
**translate.py A/B:** 5 ICU-plural/placeholder strings into es/de/ja/ar.
Low used 0 thinking tokens and medium used ~33k. Both preserved all
placeholders and produced equivalent quality.

### 2. Duplicate proactive auto-correct (job 96cf1100 and about 55% of
jobs)
Root cause: the lyrics worker calls `advance_to_screens_if_ready`
*before* `_trigger_proactive_auto_correct`. The screens worker's
`ensure_and_pre_apply` checks the suggestion cache while the proactive
run is still in flight, gets a miss, and starts a second identical
multi-model run (Claude Opus plus Gemini). In job 96cf1100 both runs
were on the same instance and finished 4s apart. From prod logs for
2026-09-17 to 10-01: **92 of 167 jobs generated twice** (9 of them
across instances), at about $0.07 per duplicate.

Fix (`backend/workers/auto_correct_worker.py`):
- In-process single-flight per job. A concurrent caller awaits the
in-flight task, shielded so it can't cancel it.
- Cross-instance GCS lease
(`jobs/{id}/lyrics/auto_correct_inflight.json`) with generation fencing
(create-only; stale takeover and release only against the observed/own
generation; owner token; 240s TTL; timed-out run keeps its lease). A
non-holder polls off the event loop for the holder's cache for up to
150s instead of regenerating. If the holder fails, the UI's existing
on-demand fallback takes over.

## Tests
- `backend/tests/test_proactive_auto_correct.py`: concurrent calls share
one run (fails on old code), waiting on a peer's lease, taking over a
stale lease, and not regenerating after a peer fails.
- `backend/tests/test_gemini_thinking_level.py`: each changed caller
sends `thinking_level=low`.
- Related suites pass locally. `test_internal_api.py` has 7 failures
locally that also fail on `origin/main` (local env).

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

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

## Summary by CodeRabbit

* **Improvements**
* AI-powered features now use a lower thinking level for tasks such as
title parsing, match evaluation, credit evaluation, bulk analysis, and
translation.
* Proactive auto-correct now coordinates concurrent suggestion requests,
reuses completed suggestions, and avoids starting a duplicate run when
another request is already in progress.
* If another request ends without producing suggestions, auto-correct
skips the request rather than immediately generating them again.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 19:35:22 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 7e51ba7cc1 fix(email): retry transient Postmark failures; diagnose missing E2E emails (v0.261.1) (#1104)
## Summary
E2E Daily #190 (2026-10-01) failed in Stage 1 because Postmark rejected
all 3 magic-link sends with a bare **nginx HTML 403**. That's an
edge/IP-level block, not Postmark's JSON error format. Since 2026-09-30
05:26 UTC there have been 11 such failures from `karaoke-backend`
(us-central1), in bursts. They also dropped real users' magic links and
a lyrics reminder. `video-encoding-job` (us-east4) was never affected.

## Changes
- **`PostmarkEmailProvider` retry**: 429, 5xx, non-JSON 403 and connect
timeouts are retried with backoff (1s, 3s; 3 attempts total).
- JSON Postmark errors (bad token, invalid request, suppressed
recipient) are not retried: they're deterministic.
- Read timeouts are not retried: Postmark may already have accepted the
email and has no idempotency key, so a retry could send it twice.
- **E2E `waitForEmail` diagnosis**: on timeout, it queries `GET
/api/admin/users/{email}/emails` and reports either "backend has NO
record of sending" (a server-side send failure) or "backend sent N
email(s) but none reached testmail.app". This replaces the misleading
testmail `AbortError`. Applies to every spec that waits for an email.
- `docs/TROUBLESHOOTING.md`: new section on Postmark HTML 403s.
- Version 0.261.0 → 0.261.1.

## Testing
- New `TestPostmarkRetry` unit tests: HTML 403 then success, giving up
after 3 attempts, 429/5xx, no retry on JSON 403/422/406, connect timeout
retried, read timeout not retried.
- `make test` passes: backend 2017 + 5436 + 150; frontend Jest 1591.
- Diagnosis helper: every branch checked with a stubbed `fetch`. Against
the real prod endpoint, today's failed E2E address shows 0 emails and an
address from a passing run shows 2.

## Not in this PR
The underlying block is probably IP-based. If retries don't absorb it,
the follow-ups are Postmark support and/or a static outgoing IP (Direct
VPC egress + Cloud NAT).

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

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

## Summary by CodeRabbit

* **Bug Fixes**
* Email delivery now automatically retries certain temporary service and
connection failures, with brief delays between attempts.
* Email wait timeouts in end-to-end testing now include additional
diagnostic details, and temporary polling errors no longer stop checks
early.

* **Documentation**
* Added troubleshooting guidance for missing emails, including how to
distinguish delivery blocks from authentication errors and what to check
when retries do not resolve the issue.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:59:19 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 d4fcab521c Translated lyrics follow-ups + review Waveforms 'separating' spinner (v0.261.0) (#1103)
## Summary
Follow-ups from Andrew's test of translated lyrics (job 948b6760), plus
a review-page UX gap found while investigating that job.

- **Translation row is now secondary:** it renders at 70% of the unsung
colour's opacity, with outline and shadow faded to match. A theme's
`karaoke.translation_color` still wins.
(`subtitles.py:TRANSLATION_OPACITY`)
- **YouTube label:** published videos with translations get "(With
Translation into X)" in the title, before "(Karaoke)". Only the
artist/title get truncated, never the label. The description gets an
up-front notice. This covers the live upload and the quota queue, and
applies only when `state_data.lyrics_translation.status ==
"translated"`. Turning translation off and re-rendering clears the
outcome.
- **Review preview modal:** an always-visible note explains the preview
is a quick black-background sync check, not the final look. Jobs with a
translation language also get a note that translations are added after
review.
- **Waveforms toggle:** shows a spinner and tooltip while audio
separation is still producing the vocal stem (peaks endpoint returns
202). Previously the rows just stayed empty.

## Testing
- Jest: lyrics-review suite (245+) incl. new
TranscriptionView/Preview/loader tests
- pytest: youtube description/queue/orchestrator, lyrics_translation,
translated-lyrics unit tests
- Linux libass render tests (Debian + prod static ffmpeg) pass
- Independent review agent: 2 findings fixed (Tooltip data-state
clobbering toggle state; stale translation outcome)

No local CodeRabbit run (CLI has no seat on this org), so leaving this
open to the CodeRabbit bot.

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

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

## Summary by CodeRabbit

* **New Features**
* YouTube titles and descriptions now identify the language of
translated lyrics. Titles are kept within the platform’s length limit.
  * Translated lyrics appear with softer opacity by default.
* The lyric-review screen explains how the quick preview differs from
the final video, including that translated lyrics are added after
review.
* A spinner and notice indicate when vocal waveforms are still being
prepared.

* **Bug Fixes**
* Translation status now reflects when translation is turned off,
preventing stale translated-language labels.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:39:56 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 bc1fc774eb Translated lyrics: don't split Japanese/Chinese translations mid-word (v0.260.1) (#1102)
## Summary
Follow-up to #1101, found while verifying it on prod (job ca2e881a,
English song → Japanese): when a long lyric line is split across rows,
its translation is shared between the pieces, and unspaced scripts were
cut at an arbitrary character — e.g. 無|駄 ("waste") across two rows,
worse in portrait.

`split_text_proportionally` now scores each split point for unspaced
scripts: free after punctuation (、。!?…), cheap after a Japanese particle
(を は が に…) or before a kanji/katakana word start following hiragana, a
full "part" of cost for a mid-word cut. It also never leaves a piece
empty when there are enough characters.

Before → after (real prod line): `ねえ、おかしいでしょ、無` / `駄な時間を省いてあげる` →
`ねえ、おかしいでしょ、` / `無駄な時間を省いてあげる`.

Thai can still split inside a word (no word-boundary data without a
dictionary).

## Testing
- New unit tests for the prod case and a particle-boundary case; all 201
lyrics output tests pass.

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

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

* **Bug Fixes**
* Improved how translated lyrics are split across rows for unspaced
text. Splits now favor punctuation and natural language boundaries,
helping avoid cutting through words where possible.
  * Thai text may still be split within words.
* **Chores**
  * Updated the project version to 0.260.1.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 14:39:13 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 f8d0febcf5 Translated lyrics beneath the karaoke lyrics for language learners (v0.260.0) (#1101)
## Summary
New job-submission option: **Add translated lyrics** → pick a language
(33 UI locales) → the karaoke videos show an AI translation of each
lyric line in smaller text beneath the synced lyrics, so language
learners can sing songs in another language while learning what the
words mean.

- **Job creation**: toggle + language picker (default = UI language) on
the Customize step, with a **live preview** of a real rendered frame
(`GET /api/themes/translation-preview?language=xx`; pre-generated sample
translations, no LLM call at preview time). Any job, public or private,
free for now. `translation_language` accepted by every creation route;
admin can edit it.
- **Post-review translation**: right after the job enters
RENDERING_VIDEO, the render worker translates the *final reviewed*
lyrics line by line with Gemini
(`backend/services/lyrics_translation.py`, `LYRICS_TRANSLATION_MODEL`,
GCS-cached so theme/admin re-renders are free) into
`jobs/{id}/lyrics/translations.json`. Not editable. A failure never
blocks the render (renders without translations, recorded in
`state_data.lyrics_translation`); a song already in the target language
gets no row.
- **Rendering** (landscape + portrait, GCE worker + local fallback):
`LyricsSegment.translation`; when present, slots get taller and screens
show 3 lines; a `Karaoke.Translation` style (unsung colour, ~½ size)
draws one static event beneath each line, sanitized, wrapped/scaled to
fit. Jobs without translations render identically.
- **RTL + LTR together**: the translation is its own ASS event with auto
paragraph direction, so e.g. a Hebrew song keeps its right-to-left
highlight with an English translation beneath (and vice versa). Long
lines split by the resizer share their translation across the pieces
(grapheme-safe for Thai/CJK).

Design: `docs/archive/2026-10-01-translated-lyrics-plan.md`.

## Testing
- `make test` all green (root 2014, backend 5416, emulator 150, frontend
1583).
- New: `tests/unit/lyrics_transcriber/output/test_translated_lyrics.py`
(layout/positions/style/sanitizing/fit/mixed RTL-LTR/Thai/portrait),
`test_translated_lyrics_render.py` (libass pixel tests incl.
Hebrew/Arabic lyrics with English/Arabic translations and CJK),
`backend/tests/test_lyrics_translation.py`,
`backend/tests/test_render_video_worker_translations.py`, GCE endpoint
test, frontend CustomizeStep/GuidedJobFlow/api tests, prod E2E
`e2e/production/translated-lyrics.spec.ts`.
- `scripts/run-render-tests-linux.sh`: 135 passed on Debian ffmpeg AND
prod's static ffmpeg (no skips).
- Real-data check: job 5710831e (Hebrew) translated to English by Gemini
and rendered with the nomad theme — RTL highlight intact, English
beneath, split line shares translation.

Local CodeRabbit CLI unavailable in this workspace (no seat), so leaving
this PR for the CodeRabbit bot; an independent local review was done and
its findings fixed in the second commit.

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

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

* **New Features**
* Added an opt-in translated-lyrics option to job setup, with language
selection and a preview.
* Translations are generated after lyric review and appear beneath
lyrics in landscape and portrait videos, with text layout for multiple
languages and writing directions.
  * Translation settings can be changed or cleared by admins.
* **Bug Fixes**
* If translation fails or is unavailable, video rendering continues
without translated lyrics.
* **Documentation**
* Updated API and product documentation with translated-lyrics setup and
behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 13:41:54 -04:00
156 changed files with 6170 additions and 742 deletions

No files matched your search

+5 -2
View File
@@ -21,7 +21,7 @@ on:
workflow_dispatch:
inputs:
variants:
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all" (= all except build)'
required: false
default: 'all'
skip_prune:
@@ -55,7 +55,10 @@ jobs:
run: |
requested='${{ github.event.inputs.variants || 'all' }}'
if [[ "$requested" == "all" || -z "$requested" ]]; then
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
# "build" (docker-build label) is excluded from "all": no job uses it
# since deploy-backend moved to ubuntu-latest + Cloud Build
# (2026-10-01). Still buildable via an explicit variants=build.
echo 'variants=["general","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
else
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
echo "variants=$json" >> "$GITHUB_OUTPUT"
+155 -231
View File
@@ -1033,6 +1033,11 @@ jobs:
PR_NUM=""
PR_TITLE=""
fi
# The backend deploy splices PR_TITLE into the comma-delimited
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
# double-quoted shell string): a comma in a PR title broke the v0.261.2
# deploy. Commas → ';', drop newlines and shell-active chars.
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
@@ -1090,7 +1095,10 @@ jobs:
deploy-backend:
name: "Deploy - Backend (Cloud Run)"
needs: [package-build]
runs-on: [self-hosted, linux, gcp, docker-build]
# GitHub-hosted (free for this public repo). Docker images are built in
# Cloud Build us-central1 (see "Build and push images" below), so nothing
# large is pulled from Artifact Registry to this runner.
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
permissions:
contents: read
@@ -1117,28 +1125,6 @@ jobs:
CPU_JOBS_REPOSITORY: karaoke-backend-gpu
CPU_JOBS_IMAGE_NAME: karaoke-backend-cpu
steps:
- name: Check disk space (aggressive for Docker builds)
run: |
echo "Checking disk space..."
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "Current disk usage: ${USAGE}%"
if [ "$USAGE" -gt 50 ]; then
echo "Disk usage above 50%, cleaning unused images..."
docker system prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After image cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 70 ]; then
echo "Still above 70%, clearing build cache..."
docker builder prune -af || true
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
echo "After build cache cleanup: ${USAGE}%"
fi
if [ "$USAGE" -gt 85 ]; then
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
exit 1
fi
- name: Checkout code
uses: actions/checkout@v4
with:
@@ -1172,6 +1158,11 @@ jobs:
PR_NUM=""
PR_TITLE=""
fi
# The backend deploy splices PR_TITLE into the comma-delimited
# `gcloud run deploy --set-env-vars "...,PR_TITLE=..."` (inside a
# double-quoted shell string): a comma in a PR title broke the v0.261.2
# deploy. Commas → ';', drop newlines and shell-active chars.
PR_TITLE=$(printf '%s' "$PR_TITLE" | tr ',' ';' | tr -d '\n\r"`$\\')
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
@@ -1759,14 +1750,19 @@ jobs:
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
# ============================================
# Docker Build with BuildKit + Registry Cache
# This replaces expensive Cloud Build with free GitHub Actions
# Registry cache persists between builds for fast rebuilds
# Image builds run in Cloud Build (us-central1), not on this runner.
#
# This job runs on a free GitHub-hosted runner. The app images are built
# FROM large bases in us-central1 AR (CPU ~4.2 GB, GPU ~13 GB compressed);
# pulling those to a GitHub-hosted runner is GCP internet egress
# (~$0.12/GB → ~$2/deploy, far more than the old self-hosted build VM).
# Cloud Build in us-central1 pulls them same-region (free) and the
# e2-standard-2 default pool is in the 2,500 build-min/month free tier
# (~7 min/deploy, CPU+GPU built in parallel). Only the hash checks below
# (manifest + ~10KB config blob) touch AR from here.
# See infrastructure/cloudbuild/build-backend-images.sh.
# ============================================
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Calculate base image hash
id: base-hash
run: |
@@ -1781,7 +1777,6 @@ jobs:
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
# Fetch hash label directly from registry (10KB config blob, not full image)
# This avoids issues with stale local Docker cache on GitHub runners
EXISTING_HASH=""
# Get the manifest (small JSON, ~1KB) - includes config digest
@@ -1812,71 +1807,133 @@ jobs:
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
fi
- name: Build and push base image (if needed)
if: steps.check-base.outputs.needs_rebuild == 'true'
timeout-minutes: 20
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile.base
push: true
tags: |
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:${{ github.sha }}
# Registry cache for ALL layers (mode=max) - persists between builds
# ignore-error=true allows build to continue if cache doesn't exist yet
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
build-args: |
BUILD_DATE=${{ github.run_id }}
BUILD_ID=${{ github.sha }}
BASE_CONTENT_HASH=${{ steps.base-hash.outputs.hash }}
# Provenance disabled for smaller image and faster push
provenance: false
- name: Ensure local base image is current (if not rebuilt)
if: steps.check-base.outputs.needs_rebuild == 'false'
- name: Calculate GPU base image hash
id: gpu-base-hash
run: |
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
# 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"
# Get the config digest from registry manifest (identifies the image content)
# This is the same value as Docker's Image ID for the same image
REGISTRY_CONFIG_DIGEST=$(docker manifest inspect $BASE_IMAGE 2>/dev/null | jq -r '.config.digest' || echo "")
- name: Check if GPU base image exists and is current
id: check-gpu-base
run: |
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
# Get local image's ID (which is the config digest)
LOCAL_IMAGE_ID=$(docker image inspect $BASE_IMAGE --format='{{.Id}}' 2>/dev/null || echo "")
# Read the base.content.hash label without pulling the image
# (manifest ~1KB + config blob ~10KB). The GPU base lives in
# us-central1 (karaoke-repo), next to Cloud Build. The one-time copy
# from the legacy us-east4 location was removed: it ran via
# `buildx imagetools create` on THIS runner, which on a GitHub-hosted
# runner would stream ~13 GB through internet egress.
host="${GPU_BASE_IMAGE%%/*}"
path="${GPU_BASE_IMAGE#*/}"
path="${path%:*}"
MANIFEST=$(docker manifest inspect "$GPU_BASE_IMAGE" 2>/dev/null || echo "")
# A base copied with `buildx imagetools create` is a single-entry
# index — follow it to the image manifest.
CHILD=$(echo "$MANIFEST" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
if [ -n "$CHILD" ] && [ "$CHILD" != "null" ]; then
MANIFEST=$(docker manifest inspect "${GPU_BASE_IMAGE%:*}@${CHILD}" 2>/dev/null || echo "")
fi
DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
EXISTING_HASH=""
if [ -n "$DIGEST" ] && [ "$DIGEST" != "null" ]; then
EXISTING_HASH=$(curl -sL -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://${host}/v2/${path}/blobs/${DIGEST}" 2>/dev/null \
| jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
fi
echo "📋 Registry GPU base image hash: ${EXISTING_HASH:-<none>}"
echo "Registry config digest: $REGISTRY_CONFIG_DIGEST"
echo "Local image ID: $LOCAL_IMAGE_ID"
if [ -z "$LOCAL_IMAGE_ID" ]; then
echo "📥 Base image not in local cache - pulling from registry"
docker pull $BASE_IMAGE
elif [ "$LOCAL_IMAGE_ID" != "$REGISTRY_CONFIG_DIGEST" ]; then
echo "🔄 Local cache has different image - pulling latest"
docker pull $BASE_IMAGE
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
echo "✅ GPU base image is up to date"
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
else
echo "✅ Local cache matches registry - skipping pull"
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or poetry.lock changed)"
echo " Current: $WANT_HASH"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> "$GITHUB_OUTPUT"
fi
- name: Build and push app image
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile
push: true
tags: |
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:latest
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:latest
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:${{ github.sha }}
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
# Registry cache for app layers
# ignore-error=true allows build to continue if cache doesn't exist yet
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
- name: Build and push images (Cloud Build us-central1)
id: images
env:
BUILD_BASE: ${{ steps.check-base.outputs.needs_rebuild }}
BUILD_GPU_BASE: ${{ steps.check-gpu-base.outputs.needs_rebuild }}
BASE_HASH: ${{ steps.base-hash.outputs.hash }}
GPU_BASE_HASH: ${{ steps.gpu-base-hash.outputs.hash }}
VERSION: ${{ steps.version_check.outputs.version }}
run: |
set -euo pipefail
# Normal deploy: app layers only → free-tier e2-standard-2 (~7 min,
# measured). A base rebuild (≈monthly, on poetry.lock / Dockerfile.*base
# changes) gets a bigger paid machine + disk + timeout.
if [ "$BUILD_BASE" = "true" ] || [ "$BUILD_GPU_BASE" = "true" ]; then
MACHINE_ARGS=(--machine-type=e2-highcpu-8 --disk-size=300 --timeout=7200s)
echo "🔄 Base rebuild needed (cpu=$BUILD_BASE gpu=$BUILD_GPU_BASE) → e2-highcpu-8"
else
MACHINE_ARGS=(--disk-size=150 --timeout=3600s)
fi
# Minimal build context (what the Dockerfiles COPY + the build script).
SRC="$RUNNER_TEMP/backend-image-src.tgz"
tar -czf "$SRC" backend karaoke_gen lyrics_transcriber_temp \
pyproject.toml poetry.lock README.md LICENSE .dockerignore \
infrastructure/cloudbuild
BUILD_ID=$(gcloud builds submit "$SRC" \
--region=us-central1 \
--project=${{ env.PROJECT_ID }} \
--config=infrastructure/cloudbuild/backend-images.yaml \
"${MACHINE_ARGS[@]}" \
--substitutions="_SHA=${{ github.sha }},_VERSION=${VERSION},_RUN_ID=${{ github.run_id }},_BUILD_BASE=${BUILD_BASE},_BASE_HASH=${BASE_HASH},_BUILD_GPU_BASE=${BUILD_GPU_BASE},_GPU_BASE_HASH=${GPU_BASE_HASH}" \
--async --format='value(id)')
# Recorded before waiting so the cancel step below can stop the build
# if this job is cancelled (ci concurrency cancels superseded deploys;
# an orphaned build would otherwise still push :latest tags).
echo "$BUILD_ID" > "$RUNNER_TEMP/cloudbuild_id"
echo "build_id=$BUILD_ID" >> "$GITHUB_OUTPUT"
echo "☁️ Cloud Build: https://console.cloud.google.com/cloud-build/builds;region=us-central1/${BUILD_ID}?project=${{ env.PROJECT_ID }}"
# Stream logs (returns when the build finishes), then check status.
gcloud builds log "$BUILD_ID" --region=us-central1 --project=${{ env.PROJECT_ID }} --stream \
|| echo "::warning::log streaming ended early; checking build status"
# Tolerate transient API errors: a failed poll must not abort the
# step (the cancel step below would then kill a healthy build).
FAILS=0
while true; do
if ! STATUS=$(gcloud builds describe "$BUILD_ID" --region=us-central1 \
--project=${{ env.PROJECT_ID }} --format='value(status)'); then
FAILS=$((FAILS + 1))
if [ "$FAILS" -ge 5 ]; then
echo "::error::Cannot read Cloud Build $BUILD_ID status"
exit 1
fi
sleep 15
continue
fi
FAILS=0
case "$STATUS" in
QUEUED|PENDING|WORKING) sleep 15 ;;
*) break ;;
esac
done
echo "Cloud Build status: $STATUS"
if [ "$STATUS" != "SUCCESS" ]; then
echo "::error::Cloud Build $BUILD_ID finished with status $STATUS"
exit 1
fi
- name: Cancel Cloud Build if this job did not finish
if: always() && steps.images.outcome != 'success' && steps.images.outcome != 'skipped'
run: |
ID_FILE="$RUNNER_TEMP/cloudbuild_id"
[ -s "$ID_FILE" ] || exit 0
gcloud builds cancel "$(cat "$ID_FILE")" --region=us-central1 \
--project=${{ env.PROJECT_ID }} --quiet || true
- name: Pre-import CPU image for us-east4 jobs
# A new image digest costs a one-time ~2.5 min "Container image import" on
@@ -1895,142 +1952,6 @@ jobs:
--quiet \
|| echo "::warning::us-east4 CPU image pre-import execution failed to start (non-fatal)"
# ============================================
# GPU Image Build (for audio worker with L4 GPU)
# Same pattern as base image: hash check → rebuild if needed.
#
# Region layout (cost): the ~13 GB GPU base image and all BuildKit
# caches live in us-central1 (karaoke-repo), next to this runner, so
# building the app layer on top of the base is same-region (free). Only
# the FINAL app image is pushed to us-east4 (karaoke-backend-gpu), where
# the audio-separation Cloud Run job pulls it same-region. That push only
# uploads the small changed app layers — the base layers already exist
# there. Previously the base lived in us-east4 and every deploy pulled
# ~13 GB across regions (~$12-16/mo AR inter-region egress).
# ============================================
- 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: |
WANT_HASH="${{ steps.gpu-base-hash.outputs.hash }}"
GPU_BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
# Legacy location (pre cost-fix). Only used to seed us-central1 once.
LEGACY_GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
# Read the base.content.hash label of an image without pulling it
# (manifest ~1KB + config blob ~10KB).
image_hash() {
local image="$1" host path manifest digest
host="${image%%/*}"
path="${image#*/}"
path="${path%:*}"
manifest=$(docker manifest inspect "$image" 2>/dev/null || echo "")
# `buildx imagetools create` (the one-time copy below) wraps the
# image in a single-entry index — follow it to the image manifest.
local child
child=$(echo "$manifest" | jq -r '.manifests[0].digest // ""' 2>/dev/null || echo "")
if [ -n "$child" ] && [ "$child" != "null" ]; then
manifest=$(docker manifest inspect "${image%:*}@${child}" 2>/dev/null || echo "")
fi
digest=$(echo "$manifest" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
if [ -z "$digest" ] || [ "$digest" = "null" ]; then
echo ""
return
fi
curl -sL -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://${host}/v2/${path}/blobs/${digest}" 2>/dev/null \
| jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo ""
}
EXISTING_HASH=$(image_hash "$GPU_BASE_IMAGE")
echo "📋 Registry GPU base image hash (us-central1): ${EXISTING_HASH:-<none>}"
if [ -n "$EXISTING_HASH" ] && [ "$EXISTING_HASH" = "$WANT_HASH" ]; then
echo "✅ GPU base image is up to date"
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# One-time migration: if the legacy us-east4 base is already current,
# copy it byte-for-byte (same digests) instead of rebuilding from
# scratch, so the image content is unchanged by the move.
LEGACY_HASH=$(image_hash "$LEGACY_GPU_BASE_IMAGE")
echo "📋 Legacy GPU base image hash (us-east4): ${LEGACY_HASH:-<none>}"
if [ -n "$LEGACY_HASH" ] && [ "$LEGACY_HASH" = "$WANT_HASH" ]; then
echo "📦 Copying current GPU base from us-east4 to us-central1 (one-time)..."
if timeout 30m docker buildx imagetools create --tag "$GPU_BASE_IMAGE" "$LEGACY_GPU_BASE_IMAGE"; then
echo "✅ GPU base copied to us-central1"
# imagetools wraps the image in a single-entry index; tag the
# child manifest too so AR's delete-untagged cleanup policy can
# never treat it as an orphan.
CHILD=$(docker manifest inspect "$GPU_BASE_IMAGE" | jq -r '.manifests[0].digest // ""' || echo "")
if [ -n "$CHILD" ]; then
gcloud artifacts docker tags add "${GPU_BASE_IMAGE%:*}@${CHILD}" \
"${GPU_BASE_IMAGE%:*}:content-${WANT_HASH:0:12}" --quiet \
|| echo "⚠️ Could not tag child manifest (non-fatal)"
fi
echo "needs_rebuild=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "⚠️ Copy failed — falling back to a rebuild"
fi
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or poetry.lock changed)"
echo " Current: $WANT_HASH"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> "$GITHUB_OUTPUT"
- 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.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.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
# Normally ~2 min (only app layers are new). After a GPU base rebuild
# this push also uploads the ~13 GB base layers to us-east4 (they can't
# be cross-mounted from the us-central1 registry), hence the headroom.
timeout-minutes: 40
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile
push: true
# Final image → us-east4 (same region as the audio-separation job).
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 }}
# Base + cache → us-central1 (same region as this runner).
build-args: |
BASE_IMAGE=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/karaoke-backend-gpu:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# Deploy to Cloud Run
# ============================================
@@ -2075,9 +1996,13 @@ jobs:
# forced scale-out, and each overflow request waited out a ~16s app
# cold start (2026-09-22 16-tab test: warm instance served in 1.2s,
# freshly-spawned ones in 16-19s). 32 + --min-instances 2 gave 64
# warm slots; min-instances was cut to 1 on 2026-09-26 (GCP cost cut,
# accepted perf trade-off: big bursts may hit a ~15s cold start) while
# staying far below the wedge-era 80. --clear-vpc-connector: the
# warm slots; min-instances was cut to 1 on 2026-09-26 and to 0 on
# 2026-10-01 (GCP cost cuts, ~$24/mo idle min-instance charge; Andrew
# accepts a ~15s cold start on the first request after idle). In
# practice the 60s /api/health uptime check and the */10 Cloud
# Scheduler jobs keep an instance warm most of the time — with
# --cpu-throttling (request-based billing) a warm-but-idle non-min
# instance costs nothing. Concurrency stays far below the wedge-era 80. --clear-vpc-connector: the
# serverless VPC connector was deleted (flacfetch is public now).
gcloud run deploy karaoke-backend \
--image $IMAGE \
@@ -2094,10 +2019,10 @@ jobs:
--timeout 1800 \
--concurrency 32 \
--max-instances 20 \
--min-instances 1 \
--min-instances 0 \
--clear-vpc-connector \
--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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
- name: Smoke candidate revision
@@ -2243,8 +2168,7 @@ jobs:
echo "Branch: ${{ github.ref_name }}"
echo "Run: ${{ github.run_number }}"
echo ""
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
echo "📊 Images built in Cloud Build us-central1: ${{ steps.images.outputs.build_id }}"
# NOTE: Pulumi infrastructure deploys are done locally, not in CI.
# CI runners run on the infrastructure Pulumi manages, creating a circular
+4 -3
View File
@@ -60,8 +60,10 @@ jobs:
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
# sees the S3 (off-site) copy, so their limits must allow a full week
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. Secrets DO
# upload to S3 nightly, so they stay at 36h. GCS job files are NOT
# tracked: their off-site copy was stopped 2026-10-01 (egress cost
# cut) — they rely on GCS versioning + soft-delete only.
# Git repos are also weekly (Sundays) AND incremental since
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
# quiet week legitimately leaves every .bundle older than 8 days.
@@ -70,7 +72,6 @@ jobs:
# a run where every repo failed still reads as stale.
TARGETS = [
("Firestore", "firestore/", 192, None),
("GCS job files", "gcs/job-files/", 36, None),
("Encrypted secrets", "secrets/", 36, None),
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
("Git repos", "git-repos/manifest.json", 192, None),
+1 -1
View File
@@ -112,7 +112,7 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
- Translation uses Gemini 3.8 Flash via Vertex AI with GCS cache for efficiency
- Translation uses Gemini 3.8 Flash via the **Gemini Developer API** (key: `GEMINI_API_KEY`, else Secret Manager `gemini-api-key` via your gcloud login — `frontend/scripts/gemini_client.py`) with GCS cache for efficiency. **Vertex AI is disabled in the GCP project — never use `vertexai=True`; backend code uses `backend/services/gemini_client.get_genai_client()`.**
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
+13
View File
@@ -98,6 +98,8 @@ class JobUpdateRequest(BaseModel):
review_mode: Optional[str] = None
# Backing-vocals preference: "auto" | "clean" | "review"
backing_preference: Optional[str] = None
# Translated lyrics language code ("" turns it off)
translation_language: Optional[str] = None
# Editable boolean fields
enable_cdg: Optional[bool] = None
@@ -136,6 +138,7 @@ EDITABLE_JOB_FIELDS = {
"is_private",
"review_mode",
"backing_preference",
"translation_language",
# Exempts a job from the stale-review auto-expiry (48h cancel+refund) —
# the stale_review_processor skips made_for_you jobs. Used for admin-driven
# batches (e.g. KaraokeHunt outreach) that must wait at review indefinitely.
@@ -1021,6 +1024,16 @@ async def update_job(
detail='review_mode must be "auto" or "always_review"',
)
# Translated lyrics: "" / null turns it off; otherwise a supported language code
if "translation_language" in updates:
from backend.services.lyrics_translation import normalize_language
raw = updates["translation_language"]
code = normalize_language(raw) if raw else None
if raw and code is None:
raise HTTPException(status_code=400, detail=f"Unsupported translation_language: {raw}")
updates["translation_language"] = code
# backing_preference likewise gates the instrumental decision — reject typos.
if "backing_preference" in updates and updates["backing_preference"] not in (
"auto", "clean", "review",
+2
View File
@@ -146,6 +146,7 @@ class AudioSearchRequest(BaseModel):
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
@@ -808,6 +809,7 @@ async def search_audio(
non_interactive=body.non_interactive,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
translation_language=body.translation_language,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
+2
View File
@@ -261,6 +261,7 @@ class BulkSettings(BaseModel):
# Full-auto review (workstream C): batch default autonomy + backing preference.
review_mode: str = "auto"
backing_preference: str = "auto"
translation_language: Optional[str] = None
class BulkSubmitRequest(BaseModel):
@@ -347,6 +348,7 @@ async def bulk_submit(
is_private=body.settings.is_private,
review_mode=body.settings.review_mode,
backing_preference=body.settings.backing_preference,
translation_language=body.settings.translation_language,
brand_prefix=settings.default_brand_prefix,
enable_youtube_upload=settings.default_enable_youtube_upload,
youtube_description=settings.default_youtube_description,
+6
View File
@@ -188,6 +188,7 @@ class CreateJobFromUrlRequest(BaseModel):
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
class CreateJobFromUrlResponse(BaseModel):
@@ -250,6 +251,7 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
# Non-interactive mode
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
@@ -496,6 +498,7 @@ async def upload_and_create_job(
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
review_mode: str = Form("auto", description="'auto' (skip review when confident) or 'always_review'"),
backing_preference: str = Form("auto", description="'auto' (retain backing where safe), 'clean', or 'review'"),
translation_language: Optional[str] = Form(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none"),
# Private (non-published) track mode
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
# Audio editing
@@ -727,6 +730,7 @@ async def upload_and_create_job(
# Review autonomy + backing-vocals preference (full-auto review)
review_mode=review_mode,
backing_preference=backing_preference,
translation_language=translation_language,
# Private (non-published) track mode
is_private=is_private,
# Tenant scoping
@@ -1382,6 +1386,7 @@ async def create_job_with_upload_urls(
non_interactive=body.non_interactive,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
translation_language=body.translation_language,
is_private=effective_is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
@@ -2088,6 +2093,7 @@ async def create_job_from_url(
non_interactive=body.non_interactive,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
translation_language=body.translation_language,
is_private=body.is_private,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else "",
+12 -35
View File
@@ -312,16 +312,14 @@ 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",
}
"""Report audio separation availability.
Separation runs in the ``audio-separation-job`` GPU Cloud Run Job (local
GPU mode, models baked into the image). The standalone ``audio-separator``
Cloud Run GPU service was shut down on 2026-10-01 (cost cut), so there is
no remote service to probe — this reports the installed package version
only and never calls out to anything.
"""
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
@@ -331,6 +329,7 @@ def check_audio_separator_status() -> Dict[str, Any]:
return {
"available": True,
"status": "ok",
"mode": "gpu_job",
"version": pkg_version,
}
@@ -338,34 +337,12 @@ def check_audio_separator_status() -> Dict[str, Any]:
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
Return the installed audio-separator package version.
Return audio separation status (installed audio-separator package version).
Does NOT call the remote GPU service — that would cold-start an expensive
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
installed package version, which matches what the audio worker uses.
No authentication required.
Does NOT call any remote service — separation runs in the
audio-separation-job GPU Cloud Run Job. No authentication required.
"""
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,
}
return check_audio_separator_status()
def _get_encoding_worker_manager():
+2
View File
@@ -2658,6 +2658,7 @@ class CreateFromSearchRequest(BaseModel):
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
@validator('display_artist', 'display_title')
def strip_whitespace(cls, v):
@@ -2815,6 +2816,7 @@ async def create_job_from_search(
is_private=body.is_private,
review_mode=body.review_mode,
backing_preference=body.backing_preference,
translation_language=body.translation_language,
tenant_id=tenant_id,
locale=get_full_locale_from_request(request),
)
+30
View File
@@ -6,6 +6,7 @@ These endpoints are public (no authentication required) to allow theme selection
before job creation.
"""
import asyncio
import logging
from typing import Optional
@@ -43,6 +44,35 @@ async def list_themes(request: Request) -> ThemesListResponse:
)
@router.get("/translation-preview")
async def get_translation_preview(language: str, request: Request) -> dict:
"""
Preview frame of a translated-lyrics karaoke video in ``language``.
Renders the default theme's karaoke frame with sample lyrics and their
(pre-generated) translation beneath each line, so users can see the option
before enabling it at job creation. Public, like the other theme endpoints.
Returns:
Object with ``image`` (JPEG data URL)
Raises:
400: Unsupported language
"""
from backend.services.lyrics_translation import normalize_language
from backend.services.translation_preview import render_translation_preview
code = normalize_language(language)
if code is None:
raise HTTPException(status_code=400, detail=f"Unsupported language: {language}")
try:
image = await asyncio.to_thread(render_translation_preview, code)
except Exception as e:
logger.error(f"Error rendering translation preview for {code}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail="Could not render the translation preview")
return {"image": image}
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
"""
+4 -4
View File
@@ -15,9 +15,9 @@ steps:
- '-f'
- 'backend/Dockerfile.gpu-base'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
- '--build-arg'
- 'BUILD_DATE=$_BUILD_DATE'
- '--build-arg'
@@ -25,8 +25,8 @@ steps:
- '.'
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'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
timeout: '3600s'
+6 -2
View File
@@ -82,9 +82,9 @@ class Settings(BaseSettings):
# Agentic AI Correction (for lyrics correction via LLM)
# Only used when skip_correction=false
# When enabled, uses Gemini via Vertex AI for intelligent lyrics correction
# When enabled, uses Gemini (Developer API, key GEMINI_API_KEY) for intelligent lyrics correction
use_agentic_ai: bool = os.getenv("USE_AGENTIC_AI", "true").lower() in ("true", "1", "yes")
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3.8-flash")
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "gemini/gemini-3.8-flash")
# Timeout for agentic correction in seconds. If correction takes longer, abort and
# use uncorrected transcription - human review will fix any issues.
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
@@ -117,6 +117,10 @@ class Settings(BaseSettings):
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
# Translated lyrics — per-job opt-in (Job.translation_language): the reviewed
# lyrics are translated line-by-line just before the karaoke video renders.
lyrics_translation_model: str = os.getenv("LYRICS_TRANSLATION_MODEL", "gemini-3.8-flash")
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
# review UI. Stateless: one whole-song LLM call returning word-level
# suggestions the reviewer accepts/rejects individually.
+17
View File
@@ -290,6 +290,11 @@ class Job(BaseModel):
# instrumental. Consumed by the auto-approval instrumental decision.
backing_preference: str = "auto"
# Translated lyrics: language code (one of the UI locales, e.g. "en", "es") whose
# LLM translation of each reviewed line is drawn in smaller text beneath it in the
# karaoke videos. None = no translation row. See backend/services/lyrics_translation.py.
translation_language: Optional[str] = None
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
tenant_id: str = "" # Tenant ID for white-label portal scoping
@@ -586,6 +591,8 @@ class JobCreate(BaseModel):
# "auto" (default) = retain backing vocals where confidently safe; "clean" =
# always strip backing vocals; "review" = always let a human pick the instrumental.
backing_preference: str = "auto"
# Translated lyrics language (see Job.translation_language); None = off
translation_language: Optional[str] = None
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
@@ -684,6 +691,16 @@ class JobCreate(BaseModel):
executor already treats any non-"auto" value as an enforcement blocker."""
return v if v in ("auto", "always_review") else "always_review"
@validator('translation_language')
def _normalize_translation_language(cls, v):
"""Supported language code; empty or unsupported values turn the feature off
(every creation route passes the client value straight through)."""
if v is None or (isinstance(v, str) and not v.strip()):
return None
from backend.services.lyrics_translation import normalize_language
return normalize_language(v)
@validator('backing_preference')
def _normalize_backing_preference(cls, v):
"""Coerce an out-of-set value to the default. Every creation route passes
@@ -0,0 +1,51 @@
"""Regenerate backend/services/translation_preview_samples.py.
The job-creation "translated lyrics" preview renders sample lyrics with their
translation beneath. Translations are generated once with the production
translation service and committed, so the preview never calls the LLM.
GOOGLE_CLOUD_PROJECT=nomadkaraoke python backend/scripts/generate_translation_preview_samples.py
"""
import os
import pprint
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from backend.services.lyrics_translation import TRANSLATION_LANGUAGES, LyricsTranslationService # noqa: E402
from backend.services.theme_preview_service import DEFAULT_SAMPLE_LYRICS # noqa: E402
# Shown instead of the English sample when the target language is English
SPANISH_SAMPLE_LYRICS = [
"Cada noche canto sin parar",
"Se apagan las luces, es mi lugar",
"Tomo el micrófono y subo al escenario",
"Doy la vuelta a la página otra vez",
]
class _NoCache:
def file_exists(self, path):
return False
def upload_json(self, path, data):
pass
def main():
service = LyricsTranslationService(storage=_NoCache())
samples = {}
for code in TRANSLATION_LANGUAGES:
source = SPANISH_SAMPLE_LYRICS if code == "en" else DEFAULT_SAMPLE_LYRICS
samples[code] = {"lyrics": source, "translations": service.translate_lines(source, code)}
print(code, samples[code]["translations"][0], file=sys.stderr)
out = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "services", "translation_preview_samples.py")
with open(out, "w", encoding="utf-8") as f:
f.write('"""Sample lyrics + translations for the translated-lyrics preview.\n\n')
f.write("Generated by backend/scripts/generate_translation_preview_samples.py; don't edit by hand.\n")
f.write('"""\n\n')
f.write("SAMPLES = " + pprint.pformat(samples, width=110, sort_dicts=False) + "\n")
if __name__ == "__main__":
main()
+4 -2
View File
@@ -54,8 +54,10 @@ MODEL_PRICING: dict[str, _Rate] = {
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
# tier; confirm against current Google pricing before trusting USD) ---
# --- Gemini (ESTIMATE — 3.x Pro preview, <=200K-token context tier;
# confirm against current Google pricing before trusting USD). Calls go
# via the Gemini Developer API (paid tier), assumed at Vertex list-price
# parity. ---
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
# Promo rate through 2026-12-31; see _RATE_CHANGES for the standard rate.
"gemini-3.8-flash": {"input": 0.75, "output": 3.75, "cache_read": 0.075},
+14 -8
View File
@@ -710,22 +710,19 @@ class AutoCorrectService:
def _call_gemini(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
from google import genai
from google.genai import types
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
# Milliseconds; bounds the call so a hung model never strands the UI.
http_options=types.HttpOptions(timeout=120_000),
)
from backend.services.gemini_client import get_genai_client, note_gemini_failure
# Deep-copy: the google-genai SDK mutates the schema dict in place,
# which would poison the shared module-level constant for other
# providers running in the same process.
import copy
try:
# Gemini Developer API (API key). Timeout in milliseconds bounds the
# call so a hung model never strands the UI.
client = get_genai_client(timeout_ms=120_000)
response = client.models.generate_content(
model=model,
contents=[user_prompt],
@@ -736,6 +733,15 @@ class AutoCorrectService:
),
)
except Exception as exc: # surface as 502, never a stuck job
if note_gemini_failure("auto_correct", exc):
# Quota / prepaid credit / key problem: retrying won't help.
# Non-retryable so compare mode drops the Gemini leg at once
# and keeps the other model's (Opus) suggestions.
raise AutoCorrectServiceError(
"Gemini is unavailable (quota/billing/key) — skipped",
status_code=503,
retryable=False,
) from exc
if _is_transient_model_error(exc):
logger.warning(
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
+13 -6
View File
@@ -295,16 +295,17 @@ class CreditEvaluationService:
"""Call Gemini and return the response text."""
from google import genai
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
)
from backend.services.gemini_client import get_genai_client
client = get_genai_client(timeout_ms=60_000)
response = client.models.generate_content(
model=self.settings.credit_eval_model,
contents=prompt,
config=genai.types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT,
# Grant/deny classification over a short signal list: low
# thinking is ample (Gemini 3 Flash defaults to high).
thinking_config=genai.types.ThinkingConfig(thinking_level="low"),
),
)
return response.text
@@ -402,7 +403,13 @@ class CreditEvaluationService:
feedback_content=feedback_content,
)
response_text = self._call_gemini(prompt)
try:
response_text = self._call_gemini(prompt)
except Exception as gemini_exc:
from backend.services.gemini_client import note_gemini_failure
note_gemini_failure("credit_evaluation", gemini_exc)
raise
evaluation = _parse_gemini_response(response_text)
evaluation.signals = signals
+28 -21
View File
@@ -562,36 +562,43 @@ class CustomLyricsService:
pdf_bytes: Optional[bytes],
settings: GenerationSettings,
) -> list[str]:
from google import genai
from google.genai import types
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
)
from backend.services.gemini_client import get_genai_client, note_gemini_failure
contents: list = [user_prompt]
if pdf_bytes is not None:
contents.append(
types.Part.from_bytes(mime_type="application/pdf", data=pdf_bytes)
)
response = client.models.generate_content(
model=self.settings.custom_lyrics_model,
contents=contents,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.4,
response_mime_type="application/json",
response_schema={
"type": "object",
"properties": {
"lines": {"type": "array", "items": {"type": "string"}}
try:
# Bounded so a stalled call can't hang the request (Gemini Developer API).
client = get_genai_client(timeout_ms=300_000)
response = client.models.generate_content(
model=self.settings.custom_lyrics_model,
contents=contents,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.4,
response_mime_type="application/json",
response_schema={
"type": "object",
"properties": {
"lines": {"type": "array", "items": {"type": "string"}}
},
"required": ["lines"],
},
"required": ["lines"],
},
),
)
),
)
except Exception as exc:
if note_gemini_failure("custom_lyrics", exc):
raise CustomLyricsServiceError(
"The AI lyrics service is temporarily unavailable. Please try "
"again later, or edit the lyrics manually.",
status_code=503,
) from exc
raise
# The model can return no text (safety block, MAX_TOKENS with no content,
# empty candidate). `response.text` is then None and json.loads(None) would
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
+61 -10
View File
@@ -12,6 +12,7 @@ import logging
import os
import re
import sys
import time
from abc import ABC, abstractmethod
from datetime import datetime, timedelta, timezone
from typing import NamedTuple, Optional, List
@@ -174,6 +175,65 @@ class PostmarkEmailProvider(EmailProvider):
API_URL = "https://api.postmarkapp.com/email"
# Seconds to sleep before each retry of a transient failure. Postmark's edge
# intermittently answers some us-central1 Cloud Run egress IPs with a bare
# nginx HTML 403 (not its JSON error format) — a fresh connection a moment
# later often succeeds. Kept short: magic-link sends block the request.
RETRY_DELAYS = (1.0, 3.0)
@staticmethod
def _is_transient_failure(response: requests.Response) -> bool:
"""True for failures worth retrying: 429, 5xx, or a non-JSON 403.
Postmark's own API errors (bad token, invalid payload, suppressed
recipient) come back as JSON and are deterministic, so retrying them
would just repeat the same answer. A 403 without a JSON body is an
edge/IP-level block, not a verdict on the request itself.
"""
status = response.status_code
if status == 429 or status >= 500:
return True
if status == 403:
try:
response.json()
except ValueError:
return True
return False
def _post_with_retry(self, payload: dict) -> requests.Response:
"""POST to Postmark, retrying transient failures with backoff.
Only connect-phase errors are retried among exceptions: a read timeout
may mean Postmark already accepted the message, and it has no
idempotency key, so retrying could send a duplicate.
"""
attempts = len(self.RETRY_DELAYS) + 1
for attempt in range(1, attempts + 1):
try:
response = requests.post(
self.API_URL,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"X-Postmark-Server-Token": self.server_token,
},
json=payload,
timeout=10,
)
except requests.ConnectTimeout:
if attempt == attempts:
raise
logger.warning(f"Postmark connect timeout (attempt {attempt}/{attempts}); retrying")
else:
if attempt == attempts or not self._is_transient_failure(response):
return response
logger.warning(
f"Postmark returned transient status {response.status_code} "
f"(attempt {attempt}/{attempts}); retrying"
)
time.sleep(self.RETRY_DELAYS[attempt - 1])
raise AssertionError("unreachable") # pragma: no cover
def __init__(self, server_token: str, from_email: str, from_name: str = "Nomad Karaoke"):
self.server_token = server_token
self.from_email = from_email
@@ -235,16 +295,7 @@ class PostmarkEmailProvider(EmailProvider):
if bcc_emails:
payload["Bcc"] = ", ".join(_dedupe_emails(bcc_emails))
response = requests.post(
self.API_URL,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"X-Postmark-Server-Token": self.server_token,
},
json=payload,
timeout=10,
)
response = self._post_with_retry(payload)
if 200 <= response.status_code < 300:
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
-1
View File
@@ -110,7 +110,6 @@ Shared infrastructure:
# ---------------------------------------------------------------------------
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-3.8-flash")
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "global")
#: Minimum number of active error patterns required before triggering LLM analysis.
MIN_PATTERNS_FOR_ANALYSIS: int = 3
@@ -1,6 +1,6 @@
"""LLM-powered incident analysis and duplicate detection for the error monitor.
Uses Gemini Flash via the google-generativeai library to:
Uses Gemini Flash via the Gemini Developer API (backend.services.gemini_client) to:
1. Group related error patterns into incidents with root-cause analysis.
2. Identify near-duplicate patterns that the regex normalizer missed.
@@ -17,13 +17,11 @@ import time
from collections import defaultdict
from dataclasses import dataclass, field
from google import genai
from google.genai import types as genai_types
from backend.services.gemini_client import get_genai_client, note_gemini_failure
from backend.services.error_monitor.config import (
GCP_PROJECT,
LLM_ANALYSIS_MODEL,
LLM_VERTEX_LOCATION,
MIN_PATTERNS_FOR_ANALYSIS,
SERVICE_DEPENDENCY_MAP,
)
@@ -96,11 +94,7 @@ def _call_llm(
for attempt in range(_RETRY_ATTEMPTS):
try:
client = genai.Client(
vertexai=True,
project=GCP_PROJECT,
location=LLM_VERTEX_LOCATION,
)
client = get_genai_client(timeout_ms=120_000)
response = client.models.generate_content(
model=LLM_ANALYSIS_MODEL,
contents=user_prompt,
@@ -111,6 +105,10 @@ def _call_llm(
)
return response.text
except Exception as exc: # noqa: BLE001
if note_gemini_failure("error_monitor", exc):
# Quota/credit/key problem: don't retry — callers fall back to
# alerts without the AI summary.
raise
last_exc = exc
delay = _RETRY_BASE_DELAY * (2**attempt)
logger.warning(
+20
View File
@@ -155,6 +155,8 @@ class RenderVideoRequest(BaseModel):
# Multi-singer / duet rendering. When True, OutputConfig is_duet is set
# so the SubtitlesGenerator and CDGGenerator emit per-singer styles.
is_duet: bool = False
# Translated lyrics (lyrics/translations.json) drawn beneath each line.
translations_gcs_path: Optional[str] = None
class JobStatus(BaseModel):
@@ -452,6 +454,17 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
else:
correction_result = base_result
# 2b. Translated lyrics (shown beneath each line)
if request.translations_gcs_path:
from karaoke_gen.lyrics_transcriber.output.translations import load_and_apply_translations
translations_path = work_dir / "translations.json"
try:
download_single_file_from_gcs(request.translations_gcs_path, translations_path)
load_and_apply_translations(correction_result.corrected_segments, str(translations_path))
except Exception as e: # translations are best-effort: never fail the render
logger.error(f"[job:{job_id}] Translated lyrics unavailable, rendering without: {e}")
jobs[job_id]["progress"] = 25
# 3. Download audio
@@ -965,6 +978,13 @@ def render_portrait_into_outputs(
with open(corrections_file, "r", encoding="utf-8") as f:
correction_result = CorrectionResult.from_dict(json.load(f))
# Translated lyrics, if the job has them (downloaded with the job's lyrics/)
translations_file = work_dir / "lyrics" / "translations.json"
if translations_file.is_file():
from karaoke_gen.lyrics_transcriber.output.translations import load_and_apply_translations
load_and_apply_translations(correction_result.corrected_segments, str(translations_file))
# Theme styles (optional — renderer fills defaults).
styles = {}
style_params = work_dir / "style" / "style_params.json"
+208
View File
@@ -0,0 +1,208 @@
"""Shared Gemini client for the backend: Gemini Developer API (API key), not Vertex.
Every backend Gemini call goes through :func:`get_genai_client`. Vertex AI is
disabled in the nomadkaraoke GCP project so AI spend never lands on it; calls are
billed to whichever AI Studio key is stored in Secret Manager ``gemini-api-key``.
Key resolution (via :meth:`backend.config.Settings.get_secret`):
1. ``GEMINI_API_KEY`` env var — injected on Cloud Run from
``gemini-api-key:latest`` (CI ``--set-secrets`` for the service, Pulumi
for the jobs).
2. Secret Manager ``gemini-api-key`` (latest) — read directly with the
runtime service account / your ADC when the env var isn't set.
Rotating the key: add a new version of ``gemini-api-key``. New instances / job
executions pick it up; no code change.
Degradation: when the key's quota or prepaid credit is exhausted (or the key is
rejected), callers must degrade rather than fail jobs. Use
:func:`is_quota_or_billing_error` to classify and :func:`note_gemini_failure`
from the caller's ``except`` block — it also sends a Discord ops alert at most
once per ``GEMINI_QUOTA_ALERT_HOURS`` (default 6h) across all instances.
"""
from __future__ import annotations
import logging
import os
import re
import threading
import time
from typing import Any, Optional
logger = logging.getLogger(__name__)
SECRET_NAME = "gemini-api-key"
QUOTA_EXHAUSTED_MESSAGE = (
"Gemini quota/credit exhausted — top up AI Studio or rotate gemini-api-key "
"(add a new version of Secret Manager secret 'gemini-api-key' in project nomadkaraoke)."
)
# Firestore dedup doc id (in ops_alerts' collection) shared by every instance/job.
_ALERT_KEY = "gemini-quota-exhausted"
_DEFAULT_ALERT_HOURS = 6.0
class GeminiKeyUnavailableError(RuntimeError):
"""No Gemini API key could be resolved (env var unset and Secret Manager failed)."""
def get_api_key() -> str:
"""Return the Gemini Developer API key or raise GeminiKeyUnavailableError."""
env_key = os.environ.get("GEMINI_API_KEY", "").strip()
if env_key:
return env_key
from backend.config import get_settings
key = (get_settings().get_secret(SECRET_NAME) or "").strip()
if not key:
raise GeminiKeyUnavailableError(
"GEMINI_API_KEY is not set and Secret Manager secret 'gemini-api-key' "
"could not be read"
)
return key
def get_genai_client(timeout_ms: Optional[int] = None) -> Any:
"""Build a google-genai client for the Gemini Developer API.
``timeout_ms`` bounds each HTTP request (milliseconds). No project/location:
those only apply to Vertex AI.
"""
from google import genai
from google.genai import types
http_options = types.HttpOptions(timeout=int(timeout_ms)) if timeout_ms else None
# vertexai=False pins the Developer API even if GOOGLE_GENAI_USE_VERTEXAI is set.
return genai.Client(vertexai=False, api_key=get_api_key(), http_options=http_options)
# Message fragments that mean "the key/account can't pay or isn't valid" — a
# retry won't help; a human must top up credit or rotate the key.
_QUOTA_PATTERNS = re.compile(
r"RESOURCE_EXHAUSTED|exceeded your current quota|quota exceeded|"
r"billing (details|account)|prepa(id|yment)|credits? (are |is |have been )?"
r"(exhausted|depleted|used up)|insufficient (credit|funds|balance)|"
r"API_KEY_INVALID|API key not valid|API key expired|API_KEY_SERVICE_BLOCKED|"
r"\b429 Too Many Requests",
re.IGNORECASE,
)
# A 429 that names a per-minute quota / carries a retry delay is an ordinary
# rate limit (transient — retry with backoff), not exhausted credit.
_RATE_LIMIT_PATTERNS = re.compile(r"PerMinute|retryDelay|retry in \d", re.IGNORECASE)
# ...unless it names a per-day quota: that won't clear for hours — treat as exhausted.
_DAILY_QUOTA_PATTERN = re.compile(r"PerDay", re.IGNORECASE)
def _is_rate_limit(text: str) -> bool:
return bool(_RATE_LIMIT_PATTERNS.search(text)) and not _DAILY_QUOTA_PATTERN.search(text)
def is_quota_or_billing_error(exc: Optional[BaseException]) -> bool:
"""True if ``exc`` (or anything in its ``__cause__`` chain) is a Gemini quota,
prepaid-credit, billing or API-key error — i.e. needs a top-up/key rotation,
not a retry.
Matches google-genai ``APIError`` (``.code`` 429 / 403 or status
RESOURCE_EXHAUSTED / PERMISSION_DENIED, or a billing/key message on a 400),
a missing key, and wrapped/stringified errors from other layers (LangChain).
Per-minute rate limits (429 naming a ``PerMinute`` quota or a retry delay)
are NOT matched — those are transient; retry them.
"""
seen: set[int] = set()
while exc is not None and id(exc) not in seen:
seen.add(id(exc))
if isinstance(exc, GeminiKeyUnavailableError):
return True
code = getattr(exc, "code", None)
if code is None:
code = getattr(exc, "status_code", None)
status = str(getattr(exc, "status", "") or "")
if code == 429 or status == "RESOURCE_EXHAUSTED":
return not _is_rate_limit(str(exc))
if code == 403 or status == "PERMISSION_DENIED":
return True
text = str(exc)
if _QUOTA_PATTERNS.search(text) and not _is_rate_limit(text):
return True
# Only explicit chaining (`raise X from e`): implicit __context__ could
# attribute an unrelated earlier error (e.g. a Firestore 403) to Gemini.
exc = exc.__cause__
return False
def _alert_hours() -> float:
try:
return float(os.environ.get("GEMINI_QUOTA_ALERT_HOURS", _DEFAULT_ALERT_HOURS))
except (TypeError, ValueError):
return _DEFAULT_ALERT_HOURS
# In-process throttle so a burst of failures in one instance doesn't hit
# Firestore on every call; the Firestore doc throttles across instances/jobs.
_last_alert_attempt: float = 0.0
_alert_lock = threading.Lock()
# Alert I/O (Firestore + Secret Manager + Discord) runs on a daemon thread so it
# never blocks the caller — several callers are on the asyncio event loop.
# Tests flip this off to run it inline.
_ALERT_IN_BACKGROUND = True
def note_gemini_failure(caller: str, exc: BaseException) -> bool:
"""Classify a Gemini failure; on quota/billing/key errors log + alert.
Call from a caller's ``except`` block. Returns True when the error is a
quota/billing/key error (caller should skip retries and degrade). Never raises.
"""
try:
if not is_quota_or_billing_error(exc):
return False
logger.error("Gemini unavailable (quota/billing/key) in %s: %s", caller, exc)
_maybe_alert(caller, exc)
return True
except Exception: # noqa: BLE001 - classification/alerting must never raise
logger.warning("note_gemini_failure failed", exc_info=True)
return False
def _maybe_alert(caller: str, exc: BaseException) -> None:
global _last_alert_attempt
window = _alert_hours() * 3600
now = time.monotonic()
with _alert_lock:
if _last_alert_attempt and now - _last_alert_attempt < window:
return
_last_alert_attempt = now
if _ALERT_IN_BACKGROUND:
threading.Thread(
target=_send_alert, args=(caller, exc, window), name="gemini-quota-alert", daemon=True
).start()
else:
_send_alert(caller, exc, window)
def _send_alert(caller: str, exc: BaseException, window: float) -> None:
global _last_alert_attempt
from backend.services import ops_alerts
err = str(exc).strip()
if len(err) > 800:
err = err[:800] + " …[truncated]"
message = (
"🟠 **Gemini API unavailable — quota / prepaid credit / key problem**\n"
f"**First seen in:** `{caller}`\n"
"Callers are degrading (auto-correct keeps Opus only, match-judge/parse-titles "
"return no suggestion, credit evals go to manual review, translations are "
"skipped).\n"
f"**Fix:** {QUOTA_EXHAUSTED_MESSAGE}\n"
f"**Error:** ```{err}```"
)
try:
ops_alerts.send_throttled_ops_alert(_ALERT_KEY, message, throttle_minutes=int(window / 60))
except Exception: # noqa: BLE001 - alerting must never raise
logger.warning("Gemini quota alert failed", exc_info=True)
# Let the next failure in this instance try again.
with _alert_lock:
_last_alert_attempt = 0.0
+2
View File
@@ -142,6 +142,8 @@ class JobManager:
review_mode=job_create.review_mode,
# Backing-vocals preference ("auto"=retain-where-safe | clean | review)
backing_preference=job_create.backing_preference,
# Translated lyrics beneath each line (None = off)
translation_language=job_create.translation_language,
# Distribution settings
brand_prefix=job_create.brand_prefix,
discord_webhook_url=job_create.discord_webhook_url,
+345
View File
@@ -0,0 +1,345 @@
"""Translated lyrics: an LLM translation of each reviewed lyric line.
A job created with ``translation_language`` gets its final (post-review) lyrics
translated once, just before the karaoke video renders. The result is stored at
``jobs/{job_id}/lyrics/translations.json`` (format in
``karaoke_gen.lyrics_transcriber.output.translations``), which the renderers draw in
smaller text beneath each line. Translations aren't editable; they're regenerated
from the reviewed text, and identical requests are served from a GCS cache (so a
re-render costs no new LLM call).
"""
from __future__ import annotations
import hashlib
import json
import logging
import time
from typing import Any, Dict, List, Optional
from backend.config import get_settings
logger = logging.getLogger(__name__)
# Languages a user can pick: the app's UI locales (code -> English name for the prompt).
TRANSLATION_LANGUAGES: Dict[str, str] = {
"ar": "Arabic",
"ca": "Catalan",
"cs": "Czech",
"da": "Danish",
"de": "German",
"el": "Greek",
"en": "English",
"es": "Spanish",
"fi": "Finnish",
"fr": "French",
"he": "Hebrew",
"hi": "Hindi",
"hr": "Croatian",
"hu": "Hungarian",
"id": "Indonesian",
"it": "Italian",
"ja": "Japanese",
"ko": "Korean",
"ms": "Malay",
"nb": "Norwegian (Bokmål)",
"nl": "Dutch",
"pl": "Polish",
"pt": "Portuguese",
"ro": "Romanian",
"ru": "Russian",
"sk": "Slovak",
"sv": "Swedish",
"th": "Thai",
"tl": "Filipino (Tagalog)",
"tr": "Turkish",
"uk": "Ukrainian",
"vi": "Vietnamese",
"zh": "Simplified Chinese",
}
TRANSLATIONS_GCS_NAME = "translations.json"
CACHE_PREFIX = "lyrics-translation-cache"
CACHE_VERSION = 1
MAX_ATTEMPTS = 2
BACKOFF_SECONDS = 2.0
# More than this share of lines coming back unchanged = the song is already in the
# target language, so a translation row would just repeat the lyrics.
SAME_LANGUAGE_THRESHOLD = 0.8
SYSTEM_PROMPT = """You translate song lyrics for karaoke videos. Each translated line is shown \
in small text directly beneath the original line while the singer sings it, so language \
learners understand what they are singing.
Rules:
- Return exactly one translation per input line, in the same order (same count).
- Translate the meaning naturally and idiomatically; it does not need to rhyme or be singable.
- A sentence often continues across lines: keep each translation aligned with the words of \
its own line where the target grammar allows, so the meaning lines up with what is being sung.
- Keep each translation about as short as its line; no explanations, notes, quotes or brackets.
- Keep names, places and brand names. Keep pure vocables (oh, ooh, la la, yeah, na na) as they are.
- If a line is already in the target language, return it unchanged.
"""
class LyricsTranslationError(Exception):
"""The lyrics couldn't be translated (model error or malformed output)."""
def normalize_language(code: Optional[str]) -> Optional[str]:
"""Supported language code for ``code`` (case/region-insensitive), else None."""
if not code:
return None
base = str(code).strip().lower().replace("_", "-")
if base in TRANSLATION_LANGUAGES:
return base
base = base.split("-")[0]
if base == "no":
base = "nb"
if base == "fil":
base = "tl"
return base if base in TRANSLATION_LANGUAGES else None
def _norm(text: str) -> str:
return " ".join((text or "").lower().split())
def is_same_language(lines: List[str], translations: List[str]) -> bool:
"""True when nearly every line came back unchanged (song already in that language)."""
pairs = [(a, b) for a, b in zip(lines, translations) if _norm(a)]
if not pairs:
return False
unchanged = sum(1 for a, b in pairs if _norm(a) == _norm(b))
return unchanged / len(pairs) >= SAME_LANGUAGE_THRESHOLD
def _user_prompt(lines: List[str], language: str, artist: Optional[str], title: Optional[str]) -> str:
song = " - ".join(p for p in (artist, title) if p) or "unknown song"
numbered = "\n".join(f"{i + 1}. {line}" for i, line in enumerate(lines))
return (
f"Song: {song}\n"
f"Target language: {TRANSLATION_LANGUAGES[language]}\n"
f"Translate these {len(lines)} lyric lines. Return JSON "
f'{{"translations": [...]}} with exactly {len(lines)} strings, one per line, '
f"without the line numbers.\n\n{numbered}"
)
def _is_transient(exc: BaseException) -> bool:
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
if isinstance(code, int) and code in {429, 500, 502, 503, 504}:
return True
text = str(exc).upper()
return any(m in text for m in ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "DEADLINE", "429", "503"))
class LyricsTranslationService:
def __init__(self, storage=None, model: Optional[str] = None):
self.settings = get_settings()
self.model = model or self.settings.lyrics_translation_model
self._storage = storage
def _get_storage(self):
if self._storage is None:
from backend.services.storage_service import StorageService
self._storage = StorageService()
return self._storage
# ---- cache (GCS, best-effort) ----
def _cache_path(self, lines: List[str], language: str, artist: Optional[str], title: Optional[str]) -> str:
payload = {"v": CACHE_VERSION, "model": self.model, "language": language,
"lines": lines, "artist": artist, "title": title}
digest = hashlib.sha256(json.dumps(payload, ensure_ascii=False).encode()).hexdigest()[:32]
return f"{CACHE_PREFIX}/{digest}.json"
def _cache_get(self, path: str, n: int) -> Optional[List[str]]:
try:
storage = self._get_storage()
if not storage.file_exists(path):
return None
data = storage.download_json(path)
translations = data.get("translations")
if isinstance(translations, list) and len(translations) == n:
return [str(t) for t in translations]
except Exception:
logger.warning("lyrics translation cache read failed for %s", path, exc_info=True)
return None
def _cache_put(self, path: str, translations: List[str]) -> None:
try:
self._get_storage().upload_json(path, {"model": self.model, "translations": translations})
except Exception:
logger.warning("lyrics translation cache write failed for %s", path, exc_info=True)
# ---- model ----
def _call_gemini(self, user_prompt: str) -> Any:
from google.genai import types
from backend.services.gemini_client import get_genai_client
client = get_genai_client(timeout_ms=90_000) # 2 attempts: render waits <= ~3 min
response = client.models.generate_content(
model=self.model,
contents=[user_prompt],
config=types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT,
temperature=0.3,
response_mime_type="application/json",
response_schema={
"type": "object",
"properties": {"translations": {"type": "array", "items": {"type": "string"}}},
"required": ["translations"],
},
),
)
if response.text is None:
raise LyricsTranslationError("model returned an empty response")
return json.loads(response.text)
def _translate_once(self, lines: List[str], language: str, artist, title) -> List[str]:
data = self._call_gemini(_user_prompt(lines, language, artist, title))
translations = data.get("translations") if isinstance(data, dict) else None
if not isinstance(translations, list) or len(translations) != len(lines):
got = len(translations) if isinstance(translations, list) else "no"
raise LyricsTranslationError(f"expected {len(lines)} translations, got {got}")
return [" ".join(str(t).split()) for t in translations]
def translate_lines(
self,
lines: List[str],
language: str,
*,
artist: Optional[str] = None,
title: Optional[str] = None,
) -> List[str]:
"""One translation per line (same order). Raises LyricsTranslationError."""
lang = normalize_language(language)
if lang is None:
raise LyricsTranslationError(f"unsupported language {language!r}")
if not lines:
return []
cache_path = self._cache_path(lines, lang, artist, title)
cached = self._cache_get(cache_path, len(lines))
if cached is not None:
logger.info("lyrics translation cache hit (%d lines, %s)", len(lines), lang)
return cached
last_error: Optional[BaseException] = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
started = time.time()
translations = self._translate_once(lines, lang, artist, title)
logger.info(
"lyrics translation: %d lines -> %s via %s in %.1fs",
len(lines), lang, self.model, time.time() - started,
)
self._cache_put(cache_path, translations)
return translations
except (LyricsTranslationError, ValueError) as exc: # malformed output: retry
last_error = exc
except Exception as exc:
from backend.services.gemini_client import note_gemini_failure
if note_gemini_failure("lyrics_translation", exc):
# Quota/credit/key problem: don't retry; the render goes ahead
# without the translation row.
raise LyricsTranslationError(
"translation service unavailable (Gemini quota/billing) — rendered without translation"
) from exc
if not _is_transient(exc):
raise LyricsTranslationError(f"translation model error: {exc}") from exc
last_error = exc
if attempt < MAX_ATTEMPTS:
backoff = BACKOFF_SECONDS * (2 ** (attempt - 1))
logger.warning(
"lyrics translation attempt %d/%d failed (%s); retrying in %.1fs",
attempt, MAX_ATTEMPTS, last_error, backoff,
)
time.sleep(backoff)
raise LyricsTranslationError(f"translation failed after {MAX_ATTEMPTS} attempts: {last_error}")
def load_final_segments(storage, job_id: str):
"""The reviewed lyric segments the video renders (corrections + review edits)."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
base = CorrectionResult.from_dict(storage.download_json(f"jobs/{job_id}/lyrics/corrections.json"))
updated_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_path):
updated = storage.download_json(updated_path)
if isinstance(updated, dict) and "corrections" in updated:
return CorrectionOperations.update_correction_result_with_data(base, updated).corrected_segments
return base.corrected_segments
def prepare_job_translations(
job_id: str, job, storage, job_manager=None, service: Optional[LyricsTranslationService] = None
) -> Optional[str]:
"""Translate a job's final lyrics and store ``translations.json``.
Returns the GCS path (relative to the bucket) when the video should show
translations, else None: no language requested, the song is already in that
language, or translation failed. A failure never blocks the render; it's logged as
an error and recorded in ``state_data.lyrics_translation`` so an admin can
re-render once fixed.
"""
stored_path = f"jobs/{job_id}/lyrics/{TRANSLATIONS_GCS_NAME}"
language = normalize_language(getattr(job, "translation_language", None))
if not language:
_remove_stale(storage, stored_path)
if job_manager is not None and (getattr(job, "state_data", None) or {}).get("lyrics_translation"):
# Translation was turned off since a previous render: clear the old outcome
# so the republished video isn't labelled "(With Translation into X)".
try:
job_manager.update_state_data(job_id, "lyrics_translation", {"status": "off"})
except Exception:
logger.warning(f"[job:{job_id}] could not clear lyrics_translation status", exc_info=True)
return None
status: Dict[str, Any] = {"language": language}
path: Optional[str] = None
try:
segments = [s for s in load_final_segments(storage, job_id) if (s.text or "").strip()]
lines = [s.text.strip() for s in segments]
service = service or LyricsTranslationService(storage=storage)
translations = service.translate_lines(lines, language, artist=job.artist, title=job.title)
status.update(model=service.model, lines=len(lines))
if is_same_language(lines, translations):
logger.info(f"[job:{job_id}] Lyrics already in {language}; no translation row")
status["status"] = "same_language"
else:
path = stored_path
storage.upload_json(path, {
"language": language,
"language_name": TRANSLATION_LANGUAGES[language],
"model": service.model,
"lines": [
{"segment_id": s.id, "text": line, "translation": tr}
for s, line, tr in zip(segments, lines, translations)
],
})
status["status"] = "translated"
except Exception as exc:
logger.error(f"[job:{job_id}] Lyrics translation to {language} failed; rendering without it: {exc}", exc_info=True)
status.update(status="failed", error=str(exc)[:500])
path = None
if path is None:
# The encoder also reads lyrics/translations.json for the portrait video
_remove_stale(storage, stored_path)
if job_manager is not None:
try:
job_manager.update_state_data(job_id, "lyrics_translation", status)
except Exception:
logger.warning(f"[job:{job_id}] could not record lyrics_translation status", exc_info=True)
return path
def _remove_stale(storage, path: str) -> None:
"""Delete a translations file left by an earlier render (best-effort)."""
try:
storage.delete_file(path, ignore_missing=True)
except Exception:
logger.warning("could not delete stale %s", path, exc_info=True)
+6 -7
View File
@@ -149,18 +149,14 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
import copy
from google import genai
from google.genai import types
from backend.config import settings
from backend.services.gemini_client import get_genai_client
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
client = get_genai_client(timeout_ms=timeout_ms)
response = client.models.generate_content(
model=model,
contents=[user_prompt],
@@ -169,6 +165,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
# Simple extraction/classification: low thinking keeps cost and
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
thinking_config=types.ThinkingConfig(thinking_level="low"),
),
)
return json.loads(response.text)
+9 -7
View File
@@ -141,6 +141,9 @@ async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
data = await (generate or _default_generate)(
model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"')
except Exception as e:
from backend.services.gemini_client import note_gemini_failure
note_gemini_failure("match_judge_free_text", e)
logger.warning(f"resolve_free_text failed: {e}")
return _none(query, "unavailable")
return verdict_from_response(data, query)
@@ -200,17 +203,13 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
from google import genai
from google.genai import types
from backend.config import settings
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=int(getattr(settings, "match_judge_timeout_ms", 12000))),
)
from backend.services.gemini_client import get_genai_client
client = get_genai_client(timeout_ms=int(getattr(settings, "match_judge_timeout_ms", 12000)))
response = client.models.generate_content(
model=model,
contents=[user_prompt],
@@ -219,6 +218,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
# Simple extraction/classification: low thinking keeps cost and
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
thinking_config=types.ThinkingConfig(thinking_level="low"),
),
)
return json.loads(response.text)
+4 -1
View File
@@ -126,7 +126,10 @@ async def judge_match(
try:
return await ai(artist, title, candidates, audio_tier)
except Exception:
except Exception as exc:
from backend.services.gemini_client import note_gemini_failure
note_gemini_failure("match_judge", exc)
# Graceful degradation: returning no-suggestion is a safe fallback (the
# user just gets no auto-match). Log at WARNING (with traceback) so a
# transient AI blip does not page as a red "new error pattern".
+35 -2
View File
@@ -134,7 +134,9 @@ def _signature(error_message: str) -> str:
return hashlib.sha256((error_message or "").encode("utf-8")).hexdigest()
def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, int, Any]:
def _should_alert(
db: Any, signature: str, now: datetime, throttle_minutes: Optional[int] = None
) -> tuple[bool, bool, int, Any]:
"""Decide whether to send, WITHOUT yet acknowledging delivery.
Returns ``(should_send, is_novel, suppressed_since_last, doc_ref)``:
@@ -182,7 +184,8 @@ def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, i
if last_alerted_raw:
try:
last_alerted = datetime.fromisoformat(last_alerted_raw)
within_window = (now - last_alerted) < timedelta(minutes=_throttle_minutes())
window = throttle_minutes if throttle_minutes is not None else _throttle_minutes()
within_window = (now - last_alerted) < timedelta(minutes=window)
except (TypeError, ValueError):
within_window = False
@@ -225,6 +228,36 @@ def _mark_alerted(doc_ref: Any, now: datetime) -> None:
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
def send_throttled_ops_alert(key: str, message: str, throttle_minutes: int) -> bool:
"""Send an ops alert at most once per ``throttle_minutes`` for ``key``.
The throttle lives in Firestore (same dedup collection as job-failure
alerts), so it holds across every Cloud Run instance and job execution.
Fails open (sends) if Firestore is unreachable. Best-effort; never raises.
Returns True if an alert was sent.
"""
try:
if not _is_enabled():
return False
from backend.services.firestore_service import get_firestore_client
now = datetime.now(timezone.utc)
should_send, _novel, suppressed, doc_ref = _should_alert(
get_firestore_client(), key, now, throttle_minutes=throttle_minutes
)
if not should_send:
return False
if suppressed:
message += f"\n_(Collapsed {suppressed} earlier occurrence(s).)_"
sent = send_ops_alert(message)
if sent:
_mark_alerted(doc_ref, now)
return sent
except Exception as exc: # noqa: BLE001 - alerting must never raise
logger.warning("ops_alerts: throttled alert %s failed: %s", key, exc)
return False
def _retry_pending(state_data: dict) -> bool:
"""True if state_data.cloud_run_retry_pending is set and unexpired."""
pending = (state_data or {}).get("cloud_run_retry_pending")
+6 -7
View File
@@ -123,18 +123,14 @@ async def _default_generate(model: str, system: str, user: str) -> dict:
def _blocking_generate(model: str, system: str, user: str) -> dict:
from google import genai
from google.genai import types
from backend.config import settings
from backend.services.gemini_client import get_genai_client
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
client = get_genai_client(timeout_ms=timeout_ms)
response = client.models.generate_content(
model=model,
contents=[user],
@@ -143,6 +139,9 @@ def _blocking_generate(model: str, system: str, user: str) -> dict:
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
# Simple extraction/classification: low thinking keeps cost and
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
thinking_config=types.ThinkingConfig(thinking_level="low"),
),
)
return json.loads(response.text)
+3
View File
@@ -56,6 +56,9 @@ async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
try:
results = await ai.ai_parse(chunk, model=model, generate=generate)
except Exception as exc:
from backend.services.gemini_client import note_gemini_failure
note_gemini_failure("parse_titles", exc)
logger.warning(
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
return _blanks(chunk)
+11 -9
View File
@@ -431,6 +431,9 @@ def analyze_filenames(
llm_rows, leftover = _llm_analyze(leftover, generate)
rows.extend(llm_rows)
except Exception as e: # pragma: no cover - resilience guard
from backend.services.gemini_client import note_gemini_failure
note_gemini_failure("tenant_bulk_analyze", e)
logger.warning("Bulk-analyze LLM pass failed, using regex result: %s", e)
unpaired = [_describe_unpaired(fn) for fn in leftover]
@@ -438,7 +441,7 @@ def analyze_filenames(
# ---------------------------------------------------------------------------
# Default Vertex-Gemini generate (mirrors backend.services.match_judge.ai)
# Default Gemini generate (mirrors backend.services.match_judge.ai)
# ---------------------------------------------------------------------------
def _default_model() -> str:
@@ -451,22 +454,18 @@ def _default_model() -> str:
def default_generate(system_prompt: str, user_prompt: str) -> dict:
"""Blocking Vertex-Gemini call producing schema-constrained JSON.
"""Blocking Gemini (Developer API) call producing schema-constrained JSON.
Wrap in ``asyncio.to_thread`` when calling from async code.
"""
from google import genai
from google.genai import types
from backend.config import settings
from backend.services.gemini_client import get_genai_client
timeout_ms = int(getattr(settings, "tenant_bulk_timeout_ms", 30000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
client = get_genai_client(timeout_ms=timeout_ms)
response = client.models.generate_content(
model=_default_model(),
contents=[user_prompt],
@@ -475,6 +474,9 @@ def default_generate(system_prompt: str, user_prompt: str) -> dict:
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
# Simple extraction/classification: low thinking keeps cost and
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
thinking_config=types.ThinkingConfig(thinking_level="low"),
),
)
return json.loads(response.text)
+17 -5
View File
@@ -249,7 +249,7 @@ def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> by
return _to_jpeg(f"{noext}.png")
def _sample_segments(lines: List[str]):
def _sample_segments(lines: List[str], translations: Optional[List[str]] = None):
"""Evenly-timed segments: line i starts at 2+3i s, words spread over 2.5 s.
Starts < 10 s and gaps < 10 s so SectionDetector adds no intro/instrumental.
@@ -266,7 +266,14 @@ def _sample_segments(lines: List[str]):
for j, w in enumerate(words_text)
]
segments.append(
LyricsSegment(id=f"s{i}", text=" ".join(words_text), words=words, start_time=start, end_time=start + 2.5)
LyricsSegment(
id=f"s{i}",
text=" ".join(words_text),
words=words,
start_time=start,
end_time=start + 2.5,
translation=(translations[i] if translations and i < len(translations) else None) or None,
)
)
return segments
@@ -330,8 +337,13 @@ class _FrameRenderer:
raise ThemePreviewError("Karaoke frame render timed out") from exc
def render_karaoke_frame(styles: Dict, lines: List[str], workdir: str) -> bytes:
"""One frame of the karaoke video with the first line about half sung."""
def render_karaoke_frame(
styles: Dict, lines: List[str], workdir: str, translations: Optional[List[str]] = None
) -> bytes:
"""One frame of the karaoke video with the first line about half sung.
``translations`` (one per line) renders the translated-lyrics layout.
"""
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
from karaoke_gen.lyrics_transcriber.output.subtitles import SubtitlesGenerator
from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE
@@ -345,7 +357,7 @@ def render_karaoke_frame(styles: Dict, lines: List[str], workdir: str) -> bytes:
font_size = karaoke.get("font_size", DEFAULT_FONT_SIZE)
max_line_length = karaoke.get("max_line_length", DEFAULT_MAX_LINE_LENGTH)
segments = SegmentResizer(max_line_length=max_line_length, logger=logger).resize_segments(
_sample_segments(lines)
_sample_segments(lines, translations)
)
subtitles = SubtitlesGenerator(
output_dir=workdir,
+64
View File
@@ -0,0 +1,64 @@
"""Preview of the translated-lyrics layout for the job-creation option.
Renders one karaoke frame of the default theme (same renderer as production, via
``theme_preview_service``) with sample lyrics and their translation in the chosen
language. Translations come from ``translation_preview_samples`` (generated once,
committed), so the preview never calls the LLM.
"""
import base64
import logging
import tempfile
import threading
from collections import OrderedDict
from typing import Optional
from backend.services.lyrics_translation import normalize_language
from backend.services.theme_preview_service import render_karaoke_frame, resolve_assets
from backend.services.theme_service import get_theme_service
from backend.services.translation_preview_samples import SAMPLES
logger = logging.getLogger(__name__)
FALLBACK_THEME_ID = "nomad"
_CACHE: "OrderedDict[tuple, str]" = OrderedDict()
_CACHE_MAX = 40
_lock = threading.Lock()
_key_locks: "dict[tuple, threading.Lock]" = {} # bounded: themes x 33 languages
def render_translation_preview(language: str, theme_id: Optional[str] = None) -> str:
"""JPEG data URL of a karaoke frame with translations in ``language``."""
code = normalize_language(language)
if code is None or code not in SAMPLES:
raise ValueError(f"Unsupported language: {language}")
theme_service = get_theme_service()
theme_id = theme_id or theme_service.get_default_theme_id() or FALLBACK_THEME_ID
key = (theme_id, code)
with _lock:
if key in _CACHE:
_CACHE.move_to_end(key)
return _CACHE[key]
key_lock = _key_locks.setdefault(key, threading.Lock())
# One render per key: concurrent cold requests wait for it instead of each running ffmpeg
with key_lock:
with _lock:
if key in _CACHE:
_CACHE.move_to_end(key)
return _CACHE[key]
return _render_and_cache(key, theme_service, theme_id, code)
def _render_and_cache(key: tuple, theme_service, theme_id: str, code: str) -> str:
style_params = theme_service.get_theme_style_params(theme_id)
if style_params is None:
raise ValueError(f"Theme not found: {theme_id}")
styles = resolve_assets(style_params, theme_id)
sample = SAMPLES[code]
with tempfile.TemporaryDirectory(prefix="translation-preview-") as workdir:
jpeg = render_karaoke_frame(styles, sample["lyrics"], workdir, translations=sample["translations"])
data_url = "data:image/jpeg;base64," + base64.b64encode(jpeg).decode()
with _lock:
_CACHE[key] = data_url
while len(_CACHE) > _CACHE_MAX:
_CACHE.popitem(last=False)
return data_url
@@ -0,0 +1,260 @@
"""Sample lyrics + translations for the translated-lyrics preview.
Generated by backend/scripts/generate_translation_preview_samples.py; don't edit by hand.
"""
SAMPLES = {'ar': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['كل ليلة أردد الغناء',
'تخفت الأضواء وها هي أغنيتي',
'أمسك الميكروفون وأعتلي المسرح',
'اقلب الصفحة، اقلب الصفحة']},
'ca': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Cada nit canto alhora',
"S'apaguen els llums i arriba la meva cançó",
"Agafo el micro i pujo a l'escenari",
'Passa pàgina, passa pàgina']},
'cs': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Každou noc si zpívám',
'Světla zhasnou a je tu má píseň',
'Vezmi mikrofon a vyjdi na pódium',
'Otoč stránku, otoč stránku']},
'da': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Hver aften synger jeg med',
'Lyset dæmpes, og her er min sang',
'Hold mikrofonen og indtag scenen',
'Vend siden, vend siden']},
'de': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Jede Nacht singe ich mit',
'Die Lichter gehen aus und hier ist mein Lied',
'Halt das Mikrofon und betritt die Bühne',
'Schlag die Seite um, schlag die Seite um']},
'el': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Κάθε βράδυ τραγουδάω μαζί',
'Τα φώτα σβήνουν και να το τραγούδι μου',
'Κράτα το μικρόφωνο κι ανέβα στη σκηνή',
'Γύρισε σελίδα, γύρισε σελίδα']},
'en': {'lyrics': ['Cada noche canto sin parar',
'Se apagan las luces, es mi lugar',
'Tomo el micrófono y subo al escenario',
'Doy la vuelta a la página otra vez'],
'translations': ['Every night I sing nonstop',
"The lights go out, it's my place",
'I grab the microphone and take the stage',
'I turn the page once again']},
'es': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Cada noche canto a coro',
'Se apagan las luces y esta es mi canción',
'Toma el micrófono y sube al escenario',
'Pasa la página, pasa la página']},
'fi': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Joka ilta laulan mukana',
'Valot sammuvat ja tässä on lauluni',
'Tartu mikkiin ja nouse lavalle',
'Käännä sivua, käännä sivua']},
'fr': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Chaque soir je chante avec',
"Les lumières s'éteignent et voici ma chanson",
'Prends le micro et monte sur scène',
'Tourne la page, tourne la page']},
'he': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['בכל לילה אני שר יחד',
'האורות כבים והנה השיר שלי',
'מחזיק במיקרופון ועולה לבמה',
'להפוך את הדף, להפוך את הדף']},
'hi': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['हर रात मैं साथ गाता हूँ',
'रोशनी धीमी होती है और ये रहा मेरा गाना',
'माइक थामो और मंच पर कदम रखो',
'पन्ना पलटो, पन्ना पलटो']},
'hr': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Svake noći pjevam uz nju',
'Svjetla se gase i evo moje pjesme',
'Uzmi mikrofon i stani na pozornicu',
'Okreni stranicu, okreni stranicu']},
'hu': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Minden éjjel együtt éneklek',
'Kialszanak a fények, és itt a dalom',
'Fogd a mikrofont, és lépj a színpadra',
'Lapozz egyet, lapozz egyet']},
'id': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Setiap malam kuikut bernyanyi',
'Lampu padam dan inilah laguku',
'Pegang mikrofon dan naik ke panggung',
'Buka lembaran baru, buka lembaran baru']},
'it': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Ogni notte canto insieme',
'Le luci si spengono ed ecco la mia canzone',
'Prendo il microfono e salgo sul palco',
'Volto pagina, volto pagina']},
'ja': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['毎晩 一緒に歌う', '明かりが落ち 私の歌が始まる', 'マイクを握り ステージに立つ', 'ページをめくって ページをめくる']},
'ko': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['매일 밤 난 따라 불러', '불이 꺼지고 내 노래가 시작돼', '마이크를 잡고 무대에 올라', '페이지를 넘겨, 페이지를 넘겨']},
'ms': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Setiap malam aku ikut menyanyi',
'Lampu terpadam dan inilah laguku',
'Pegang mikrofon dan naik ke pentas',
'Selak halaman, selak halaman']},
'nb': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Hver kveld synger jeg med',
'Lyset dempes og her er sangen min',
'Hold mikrofonen og innta scenen',
'Bla om, bla om']},
'nl': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Elke avond zing ik mee',
'Het licht gaat uit en hier is mijn lied',
'Pak de microfoon en betreed het podium',
'Sla de bladzijde om, sla de bladzijde om']},
'pl': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Każdej nocy śpiewam razem z nimi',
'Gasną światła i oto moja piosenka',
'Chwytam mikrofon i wchodzę na scenę',
'Przewróć stronę, przewróć stronę']},
'pt': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Toda noite eu canto junto',
'Luzes se apagam e aqui está minha canção',
'Seguro o microfone e subo ao palco',
'Vire a página, vire a página']},
'ro': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['În fiecare noapte cânt și eu',
'Luminile se sting și iată cântecul meu',
'Iau microfonul și urc pe scenă',
'Întorc pagina, întorc pagina']},
'ru': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Каждую ночь я подпеваю',
'Гаснет свет, и вот моя песня',
'Беру микрофон и выхожу на сцену',
'Переверни страницу, переверни страницу']},
'sk': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Každú noc si spievam',
'Svetlá zhasnú a tu je moja pieseň',
'Chyť mikrofón a vstúp na pódium',
'Obráť list, obráť list']},
'sv': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Varje kväll sjunger jag med',
'Ljuset släcks och här är min sång',
'Håll micken och inta scenen',
'Vänd blad, vänd blad']},
'th': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['ทุกคืนฉันร้องตามไป',
'แสงไฟดับลงและนี่คือเพลงของฉัน',
'จับไมค์แล้วก้าวขึ้นเวที',
'เปิดหน้าใหม่ เปิดหน้าใหม่']},
'tl': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Gabi-gabi akong sumasabay',
'Nandidilim ang ilaw at heto ang awit ko',
'Hawakan ang mic at umakyat sa entablado',
'Ilipat ang pahina, ilipat ang pahina']},
'tr': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Her gece şarkıya eşlik ederim',
'Işıklar söner ve işte şarkım',
'Mikrofonu tut ve sahneye çık',
'Sayfayı çevir, sayfayı çevir']},
'uk': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Щоночі я підспівую',
'Світло гасне, і ось моя пісня',
'Тримаю мікрофон і виходжу на сцену',
'Перегорни сторінку, перегорни сторінку']},
'vi': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['Mỗi đêm tôi đều hát theo',
'Đèn tắt dần và đây là bài hát của tôi',
'Cầm lấy mic và bước lên sân khấu',
'Lật sang trang, lật sang trang']},
'zh': {'lyrics': ['Every night I sing along',
"Lights go down and here's my song",
'Hold the mic and take the stage',
'Turn the page, turn the page'],
'translations': ['每晚我都跟着唱', '灯光暗下,这是我的歌', '握紧麦克风,登上舞台', '翻过这一页,翻过这一页']}}
+47 -1
View File
@@ -20,7 +20,7 @@ predate placeholders keep the historical behaviour of appending
``\n\nBrand Code: <code>`` when a brand code is available.
"""
import re
from typing import List, Optional
from typing import Any, Dict, List, Optional
# Total length budget for the YouTube ``tags`` field (API rejects > 500 chars,
# counted as the sum of tag lengths plus separators). Stay comfortably under.
@@ -44,11 +44,50 @@ def _collapse_blank_lines(text: str) -> str:
return re.sub(r"\n{3,}", "\n\n", text)
# YouTube rejects titles over 100 chars; the upload service truncates at 95.
YOUTUBE_TITLE_MAX = 95
def translated_language_name(state_data: Optional[Dict[str, Any]]) -> Optional[str]:
"""English name of the language a job's video shows translated lyrics in, else None.
Only a ``translated`` outcome counts: a requested translation that failed or was
skipped (song already in that language) renders without a translation row, so the
published video must not claim one.
"""
info = (state_data or {}).get("lyrics_translation") or {}
if info.get("status") != "translated":
return None
from backend.services.lyrics_translation import TRANSLATION_LANGUAGES
return TRANSLATION_LANGUAGES.get(info.get("language") or "")
def build_youtube_title(
artist: Optional[str], title: Optional[str], translation_language_name: Optional[str] = None
) -> str:
"""``Artist - Title (Karaoke)``, labelled when the video carries translated lyrics.
The translation label sits before "(Karaoke)" (like the tempo label, which is part
of the title) and is never truncated away: an over-long artist/title is shortened
instead. Untranslated titles are returned as-is for the caller's usual truncation.
"""
base = f"{artist} - {title}"
if not translation_language_name:
return f"{base} (Karaoke)"
suffix = f" (With Translation into {translation_language_name}) (Karaoke)"
budget = YOUTUBE_TITLE_MAX - len(suffix)
if len(base) > budget:
base = base[: budget - 4].rsplit(" ", 1)[0].rstrip(" -") + " ..."
return f"{base}{suffix}"
def render_youtube_description(
artist: Optional[str] = None,
title: Optional[str] = None,
brand_code: Optional[str] = None,
template: Optional[str] = None,
translation_language_name: Optional[str] = None,
) -> str:
"""Render a YouTube description from the template + per-video values.
@@ -58,6 +97,8 @@ def render_youtube_description(
brand_code: NOMAD-#### style code, or falsy to omit the brand-code line.
template: Override template. Defaults to
``Settings.default_youtube_description``.
translation_language_name: When the video shows translated lyrics (see
``translated_language_name``), an up-front notice says so.
Returns:
The fully rendered description string, stripped of trailing whitespace.
@@ -104,6 +145,11 @@ def render_youtube_description(
notice = tempo_description_notice(title)
if notice:
result = f"{notice}\n\n{result}"
if translation_language_name:
result = (
f"This karaoke video includes translated lyrics ({translation_language_name}) "
f"beneath each line.\n\n{result}"
)
return _collapse_blank_lines(result).strip()
+2
View File
@@ -18,6 +18,8 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
os.environ.setdefault('GCS_BUCKET_NAME', 'test-bucket')
os.environ.setdefault('FIRESTORE_COLLECTION', 'jobs')
os.environ.setdefault('ENVIRONMENT', 'test')
# Gemini Developer API key: never let a test fall through to Secret Manager.
os.environ.setdefault('GEMINI_API_KEY', 'test-gemini-key')
import pytest
from unittest.mock import Mock, MagicMock, AsyncMock, patch
@@ -0,0 +1,304 @@
"""Tests for backend.services.gemini_client (Gemini Developer API helper) and the
per-caller graceful degradation when Gemini's quota/credit/key is unusable."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from backend.services import gemini_client
from backend.services.gemini_client import (
GeminiKeyUnavailableError,
get_api_key,
get_genai_client,
is_quota_or_billing_error,
note_gemini_failure,
)
class FakeAPIError(Exception):
"""Mimics google.genai.errors.APIError (numeric ``code`` + ``status``)."""
def __init__(self, code, status, message=""):
super().__init__(f"{code} {status}. {message}")
self.code = code
self.status = status
QUOTA = FakeAPIError(429, "RESOURCE_EXHAUSTED", "Your prepayment credits are depleted")
RATE_LIMIT = FakeAPIError(
429, "RESOURCE_EXHAUSTED",
"quotaId: GenerateRequestsPerMinutePerProjectPerModel-PaidTier, retryDelay: 5s",
)
@pytest.fixture(autouse=True)
def _reset_alert_throttle(monkeypatch):
monkeypatch.setattr(gemini_client, "_last_alert_attempt", 0.0)
monkeypatch.setattr(gemini_client, "_ALERT_IN_BACKGROUND", False)
# ---- classifier -------------------------------------------------------------
@pytest.mark.parametrize(
"exc",
[
QUOTA,
FakeAPIError(429, "RESOURCE_EXHAUSTED", "You exceeded your current quota"),
FakeAPIError(403, "PERMISSION_DENIED", "Generative Language API has not been used"),
FakeAPIError(400, "INVALID_ARGUMENT", "API key not valid. Please pass a valid API key."),
FakeAPIError(400, "FAILED_PRECONDITION", "check your plan and billing details"),
RuntimeError("API key expired. Please renew the API key."),
GeminiKeyUnavailableError("no key"),
RuntimeError("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerDayPerProjectPerModel, retryDelay 3600s"),
],
)
def test_classifier_positive(exc):
assert is_quota_or_billing_error(exc)
@pytest.mark.parametrize(
"exc",
[
RATE_LIMIT,
FakeAPIError(500, "INTERNAL", "Internal error"),
FakeAPIError(503, "UNAVAILABLE", "The model is overloaded"),
FakeAPIError(400, "INVALID_ARGUMENT", "Request contains an invalid argument."),
TimeoutError("timed out"),
ValueError("processed 429 tokens"),
None,
],
)
def test_classifier_negative(exc):
assert not is_quota_or_billing_error(exc)
def test_classifier_walks_cause_chain():
try:
try:
raise QUOTA
except FakeAPIError as inner:
raise RuntimeError("wrapped") from inner
except RuntimeError as outer:
assert is_quota_or_billing_error(outer)
# ---- key + client -------------------------------------------------------------
def test_env_key_wins(monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", " env-key ")
with patch("backend.config.Settings.get_secret") as get_secret:
assert get_api_key() == "env-key"
get_secret.assert_not_called()
def test_falls_back_to_secret_manager(monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
with patch("backend.config.Settings.get_secret", return_value="sm-key") as get_secret:
assert get_api_key() == "sm-key"
get_secret.assert_called_once_with("gemini-api-key")
def test_missing_key_raises(monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
with patch("backend.config.Settings.get_secret", return_value=None):
with pytest.raises(GeminiKeyUnavailableError):
get_api_key()
def test_client_uses_api_key_never_vertex(monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
with patch("google.genai.Client") as client_cls:
get_genai_client(timeout_ms=1234)
kwargs = client_cls.call_args.kwargs
assert kwargs["api_key"] == "k"
assert kwargs["http_options"].timeout == 1234
assert kwargs["vertexai"] is False and "project" not in kwargs and "location" not in kwargs
# ---- note_gemini_failure / alert throttle --------------------------------------
def test_note_failure_ignores_ordinary_errors():
with patch.object(gemini_client, "_maybe_alert") as alert:
assert note_gemini_failure("x", RATE_LIMIT) is False
alert.assert_not_called()
def test_note_failure_alerts_once_per_window():
with patch("backend.services.ops_alerts.send_throttled_ops_alert", return_value=True) as send:
assert note_gemini_failure("auto_correct", QUOTA) is True
assert note_gemini_failure("match_judge", QUOTA) is True
send.assert_called_once()
key, message = send.call_args.args
assert key == "gemini-quota-exhausted"
assert "auto_correct" in message and "rotate gemini-api-key" in message
assert send.call_args.kwargs["throttle_minutes"] == 360
def test_note_failure_never_raises_and_rearms_after_failed_send():
with patch("backend.services.ops_alerts.send_throttled_ops_alert", side_effect=RuntimeError) as send:
assert note_gemini_failure("x", QUOTA) is True
assert note_gemini_failure("x", QUOTA) is True
# A failed send doesn't silence the instance for 6h.
assert send.call_count == 2
def test_alert_runs_in_background_thread(monkeypatch):
import threading
monkeypatch.setattr(gemini_client, "_ALERT_IN_BACKGROUND", True)
done = threading.Event()
seen = {}
def fake_send(*_a, **_k):
seen["thread"] = threading.current_thread().name
done.set()
return True
with patch("backend.services.ops_alerts.send_throttled_ops_alert", side_effect=fake_send):
assert note_gemini_failure("x", QUOTA) is True
assert done.wait(5)
assert seen["thread"] == "gemini-quota-alert"
def test_throttled_ops_alert_respects_firestore_window(monkeypatch):
from backend.services import ops_alerts
monkeypatch.setenv("FAILURE_ALERTS_ENABLED", "true")
db = MagicMock()
with patch("backend.services.firestore_service.get_firestore_client", return_value=db), \
patch.object(ops_alerts, "_should_alert", return_value=(False, False, 0, None)) as should, \
patch.object(ops_alerts, "send_ops_alert") as send:
assert ops_alerts.send_throttled_ops_alert("k", "msg", throttle_minutes=360) is False
send.assert_not_called()
assert should.call_args.kwargs["throttle_minutes"] == 360
with patch("backend.services.firestore_service.get_firestore_client", return_value=db), \
patch.object(ops_alerts, "_should_alert", return_value=(True, False, 2, "ref")), \
patch.object(ops_alerts, "send_ops_alert", return_value=True) as send, \
patch.object(ops_alerts, "_mark_alerted") as mark:
assert ops_alerts.send_throttled_ops_alert("k", "msg", throttle_minutes=360) is True
assert "Collapsed 2" in send.call_args.args[0]
mark.assert_called_once()
# ---- per-caller degradation ----------------------------------------------------
def _quota_client():
client = MagicMock()
client.models.generate_content.side_effect = QUOTA
return client
def test_auto_correct_quota_is_non_retryable_and_skips_gemini_leg():
from backend.services.auto_correct.service import AutoCorrectService, AutoCorrectServiceError
service = AutoCorrectService()
with patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
patch.object(gemini_client, "_maybe_alert"), \
patch("backend.services.auto_correct.service.time.sleep") as sleep:
with pytest.raises(AutoCorrectServiceError) as ei:
service._call_model("gemini-3.8-flash", "sys", "user", job_id="j")
assert ei.value.retryable is False and ei.value.status_code == 503
sleep.assert_not_called()
def test_auto_correct_compare_keeps_opus_when_gemini_quota_exhausted():
from backend.services.auto_correct.service import AutoCorrectService, AutoCorrectServiceError
from backend.services.auto_correct.settings import AutoCorrectSettings
segments = [{"id": "s1", "words": [{"id": "w0", "text": "glory"}]}]
refs = {"genius": {"segments": [{"text": "chlorine"}]}}
sugg = {"op": "replace", "start_idx": 0, "end_idx": 0, "new_text": "chlorine",
"reason": "r", "category": "mishearing", "confidence": 0.9}
def fake_call(model, *_a, **_k):
if model.startswith("gemini"):
raise AutoCorrectServiceError("Gemini is unavailable", status_code=503)
return {"suggestions": [sugg]}, None
service = AutoCorrectService()
with patch.object(service.settings, "auto_correct_compare_models", "claude-opus-5-5;gemini-3.8-flash"), \
patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", side_effect=fake_call):
result = service.suggest(
job_id="j", segments=segments, reference_lyrics=refs, artist="A", title="T",
settings=AutoCorrectSettings(compare_models=True),
)
assert result.model == "claude-opus-5-5"
assert any("gemini-3.8-flash failed" in w for w in result.warnings)
@pytest.mark.asyncio
async def test_match_judge_quota_returns_no_suggestion_and_alerts():
from backend.services.match_judge import service as mj
async def no_candidates(*_a, **_k):
return []
async def boom(*_a, **_k):
raise QUOTA
with patch.object(gemini_client, "_maybe_alert") as alert:
verdict = await mj.judge_match(
"A", "T", search_tracks=no_candidates, ai_judge=boom, enabled=True
)
assert verdict.reason == "ai failed"
alert.assert_called_once()
def test_custom_lyrics_quota_is_clean_503():
from backend.services.custom_lyrics.settings import GenerationSettings
from backend.services.custom_lyrics_service import CustomLyricsService, CustomLyricsServiceError
service = CustomLyricsService()
with patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
patch.object(gemini_client, "_maybe_alert"):
with pytest.raises(CustomLyricsServiceError) as ei:
service._call_gemini(system_prompt="s", user_prompt="u", pdf_bytes=None,
settings=GenerationSettings())
assert ei.value.status_code == 503
assert "temporarily unavailable" in str(ei.value)
def test_credit_eval_quota_goes_to_manual_review():
from backend.services.credit_evaluation_service import CreditEvaluationService
svc = CreditEvaluationService.__new__(CreditEvaluationService)
svc.settings = MagicMock(credit_eval_enabled=True, credit_eval_model="gemini-3.8-flash")
signals = {"fingerprint_matches": [{"x": 1}], "ip_matches": [], "recent_signups_ip": 0,
"recent_signups_fp": 0, "user_data": {}, "ip_geo": None, "user_agent": None}
with patch.object(svc, "_collect_signals", return_value=signals), \
patch.object(svc, "_log_evaluation"), \
patch("backend.services.gemini_client.get_genai_client", return_value=_quota_client()), \
patch.object(gemini_client, "_maybe_alert") as alert:
evaluation = svc.evaluate("a@b.c", "welcome")
assert evaluation.decision == "pending_review"
alert.assert_called_once()
def test_error_monitor_llm_does_not_retry_on_quota():
from backend.services.error_monitor import llm_analysis
with patch.object(llm_analysis, "get_genai_client", return_value=_quota_client()), \
patch.object(gemini_client, "_maybe_alert"), \
patch.object(llm_analysis.time, "sleep") as sleep:
with pytest.raises(FakeAPIError):
llm_analysis._call_llm("sys", "user")
sleep.assert_not_called()
def test_classifier_ignores_implicit_context():
"""A Gemini-unrelated 403 raised earlier must not be blamed on Gemini."""
try:
try:
raise FakeAPIError(403, "PERMISSION_DENIED", "firestore says no")
except FakeAPIError:
raise ValueError("later, unrelated failure") # implicit __context__ only
except ValueError as exc:
assert not is_quota_or_billing_error(exc)
+6 -5
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import io
import os
import json
from unittest.mock import MagicMock, patch
@@ -103,11 +104,11 @@ def test_text_only_happy_path(service: CustomLyricsService) -> None:
assert result.line_count_mismatch is False
assert result.iterations_used == 0
assert result.model == "gemini-3.1-pro-preview"
assert mock_client_cls.call_args.kwargs == {
"vertexai": True,
"project": "test-project",
"location": "global",
}
# Gemini Developer API (API key) — never Vertex AI.
kwargs = mock_client_cls.call_args.kwargs
assert kwargs["api_key"] == os.environ["GEMINI_API_KEY"]
assert kwargs["vertexai"] is False and "project" not in kwargs
assert kwargs["http_options"].timeout == 300_000
def test_docx_input_parsed_to_text(
+103
View File
@@ -257,6 +257,109 @@ class TestPostmarkEmailProvider:
assert result is False
class TestPostmarkRetry:
"""Transient Postmark failures are retried; deterministic errors are not."""
def _response(self, status_code, body=None, json_body=True):
resp = Mock()
resp.status_code = status_code
if json_body:
resp.json.return_value = body or {"MessageID": "abc"}
else:
resp.json.side_effect = ValueError("not json")
resp.text = "" if json_body else "<html><center><h1>403 Forbidden</h1></center></html>"
return resp
def _send(self, provider):
return provider.send_email_detailed(
to_email="user@example.com", subject="Test", html_content="<p>x</p>"
)
@pytest.fixture(autouse=True)
def no_sleep(self):
with patch("backend.services.email_service.time.sleep") as mock_sleep:
self.mock_sleep = mock_sleep
yield
@pytest.fixture
def provider(self):
return PostmarkEmailProvider(server_token="t", from_email="f@e.com")
def test_html_403_then_success_is_retried(self, provider):
"""The prod failure mode: nginx HTML 403 from Postmark's edge, then OK."""
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = [self._response(403, json_body=False), self._response(200)]
result = self._send(provider)
assert result.success is True
assert result.message_id == "abc"
assert mock_post.call_count == 2
self.mock_sleep.assert_called_once_with(1.0)
def test_html_403_gives_up_after_all_attempts(self, provider):
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(403, json_body=False)
result = self._send(provider)
assert result.success is False
assert mock_post.call_count == 3
assert [c.args[0] for c in self.mock_sleep.call_args_list] == [1.0, 3.0]
@pytest.mark.parametrize("status", [429, 500, 503])
def test_rate_limit_and_server_errors_are_retried(self, provider, status):
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = [self._response(status, body={"ErrorCode": 0}), self._response(200)]
result = self._send(provider)
assert result.success is True
assert mock_post.call_count == 2
@pytest.mark.parametrize(
"status,body",
[
(403, {"ErrorCode": 10, "Message": "Bad or missing API token"}), # JSON 403 = real auth error
(422, {"ErrorCode": 300, "Message": "Invalid email request"}),
(422, {"ErrorCode": 406, "Message": "Inactive recipient"}),
],
)
def test_deterministic_postmark_errors_not_retried(self, provider, status, body):
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.return_value = self._response(status, body=body)
result = self._send(provider)
assert result.success is False
assert mock_post.call_count == 1
self.mock_sleep.assert_not_called()
def test_connect_timeout_is_retried(self, provider):
import requests as _requests
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = [_requests.ConnectTimeout("slow"), self._response(200)]
result = self._send(provider)
assert result.success is True
assert mock_post.call_count == 2
def test_connect_timeout_on_every_attempt_fails_cleanly(self, provider):
import requests as _requests
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = _requests.ConnectTimeout("slow")
result = self._send(provider)
assert result.success is False
assert mock_post.call_count == 3
def test_read_timeout_not_retried_to_avoid_duplicate_send(self, provider):
"""Postmark may have accepted the message; it has no idempotency key."""
import requests as _requests
with patch("backend.services.email_service.requests.post") as mock_post:
mock_post.side_effect = _requests.ReadTimeout("no response")
result = self._send(provider)
assert result.success is False
assert mock_post.call_count == 1
class TestEmailServiceProviderSelection:
"""Tests for EmailService._get_provider() selection logic."""
@@ -0,0 +1,63 @@
"""Simple classification/extraction Gemini callers must request LOW thinking.
Gemini 3 Flash defaults to high/dynamic thinking, and thinking tokens are billed
as output — the dominant Vertex cost. These callers do short structured
extraction or grant/deny classification, so low thinking is ample (cost cut
2026-10-01). Quality-sensitive callers (auto-correct, custom lyrics, lyrics
translation) deliberately keep the model default and are not covered here.
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
def _fake_client():
client = MagicMock()
client.models.generate_content.return_value = SimpleNamespace(text="{}")
return client
def _thinking_level(client) -> str:
config = client.models.generate_content.call_args.kwargs["config"]
return config.thinking_config.thinking_level.value.lower()
@pytest.mark.parametrize(
"module_path",
[
"backend.services.match_judge.ai",
"backend.services.match_judge.free_text",
"backend.services.parse_titles.ai",
],
)
def test_blocking_generate_uses_low_thinking(module_path) -> None:
import importlib
mod = importlib.import_module(module_path)
client = _fake_client()
with patch("google.genai.Client", return_value=client):
mod._blocking_generate("gemini-3.8-flash", "sys", "user")
assert _thinking_level(client) == "low"
def test_tenant_bulk_generate_uses_low_thinking() -> None:
from backend.services.tenant_bulk import analyze
client = _fake_client()
with patch("google.genai.Client", return_value=client):
analyze.default_generate("sys", "user")
assert _thinking_level(client) == "low"
def test_credit_eval_uses_low_thinking() -> None:
from backend.services.credit_evaluation_service import CreditEvaluationService
client = _fake_client()
svc = CreditEvaluationService.__new__(CreditEvaluationService)
svc.settings = SimpleNamespace(google_cloud_project="p", credit_eval_model="gemini-3.8-flash")
with patch("google.genai.Client", return_value=client):
svc._call_gemini("prompt")
assert _thinking_level(client) == "low"
+317
View File
@@ -0,0 +1,317 @@
"""Translated lyrics: LLM translation service + per-job translations.json."""
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from backend.services import lyrics_translation as lt
from backend.services.lyrics_translation import (
LyricsTranslationError,
LyricsTranslationService,
is_same_language,
normalize_language,
prepare_job_translations,
)
class FakeStorage:
def __init__(self, files=None):
self.files = dict(files or {})
self.deleted = []
def file_exists(self, path):
return path in self.files
def download_json(self, path):
return self.files[path]
def upload_json(self, path, data):
self.files[path] = data
def delete_file(self, path, ignore_missing=False):
self.deleted.append(path)
self.files.pop(path, None)
return True
@pytest.fixture(autouse=True)
def no_sleep(monkeypatch):
monkeypatch.setattr(lt.time, "sleep", lambda s: None)
# ---- language codes ----
@pytest.mark.parametrize("raw,expected", [
("es", "es"), ("ES", "es"), ("pt-BR", "pt"), ("zh_CN", "zh"), ("no", "nb"), ("fil", "tl"),
("xx", None), ("", None), (None, None),
])
def test_normalize_language(raw, expected):
assert normalize_language(raw) == expected
def test_supported_languages_match_ui_locales():
import os
messages = os.path.join(os.path.dirname(__file__), "..", "..", "frontend", "messages")
locales = {f[:-5] for f in os.listdir(messages) if f.endswith(".json") and not f.startswith(".")}
assert set(lt.TRANSLATION_LANGUAGES) == locales
def test_is_same_language():
lines = ["Hola amigo", "Te quiero", "La la la", "Adiós"]
assert is_same_language(lines, ["hola amigo", "Te quiero", "La la la", "Adiós"])
assert not is_same_language(lines, ["Hi friend", "I love you", "La la la", "Bye"])
assert not is_same_language([], [])
# ---- translate_lines ----
def make_service(responses, storage=None):
svc = LyricsTranslationService(storage=storage or FakeStorage(), model="test-model")
svc._call_gemini = MagicMock(side_effect=responses)
return svc
def test_translate_lines_returns_one_per_line_and_caches():
storage = FakeStorage()
svc = make_service([{"translations": ["Hola mundo", "Adiós"]}], storage)
assert svc.translate_lines(["Hello world", "Goodbye"], "es") == ["Hola mundo", "Adiós"]
cached = [p for p in storage.files if p.startswith(lt.CACHE_PREFIX)]
assert len(cached) == 1
# Second call is served from the cache
svc2 = make_service([AssertionError("should not call the model")], storage)
assert svc2.translate_lines(["Hello world", "Goodbye"], "es") == ["Hola mundo", "Adiós"]
def test_cache_key_depends_on_language_and_lines():
svc = make_service([])
a = svc._cache_path(["x"], "es", None, None)
assert a != svc._cache_path(["x"], "fr", None, None)
assert a != svc._cache_path(["y"], "es", None, None)
def test_wrong_count_is_retried():
svc = make_service([{"translations": ["only one"]}, {"translations": ["uno", "dos"]}])
assert svc.translate_lines(["one", "two"], "es") == ["uno", "dos"]
assert svc._call_gemini.call_count == 2
def test_gives_up_after_max_attempts():
svc = make_service([{"translations": []}] * lt.MAX_ATTEMPTS)
with pytest.raises(LyricsTranslationError):
svc.translate_lines(["one", "two"], "es")
assert svc._call_gemini.call_count == lt.MAX_ATTEMPTS
def test_transient_error_retried_permanent_error_raised():
# Per-minute rate limit: transient, retried.
transient = Exception("429 RESOURCE_EXHAUSTED quotaId GenerateRequestsPerMinutePerProjectPerModel")
svc = make_service([transient, {"translations": ["uno"]}])
assert svc.translate_lines(["one"], "es") == ["uno"]
svc = make_service([Exception("400 invalid argument")])
with pytest.raises(LyricsTranslationError):
svc.translate_lines(["one"], "es")
assert svc._call_gemini.call_count == 1
def test_quota_exhausted_not_retried_and_alerts():
class QuotaError(Exception):
code = 403
status = "PERMISSION_DENIED"
svc = make_service([QuotaError("Your prepayment credits are depleted")])
with patch("backend.services.gemini_client._maybe_alert") as alert:
with pytest.raises(LyricsTranslationError, match="unavailable"):
svc.translate_lines(["one"], "es")
assert svc._call_gemini.call_count == 1
alert.assert_called_once()
def test_unsupported_language_raises():
with pytest.raises(LyricsTranslationError):
make_service([]).translate_lines(["one"], "xx")
def test_prompt_lists_numbered_lines_and_language():
prompt = lt._user_prompt(["first", "second"], "he", "Artist", "Song")
assert "Hebrew" in prompt and "1. first\n2. second" in prompt and "exactly 2 strings" in prompt
# ---- prepare_job_translations ----
def corrections(*texts):
segs = []
for i, text in enumerate(texts):
words = [{"id": f"w{i}{j}", "text": w, "start_time": i * 3 + j * 0.5, "end_time": i * 3 + j * 0.5 + 0.4}
for j, w in enumerate(text.split())]
segs.append({"id": f"s{i}", "text": text, "words": words,
"start_time": words[0]["start_time"] if words else i * 3,
"end_time": words[-1]["end_time"] if words else i * 3})
return {
"original_segments": segs, "corrected_segments": segs, "corrections": [], "corrections_made": 0,
"confidence": 1.0, "reference_lyrics": {}, "anchor_sequences": [], "gap_sequences": [],
"resized_segments": [], "metadata": {}, "correction_steps": [], "word_id_map": {}, "segment_id_map": {},
}
def job(language="es", job_id="job1"):
return SimpleNamespace(job_id=job_id, translation_language=language, artist="A", title="T")
def test_no_language_removes_stale_file_and_returns_none():
storage = FakeStorage({"jobs/job1/lyrics/translations.json": {"lines": []}})
assert prepare_job_translations("job1", job(None), storage) is None
assert "jobs/job1/lyrics/translations.json" in storage.deleted
def test_translation_turned_off_clears_previous_outcome():
# A re-render after an admin removes the language must not keep the old
# "translated" outcome, or YouTube would still be labelled with a translation.
from backend.services.youtube_description import translated_language_name
j = job(None)
j.state_data = {"lyrics_translation": {"language": "es", "status": "translated"}}
jm = MagicMock()
assert prepare_job_translations("job1", j, FakeStorage({}), jm) is None
jm.update_state_data.assert_called_once_with("job1", "lyrics_translation", {"status": "off"})
assert translated_language_name({"lyrics_translation": {"status": "off"}}) is None
def test_translates_final_reviewed_lyrics():
storage = FakeStorage({
"jobs/job1/lyrics/corrections.json": corrections("Hello world", "Goodbye"),
# Review edited the first line: the translation must use the edited text
"jobs/job1/lyrics/corrections_updated.json": corrections("Hello there world", "Goodbye"),
})
svc = make_service([{"translations": ["Hola mundo", "Adiós"]}], storage)
jm = MagicMock()
path = prepare_job_translations("job1", job(), storage, jm, service=svc)
assert path == "jobs/job1/lyrics/translations.json"
data = storage.files[path]
assert data["language"] == "es" and data["language_name"] == "Spanish"
assert data["lines"][0] == {"segment_id": "s0", "text": "Hello there world", "translation": "Hola mundo"}
sent = svc._call_gemini.call_args[0][0]
assert "Hello there world" in sent
jm.update_state_data.assert_called_once()
assert jm.update_state_data.call_args[0][2]["status"] == "translated"
def test_same_language_song_gets_no_translation_row():
storage = FakeStorage({"jobs/job1/lyrics/corrections.json": corrections("Hola amigo", "Te quiero")})
svc = make_service([{"translations": ["Hola amigo", "Te quiero"]}], storage)
jm = MagicMock()
assert prepare_job_translations("job1", job(), storage, jm, service=svc) is None
assert jm.update_state_data.call_args[0][2]["status"] == "same_language"
assert "jobs/job1/lyrics/translations.json" not in storage.files
def test_failure_never_blocks_render():
storage = FakeStorage({
"jobs/job1/lyrics/corrections.json": corrections("Hello"),
"jobs/job1/lyrics/translations.json": {"lines": []}, # stale from an earlier render
})
svc = make_service([Exception("400 bad request")], storage)
jm = MagicMock()
assert prepare_job_translations("job1", job(), storage, jm, service=svc) is None
status = jm.update_state_data.call_args[0][2]
assert status["status"] == "failed" and "bad request" in status["error"]
assert "jobs/job1/lyrics/translations.json" not in storage.files
# ---- job model ----
def test_job_create_normalizes_translation_language():
from backend.models.job import JobCreate
assert JobCreate(artist="a", title="b", translation_language="ES").translation_language == "es"
assert JobCreate(artist="a", title="b", translation_language="").translation_language is None
assert JobCreate(artist="a", title="b", translation_language="klingon").translation_language is None
assert JobCreate(artist="a", title="b").translation_language is None
def test_job_manager_copies_translation_language():
from backend.models.job import JobCreate
from backend.services.job_manager import JobManager
with patch("backend.services.job_manager.FirestoreService"), patch("backend.services.job_manager.StorageService"):
manager = JobManager()
manager.firestore = MagicMock()
created = manager.create_job(JobCreate(artist="a", title="b", theme_id="nomad", translation_language="ja"))
assert created.translation_language == "ja"
saved = manager.firestore.create_job.call_args[0][0]
assert saved.translation_language == "ja"
# ---- preview ----
def test_preview_samples_cover_every_language():
from backend.services.translation_preview_samples import SAMPLES
assert set(SAMPLES) == set(lt.TRANSLATION_LANGUAGES)
for code, sample in SAMPLES.items():
assert len(sample["lyrics"]) == len(sample["translations"]) == 4, code
assert all(t.strip() for t in sample["translations"]), code
def test_preview_route_rejects_unknown_language():
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.themes import router
app = FastAPI()
app.include_router(router, prefix="/api")
client = TestClient(app)
assert client.get("/api/themes/translation-preview?language=xx").status_code == 400
with patch("backend.services.translation_preview.render_translation_preview", return_value="data:image/jpeg;base64,AA"):
resp = client.get("/api/themes/translation-preview?language=he")
assert resp.status_code == 200 and resp.json() == {"image": "data:image/jpeg;base64,AA"}
def test_preview_renders_sample_with_translations():
from backend.services import translation_preview as tp
tp._CACHE.clear()
theme_service = MagicMock()
theme_service.get_default_theme_id.return_value = "nomad"
theme_service.get_theme_style_params.return_value = {"karaoke": {}}
with patch.object(tp, "get_theme_service", return_value=theme_service), \
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
patch.object(tp, "render_karaoke_frame", return_value=b"jpeg") as render:
url = tp.render_translation_preview("fr")
tp.render_translation_preview("fr") # cached
assert url.startswith("data:image/jpeg;base64,")
render.assert_called_once()
assert render.call_args.kwargs["translations"] == tp.SAMPLES["fr"]["translations"]
def test_concurrent_cold_previews_render_once():
import threading
import time as _time
from backend.services import translation_preview as tp
tp._CACHE.clear()
theme_service = MagicMock()
theme_service.get_default_theme_id.return_value = "nomad"
theme_service.get_theme_style_params.return_value = {"karaoke": {}}
def slow_render(*a, **k):
_time.sleep(0.2)
return b"jpeg"
with patch.object(tp, "get_theme_service", return_value=theme_service), \
patch.object(tp, "resolve_assets", side_effect=lambda s, t: s), \
patch.object(tp, "render_karaoke_frame", side_effect=slow_render) as render:
threads = [threading.Thread(target=tp.render_translation_preview, args=("de",)) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
assert render.call_count == 1
@@ -122,3 +122,228 @@ async def test_lyrics_worker_trigger_swallows_errors() -> None:
with patch("backend.services.worker_service.WorkerService", return_value=ws):
await _trigger_proactive_auto_correct("job-1", job_log) # must not raise
job_log.warning.assert_called()
# ---- de-duplication (lyrics trigger vs screens pre-apply race) ----
import google.api_core.exceptions as gexc # noqa: E402
class _FakeBlob:
def __init__(self, bucket, path):
self.bucket, self.path = bucket, path
self.generation = None
def upload_from_string(self, data, content_type=None, if_generation_match=None):
current = self.bucket.objects.get(self.path)
current_gen = current[0] if current else 0
if if_generation_match is not None and if_generation_match != current_gen:
raise gexc.PreconditionFailed("generation mismatch")
self.bucket.next_gen += 1
self.generation = self.bucket.next_gen
self.bucket.objects[self.path] = (self.generation, data)
def download_as_bytes(self):
return self.bucket.objects[self.path][1].encode()
def delete(self, if_generation_match=None):
current = self.bucket.objects.get(self.path)
if current is None:
raise gexc.NotFound("gone")
if if_generation_match is not None and if_generation_match != current[0]:
raise gexc.PreconditionFailed("generation mismatch")
del self.bucket.objects[self.path]
class _FakeBucket:
def __init__(self):
self.objects: dict = {}
self.next_gen = 100
def blob(self, path):
return _FakeBlob(self, path)
def get_blob(self, path):
if path not in self.objects:
return None
b = _FakeBlob(self, path)
b.generation = self.objects[path][0]
return b
def put_lease(self, job_id, acquired_at):
import json as _json
self.next_gen += 1
self.objects[f"jobs/{job_id}/lyrics/auto_correct_inflight.json"] = (
self.next_gen, _json.dumps({"acquired_at": acquired_at}))
def _patch_with_bucket(service):
p_set, p_st, p_jm, _p_svc, storage = _patch(service=service)
bucket = _FakeBucket()
storage.bucket = bucket
storage.file_exists.side_effect = lambda p: p.endswith("corrections.json") or p in bucket.objects
return p_set, p_st, p_jm, storage, bucket
@pytest.mark.asyncio
async def test_concurrent_calls_on_same_instance_share_one_run() -> None:
"""Regression (job 96cf1100): the lyrics trigger and the screens pre-apply
both called this within seconds and each ran the multi-model suggest."""
import asyncio as _asyncio
import threading
release = threading.Event()
svc = MagicMock()
def _slow_suggest(**_kw):
release.wait(5)
return SimpleNamespace(suggestions=[1, 2, 3], model="m", elapsed_seconds=1.0)
svc.suggest.side_effect = _slow_suggest
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
first = _asyncio.create_task(process_proactive_auto_correct("job-dup"))
await _asyncio.sleep(0.05)
assert "jobs/job-dup/lyrics/auto_correct_inflight.json" in bucket.objects # lease held
second = _asyncio.create_task(process_proactive_auto_correct("job-dup"))
await _asyncio.sleep(0.05)
release.set()
r1, r2 = await _asyncio.gather(first, second)
assert svc.suggest.call_count == 1
assert r1 == r2 == {"status": "generated", "suggestions": 3}
assert bucket.objects == {} # our lease released
# A later (non-concurrent) call isn't blocked by a leftover in-flight entry.
await process_proactive_auto_correct("job-dup")
assert svc.suggest.call_count == 2 # in prod this hits the service's own GCS cache
@pytest.mark.asyncio
async def test_peer_instance_holding_lease_is_awaited_not_duplicated(monkeypatch) -> None:
import time as _time
from backend.workers import auto_correct_worker as w
monkeypatch.setattr(w, "PEER_POLL_SECONDS", 0)
svc = MagicMock()
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
bucket.put_lease("job-peer", _time.time()) # fresh lease held by another instance
peer_cache = iter([None, None, [{"id": "s1"}, {"id": "s2"}]])
with p_set, p_st, p_jm, \
patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc), \
patch("backend.services.auto_approval.executor._load_ai_suggestions",
side_effect=lambda *_a: next(peer_cache)):
result = await process_proactive_auto_correct("job-peer")
assert result == {"status": "deduped", "suggestions": 2}
svc.suggest.assert_not_called()
assert "jobs/job-peer/lyrics/auto_correct_inflight.json" in bucket.objects # never released theirs
@pytest.mark.asyncio
async def test_stale_peer_lease_is_taken_over_with_generation_fence() -> None:
svc = MagicMock()
svc.suggest.return_value = SimpleNamespace(suggestions=[1], model="m", elapsed_seconds=1.0)
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
bucket.put_lease("job-stale", 0) # leftover from a crashed instance
with p_set, p_st, p_jm, patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc):
result = await process_proactive_auto_correct("job-stale")
assert result["status"] == "generated"
svc.suggest.assert_called_once()
assert bucket.objects == {}
def test_stale_takeover_loses_to_a_concurrent_takeover() -> None:
from backend.workers import auto_correct_worker as w
bucket = _FakeBucket()
bucket.put_lease("j", 0)
storage = SimpleNamespace(bucket=bucket)
real_get_blob = bucket.get_blob
def _get_blob_then_race(path):
observed = real_get_blob(path)
bucket.put_lease("j", 0) # another instance takes over after our read
return observed
bucket.get_blob = _get_blob_then_race
assert w._acquire_lease(storage, "j") == (False, None)
def test_own_lease_after_lost_create_response_counts_as_held(monkeypatch) -> None:
"""Upload retry after a lost response 412s on our own write: still ours."""
import json as _json
from backend.workers import auto_correct_worker as w
bucket = _FakeBucket()
storage = SimpleNamespace(bucket=bucket)
monkeypatch.setattr(w.uuid, "uuid4", lambda: SimpleNamespace(hex="mytoken"))
real_blob = bucket.blob
def _blob_lost_response(path):
b = real_blob(path)
orig = b.upload_from_string
def _upload(data, content_type=None, if_generation_match=None):
orig(data, content_type=content_type, if_generation_match=if_generation_match)
raise gexc.PreconditionFailed("retry of a create that already landed")
b.upload_from_string = _upload
return b
bucket.blob = _blob_lost_response
held, gen = w._acquire_lease(storage, "j")
assert held and gen == bucket.objects["jobs/j/lyrics/auto_correct_inflight.json"][0]
assert _json.loads(bucket.objects["jobs/j/lyrics/auto_correct_inflight.json"][1])["token"] == "mytoken"
def test_release_never_deletes_a_lease_someone_else_took_over() -> None:
import time as _time
from backend.workers import auto_correct_worker as w
bucket = _FakeBucket()
storage = SimpleNamespace(bucket=bucket)
held, gen = w._acquire_lease(storage, "j")
assert held and gen is not None
bucket.put_lease("j", _time.time()) # superseded (e.g. our run outlived the TTL)
w._release_lease(storage, "j", gen)
assert "jobs/j/lyrics/auto_correct_inflight.json" in bucket.objects
@pytest.mark.asyncio
async def test_peer_failure_does_not_regenerate(monkeypatch) -> None:
import time as _time
from backend.workers import auto_correct_worker as w
monkeypatch.setattr(w, "PEER_POLL_SECONDS", 0)
svc = MagicMock()
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
bucket.put_lease("job-peer-fail", _time.time())
lease = "jobs/job-peer-fail/lyrics/auto_correct_inflight.json"
def _no_cache(*_a):
bucket.objects.pop(lease, None) # peer finishes (fails) without writing a cache
return None
with p_set, p_st, p_jm, \
patch("backend.services.auto_correct.get_auto_correct_service", return_value=svc), \
patch("backend.services.auto_approval.executor._load_ai_suggestions", side_effect=_no_cache):
result = await process_proactive_auto_correct("job-peer-fail")
assert result == {"status": "skipped", "reason": "peer_failed"}
svc.suggest.assert_not_called()
@pytest.mark.asyncio
async def test_timed_out_run_keeps_its_lease(monkeypatch) -> None:
from backend.workers import auto_correct_worker as w
svc = MagicMock()
p_set, p_st, p_jm, storage, bucket = _patch_with_bucket(svc)
async def _timeout(*_a, **_k):
raise TimeoutError()
monkeypatch.setattr(w, "_run_suggest", _timeout)
with p_set, p_st, p_jm:
result = await process_proactive_auto_correct("job-slow")
assert result["status"] == "error"
# suggest() may still be running in its thread: the lease must stay until TTL.
assert "jobs/job-slow/lyrics/auto_correct_inflight.json" in bucket.objects
@@ -0,0 +1,64 @@
"""Render worker: translated lyrics are prepared before render and passed to the encoder."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.services.encoding_errors import EncodingWorkerCapacityError
def _job(translation_language):
job = MagicMock()
job.artist = "Test Artist"
job.title = "Test Title"
job.input_media_gcs_path = "jobs/test/audio.flac"
job.style_assets = {}
job.style_params_gcs_path = None
job.subtitle_offset_ms = 0
job.prep_only = False
job.state_data = {}
job.file_urls = {}
job.translation_language = translation_language
return job
async def _render_config(translation_language, prepared_path):
from backend.workers import render_video_worker as rvw
job_manager = MagicMock()
job_manager.get_job.return_value = _job(translation_language)
job_manager.transition_to_state.return_value = True
encoding_service = MagicMock()
encoding_service.is_enabled = True
# Stop right after the render is submitted
encoding_service.render_video_on_gce = AsyncMock(
side_effect=EncodingWorkerCapacityError("full", vm_name="vm", zone="z", code="ZONE_RESOURCE_POOL_EXHAUSTED")
)
storage = MagicMock()
storage.file_exists.return_value = False
settings = MagicMock()
settings.gcs_bucket_name = "bucket"
with patch.object(rvw, "JobManager", return_value=job_manager), \
patch.object(rvw, "StorageService", return_value=storage), \
patch.object(rvw, "get_settings", return_value=settings), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch.object(rvw, "validate_worker_can_run", return_value=None), \
patch.object(rvw, "get_encoding_service", return_value=encoding_service), \
patch.object(rvw, "prepare_job_translations", return_value=prepared_path) as prepare:
await rvw.process_render_video("test-job-id")
prepare.assert_called_once()
return encoding_service.render_video_on_gce.call_args[0][1]
@pytest.mark.asyncio
async def test_translations_path_passed_to_encoder():
config = await _render_config("es", "jobs/test-job-id/lyrics/translations.json")
assert config["translations_gcs_path"] == "gs://bucket/jobs/test-job-id/lyrics/translations.json"
@pytest.mark.asyncio
async def test_no_translations_when_not_prepared():
config = await _render_config(None, None)
assert "translations_gcs_path" not in config
@@ -205,3 +205,27 @@ class TestSystemStatusAdmin:
assert admin["active_zone"] == "us-central1-a"
# "n2c" family token → n2-highcpu-16 (inferred from the VM name).
assert admin["active_machine_type"] == "n2-highcpu-16"
class TestAudioSeparatorStatus:
"""Separation runs in the audio-separation-job GPU Cloud Run Job; the
standalone audio-separator service was shut down (2026-10-01), so the
status must not depend on AUDIO_SEPARATOR_API_URL or call anything."""
def test_reports_ok_without_api_url(self, monkeypatch):
from backend.api.routes.health import check_audio_separator_status
monkeypatch.delenv("AUDIO_SEPARATOR_API_URL", raising=False)
status = check_audio_separator_status()
assert status["available"] is True
assert status["status"] == "ok"
assert status["mode"] == "gpu_job"
assert "version" in status
@pytest.mark.asyncio
async def test_endpoint_matches_status_helper(self):
from backend.api.routes.health import audio_separator_health
from backend.api.routes.health import check_audio_separator_status
assert await audio_separator_health() == check_audio_separator_status()
@@ -1222,8 +1222,42 @@ class TestVideoWorkerOrchestratorDistribution:
await orchestrator._upload_to_youtube()
mock_service.upload_video.assert_called_once()
assert mock_service.upload_video.call_args.kwargs["title"] == "Test Artist - Test Title (Karaoke)"
assert orchestrator.result.youtube_url == "https://youtube.com/watch?v=video123"
@pytest.mark.asyncio
async def test_upload_to_youtube_labels_translated_video(self):
"""A video showing translated lyrics says so in its YouTube title + description."""
with tempfile.TemporaryDirectory() as temp_dir:
video_file = os.path.join(temp_dir, "test.mp4")
with open(video_file, "w") as f:
f.write("dummy video")
config = OrchestratorConfig(
job_id="test-job",
artist="Manel",
title="Benvolgut",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_youtube_upload=True,
youtube_credentials={"token": "test"},
translation_language_name="English",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.final_video_lossy = video_file
with patch.object(orchestrator, "_get_youtube_service") as mock_get:
mock_service = MagicMock()
mock_service.upload_video.return_value = ("v", "https://youtube.com/watch?v=v")
mock_get.return_value = mock_service
await orchestrator._upload_to_youtube()
kwargs = mock_service.upload_video.call_args.kwargs
assert kwargs["title"] == "Manel - Benvolgut (With Translation into English) (Karaoke)"
assert "translated lyrics (English)" in kwargs["description"]
@pytest.mark.asyncio
async def test_upload_to_dropbox(self):
"""Test Dropbox upload."""
+35
View File
@@ -3,9 +3,12 @@ import pytest
from backend.config import get_settings
from backend.services.youtube_description import (
YOUTUBE_TITLE_MAX,
build_youtube_tags,
build_youtube_title,
hashtagify,
render_youtube_description,
translated_language_name,
)
@@ -109,3 +112,35 @@ class TestBuildTags:
tags = build_youtube_tags("A" * 300, "B" * 300)
total = sum(len(t) + 1 for t in tags)
assert total <= 460
class TestTranslationLabel:
"""Published videos with translated lyrics say so (Andrew: like the tempo label)."""
def test_only_a_successful_translation_counts(self):
assert translated_language_name({"lyrics_translation": {"language": "es", "status": "translated"}}) == "Spanish"
assert translated_language_name({"lyrics_translation": {"language": "es", "status": "failed"}}) is None
assert translated_language_name({"lyrics_translation": {"language": "es", "status": "same_language"}}) is None
assert translated_language_name({}) is None
assert translated_language_name(None) is None
def test_untranslated_title_unchanged(self):
assert build_youtube_title("Manel", "Benvolgut") == "Manel - Benvolgut (Karaoke)"
def test_translated_title_label_before_karaoke(self):
assert (
build_youtube_title("Manel", "Benvolgut", "English")
== "Manel - Benvolgut (With Translation into English) (Karaoke)"
)
def test_long_title_truncates_song_not_label(self):
out = build_youtube_title("A Very Long Artist Name Indeed", "An Extremely Long Song Title That Goes On And On", "Portuguese")
assert len(out) <= YOUTUBE_TITLE_MAX
assert out.endswith(" ... (With Translation into Portuguese) (Karaoke)")
assert out.startswith("A Very Long Artist Name Indeed - ")
def test_description_notice(self):
desc = render_youtube_description("Manel", "Benvolgut", template="Body", translation_language_name="English")
assert desc.startswith("This karaoke video includes translated lyrics (English) beneath each line.")
assert desc.endswith("Body")
assert "translation" not in render_youtube_description("Manel", "Benvolgut", template="Body")
@@ -291,3 +291,33 @@ class TestUpdateJobYouTubeUrl:
with patch('backend.workers.youtube_queue_processor.JobManager', return_value=mock_job_manager):
with pytest.raises(RuntimeError, match="firestore down"):
_update_job_youtube_url("job-123", "https://youtube.com/watch?v=abc")
class TestProcessSingleUploadTranslationLabel:
"""Queued uploads label translated videos exactly like the live upload path."""
def test_translated_job_title_and_description_labelled(self, tmp_path):
import asyncio
from types import SimpleNamespace
from backend.workers.youtube_queue_processor import _process_single_upload
job = SimpleNamespace(
job_id="job-tr", artist="Manel", title="Benvolgut",
state_data={"lyrics_translation": {"language": "en", "status": "translated"}},
)
youtube = MagicMock()
youtube.upload_video.return_value = ("vid", "https://youtube.com/watch?v=vid")
settings = SimpleNamespace(default_youtube_description="Body")
with patch('backend.workers.youtube_queue_processor.JobManager') as jm, \
patch('backend.workers.youtube_queue_processor.StorageService'), \
patch('backend.workers.youtube_queue_processor._download_video_from_gcs', return_value=str(tmp_path / "v.mkv")), \
patch('backend.workers.youtube_queue_processor._download_thumbnail_from_gcs', return_value=None), \
patch('backend.workers.youtube_queue_processor._create_youtube_service', return_value=youtube):
jm.return_value.get_job.return_value = job
url = asyncio.run(_process_single_upload("job-tr", {}, MagicMock(), settings))
assert url == "https://youtube.com/watch?v=vid"
kwargs = youtube.upload_video.call_args.kwargs
assert kwargs["title"] == "Manel - Benvolgut (With Translation into English) (Karaoke)"
assert kwargs["description"].startswith("This karaoke video includes translated lyrics (English)")
+204 -35
View File
@@ -14,30 +14,177 @@ failure just means the UI does the call on demand instead.
from __future__ import annotations
import asyncio
import json
import logging
import time
import uuid
from typing import Dict, Optional, Tuple
logger = logging.getLogger(__name__)
# --- De-duplication -------------------------------------------------------
# Two callers race to generate the same suggestions: the lyrics worker's HTTP
# trigger (internal /workers/auto-correct) and the screens worker's pre-apply
# (ensure_and_pre_apply → generate on cache miss). Screens is triggered BEFORE
# the lyrics worker fires its proactive trigger, so the pre-apply routinely
# checks the cache while the proactive run is still in flight and starts a
# second identical multi-model run (prod 2026-09-17..10-01: 92/167 jobs ran it
# twice, ~$0.07 each). Two guards:
# 1. In-process single-flight: a concurrent caller on the same instance awaits
# the in-flight run instead of starting another (~90% of duplicates).
# 2. Cross-instance GCS lease (create-only object): a caller on another
# instance waits for the holder's cache instead of regenerating.
_INFLIGHT: Dict[str, "asyncio.Task[dict]"] = {}
LEASE_PATH = "jobs/{job_id}/lyrics/auto_correct_inflight.json"
# Generation is bounded at 180s; anything older is a crashed holder's leftover.
LEASE_TTL_SECONDS = 240
# How long a non-holder waits for the holder's cache (fits inside the lyrics
# trigger's 200s HTTP timeout).
PEER_WAIT_SECONDS = 150
PEER_POLL_SECONDS = 3
def _precondition_failed():
try:
from google.api_core.exceptions import PreconditionFailed
return PreconditionFailed
except Exception: # pragma: no cover - google libs always present in prod
return ()
def _write_lease(storage, path: str, if_generation_match: int, token: str) -> Optional[int]:
"""Conditional lease write; returns the generation we wrote (our fence token)."""
blob = storage.bucket.blob(path)
blob.upload_from_string(
json.dumps({"acquired_at": time.time(), "token": token}),
content_type="application/json",
if_generation_match=if_generation_match,
)
return blob.generation
def _acquire_lease(storage, job_id: str) -> Tuple[bool, Optional[int]]:
"""Try to take the cross-instance lease.
Returns ``(held, generation)``. Every write is generation-fenced: create-only
first, and a stale-lease takeover only succeeds against the exact generation
we observed, so two instances can't both take over the same stale lease.
Fails OPEN (``(True, None)``) on unexpected storage errors — the lease is an
optimisation and must never stop suggestions from being generated.
"""
path = LEASE_PATH.format(job_id=job_id)
precondition_failed = _precondition_failed()
token = uuid.uuid4().hex
try:
try:
return True, _write_lease(storage, path, if_generation_match=0, token=token)
except precondition_failed:
pass
existing = storage.bucket.get_blob(path)
if existing is None: # holder released between our two calls — retry once
try:
return True, _write_lease(storage, path, if_generation_match=0, token=token)
except precondition_failed:
return False, None
try:
lease = json.loads(existing.download_as_bytes())
except Exception: # noqa: BLE001 — unreadable lease → treat as stale
lease = {}
if lease.get("token") == token:
# Our own create succeeded but its response was lost and the client's
# retry hit the precondition — we DO hold it.
return True, existing.generation
acquired_at = float(lease.get("acquired_at") or 0)
if time.time() - acquired_at <= LEASE_TTL_SECONDS:
return False, None
# Stale (crashed holder): take over only the generation we just read.
try:
return True, _write_lease(storage, path, if_generation_match=existing.generation, token=token)
except precondition_failed:
return False, None # another instance took it over first
except Exception as e: # noqa: BLE001 — fail open
logger.info("[job:%s] auto-correct lease unavailable, proceeding: %s", job_id, e)
return True, None
def _release_lease(storage, job_id: str, generation: Optional[int]) -> None:
"""Delete OUR lease generation only — never a lease someone else took over."""
if generation is None:
return # unknown fence token: let it go stale rather than risk deleting another's
try:
storage.bucket.blob(LEASE_PATH.format(job_id=job_id)).delete(if_generation_match=generation)
except Exception as e: # noqa: BLE001 — gone/superseded/failed: it just goes stale
logger.info("[job:%s] auto-correct lease not released: %s", job_id, e)
async def _wait_for_peer(storage, job_id: str) -> dict:
"""Another instance is generating: wait for its cache instead of re-running."""
from backend.services.auto_approval.executor import _load_ai_suggestions
lease_path = LEASE_PATH.format(job_id=job_id)
deadline = time.monotonic() + PEER_WAIT_SECONDS
while time.monotonic() < deadline:
# Off-loop: these are blocking GCS calls, polled repeatedly.
suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
if suggestions is not None:
logger.info("[job:%s] proactive auto-correct deduped: used peer's cache", job_id)
return {"status": "deduped", "suggestions": len(suggestions)}
if not await asyncio.to_thread(storage.file_exists, lease_path):
# Holder finished without a cache (its run failed). Don't retry here:
# the review UI requests suggestions on demand as the fallback.
suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
if suggestions is not None:
return {"status": "deduped", "suggestions": len(suggestions)}
return {"status": "skipped", "reason": "peer_failed"}
await asyncio.sleep(PEER_POLL_SECONDS)
logger.info("[job:%s] proactive auto-correct: peer still running after %ss", job_id, PEER_WAIT_SECONDS)
return {"status": "skipped", "reason": "peer_timeout"}
async def process_proactive_auto_correct(job_id: str) -> dict:
"""Generate + cache auto-correct suggestions for a job. Never raises.
Returns a small status dict for the endpoint to echo. Gated by
settings.auto_correct_proactive_enabled; reads the corrections.json the
Single-flight per job (see the de-duplication note above): concurrent
callers share one generation run.
"""
from backend.config import get_settings
if not get_settings().auto_correct_proactive_enabled:
return {"status": "disabled"}
existing = _INFLIGHT.get(job_id)
if existing is not None:
logger.info("[job:%s] proactive auto-correct already in flight here; joining it", job_id)
try:
# shield: a cancelled joiner must not cancel the shared run
return await asyncio.shield(existing)
except Exception as e: # noqa: BLE001 — never raise
return {"status": "error", "message": str(e)}
task = asyncio.ensure_future(_generate(job_id))
_INFLIGHT[job_id] = task
def _clear(t, _job_id=job_id):
if _INFLIGHT.get(_job_id) is t:
_INFLIGHT.pop(_job_id, None)
task.add_done_callback(_clear)
try:
return await asyncio.shield(task)
except Exception as e: # noqa: BLE001 — never raise
return {"status": "error", "message": str(e)}
async def _generate(job_id: str) -> dict:
"""Generate + cache auto-correct suggestions for a job. Never raises.
Returns a small status dict for the endpoint to echo. Reads the corrections.json the
lyrics worker just wrote (the same data the review UI loads on first open)
and runs the multi-model path with default settings so the cache key lines
up with the UI request.
"""
from backend.config import get_settings
settings = get_settings()
if not settings.auto_correct_proactive_enabled:
return {"status": "disabled"}
try:
from backend.services.auto_correct import get_auto_correct_service
from backend.services.auto_correct.settings import AutoCorrectSettings
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
storage = StorageService()
@@ -57,30 +204,52 @@ async def process_proactive_auto_correct(job_id: str) -> dict:
)
return {"status": "skipped", "reason": "no_references"}
job = JobManager().get_job(job_id)
service = get_auto_correct_service()
result = await asyncio.wait_for(
asyncio.to_thread(
service.suggest,
job_id=job_id,
segments=segments,
reference_lyrics=reference_lyrics,
artist=getattr(job, "artist", None) if job else None,
title=getattr(job, "title", None) if job else None,
# Must match what the review UI sends (default settings,
# multi-model) or the cache key won't line up.
settings=AutoCorrectSettings(compare_models=True),
# Already loaded — saves the service re-fetching it for the
# deterministic (P4/P5) generators.
correction_data=data,
),
timeout=180,
)
logger.info(
"[job:%s] proactive auto-correct done: %d suggestions cached (models=%s, %.1fs)",
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
)
return {"status": "generated", "suggestions": len(result.suggestions)}
# Off-loop: up to 4 blocking GCS round-trips.
held, lease_generation = await asyncio.to_thread(_acquire_lease, storage, job_id)
if not held:
return await _wait_for_peer(storage, job_id)
try:
return await _run_suggest(job_id, data, segments, reference_lyrics)
except asyncio.TimeoutError:
# wait_for can't stop the worker thread: suggest() may still finish
# and write the cache. Keep the lease (it expires via the TTL) so no
# one starts a duplicate run meanwhile.
lease_generation = None
raise
finally:
await asyncio.to_thread(_release_lease, storage, job_id, lease_generation)
except Exception as e: # noqa: BLE001 — proactive is best-effort, never fatal
logger.warning("[job:%s] proactive auto-correct failed (non-fatal): %s", job_id, e, exc_info=True)
return {"status": "error", "message": str(e)}
async def _run_suggest(job_id: str, data: dict, segments: list, reference_lyrics: dict) -> dict:
from backend.services.auto_correct import get_auto_correct_service
from backend.services.auto_correct.settings import AutoCorrectSettings
from backend.services.job_manager import JobManager
job = JobManager().get_job(job_id)
service = get_auto_correct_service()
result = await asyncio.wait_for(
asyncio.to_thread(
service.suggest,
job_id=job_id,
segments=segments,
reference_lyrics=reference_lyrics,
artist=getattr(job, "artist", None) if job else None,
title=getattr(job, "title", None) if job else None,
# Must match what the review UI sends (default settings,
# multi-model) or the cache key won't line up.
settings=AutoCorrectSettings(compare_models=True),
# Already loaded — saves the service re-fetching it for the
# deterministic (P4/P5) generators.
correction_data=data,
),
timeout=180,
)
logger.info(
"[job:%s] proactive auto-correct done: %d suggestions cached (models=%s, %.1fs)",
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
)
return {"status": "generated", "suggestions": len(result.suggestions)}
+30
View File
@@ -25,6 +25,7 @@ Observability:
- Logs include [job:ID] prefix for easy filtering in Cloud Logging
- Worker start/end timing logged with WORKER_START/WORKER_END markers
"""
import asyncio
import logging
import os
import tempfile
@@ -39,6 +40,8 @@ from backend.exceptions import InvalidStateTransitionError
from backend.utils.audio_filenames import local_audio_filename
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.lyrics_translation import prepare_job_translations
from karaoke_gen.lyrics_transcriber.output.translations import apply_translations
from backend.services.job_health_service import validate_worker_can_run
from backend.workers.supersede import capture_generation, check_superseded, encoding_worker_job_id
from backend.config import get_settings
@@ -195,6 +198,20 @@ async def process_render_video(job_id: str) -> bool:
encoding_service = get_encoding_service()
use_gce = encoding_service.is_enabled
async def prepare_translations() -> Optional[str]:
"""Translate the final (reviewed) lyrics once, after the job is in
RENDERING_VIDEO. Never blocks the render (failure = no translations)."""
try:
path = await asyncio.to_thread(
prepare_job_translations, job_id, job, storage, job_manager
)
except Exception as exc:
logger.error(f"[job:{job_id}] Translated lyrics skipped: {exc}", exc_info=True)
return None
if path:
job_log.info(f"Rendering with translated lyrics ({job.translation_language})")
return path
if use_gce:
# ============ GCE RENDER VIDEO PATH ============
job_log.info("GCE encoding enabled - delegating render_video to encoding worker")
@@ -207,6 +224,7 @@ async def process_render_video(job_id: str) -> bool:
progress=75,
message="Rendering karaoke video on encoding worker"
)
translations_gcs = await prepare_translations()
# Build render config from job metadata (no downloads needed on Cloud Run!)
bucket_name = settings.gcs_bucket_name
@@ -229,6 +247,9 @@ async def process_render_video(job_id: str) -> bool:
"is_duet": is_duet,
}
if translations_gcs:
render_config["translations_gcs_path"] = f"gs://{bucket_name}/{translations_gcs}"
if has_updated:
render_config["updated_corrections_gcs_path"] = f"gs://{bucket_name}/{updated_corrections_gcs}"
@@ -405,6 +426,7 @@ async def process_render_video(job_id: str) -> bool:
progress=75,
message="Rendering karaoke video with corrected lyrics"
)
translations_gcs = await prepare_translations()
with tempfile.TemporaryDirectory() as temp_dir:
job_log.info(f"Created temp directory: {temp_dir}")
@@ -481,6 +503,14 @@ async def process_render_video(job_id: str) -> bool:
# "'<' not supported between instances of 'NoneType' and 'float'".
# Failing here gives the user an actionable message and never sends a
# broken job to the GCE encoder (which runs its own pinned wheel).
if translations_gcs:
try:
apply_translations(
correction_result.corrected_segments, storage.download_json(translations_gcs)
)
except Exception as exc:
job_log.error(f"Could not apply translated lyrics, rendering without: {exc}")
try:
validate_segment_timing(correction_result.corrected_segments)
except LyricsTimingError as timing_err:
+2
View File
@@ -45,6 +45,7 @@ from backend.services.admin_rerender_service import (
from backend.services.job_health_service import validate_worker_can_run
from backend.services.rclone_service import get_rclone_service
from backend.services.youtube_service import get_youtube_service
from backend.services.youtube_description import translated_language_name
from backend.services.encoding_service import get_encoding_service, run_with_lost_job_resubmit
from backend.config import get_settings
from backend.workers.style_helper import load_style_config
@@ -624,6 +625,7 @@ async def redistribute_video(job_id: str) -> bool:
discord_webhook_url=dist.discord_webhook_url,
youtube_credentials=youtube_credentials,
youtube_description_template=dist.youtube_description,
translation_language_name=translated_language_name(job.state_data),
dropbox_path=dist.dropbox_path,
gdrive_folder_id=dist.gdrive_folder_id,
enable_cdg=getattr(job, 'enable_cdg', False),
+12 -5
View File
@@ -27,6 +27,7 @@ from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.youtube_description import translated_language_name
from backend.services.tracing import job_span, add_span_event
from backend.workers.supersede import capture_generation, encoding_worker_job_id
from backend.services.theme_rerender_service import rerender_brand_code
@@ -68,6 +69,8 @@ class OrchestratorConfig:
discord_webhook_url: Optional[str] = None
youtube_credentials: Optional[Dict[str, Any]] = None
youtube_description_template: Optional[str] = None
# Set when the video shows translated lyrics (labels the YouTube title/description)
translation_language_name: Optional[str] = None
cdg_styles: Optional[Dict[str, Any]] = None
# Dropbox/GDrive configuration
@@ -812,21 +815,24 @@ class VideoWorkerOrchestrator:
try:
youtube_service = self._get_youtube_service()
# Build video title
title = f"{self.config.artist} - {self.config.title} (Karaoke)"
# Build description + tags via the shared renderer (single source of
# truth, also used by the bulk-rewrite tool).
# Build title + description + tags via the shared renderer (single
# source of truth, also used by the queue processor + bulk-rewrite tool).
from backend.services.youtube_description import (
build_youtube_tags,
build_youtube_title,
render_youtube_description,
)
title = build_youtube_title(
self.config.artist, self.config.title, self.config.translation_language_name
)
description = render_youtube_description(
artist=self.config.artist,
title=self.config.title,
brand_code=self.result.brand_code,
template=self.config.youtube_description_template or None,
translation_language_name=self.config.translation_language_name,
)
# Upload
@@ -1245,6 +1251,7 @@ def create_orchestrator_config_from_job(
discord_webhook_url=dist.discord_webhook_url,
youtube_credentials=youtube_credentials,
youtube_description_template=dist.youtube_description,
translation_language_name=translated_language_name(job.state_data),
cdg_styles=cdg_styles,
# Dropbox/GDrive (overridden for private tracks)
+12 -7
View File
@@ -257,23 +257,28 @@ async def _process_single_upload(
# Build metadata
artist = entry.get("artist", job.artist or "Unknown")
title = entry.get("title", job.title or "Unknown")
youtube_title = f"{artist} - {title} (Karaoke)"
# Render title + description + tags via the shared renderer (single source
# of truth, also used by the live upload + bulk-rewrite tool).
from backend.services.youtube_description import (
build_youtube_tags,
build_youtube_title,
render_youtube_description,
translated_language_name,
)
translation_name = translated_language_name(job.state_data)
youtube_title = build_youtube_title(artist, title, translation_name)
if len(youtube_title) > 95:
youtube_title = youtube_title[:92] + " ..."
brand_code = entry.get("brand_code") or job.state_data.get("brand_code")
# Render description + tags via the shared renderer (single source of
# truth, also used by the bulk-rewrite tool).
from backend.services.youtube_description import (
build_youtube_tags,
render_youtube_description,
)
description = render_youtube_description(
artist=artist,
title=title,
brand_code=brand_code,
template=settings.default_youtube_description or None,
translation_language_name=translation_name,
)
# Upload
+24 -3
View File
@@ -736,7 +736,7 @@ Content-Type: application/json
AI correction suggestions for the lyrics review UI. Stateless: one whole-song
LLM call per model (Claude models use the Anthropic API via the
`anthropic-api-key` secret, Gemini models use Vertex AI) compares the
`anthropic-api-key` secret, Gemini models use the Gemini Developer API, key `gemini-api-key`) compares the
client's current transcription against the reference sources and returns
word-id-keyed suggestions. Nothing is applied server-side — the reviewer
accepts/rejects each suggestion in the UI and persistence flows through the
@@ -1017,7 +1017,7 @@ Content-Type: application/json
```
Decides the official formatting for a typed artist/title and whether it matches a
real song. A deterministic normalizer + the catalog run first; a light Vertex
real song. A deterministic normalizer + the catalog run first; a light Gemini
Gemini model (`MATCH_JUDGE_MODEL`, default `gemini-3.8-flash`) is consulted
**only** when those aren't confident. `audio_confidence_tier` (1=strong..3=weak,
optional) lets the judge tell whether weak audio results hint at a typo. The call
@@ -1224,6 +1224,27 @@ GET /api/themes
No auth required. Returns available video themes.
```http
GET /api/themes/translation-preview?language=es
```
No auth required. Returns `{"image": "data:image/jpeg;base64,..."}`: a real karaoke-video frame
of the default theme with sample lyrics and their translation (in `language`) beneath each line —
the preview shown when a user turns on translated lyrics at job creation. `language` is one of the
33 UI locale codes (400 otherwise). Sample translations are pre-generated
(`backend/services/translation_preview_samples.py`), so no LLM call is made.
### Translated Lyrics
Every job-creation endpoint (URL, search, upload, bulk `settings`) accepts an optional
`translation_language` (UI locale code, e.g. `"en"`, `"es"`, `"he"`; omitted/unsupported = off;
admin job PATCH can set it, `""` clears it). After lyrics review, the render worker translates the
final lyrics line by line (`LYRICS_TRANSLATION_MODEL`, default `gemini-3.8-flash`) into
`jobs/{id}/lyrics/translations.json` and the landscape + portrait videos show each translation in
smaller text beneath its line (3 lines per screen). Outcome in `state_data.lyrics_translation`
(`status`: `translated` / `same_language` / `failed`; a failure renders without translations).
See [archive/2026-10-01-translated-lyrics-plan.md](archive/2026-10-01-translated-lyrics-plan.md).
### Tenant Config
```http
@@ -1319,7 +1340,7 @@ Artist/Title. Pure analysis — filenames only, no uploads, no state written.
- **Auth:** tenant session required; gated on the tenant's `features.bulk_upload` flag (403 otherwise).
- **Limits:** max 100 audio files per request (non-audio files don't count toward the cap; 2000-filename payload guard).
- **Two passes:** deterministic regex for the `S<code>-<1|2> Artist - Title <Guide|BV|Instru>`
convention, then a Vertex-Gemini pass (`backend/services/tenant_bulk/analyze.py`) for
convention, then a Gemini pass (`backend/services/tenant_bulk/analyze.py`) for
whatever the regex couldn't confidently pair. Falls back to regex-only if the model errors.
Response:
+8 -5
View File
@@ -252,7 +252,7 @@ LyricsTranscriber LyricsTranscriber
|---------|---------|----------|
| 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.8 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Gemini Developer API (`gemini-api-key`) | Agentic AI correction (Gemini 3.8 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Genius | Reference lyrics | Yes |
| Flacfetch | Audio downloads (YouTube, torrents) | Recommended* |
| YouTube API | Video upload | Optional |
@@ -605,10 +605,13 @@ Audio stem separation runs **directly inside the audio worker Cloud Run Job**
- **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.
**The `audio-separator` Cloud Run GPU service** (us-east4, scale-to-zero) is no longer used by
prod gen jobs, but it still serves external remote-separation clients (`audio-separator-remote` /
local `karaoke-gen` CLI with `AUDIO_SEPARATOR_API_URL`; ~40 `/separate` calls/month as of
2026-09). Keep it at min-instances 0; don't remove it without checking its request logs first.
**The `audio-separator` Cloud Run GPU service** (us-east4) was **shut down on 2026-10-01**
(GCP cost cut, ~$22/mo). Prod gen jobs never used it; its only callers were Andrew's own
remote-separation clients (`audio-separator-remote` / local `karaoke-gen` CLI with
`AUDIO_SEPARATOR_API_URL`). Leave `AUDIO_SEPARATOR_API_URL` unset to separate locally. It
is still defined in Pulumi behind the `audioSeparatorServiceEnabled` flag — see
[GCP-COST-OPTIMIZATION.md](GCP-COST-OPTIMIZATION.md#audio-separator-service-shut-down-on-demand-redeploy)
to bring it back on demand.
### Quick version (kjbox make-it jobs)
+26 -7
View File
@@ -1,6 +1,6 @@
# Disaster Recovery Runbook
**Last updated:** 2026-06-18
**Last updated:** 2026-10-01
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
**Implementation plan:** `docs/archive/2026-03-29-business-continuity-plan.md`
**External services reference:** `docs/archive/2026-03-29-external-services-config.md`
@@ -13,7 +13,7 @@
| 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 |
| GCS job files | **GCS only** — object versioning (non-current kept 30d) + soft-delete (7d). Off-site S3 copy **stopped 2026-10-01**; S3 `gcs/job-files/` is a frozen snapshot up to 2026-09-30 | Restore non-current/soft-deleted generation in GCS | N/A off-site (frozen); in-GCS recovery window 7–30d |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 7 days (weekly, Sundays; incremental) |
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
@@ -109,7 +109,7 @@ gcloud storage cp gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac#GE
gs://karaoke-gen-storage-nomadkaraoke/jobs/JOB_ID/file.flac
```
**Option C — Restore from S3 (if A and B both miss the window):**
**Option C — Restore from S3 (if A and B both miss the window; only works for files that existed by 2026-09-30 — the nightly S3 copy of job files was stopped 2026-10-01, see § "Job files: off-site copy stopped"):**
```bash
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/jobs/JOB_ID/ /tmp/gcs-restore/
@@ -209,7 +209,9 @@ aws s3api restore-object --bucket nomadkaraoke-backup \
# Create new bucket
gsutil mb -l US-CENTRAL1 gs://karaoke-gen-storage-nomadkaraoke-v2/
# Sync from S3 (146 GB last we measured — needs a host with comparable disk + bandwidth)
# Sync from S3 (146 GB last we measured — needs a host with comparable disk + bandwidth).
# NOTE: frozen snapshot — job files created/changed after 2026-09-30 are NOT in S3
# (off-site copy stopped 2026-10-01). Newer outputs must be regenerated.
aws s3 sync s3://nomadkaraoke-backup/gcs/job-files/ /tmp/gcs-restore/
gsutil -m cp -r /tmp/gcs-restore/ gs://karaoke-gen-storage-nomadkaraoke-v2/
```
@@ -301,7 +303,7 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
- YouTube OAuth (redirect URIs)
- Stripe webhook endpoint URL (secret regenerates)
- AudioShake API key (rotate as a precaution if old project was compromised)
- Gemini / Vertex API (project-scoped — needs new project enabled)
- Gemini Developer API key (`gemini-api-key` secret; key lives in an AI Studio project outside nomadkaraoke — just copy the secret)
- Discord webhook URLs (re-issue if old GCP exposure could have leaked them)
- Cloudflare API tokens (rotate)
@@ -462,13 +464,13 @@ export AWS_DEFAULT_REGION=us-east-1
## Backup freshness monitor
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/manifest.json` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
| Prefix | S3 upload cadence | Monitor limit |
|--------|-------------------|---------------|
| `gcs/job-files/`, `secrets/` | nightly | 36h |
| `secrets/` | nightly | 36h |
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
| `git-repos/manifest.json` | weekly (Sundays), incremental | 192h (≈8 days) + manifest must show 0 bundle errors |
@@ -549,6 +551,23 @@ re-import). The raw source files are not.
| Full Spotify dataset retrieval + transfer (~100 GB) | ~$25 total |
| Full GCS job-files egress (~150 GB) | ~$14 |
## Job files: off-site copy stopped (2026-10-01)
The nightly `backup-to-aws` step that delta-synced `karaoke-gen-storage-nomadkaraoke`
(`jobs/`, `tenants/`, `themes/`) → staging `gcs/job-files/` → S3 was removed on
2026-10-01 as a GCP cost cut (~$15/mo cross-cloud egress; business cash constraint).
Job outputs are regenerable from their inputs, and the primary bucket keeps
**object versioning** (non-current versions deleted 30 days after being superseded)
plus **7-day soft-delete**, which covers accidental overwrite/delete. What is
*not* covered any more: loss of the whole GCP project/bucket for files created after
2026-09-30. The existing S3 `gcs/job-files/` objects were deliberately left in place
(frozen snapshot). Firestore (weekly), secrets (nightly), BigQuery, kn-data and git
bundle backups are unchanged. The freshness monitor no longer checks `gcs/job-files/`.
To re-enable: restore the Step 3 `sync_gcs_to_staging(source_bucket="karaoke-gen-storage-nomadkaraoke", staging_prefix="gcs/job-files/")`
call in `infrastructure/functions/backup_to_aws/main.py` (see git history) and
re-add the `gcs/job-files/` row to `.github/workflows/dr-backup-freshness.yml`.
## Incident: S3 overwrites silently failing 2026-09-14 → 2026-09-26
The incremental S3 upload (#997) checked "already in S3?" with `HeadObject`,
+13 -4
View File
@@ -170,10 +170,19 @@ karaoke-gen's test/package jobs (package/backend unit + integration + emulator
tests, package builds, full frontend E2E) moved to **GitHub-hosted
`ubuntu-latest`** runners — free for this public repo, and they never needed GCP
credentials. That removed ~390 `gha-general-*` VMs/month. Only jobs that need
the GCE runners still request them: `deploy-backend` (`docker-build` label —
Docker image builds, same-region Artifact Registry) and the GPU integration
tests in python-audio-separator (`gpu`). No workflow currently requests the
plain general label; the `gha-runner-general` family is kept as a fallback.
the GCE runners still request them: the GPU integration tests in
python-audio-separator (`gpu`). No workflow currently requests the plain general
label; the `gha-runner-general` family is kept as a fallback.
**2026-10-01:** `deploy-backend` also moved off the `docker-build` (`gha-build-*`,
e2-standard-8) runners to `ubuntu-latest`; its Docker images are now built by
Cloud Build in us-central1 (`infrastructure/cloudbuild/`). Building on the
hosted runner itself was rejected: the app images are built FROM ~4.2 GB (CPU)
and ~13 GB (GPU) bases in us-central1 AR, so every deploy would pull ~17 GB over
GCP internet egress (~$2/deploy, ~$250/mo). Cloud Build pulls them same-region
for free and its e2-standard-2 minutes are in the 2,500 min/month free tier
(~7 min/deploy). The `build` family stays in the dispatcher but is unused and
excluded from the monthly image bake (`variants=all`).
## High-level architecture
+51 -2
View File
@@ -171,6 +171,7 @@ If all optimizations implemented:
- **2026-02-10:** Initial analysis and GitHub runner optimization implemented
- **2026-02-10:** Runners reduced from 20 → 3 with auto-scaling, saving $1,390/month
- **2026-03-03:** Added dedicated on-demand build runner (`e2-standard-8`) for Docker deploys to prevent spot preemption during builds (~$0.27/hr only when deploying)
- **2026-10-01:** Retired the `gha-build-*` build runner (~$21/mo at ~120 deploys/mo). `deploy-backend` runs on free `ubuntu-latest`; images build in Cloud Build us-central1 (same-region AR pulls, e2-standard-2 free tier, ~7 build-min/deploy). Not built on the hosted runner because pulling the 4.2 GB CPU + 13 GB GPU bases is internet egress (~$2/deploy).
## 2026-09-26 cuts (post-credit-expiry, target: whole project < $300/mo)
@@ -185,5 +186,53 @@ If all optimizations implemented:
| Firestore PITR disabled (nightly export remains) | `database.py` | PITR storage |
| `recover-stuck-downloads` / `retry-pending-render-jobs` every 5 → 10 min | `__main__.py` | ~half their Firestore reads |
Kept: the `audio-separator` Cloud Run GPU service (still used by external remote-CLI
clients; already scale-to-zero).
Kept (at the time): the `audio-separator` Cloud Run GPU service — shut down in round 2 below.
## 2026-10-01 cuts, round 2 (run-rate ~$400 → target < $300/mo)
| Change | Where | Est. saving |
|--------|-------|-------------|
| `karaoke-backend` min-instances 1 → 0 (Andrew accepts a ~15s cold start on the first request after idle). With `--cpu-throttling` (request-based billing), idle non-min instances are free, so the 60s `/api/health` uptime check and the `*/10` schedulers keeping it warm don't cost idle charges | `ci.yml` | ~$24/mo |
| `audio-separator` Cloud Run GPU service (us-east4) + its SA, IAM, output bucket and `audio-separator` AR repo (~42 GB) **deleted**; python-audio-separator's `deploy-to-cloudrun.yml` made manual-only | `__main__.py` (flag `audioSeparatorServiceEnabled`, default off) | ~$22/mo |
| `backup-to-aws` no longer copies job files to S3 (they rely on GCS versioning + soft-delete); freshness monitor no longer checks `gcs/job-files/` | `functions/backup_to_aws/main.py`, `dr-backup-freshness.yml`, `DISASTER-RECOVERY.md` | ~$15/mo egress |
| Artifact Registry cleanup: per package keep the 20 most recent versions (≈10 tagged deploy images; each build also leaves a cache manifest) + tags `latest`/`content-`/`cache`, delete everything else (tagged *or* untagged) older than 7 days. **Applied in DRY-RUN mode** (`CLEANUP_POLICY_DRY_RUN = True` in `artifact_registry.py`) — flip to `False` + targeted `pulumi up` on `karaoke-artifact-repo` / `karaoke-backend-gpu-artifact-repo` after reviewing the dry-run audit logs. After the next GPU base rebuild, delete the superseded `karaoke-backend-gpu-base:content-daa414741653` tag by hand (the `content-` KEEP rule would otherwise keep it forever). Before, tagged per-commit images were never deleted (~265 + ~244 tagged backend versions had piled up). Legacy 13 GB `karaoke-backend-gpu-base` package in us-east4 deleted (gcloud). `gcf-artifacts` (Google-managed, not in Pulumi) got a gcloud policy (also dry-run for now; enable with `gcloud artifacts repositories set-cleanup-policies gcf-artifacts --location=us-central1 --policy=<file> --no-dry-run`): keep 3 most recent + all tagged, delete untagged > 7d | `artifact_registry.py`, `gpu_artifact_registry.py` | ~$8–10/mo |
| Secret Manager: 12 superseded versions disabled → destroyed (none pinned; all consumers use `:latest`) | gcloud (out of Pulumi) | < $1/mo |
### Audio separator service (shut down, on-demand redeploy)
The standalone `audio-separator` API (L4 GPU Cloud Run service, us-east4) is still
defined in `infrastructure/modules/audio_separator_service.py`, gated behind a Pulumi
config flag. To bring it back:
```bash
cd infrastructure
STACK=nomadkaraoke/karaoke-gen-infrastructure/prod
PULUMI="env -u GOOGLE_APPLICATION_CREDENTIALS GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token --account=admin@nomadkaraoke.com) pulumi"
pulumi config set audioSeparatorServiceEnabled true --stack $STACK
# 1) Create ONLY the (empty) Artifact Registry repo first — the service references
# api:latest, which must exist before Cloud Run will accept the service.
$PULUMI up --stack $STACK --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:artifactregistry/repository:Repository::audio-separator-artifact-repo'
# 2) Build + push api:<sha> and api:latest (from a python-audio-separator checkout)
gcloud builds submit --config cloudbuild.yaml --region=us-east4 --project=nomadkaraoke --substitutions=SHORT_SHA=$(git rev-parse --short=8 HEAD)
# 3) Create the service, SA, IAM and output bucket
$PULUMI up --stack $STACK
# Later image updates: gh workflow run deploy-to-cloudrun.yml --repo nomadkaraoke/python-audio-separator
export AUDIO_SEPARATOR_API_URL=$(gcloud run services describe audio-separator --region us-east4 --project nomadkaraoke --format='value(status.url)')
```
The output bucket is protected by the project's `deny-destructive-operations` IAM deny
policy. When you shut the service down again (`pulumi config rm audioSeparatorServiceEnabled`
+ `pulumi up`), delete the bucket first with
`gcloud storage rm -r gs://nomadkaraoke-audio-separator-outputs --impersonate-service-account=break-glass@nomadkaraoke.iam.gserviceaccount.com`,
then `pulumi refresh --target <bucket urn>`.
### Out-of-Pulumi changes (2026-10-01)
- `gcloud artifacts packages delete karaoke-backend-gpu-base --repository=karaoke-backend-gpu --location=us-east4`
(13 GB legacy base; the base has lived in us-central1 `karaoke-repo` since 2026-09-27; the CI one-time-copy fallback that read it was removed).
- `gcloud artifacts repositories set-cleanup-policies gcf-artifacts --location=us-central1` (policy above).
- Secret versions disabled, then destroyed: `encoding-worker-fallback-vms` v1–4, `flacfetch-api-url` v1,
`github-runner-pat` v1, `pushbullet-api-key` v1–2, `rapidapi-key` v1, `spotify-cookie` v1,
`discord-releases-webhook` v1–2. App-rotated secrets (`dropbox-oauth-credentials`, `spotify-oauth-token`,
`youtube-cookies`) keep their own retention and were left alone, as was `gemini-api-key`.
- `gs://nomadkaraoke-audio-separator-outputs` deleted via break-glass SA (IAM deny policy blocks Pulumi).
+11 -5
View File
@@ -1403,11 +1403,17 @@ For indefinite loops (like polling), use outer timeout (total duration) + inner
### Secret Manager Access
Service account needs `roles/secretmanager.secretAccessor`. Mount as env var or volume. Use GCP workload identity, not key files.
### Vertex AI Auth
Use `project` parameter with `ChatGoogleGenerativeAI` to trigger Vertex AI backend with ADC. Don't require `GOOGLE_API_KEY`.
### Gemini 3 Requires Global Location
Gemini 3 models require `location="global"`, not regional endpoints like `us-central1`.
### Gemini: Developer API key, never Vertex (2026-10-01)
All Gemini calls use the **Gemini Developer API** (AI Studio key in Secret Manager
`gemini-api-key`, billed outside the nomadkaraoke project) via
`backend/services/gemini_client.get_genai_client()`; `aiplatform.googleapis.com` and
`generativelanguage.googleapis.com` are **disabled** in nomadkaraoke so no AI spend lands
on it. Key = `GEMINI_API_KEY` env (CI `--set-secrets` for the service, Pulumi for jobs),
else Secret Manager read at runtime. Rotate = add a secret version (new instances/job
executions pick it up). Classify failures with `note_gemini_failure(caller, exc)`:
quota/billing/key errors (not per-minute 429s) skip retries, degrade, and Discord-alert
at most once per 6h. (Supersedes the old "Vertex AI Auth" / "global location" notes —
the Developer API has no project/location.)
### LangChain: REST over gRPC
Use `langchain-google-genai` (REST) instead of `langchain-google-vertexai` (gRPC) to avoid silent hangs.
+2 -2
View File
@@ -132,7 +132,7 @@ Commercial producers pay for API access or custom integration to generate tracks
### What Works
- Audio upload and separation (Cloud Run GPU)
- Lyrics transcription (AudioShake API)
- Agentic AI correction (Gemini 3 Flash via Vertex AI)
- Agentic AI correction (Gemini 3 Flash via the Gemini Developer API)
- Human lyrics review (React UI)
- Preview video generation
- Instrumental selection (clean vs. with backing vocals)
@@ -190,7 +190,7 @@ Commercial producers pay for API access or custom integration to generate tracks
- **Secrets**: Google Secret Manager
- **Audio Separation**: Cloud Run GPU (L4, us-east4)
- **Lyrics Transcription**: AudioShake API
- **AI Correction**: Vertex AI (Gemini 3 Flash)
- **AI Correction**: Gemini Developer API (Gemini 3 Flash)
- **Payments**: Stripe
- **Email**: Postmark
- **IaC**: Pulumi
+9
View File
@@ -57,6 +57,15 @@
## Recent Changes
- **Gemini moved off Vertex AI** (2026-10-01, v0.262.0): every Gemini call (auto-correct compare leg, match-judge, parse-titles, credit eval, tenant bulk analyze, custom lyrics, lyrics translation, error-monitor LLM, agentic correction, translate.py) now uses the Gemini Developer API with the `gemini-api-key` secret via `backend/services/gemini_client.py`, so no AI spend lands on the nomadkaraoke project (Vertex APIs disabled there). Quota/billing/key failures degrade per caller and send one Discord ops alert per 6h. See LESSONS-LEARNED "Gemini: Developer API key, never Vertex".
- **Translated lyrics follow-ups + review waveform spinner** (2026-10-01, v0.261.0):
- The translation row now renders at 70% of the unsung colour's opacity, with outline and shadow faded to match, so it reads as secondary to the sung line (`subtitles.py:TRANSLATION_OPACITY`). A theme's `karaoke.translation_color` still wins.
- Published videos with translations get "(With Translation into X)" in the YouTube title, before "(Karaoke)". Only the artist/title get truncated, never the label. The description also gets a notice. This applies to the live upload and the quota queue, but only when `state_data.lyrics_translation.status == "translated"` (`youtube_description.build_youtube_title`).
- The review preview modal explains that the preview is a quick black-background sync check, and that translated lyrics are added after review.
- Lyrics review Waveforms toggle: shows a spinner and tooltip while audio separation is still producing the vocal stem (the peaks endpoint returns 202). Previously the rows were just empty (`VocalsAudioDataLoaderContext.status`).
- **Translated lyrics: Japanese/Chinese translations no longer split mid-word** (2026-10-01, v0.260.1): when a long lyric line is split across rows, its translation is shared between them. Unspaced scripts were cut at an arbitrary character, so prod job ca2e881a showed 無|駄 ("waste") across two rows. `split_text_proportionally` now prefers punctuation, then a break after a Japanese particle or before a kanji/katakana word start, and only cuts mid-word as a last resort; it no longer leaves a piece empty when there are enough characters. Thai can still split inside a word (no word-boundary data).
- **Translated lyrics for language learners** (2026-10-01, v0.260.0): an "Add translated lyrics" option at job creation (any job, free for now) with a language picker (33 UI locales) and a live preview of the real video frame (`GET /api/themes/translation-preview`). After review, the render worker translates the final lyrics line by line with Gemini (`backend/services/lyrics_translation.py`, GCS-cached so re-renders are free) into `lyrics/translations.json`; the landscape and portrait videos draw each translation in smaller unsung-colour text beneath its line, 3 lines per screen (`ass/config.py:translation_layout`, `LyricsLine._create_translation_event`). Translations are their own ASS events with auto paragraph direction, so mixed scripts work (a Hebrew song keeps its right-to-left highlight with an English translation beneath, and vice versa); long translations wrap/scale to fit; a line split by the resizer shares its translation across the pieces. Not editable; a translation failure renders without it (`state_data.lyrics_translation`). See [archive/2026-10-01-translated-lyrics-plan.md](archive/2026-10-01-translated-lyrics-plan.md).
- **Re-render works for tenants that archive to Dropbox** (2026-09-30, v0.254.1): randy-vild jobs get a brand code and a Dropbox archive folder (`RVILD-0001 - …`), so v0.253.0's "never distributed" guard rejected the very jobs the button was for. A re-render now reuses the job's brand code and overwrites the same folder instead of allocating a new code. YouTube/GDrive-published jobs are still rejected.
- **Tenant "Re-render" with the current theme + edited tenant tracks no longer lose their downloads** (2026-09-30, v0.253.0): Finished portal tracks have a **Re-render** button (`POST /api/jobs/{id}/rerender`). It re-applies the tenant's current theme and rebuilds the screens, lyrics video, encodes and CDG/TXT from the already-reviewed lyrics, with no review step (`backend/services/theme_rerender_service.py`, same mechanism as the private→public visibility change). The encoding worker caches finished jobs by id in memory, so a re-run submitted while the VM was still up could get the previous render back. Render and encode now submit as `{job_id}_g{worker_generation}` (`encoding_worker_job_id`). Separately, `outputs_deleted_at` (set by Edit) was only cleared when the re-render uploaded to YouTube/Dropbox/GDrive, so edited tenant jobs re-rendered but hid every download (job 2579a1ea). Every successful render now clears it.
- **Hold a word's resize handle at the row edge to keep extending it** (2026-09-30, v0.252.0): in the lyrics review Waveforms rows (and the Edit Segment timeline) the view is the segment ±1s and was fixed during a drag, so a word ending 5s+ too early took several drag-release cycles. Holding a resize handle within 24px of the edge it's heading toward (or past it) now keeps growing the word at 1–4 s/s (faster nearer the edge), zooming the view out so the handle stays under the cursor. It stops when the pointer leaves the zone, on release, or at the neighbouring word, including the next/previous line's first/last word (`computeNeighbourBoundsBySegment`), else the audio bounds. Drags are tracked on `window`, so leaving the row no longer abandons them, and resizes clamp to the neighbour instead of freezing short of it (`TimelineEditor.tsx`).
+1 -1
View File
@@ -99,7 +99,7 @@ the same KaraokeNerds check the normal job-submission flow uses runs at two poin
- **Auth:** reuses gen's passwordless magic-link system. Board sign-in sends
`purpose="requests_board"`, which creates an identity **without** granting a welcome credit and
with a higher per-IP signup cap (so a whole venue on shared WiFi can sign in).
- **Auto-correct:** reuses `match_judge` (Vertex Gemini) — the same artist/title canonicalizer the
- **Auto-correct:** reuses `match_judge` (Gemini) — the same artist/title canonicalizer the
job-submission flow uses.
- **Storage:** two Firestore collections — `song_requests` (one doc per song, with a denormalized
`vote_count`) and `song_request_votes` (one doc per person per day, id `{email}__{YYYY-MM-DD}`,
+2 -2
View File
@@ -31,7 +31,7 @@ GitHub-hosted runners work but are slower (2 vCPU, 7GB RAM) and costs scale line
| Component | Spec | Purpose |
|-----------|------|---------|
| General runners | 3x `github-runner-{1..3}`, `e2-standard-4`, 200GB SSD | Execute CI jobs (lint, test, type check, build) |
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | Docker image builds (needs more CPU/RAM) |
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | **Unused since 2026-10-01** — `deploy-backend` runs on `ubuntu-latest` and builds images in Cloud Build (see EPHEMERAL-GHA-RUNNERS.md) |
| GPU runners | 3x `github-gpu-runner-{1..3}`, `n1-standard-4` + T4 GPU, 200GB SSD | Audio separation model testing |
| Cloud Function | `github-runner-manager`, Gen2, Python 3.12, 5min timeout | Start/stop VMs based on webhooks and idle checks |
| Cloud Scheduler | `runner-manager-idle-check`, every 5 min | Orphan cleanup + stalled-job re-dispatch (see EPHEMERAL-GHA-RUNNERS.md) |
@@ -52,7 +52,7 @@ All runner VMs are in `us-central1-a`.
| Label Set | VMs | Used By |
|-----------|-----|---------|
| `[self-hosted, linux, x64, gcp, large-disk]` | general runners | Most CI jobs |
| `[self-hosted, linux, x64, gcp, large-disk, docker-build]` | build runner | Docker image builds |
| `[self-hosted, linux, x64, gcp, large-disk, docker-build]` | build runner | Unused since 2026-10-01 (images build in Cloud Build) |
| `[self-hosted, linux, x64, gcp, gpu]` | GPU runners | Audio separation tests |
## How Auto-Scaling Works
+4 -1
View File
@@ -224,7 +224,10 @@ sung pixels always precede unsung ones in reading order (pins word order *and* i
fill direction), progress is monotonic and in time with the words, the lead-in lands
outside the start edge, and libass found every glyph. `tests/unit/test_font_fallback_render.py`
does the same for PIL-rendered title cards / portrait headers (no `.notdef` tofu, Hebrew
title reads right-to-left).
title reads right-to-left). `test_translated_lyrics_render.py` covers translated lyrics: the
translation row renders beneath its line (smaller, centred, never highlighted, every glyph
found) for Latin/Hebrew/Arabic/CJK translations and mixed directions (Hebrew/Arabic lyrics with
English or Arabic translations), and an RTL lyric still fills right-to-left.
- **CI** installs `fonts-noto-core fonts-noto-cjk` and runs with `CI=true`, where these
tests fail instead of skipping on a missing precondition.
+28
View File
@@ -60,6 +60,34 @@ defense-in-depth beneath the signing-free review path.
---
## Emails not arriving / E2E "Timed out waiting for email" (Postmark HTML 403)
**Symptom:** magic links or job emails never arrive; E2E Daily Stage 1 fails at
"Sign up via magic link". Backend logs show
`Postmark returned status 403: <html>…403 Forbidden…` followed by
`Failed to send magic link email to …`.
**Cause:** a bare nginx HTML 403 (not Postmark's JSON error format) is an edge/IP-level
block at `api.postmarkapp.com`, not a token or payload problem. Seen intermittently
from `karaoke-backend` (us-central1, shared Cloud Run egress IPs) since 2026-09-30;
us-east4 Cloud Run Jobs were unaffected. A JSON 403 (`ErrorCode=10`) is a real bad-token error instead.
**Mitigation in code:** `PostmarkEmailProvider` retries 429 / 5xx / non-JSON 403 /
connect timeouts (backoff 1s, 3s). JSON Postmark errors and read timeouts are not
retried (deterministic, or risk of a duplicate send).
**Diagnosis:**
```bash
gcloud logging read 'resource.labels.service_name="karaoke-backend" AND (textPayload:"Postmark returned status" OR textPayload:"Failed to send")' \
--project nomadkaraoke --freshness 2d --limit 50 --format='value(timestamp,textPayload)'
```
The E2E `waitForEmail` helper now checks `GET /api/admin/users/{email}/emails` on
timeout and reports whether the backend sent anything ("backend has NO record…" =
server-side send failure; "backend sent N email(s)…" = delivery/testmail problem).
**If it persists after retries:** contact Postmark support with failure timestamps, or
give the backend a static egress IP (Direct VPC egress + Cloud NAT).
## Fast rollback (bad backend deploy)
**When to use:** a merge-to-main deploy shipped a bad backend revision — the
@@ -0,0 +1,90 @@
# Translated lyrics beneath the karaoke lyrics (2026-10-01)
## Goal
> a karaoke-gen feature to produce karaoke videos with lyrics translations rendered in smaller
> text below the primary synced lyrics - so eg. language learners can easily sing karaoke of
> some cool songs in a language which isn't their primary language, while learning the meanings
> of the lyrics at the same time rather than just blindly repeating the sounds
Decisions (Andrew, 2026-10-01): every job, a job-submission option (free for now; may cost
credits later); a toggle with a language picker that shows a preview of the final look; no
editing; translate the lyrics **post-review** so the corrected text is translated. Mixed
directions must work (e.g. a Hebrew song with English translations). 3 lyric lines per screen
when translating. Landscape + portrait videos.
## Design
**Data.** `Job.translation_language` (one of the 33 UI locale codes, `None` = off). Every
creation route accepts `translation_language`; `JobCreate` normalizes it (unsupported → off).
Admin PATCH can set/clear it.
**When.** `render_video_worker` calls `prepare_job_translations` right after the job enters
RENDERING_VIDEO (so retries see it as rendering), before the render itself (≤ 2 × 90s attempts): it
loads the final segments (corrections.json + corrections_updated.json, exactly what renders),
translates every line in one Gemini call (`backend/services/lyrics_translation.py`,
`LYRICS_TRANSLATION_MODEL`, default gemini-3.8-flash via Vertex), and writes
`jobs/{id}/lyrics/translations.json` (`{language, language_name, model, lines: [{segment_id,
text, translation}]}`). Identical requests hit a GCS cache (`lyrics-translation-cache/`), so a
theme re-render or admin re-render costs nothing. Status goes to `state_data.lyrics_translation`
(`translated` / `same_language` / `failed`). A failure **never blocks the render**: it's logged
as an error (error monitor) and the video renders without translations (admin can re-render).
If most lines come back unchanged the song is already in that language → no row. A stale file is
deleted whenever a render has no translations (the encoder reads it for the portrait video).
**Render.** `LyricsSegment.translation` (optional, round-trips through to/from_dict).
`karaoke_gen/lyrics_transcriber/output/translations.py` applies the file by segment id (text
fallback). The GCE render request gets `translations_gcs_path`; the portrait render reads
`lyrics/translations.json` from the job download. The review preview video does not show
translations (they don't exist until after review).
- `SubtitlesGenerator.generate_ass`: if any segment has a translation, it uses a copy of the
ScreenConfig with taller slots (`ass/config.py:translation_layout`): lyric line + gap
(0.12×font) + `translation_max_rows` × 1.15 × translation font (0.5×font), and
`max_visible_lines = min(theme, 3)`. Positions/timing math is unchanged (it only uses
`line_height`). Without translations the output is byte-identical to before.
- Style `Karaoke.Translation`: the lyric style at the smaller size, in the **unsung** colour,
outline scaled; `Encoding=-1` inherited, so libass picks paragraph direction per event.
- `LyricsLine._create_translation_event`: one static Dialogue (no `\k`), same start/end/fade as
the line, at `y + lyric_line_height + gap`. Text is sanitized (no `{}`/`\`), case-transformed
like the lyric, wrapped to `translation_max_rows` (default 1), then uniformly scaled
(`\fscx\fscy`) to fit 92% of the width.
- **RTL/LTR mix:** the translation is its own event without the lyric's RTL fill tags, so a
Hebrew line keeps its right-to-left highlight while an English translation beneath lays out
left-to-right (and vice versa). Covered by pixel render tests.
- **Split lines:** `SegmentResizer` splits long lines into pieces shown together; the
translation is shared across the pieces in proportion to their width
(`split_text_proportionally`, word boundaries; CJK/Thai between grapheme clusters, so a Thai
tone mark never starts a piece), so no piece has an empty row. Trade-off (accepted): the split
is by length, not meaning, so for languages with very different word order a fragment can sit
under the "wrong" half, and the pieces can straddle a screen change. Reading both rows in order
still gives the full translation. Portrait orphan merges concatenate translations; the portrait top padding is
recomputed for the taller block.
- Section cards (INSTRUMENTAL) keep the lyric line height, so they don't move. Shrink-to-fit
estimates width from the character count when the style font file is missing.
- Theme keys (optional, `karaoke` block): `translation_font_size` / `translation_font_ratio`,
`translation_color`, `translation_max_rows`, `translation_max_visible_lines`.
**Preview.** `GET /api/themes/translation-preview?language=xx` → `{image}` (JPEG data URL):
the default theme's real karaoke frame (theme_preview_service renderer) with sample lyrics and
committed sample translations (`backend/services/translation_preview_samples.py`, generated by
`backend/scripts/generate_translation_preview_samples.py`; English target uses a Spanish
sample). No LLM call at preview time; in-memory cache per (theme, language).
**Frontend.** CustomizeStep: "Add translated lyrics" toggle → language select (default UI
locale, names via `Intl.DisplayNames`) + preview image + hint; GuidedJobFlow passes
`translation_language` to job creation. Admin job edit field.
## Tests
- `tests/unit/lyrics_transcriber/output/test_translated_lyrics.py` — data model, resizer
sharing, ASS layout/style/positions, sanitizing, scale-to-fit, mixed RTL/LTR, portrait.
- `tests/unit/lyrics_transcriber/output/test_translated_lyrics_render.py` — libass pixel
tests (Latin, Hebrew, Arabic, CJK translations; Hebrew/Arabic lyrics with English/Arabic
translations; RTL highlight unaffected). Run in Linux: `scripts/run-render-tests-linux.sh`.
- `backend/tests/test_lyrics_translation.py` — service (retry, cache, count validation),
job preparation (reviewed text, same-language, failure, stale cleanup), model, preview route.
- `backend/tests/test_render_video_worker_translations.py`, `tests/unit/test_gce_render_video_endpoint.py`.
## Follow-ups
- Credits pricing for translated jobs (LLM cost is ~1 flash call per job).
- Optional: show translations in the review preview video; editable translations.
- CDG/TXT outputs don't include translations.
@@ -534,6 +534,7 @@ function LyricsReviewWrapper({ job, isLocalMode = false, isReplay = false }: { j
isLocalMode={isLocalMode}
jobId={job.job_id}
hasExistingInstrumental={!!job.existing_instrumental_gcs_path}
translationLanguage={job.translation_language}
/>
</main>
</div>
+2
View File
@@ -1336,6 +1336,8 @@ function AdminJobsPageContent() {
{ key: "theme_id", label: "Theme", value: selectedJob.theme_id || "default" },
{ key: "brand_prefix", label: "Brand Prefix", value: selectedJob.brand_prefix },
{ key: "customer_email", label: "Customer Email", value: selectedJob.customer_email },
// Language code (e.g. "es"); clear to turn translated lyrics off
{ key: "translation_language", label: "Translation", value: selectedJob.translation_language || "" },
].map(({ key, label, value }) => (
<div key={key} className="flex items-center gap-2 group">
<span className="text-[10px] font-medium text-muted-foreground uppercase w-20 shrink-0">{label}</span>
@@ -117,6 +117,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
// Full-auto review (workstream C): up-front autonomy + backing-vocals preference.
const [reviewMode, setReviewMode] = useState<ReviewMode>("auto")
const [backingPreference, setBackingPreference] = useState<BackingPreference>("auto")
// Translated lyrics: UI locale code to translate each lyric line into, or null = off.
const [translationLanguage, setTranslationLanguage] = useState<string | null>(null)
// Custom style state
const [karaokeBackground, setKaraokeBackground] = useState<File | null>(null)
@@ -188,6 +190,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
requires_audio_edit: requiresAudioEdit || undefined,
review_mode: reviewMode,
backing_preference: backingPreference,
translation_language: translationLanguage ?? undefined,
})
createdJobId = response.job_id
} else if (audioSource === "upload" && pendingFile) {
@@ -199,6 +202,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
requires_audio_edit: requiresAudioEdit || undefined,
review_mode: reviewMode,
backing_preference: backingPreference,
translation_language: translationLanguage ?? undefined,
instrumentalFile: isPrivate && !requiresAudioEdit ? instrumentalFile : null,
},
report,
@@ -217,6 +221,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
requires_audio_edit: requiresAudioEdit || undefined,
review_mode: reviewMode,
backing_preference: backingPreference,
translation_language: translationLanguage ?? undefined,
})
createdJobId = response.job_id
} else {
@@ -278,6 +283,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
setRequiresAudioEdit(false)
setReviewMode("auto")
setBackingPreference("auto")
setTranslationLanguage(null)
setKaraokeBackground(null)
setIntroBackground(null)
setColorOverrides({})
@@ -582,6 +588,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
onReviewModeChange={setReviewMode}
backingPreference={backingPreference}
onBackingPreferenceChange={setBackingPreference}
translationLanguage={translationLanguage}
onTranslationLanguageChange={setTranslationLanguage}
onConfirm={handleConfirm}
onBack={() => setStep(3)}
isSubmitting={isSubmitting}
@@ -0,0 +1,191 @@
"use client"
import { useEffect, useMemo, useRef, useState } from "react"
import { useLocale, useTranslations } from "next-intl"
import { Languages, Loader2 } from "lucide-react"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { routing } from "@/i18n/routing"
import { api } from "@/lib/api"
/** Languages a job's lyrics can be translated into (same set as the UI locales). */
export const TRANSLATION_LANGUAGES: readonly string[] = routing.locales
interface TranslatedLyricsOptionProps {
/** Selected language code, or null when translated lyrics are off. */
value: string | null
onChange: (value: string | null) => void
disabled?: boolean
}
/**
* Opt-in for a karaoke video that shows an AI translation of each lyric line in
* smaller text beneath the synced lyrics. The translation is generated by the
* backend after lyrics review, so it isn't editable here. Shows a real rendered
* sample frame (default theme) for the chosen language.
*/
export function TranslatedLyricsOption({ value, onChange, disabled }: TranslatedLyricsOptionProps) {
const t = useTranslations("jobFlow")
const uiLocale = useLocale()
const enabled = value !== null
const languages = useMemo(() => {
let names: Intl.DisplayNames | null = null
try {
names = new Intl.DisplayNames([uiLocale], { type: "language" })
} catch {
names = null
}
return TRANSLATION_LANGUAGES
.map((code) => ({ code, label: names?.of(code) ?? code }))
.sort((a, b) => a.label.localeCompare(b.label, uiLocale))
}, [uiLocale])
const defaultLanguage = TRANSLATION_LANGUAGES.includes(uiLocale) ? uiLocale : "en"
const languageLabel = (code: string) => languages.find((l) => l.code === code)?.label ?? code
// Preview frames cached per language. Responses are stored under the language
// they were requested for, so a slow response for a previously selected
// language never replaces the preview of the current one.
const [previews, setPreviews] = useState<Record<string, string>>({})
const [failed, setFailed] = useState<Record<string, boolean>>({})
const inFlight = useRef<Set<string>>(new Set())
const mounted = useRef(true)
useEffect(() => {
mounted.current = true
return () => { mounted.current = false }
}, [])
useEffect(() => {
if (!value || previews[value] || failed[value] || inFlight.current.has(value)) return
const language = value
inFlight.current.add(language)
api.getTranslationPreview(language)
.then((res) => {
if (mounted.current) setPreviews((prev) => ({ ...prev, [language]: res.image }))
})
.catch(() => {
if (mounted.current) setFailed((prev) => ({ ...prev, [language]: true }))
})
.finally(() => {
inFlight.current.delete(language)
})
}, [value, previews, failed])
function handleToggle(checked: boolean) {
onChange(checked ? defaultLanguage : null)
}
function clearFailure(code: string) {
setFailed((prev) => {
const next = { ...prev }
delete next[code]
return next
})
}
function handleLanguageChange(code: string) {
// Selecting a language whose preview failed retries it.
if (failed[code]) clearFailure(code)
onChange(code)
}
const previewImage = value ? previews[value] : undefined
const previewFailed = value ? !!failed[value] : false
return (
<div
className="space-y-4 rounded-lg border p-4"
style={{ borderColor: 'var(--card-border)', backgroundColor: 'rgba(255,255,255,0.02)' }}
data-testid="translated-lyrics-option"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<Languages className="w-4 h-4" style={{ color: 'var(--brand-pink)' }} />
<Label htmlFor="translated-lyrics-toggle" className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
{t('translatedLyricsToggle')}
</Label>
</div>
<p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>
{t('translatedLyricsToggleHint')}
</p>
</div>
<Switch
id="translated-lyrics-toggle"
checked={enabled}
onCheckedChange={handleToggle}
disabled={disabled}
/>
</div>
{enabled && value && (
<div className="space-y-3">
<div className="space-y-1.5">
<Label htmlFor="translated-lyrics-language" className="text-xs" style={{ color: 'var(--text-muted)' }}>
{t('translatedLyricsLanguageLabel')}
</Label>
<select
id="translated-lyrics-language"
value={value}
onChange={(e) => handleLanguageChange(e.target.value)}
disabled={disabled}
className="w-full h-9 rounded-md border px-2 text-sm"
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
>
{languages.map((lang) => (
<option key={lang.code} value={lang.code}>{lang.label}</option>
))}
</select>
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
{t('translatedLyricsHint', { language: languageLabel(value) })}
</p>
</div>
<div
className="relative w-full aspect-video overflow-hidden rounded-md border"
style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--secondary)' }}
>
{previewImage ? (
/* eslint-disable-next-line @next/next/no-img-element */
<img
src={previewImage}
alt={t('translatedLyricsPreviewAlt', { language: languageLabel(value) })}
className="w-full h-full object-contain"
data-testid="translated-lyrics-preview"
/>
) : previewFailed ? (
<div className="absolute inset-0 flex items-center justify-center p-4 text-center">
<div className="space-y-2">
<p className="text-xs" style={{ color: 'var(--text-muted)' }} data-testid="translated-lyrics-preview-error">
{t('translatedLyricsPreviewError')}
</p>
<button
type="button"
onClick={() => clearFailure(value)}
disabled={disabled}
className="text-xs underline"
style={{ color: 'var(--brand-pink)' }}
data-testid="translated-lyrics-preview-retry"
>
{t('translatedLyricsPreviewRetry')}
</button>
</div>
</div>
) : (
<div
className="absolute inset-0 flex flex-col items-center justify-center gap-2 animate-pulse"
data-testid="translated-lyrics-preview-loading"
>
<Loader2 className="w-5 h-5 animate-spin" style={{ color: 'var(--text-muted)' }} />
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
{t('translatedLyricsPreviewLoading')}
</p>
</div>
)}
</div>
</div>
)}
</div>
)
}
@@ -1,5 +1,12 @@
import { render, screen, fireEvent } from "@testing-library/react"
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react"
import { CustomizeStep } from "../steps/CustomizeStep"
import { api } from "@/lib/api"
jest.mock("@/lib/api", () => ({
api: { getTranslationPreview: jest.fn() },
}))
const mockGetTranslationPreview = api.getTranslationPreview as jest.Mock
// Mock canvas-based components — they require browser APIs not available in jsdom
jest.mock("../TitleCardPreview", () => ({
@@ -61,6 +68,10 @@ const defaultProps = {
onIntroBackgroundChange: jest.fn(),
colorOverrides: {},
onColorOverridesChange: jest.fn(),
reviewMode: "auto" as const,
onReviewModeChange: jest.fn(),
backingPreference: "auto" as const,
onBackingPreferenceChange: jest.fn(),
onConfirm: jest.fn(),
onBack: jest.fn(),
isSubmitting: false,
@@ -216,3 +227,132 @@ describe("CustomizeStep", () => {
expect(createBtn).toBeDisabled()
})
})
describe("CustomizeStep — translated lyrics", () => {
beforeEach(() => {
jest.clearAllMocks()
global.URL.createObjectURL = jest.fn(() => "blob:mock")
global.URL.revokeObjectURL = jest.fn()
mockGetTranslationPreview.mockImplementation(async (lang: string) => ({ image: `data:image/jpeg;base64,${lang}` }))
})
it("hides the option when no change handler is provided", () => {
render(<CustomizeStep {...defaultProps} />)
expect(screen.queryByText("Add translated lyrics")).not.toBeInTheDocument()
})
it.each([false, true])("is off by default with no language select or preview (isPrivate=%s)", (isPrivate) => {
render(
<CustomizeStep {...defaultProps} isPrivate={isPrivate}
translationLanguage={null} onTranslationLanguageChange={jest.fn()} />
)
const toggle = screen.getByRole("switch", { name: "Add translated lyrics" })
expect(toggle).toHaveAttribute("aria-checked", "false")
expect(screen.queryByLabelText("Translate lyrics into")).not.toBeInTheDocument()
expect(mockGetTranslationPreview).not.toHaveBeenCalled()
})
it("turning the toggle on selects the UI locale", () => {
const onChange = jest.fn()
render(<CustomizeStep {...defaultProps} translationLanguage={null} onTranslationLanguageChange={onChange} />)
fireEvent.click(screen.getByRole("switch", { name: "Add translated lyrics" }))
// jest.setup mocks useLocale() → "en"
expect(onChange).toHaveBeenCalledWith("en")
})
it("turning the toggle off clears the language", async () => {
const onChange = jest.fn()
render(<CustomizeStep {...defaultProps} translationLanguage="es" onTranslationLanguageChange={onChange} />)
await screen.findByTestId("translated-lyrics-preview")
fireEvent.click(screen.getByRole("switch", { name: "Add translated lyrics" }))
expect(onChange).toHaveBeenCalledWith(null)
})
it("when on, shows a language select with all 33 languages, a hint and the preview", async () => {
render(<CustomizeStep {...defaultProps} translationLanguage="es" onTranslationLanguageChange={jest.fn()} />)
const select = screen.getByLabelText("Translate lyrics into") as HTMLSelectElement
expect(select.value).toBe("es")
expect(select.options).toHaveLength(33)
// Options are labelled with language names, sorted by label
const labels = Array.from(select.options).map((o) => o.textContent || "")
expect(labels).toContain("Spanish")
expect([...labels].sort((a, b) => a.localeCompare(b, "en"))).toEqual(labels)
expect(screen.getByText(/translates each line into Spanish/)).toBeInTheDocument()
expect(screen.getByTestId("translated-lyrics-preview-loading")).toBeInTheDocument()
const img = await screen.findByTestId("translated-lyrics-preview")
expect(img).toHaveAttribute("src", "data:image/jpeg;base64,es")
expect(mockGetTranslationPreview).toHaveBeenCalledWith("es")
})
it("changing the language calls onChange and refetches the preview, caching per language", async () => {
const onChange = jest.fn()
const { rerender } = render(
<CustomizeStep {...defaultProps} translationLanguage="es" onTranslationLanguageChange={onChange} />
)
await screen.findByTestId("translated-lyrics-preview")
fireEvent.change(screen.getByLabelText("Translate lyrics into"), { target: { value: "fr" } })
expect(onChange).toHaveBeenCalledWith("fr")
rerender(<CustomizeStep {...defaultProps} translationLanguage="fr" onTranslationLanguageChange={onChange} />)
await waitFor(() =>
expect(screen.getByTestId("translated-lyrics-preview")).toHaveAttribute("src", "data:image/jpeg;base64,fr")
)
expect(mockGetTranslationPreview).toHaveBeenCalledWith("fr")
// Switching back uses the cached preview — no second request for "es"
rerender(<CustomizeStep {...defaultProps} translationLanguage="es" onTranslationLanguageChange={onChange} />)
expect(screen.getByTestId("translated-lyrics-preview")).toHaveAttribute("src", "data:image/jpeg;base64,es")
expect(mockGetTranslationPreview.mock.calls.filter(([l]) => l === "es")).toHaveLength(1)
})
it("ignores a stale preview response for a previously selected language", async () => {
let resolveEs: (v: { image: string }) => void = () => {}
mockGetTranslationPreview.mockImplementation((lang: string) =>
lang === "es"
? new Promise((resolve) => { resolveEs = resolve })
: Promise.resolve({ image: `data:image/jpeg;base64,${lang}` })
)
const { rerender } = render(
<CustomizeStep {...defaultProps} translationLanguage="es" onTranslationLanguageChange={jest.fn()} />
)
rerender(<CustomizeStep {...defaultProps} translationLanguage="de" onTranslationLanguageChange={jest.fn()} />)
await waitFor(() =>
expect(screen.getByTestId("translated-lyrics-preview")).toHaveAttribute("src", "data:image/jpeg;base64,de")
)
await act(async () => { resolveEs({ image: "data:image/jpeg;base64,es" }) })
expect(screen.getByTestId("translated-lyrics-preview")).toHaveAttribute("src", "data:image/jpeg;base64,de")
})
it("shows a graceful error when the preview fails", async () => {
mockGetTranslationPreview.mockRejectedValue(new Error("boom"))
render(<CustomizeStep {...defaultProps} translationLanguage="ja" onTranslationLanguageChange={jest.fn()} />)
expect(await screen.findByTestId("translated-lyrics-preview-error")).toHaveTextContent("Couldn't load the preview")
expect(screen.queryByTestId("translated-lyrics-preview")).not.toBeInTheDocument()
})
it("retries a failed preview", async () => {
mockGetTranslationPreview.mockRejectedValueOnce(new Error("boom"))
mockGetTranslationPreview.mockResolvedValueOnce({ image: "data:image/jpeg;base64,ja" })
render(<CustomizeStep {...defaultProps} translationLanguage="ja" onTranslationLanguageChange={jest.fn()} />)
fireEvent.click(await screen.findByTestId("translated-lyrics-preview-retry"))
await waitFor(() =>
expect(screen.getByTestId("translated-lyrics-preview")).toHaveAttribute("src", "data:image/jpeg;base64,ja")
)
expect(mockGetTranslationPreview).toHaveBeenCalledTimes(2)
})
it("disables the toggle and select while submitting", async () => {
render(
<CustomizeStep {...defaultProps} isSubmitting={true}
translationLanguage="es" onTranslationLanguageChange={jest.fn()} />
)
await screen.findByTestId("translated-lyrics-preview")
expect(screen.getByRole("switch", { name: "Add translated lyrics" })).toBeDisabled()
expect(screen.getByLabelText("Translate lyrics into")).toBeDisabled()
})
})
@@ -0,0 +1,136 @@
/**
* GuidedJobFlow — translated lyrics wiring.
*
* Drives the real GuidedJobFlow through all four steps (step components are
* stubbed down to the callbacks the flow relies on) and asserts the
* translation language chosen on the Customize step reaches every job-creation
* call as `translation_language`, and is omitted when the option is off.
*/
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
jest.mock("@/lib/api", () => {
class ApiError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.status = status
}
}
return {
ApiError,
api: {
createJobFromSearch: jest.fn(),
createJobFromUrl: jest.fn(),
createJobFromUploadedAudio: jest.fn(),
},
}
})
jest.mock("@/lib/auth", () => ({
useAuth: jest.fn(() => ({ user: { role: "user", credits: 5 }, isLoading: false })),
}))
jest.mock("@/lib/tenant", () => ({
useTenant: jest.fn(() => ({ features: {} })),
}))
jest.mock("@/components/credits/BuyCreditsDialog", () => ({ BuyCreditsDialog: () => null }))
jest.mock("@/components/upload/UploadProgressModal", () => ({ UploadProgressModal: () => null }))
jest.mock("../steps/SongInfoStep", () => ({
SongInfoStep: ({ onArtistChange, onTitleChange, onNext }: any) => (
<button onClick={() => { onArtistChange("Artist"); onTitleChange("Song"); onNext() }}>step1-next</button>
),
}))
jest.mock("../steps/AudioSourceStep", () => ({
AudioSourceStep: ({ onUrlReady, onFileReady, onSearchCompleted, onSearchResultChosen }: any) => (
<div>
<button onClick={() => onUrlReady("https://youtube.com/watch?v=abc")}>use-url</button>
<button onClick={() => onFileReady(new File(["x"], "song.mp3", { type: "audio/mpeg" }))}>use-file</button>
<button onClick={() => { onSearchCompleted("session-1"); onSearchResultChosen(0) }}>use-search</button>
</div>
),
}))
jest.mock("../steps/VisibilityStep", () => ({
VisibilityStep: ({ onNext }: any) => <button onClick={onNext}>step3-next</button>,
}))
jest.mock("../steps/CustomizeStep", () => ({
CustomizeStep: ({ translationLanguage, onTranslationLanguageChange, onConfirm }: any) => (
<div>
<span data-testid="translation-value">{String(translationLanguage)}</span>
<button onClick={() => onTranslationLanguageChange("es")}>pick-spanish</button>
<button onClick={onConfirm}>confirm</button>
</div>
),
}))
import { api } from "@/lib/api"
import { GuidedJobFlow } from "../GuidedJobFlow"
const mockApi = api as jest.Mocked<typeof api>
function goToCustomize(source: "use-url" | "use-file" | "use-search") {
fireEvent.click(screen.getByText("step1-next"))
fireEvent.click(screen.getByText(source))
fireEvent.click(screen.getByText("step3-next"))
}
describe("GuidedJobFlow — translated lyrics", () => {
beforeEach(() => {
jest.clearAllMocks()
mockApi.createJobFromUrl.mockResolvedValue({ status: "success", job_id: "job-url", message: "ok" })
mockApi.createJobFromSearch.mockResolvedValue({ status: "success", job_id: "job-search", message: "ok" })
mockApi.createJobFromUploadedAudio.mockResolvedValue({ status: "success", job_id: "job-upload", message: "ok" } as any)
})
it("defaults to off and omits translation_language", async () => {
render(<GuidedJobFlow onJobCreated={jest.fn()} />)
goToCustomize("use-url")
expect(screen.getByTestId("translation-value")).toHaveTextContent("null")
fireEvent.click(screen.getByText("confirm"))
await waitFor(() => expect(mockApi.createJobFromUrl).toHaveBeenCalled())
const options = mockApi.createJobFromUrl.mock.calls[0][3]
expect(options?.translation_language).toBeUndefined()
})
it("passes translation_language to createJobFromUrl", async () => {
render(<GuidedJobFlow onJobCreated={jest.fn()} />)
goToCustomize("use-url")
fireEvent.click(screen.getByText("pick-spanish"))
expect(screen.getByTestId("translation-value")).toHaveTextContent("es")
fireEvent.click(screen.getByText("confirm"))
await waitFor(() => expect(mockApi.createJobFromUrl).toHaveBeenCalled())
expect(mockApi.createJobFromUrl.mock.calls[0][3]).toEqual(
expect.objectContaining({ translation_language: "es" })
)
})
it("passes translation_language to createJobFromSearch", async () => {
render(<GuidedJobFlow onJobCreated={jest.fn()} />)
goToCustomize("use-search")
fireEvent.click(screen.getByText("pick-spanish"))
fireEvent.click(screen.getByText("confirm"))
await waitFor(() => expect(mockApi.createJobFromSearch).toHaveBeenCalled())
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
expect.objectContaining({ search_session_id: "session-1", translation_language: "es" })
)
})
it("passes translation_language to createJobFromUploadedAudio", async () => {
render(<GuidedJobFlow onJobCreated={jest.fn()} />)
goToCustomize("use-file")
fireEvent.click(screen.getByText("pick-spanish"))
fireEvent.click(screen.getByText("confirm"))
await waitFor(() => expect(mockApi.createJobFromUploadedAudio).toHaveBeenCalled())
expect(mockApi.createJobFromUploadedAudio.mock.calls[0][3]).toEqual(
expect.objectContaining({ translation_language: "es" })
)
})
})
@@ -9,6 +9,7 @@ import { ArrowLeft, Loader2, Palette, Image as ImageIcon, Paintbrush, Sparkles }
import { TitleCardPreview } from "../TitleCardPreview"
import { KaraokeBackgroundPreview } from "../KaraokeBackgroundPreview"
import { ImageUploadField } from "../ImageUploadField"
import { TranslatedLyricsOption } from "../TranslatedLyricsOption"
export interface ColorOverrides {
artist_color?: string
@@ -38,6 +39,10 @@ interface CustomizeStepProps {
onReviewModeChange: (value: ReviewMode) => void
backingPreference: BackingPreference
onBackingPreferenceChange: (value: BackingPreference) => void
/** Language code for translated lyrics beneath the synced lyrics; null = off. */
translationLanguage?: string | null
/** Omit to hide the translated-lyrics option entirely. */
onTranslationLanguageChange?: (value: string | null) => void
onConfirm: () => void
onBack: () => void
isSubmitting: boolean
@@ -305,6 +310,8 @@ export function CustomizeStep({
onReviewModeChange,
backingPreference,
onBackingPreferenceChange,
translationLanguage = null,
onTranslationLanguageChange,
onConfirm,
onBack,
isSubmitting,
@@ -469,6 +476,14 @@ export function CustomizeStep({
t={t}
/>
{onTranslationLanguageChange && (
<TranslatedLyricsOption
value={translationLanguage}
onChange={onTranslationLanguageChange}
disabled={disabled || isSubmitting}
/>
)}
<Button
onClick={onConfirm}
disabled={disabled || isSubmitting}
@@ -754,6 +769,14 @@ export function CustomizeStep({
t={t}
/>
{onTranslationLanguageChange && (
<TranslatedLyricsOption
value={translationLanguage}
onChange={onTranslationLanguageChange}
disabled={disabled || isSubmitting}
/>
)}
{/* Create button */}
<Button
onClick={onConfirm}
@@ -132,6 +132,9 @@ export interface LyricsAnalyzerProps {
isLocalMode?: boolean
jobId?: string
hasExistingInstrumental?: boolean
/** Language the lyrics get translated into after review (job option), if any —
* the preview modal explains the translation isn't in the preview. */
translationLanguage?: string | null
}
export default function LyricsAnalyzer({
@@ -143,6 +146,7 @@ export default function LyricsAnalyzer({
isLocalMode = false,
jobId,
hasExistingInstrumental = false,
translationLanguage = null,
}: LyricsAnalyzerProps) {
const t = useTranslations('lyricsReview')
const router = useRouter()
@@ -1925,6 +1929,7 @@ export default function LyricsAnalyzer({
apiClient={apiClient}
timingOffsetMs={timingOffsetMs}
isDuet={isDuet}
translationLanguage={translationLanguage}
completesReview={hasExistingInstrumental || ((offerInlineInstrumentalChoice || autoInstrumentalConfident) && !reviewInstrumentalAnyway)}
offerInlineChoice={offerInlineInstrumentalChoice}
autoConfident={autoInstrumentalConfident}
@@ -1,6 +1,6 @@
'use client'
import { useTranslations } from 'next-intl'
import { useLocale, useTranslations } from 'next-intl'
import {
useState,
useEffect,
@@ -69,6 +69,9 @@ interface PreviewVideoSectionProps {
autoSelection?: string | null
/** Reports the video's current playback time (drives the backing-vocals playhead). */
onTimeUpdate?: (currentTime: number) => void
/** Job's translation language: translations are generated after review, so they
* can't appear in this preview — say so rather than surprise the reviewer. */
translationLanguage?: string | null
}
type PreviewState =
@@ -88,10 +91,20 @@ function PreviewVideoSection(
instrumentalOptions,
autoSelection,
onTimeUpdate,
translationLanguage = null,
}: PreviewVideoSectionProps,
ref: React.Ref<PreviewVideoHandle>
) {
const t = useTranslations('lyricsReview.previewVideo')
const uiLocale = useLocale()
const translationLanguageName = useMemo(() => {
if (!translationLanguage) return null
try {
return new Intl.DisplayNames([uiLocale], { type: 'language' }).of(translationLanguage) ?? translationLanguage
} catch {
return translationLanguage
}
}, [translationLanguage, uiLocale])
const [previewState, setPreviewState] = useState<PreviewState>({ status: 'generating' })
const [retryNonce, setRetryNonce] = useState(0)
// Whether the instrumental stem (vs the original with-vocals audio) is playing.
@@ -557,6 +570,16 @@ function PreviewVideoSection(
</div>
)}
{/* The preview is a fast sync check, not the final render — without this,
reviewers expecting a WYSIWYG preview read the black background (and missing
translation row) as a problem with their video. */}
<p className="mt-2 text-center text-xs text-muted-foreground" data-testid="preview-differs-note">
{t('previewDiffersNote')}
{translationLanguageName && (
<> {t('previewNoTranslationNote', { language: translationLanguageName })}</>
)}
</p>
{showToggle && (
// Preview audio is audition only — it changes what you hear while checking
// the preview, NOT which instrumental the final video uses. The final-output
@@ -1,11 +1,12 @@
'use client'
import { useTranslations } from 'next-intl'
import { Fragment, useState, useMemo } from 'react'
import { Fragment, useContext, useState, useMemo } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import { Play, Trash2, Type, Clock, AudioWaveform, AlertTriangle } from 'lucide-react'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { Play, Trash2, Type, Clock, AudioWaveform, AlertTriangle, Loader2 } from 'lucide-react'
import { HighlightedText } from './shared/HighlightedText'
import { TranscriptionViewProps, TranscriptionWordPosition, MissingLyricsMarker } from '@/lib/lyrics-review/types'
import { formatGapTime } from '@/lib/lyrics-review/utils/missingLyrics'
@@ -17,6 +18,7 @@ import {
import { buildSegmentDecorations } from '@/lib/lyrics-review/utils/wordDecorations'
import { TIMELINE_PAD_SECONDS } from './TimelineEditor'
import WaveformSegmentRow from './WaveformSegmentRow'
import { VocalsAudioDataLoaderContext } from './VocalsAudioDataLoader'
import SegmentDetailsModal from './modals/SegmentDetailsModal'
import SingerChip from './SingerChip'
import { resolveSegmentSinger, hasWordOverrides } from '@/lib/lyrics-review/duet'
@@ -65,6 +67,11 @@ export default function TranscriptionView({
// timeline. Keeping `advancedMode` derived avoids churning the HighlightedText wiring.
const advancedMode = viewMode === 'advanced'
const waveformsMode = viewMode === 'waveforms'
// Review opens as soon as lyrics are ready, while audio separation is often still
// running — the strips stay empty until the vocal stem lands, so the Waveforms
// toggle shows a spinner + tooltip until then.
const { status: vocalsStatus } = useContext(VocalsAudioDataLoaderContext)
const vocalsSeparating = vocalsStatus === 'separating'
// Greyed read-only neighbour words per segment, for the Waveforms inline timeline padding.
// Only computed in Waveforms mode. `data.corrected_segments` here is already offset-applied
@@ -200,10 +207,24 @@ export default function TranscriptionView({
<Clock className="h-3.5 w-3.5 mr-1.5" />
{t('advanced')}
</ToggleGroupItem>
<ToggleGroupItem value="waveforms" aria-label="waveforms view" className="h-7 px-2.5 text-[0.75rem]">
<AudioWaveform className="h-3.5 w-3.5 mr-1.5" />
{t('waveforms')}
</ToggleGroupItem>
{vocalsSeparating ? (
// Only wrap while separating: TooltipTrigger's own data-state overrides the
// toggle's data-state="on", which would hide the selected styling.
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem value="waveforms" aria-label="waveforms view" className="h-7 px-2.5 text-[0.75rem]">
<Loader2 data-testid="waveforms-separating-spinner" className="h-3.5 w-3.5 mr-1.5 animate-spin" />
{t('waveforms')}
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent>{t('waveformsSeparating')}</TooltipContent>
</Tooltip>
) : (
<ToggleGroupItem value="waveforms" aria-label="waveforms view" className="h-7 px-2.5 text-[0.75rem]">
<AudioWaveform className="h-3.5 w-3.5 mr-1.5" />
{t('waveforms')}
</ToggleGroupItem>
)}
</ToggleGroup>
</div>
@@ -7,7 +7,15 @@ import { createContext, PropsWithChildren, useEffect, useState } from 'react'
// Excludes legitimate separation-in-progress waits shorter than one 202 poll.
const SLOW_LOAD_REPORT_MS = 20_000
export const VocalsAudioDataLoaderContext = createContext<{ audioData: AudioData | null }>({ audioData: null })
/** `separating`: the vocal stem doesn't exist yet (endpoint 202) — audio
* separation is still running in the background, so the Waveforms view can
* tell the reviewer strips are on their way rather than showing empty rows. */
export type VocalsAudioStatus = 'idle' | 'loading' | 'separating' | 'ready' | 'failed'
export const VocalsAudioDataLoaderContext = createContext<{ audioData: AudioData | null; status: VocalsAudioStatus }>({
audioData: null,
status: 'idle',
})
export interface AudioDataLoaderProps extends PropsWithChildren {
audioUrl: string | null
@@ -31,9 +39,11 @@ const TRANSIENT_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000]
export const VocalsAudioDataLoader = ({ audioUrl, peaksUrl, children }: AudioDataLoaderProps) => {
const [audioData, setAudioData] = useState<AudioData | null>(null)
const [status, setStatus] = useState<VocalsAudioStatus>('idle')
useEffect(() => {
if (!audioUrl && !peaksUrl) return
setStatus('loading')
// Guard against (a) an unhandled rejection when the endpoint 404s (no vocal
// stem for this job) and (b) a stale in-flight fetch resolving after a newer
@@ -58,10 +68,12 @@ export const VocalsAudioDataLoader = ({ audioUrl, peaksUrl, children }: AudioDat
})
}
setAudioData(audioData)
setStatus('ready')
})
.catch((error) => {
if (cancelled) return
if (error instanceof AudioNotReadyError && attempt < NOT_READY_MAX_RETRIES) {
setStatus('separating')
retryTimer = setTimeout(() => load(attempt + 1, transientAttempt, usePeaks), NOT_READY_RETRY_MS)
return
}
@@ -91,6 +103,7 @@ export const VocalsAudioDataLoader = ({ audioUrl, peaksUrl, children }: AudioDat
transient_retries: transientAttempt,
})
setAudioData(null)
setStatus('failed')
})
}
@@ -100,11 +113,12 @@ export const VocalsAudioDataLoader = ({ audioUrl, peaksUrl, children }: AudioDat
cancelled = true
if (retryTimer) clearTimeout(retryTimer)
setAudioData(null)
setStatus('idle')
}
}, [audioUrl, peaksUrl])
return (
<VocalsAudioDataLoaderContext.Provider value={{ audioData }}>
<VocalsAudioDataLoaderContext.Provider value={{ audioData, status }}>
{children}
</VocalsAudioDataLoaderContext.Provider>
)
@@ -52,6 +52,31 @@ describe('PreviewVideoSection', () => {
expect(apiClient.getPreviewVideoStatus).not.toHaveBeenCalled()
})
it('explains the preview is a quick sync-check render, not the final look', async () => {
renderSection(makeApiClient())
await flush()
const note = screen.getByTestId('preview-differs-note')
expect(note).toHaveTextContent(/plain black background/)
expect(note).not.toHaveTextContent(/Translated lyrics/)
})
it('says translated lyrics are added after review when the job has a translation language', async () => {
render(
<PreviewVideoSection
apiClient={makeApiClient()}
isModalOpen={true}
updatedData={data}
translationLanguage="es"
/>
)
await flush()
expect(screen.getByTestId('preview-differs-note')).toHaveTextContent(
'Translated lyrics (Spanish) are added after review'
)
})
it('polls the status endpoint until ready when encoding runs in background', async () => {
const apiClient = makeApiClient({
generatePreviewVideo: jest.fn().mockResolvedValue({
@@ -26,7 +26,7 @@ function renderEditor(props: Partial<React.ComponentProps<typeof TimelineEditor>
}
const utils = render(
<VocalsAudioDataLoaderContext.Provider
value={{ audioData: { amplitudes: [0.1, 0.2], duration: 20 } as never }}
value={{ audioData: { amplitudes: [0.1, 0.2], duration: 20 } as never, status: 'ready' }}
>
<TimelineEditor {...merged} />
</VocalsAudioDataLoaderContext.Provider>
@@ -113,7 +113,7 @@ describe('TimelineEditor resize edge auto-extend', () => {
const onCommit = jest.fn()
const utils = render(
<VocalsAudioDataLoaderContext.Provider
value={{ audioData: { amplitudes: [0.1], duration: 60 } as never }}
value={{ audioData: { amplitudes: [0.1], duration: 60 } as never, status: 'ready' }}
>
<Host initial={words} onUpdate={(w) => (latest = w)} onCommit={onCommit} {...extra} />
</VocalsAudioDataLoaderContext.Provider>
@@ -0,0 +1,52 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import TranscriptionView from '../TranscriptionView'
import { VocalsAudioDataLoaderContext, VocalsAudioStatus } from '../VocalsAudioDataLoader'
import type { CorrectionData } from '@/lib/lyrics-review/types'
const data = {
corrected_segments: [
{ id: 's1', text: 'intro', start_time: 0, end_time: 5, words: [{ id: 'w1', text: 'intro', start_time: 0, end_time: 5 }] },
],
original_segments: [],
reference_lyrics: {},
anchor_sequences: [],
gap_sequences: [],
corrections: [],
} as unknown as CorrectionData
const renderWithStatus = (status: VocalsAudioStatus, viewMode: 'simple' | 'waveforms' = 'simple') =>
render(
<VocalsAudioDataLoaderContext.Provider value={{ audioData: null, status }}>
<TranscriptionView
data={data}
onElementClick={jest.fn()}
flashingType={null}
highlightInfo={null}
mode="edit"
viewMode={viewMode}
/>
</VocalsAudioDataLoaderContext.Provider>
)
describe('TranscriptionView Waveforms toggle while separation runs', () => {
it('shows a spinner with an explanatory tooltip while the vocal stem is being separated', async () => {
renderWithStatus('separating')
expect(screen.getByTestId('waveforms-separating-spinner')).toBeInTheDocument()
await userEvent.hover(screen.getByRole('radio', { name: 'waveforms view' }))
expect(
(await screen.findAllByText(/Separating vocals from the music/)).length
).toBeGreaterThan(0)
})
it.each<VocalsAudioStatus>(['loading', 'ready', 'failed', 'idle'])('shows the normal icon when status is %s', (status) => {
renderWithStatus(status)
expect(screen.queryByTestId('waveforms-separating-spinner')).not.toBeInTheDocument()
})
it('keeps the selected styling on the Waveforms toggle once the waveforms load', () => {
renderWithStatus('ready', 'waveforms')
expect(screen.getByRole('radio', { name: 'waveforms view' })).toHaveAttribute('data-state', 'on')
})
})
@@ -17,8 +17,13 @@ const AUDIO_DATA: AudioData = {
}
const Probe = () => {
const { audioData } = useContext(VocalsAudioDataLoaderContext)
return <div data-testid="probe">{audioData ? 'loaded' : 'empty'}</div>
const { audioData, status } = useContext(VocalsAudioDataLoaderContext)
return (
<>
<div data-testid="probe">{audioData ? 'loaded' : 'empty'}</div>
<div data-testid="status">{status}</div>
</>
)
}
// Flush the pending promise chain inside the loader's .then/.catch handlers.
@@ -63,6 +68,7 @@ describe('VocalsAudioDataLoader', () => {
)
await flushPromises()
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
expect(screen.getByTestId('status')).toHaveTextContent('separating')
await act(async () => {
jest.advanceTimersByTime(15_000)
@@ -74,6 +80,7 @@ describe('VocalsAudioDataLoader', () => {
})
expect(fetchAudioData).toHaveBeenCalledTimes(3)
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
expect(screen.getByTestId('status')).toHaveTextContent('ready')
})
it('does not retry on a terminal error (e.g. 404: job has no vocal stem)', async () => {
@@ -92,6 +99,7 @@ describe('VocalsAudioDataLoader', () => {
})
expect(fetchAudioData).toHaveBeenCalledTimes(1)
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
expect(screen.getByTestId('status')).toHaveTextContent('failed')
expect(consoleError).toHaveBeenCalled()
consoleError.mockRestore()
@@ -39,6 +39,8 @@ interface ReviewChangesModalProps {
apiClient?: ApiClient | null
timingOffsetMs?: number
isDuet?: boolean
/** Job's post-review translation language, if any (shown as a preview caveat). */
translationLanguage?: string | null
/** When true (e.g. tenant / uploaded-instrumental jobs) approving here completes the
* track directly — there is no instrumental-review step — so the CTA reflects that. */
completesReview?: boolean
@@ -70,6 +72,7 @@ export default function ReviewChangesModal({
apiClient = null,
timingOffsetMs = 0,
isDuet,
translationLanguage = null,
completesReview = false,
offerInlineChoice = false,
autoConfident = false,
@@ -155,6 +158,7 @@ export default function ReviewChangesModal({
updatedData={data}
timingOffsetMs={timingOffsetMs}
isDuet={isDuet}
translationLanguage={translationLanguage}
instrumentalOptions={instrumentalOptions}
autoSelection={selected}
onTimeUpdate={setPreviewTime}
+57 -7
View File
@@ -20,6 +20,50 @@
const TESTMAIL_API_KEY = process.env.TESTMAIL_API_KEY;
const TESTMAIL_NAMESPACE = process.env.TESTMAIL_NAMESPACE;
const TESTMAIL_API_URL = 'https://api.testmail.app/api/json';
const ADMIN_API_URL = process.env.E2E_API_URL || 'https://api.nomadkaraoke.com';
/**
* When an expected email never reaches testmail.app, ask the backend whether it
* ever sent one. Turns an opaque "no email" timeout into either "backend never
* sent it" (e.g. Postmark rejected the send — check backend logs) or "sent but
* not delivered" (Postmark → testmail.app delivery problem).
*
* Uses the admin email-history endpoint, which merges Postmark's outbound
* records with our email_log; failed sends appear in neither. Best-effort:
* returns null if no admin token is set or the lookup itself fails.
*/
export async function diagnoseMissingEmail(emailAddress: string): Promise<string | null> {
const adminToken = process.env.E2E_ADMIN_TOKEN;
if (!adminToken) return null;
try {
const response = await fetch(
`${ADMIN_API_URL}/api/admin/users/${encodeURIComponent(emailAddress)}/emails`,
{ headers: { 'X-Admin-Token': adminToken }, signal: AbortSignal.timeout(15000) },
);
if (!response.ok) return `email-history lookup failed (HTTP ${response.status})`;
const data: { count?: number; emails?: Array<{ subject?: string; status?: string | null }> } =
await response.json();
const emails = data.emails || [];
if (emails.length === 0) {
return (
'backend has NO record of sending any email to this address — the send failed server-side ' +
'(check karaoke-backend logs for "Postmark returned status" / "Failed to send")'
);
}
const summary = emails
.slice(0, 3)
.map((e) => `"${e.subject ?? '?'}"${e.status ? ` (${e.status})` : ''}`)
.join(', ');
return (
`backend sent ${emails.length} email(s) to this address [${summary}] but none reached ` +
'testmail.app — likely a Postmark → testmail.app delivery or testmail.app API problem'
);
} catch (error) {
return `email-history lookup failed: ${error instanceof Error ? error.message : String(error)}`;
}
}
/**
* Inbox object compatible with existing test code
@@ -147,6 +191,7 @@ export async function createEmailHelper(): Promise<EmailHelper> {
// For longer timeouts, we poll multiple times
const pollInterval = Math.min(timeout, 30000); // 30s max per poll
const startTime = Date.now();
let lastPollError: string | null = null;
while (Date.now() - startTime < timeout) {
const remainingTime = timeout - (Date.now() - startTime);
@@ -196,18 +241,23 @@ export async function createEmailHelper(): Promise<EmailHelper> {
};
}
} catch (error) {
// If it's a timeout or network error, continue polling
if (Date.now() - startTime < timeout) {
console.log(`Polling for email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed): ${error instanceof Error ? error.message : String(error)}`);
continue;
}
throw error;
// A timeout or network error just means "no email yet" — keep polling
// until the overall timeout, then report the diagnosis below rather than
// the last (misleading) AbortError from a livequery that simply waited.
lastPollError = error instanceof Error ? error.message : String(error);
console.log(`Polling for email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed): ${lastPollError}`);
} finally {
clearTimeout(abortTimer);
}
}
throw new Error(`Timed out waiting for email after ${timeout}ms`);
const emailAddress = `${TESTMAIL_NAMESPACE}.${inboxId}@inbox.testmail.app`;
const diagnosis = await diagnoseMissingEmail(emailAddress);
throw new Error(
`Timed out waiting for email to ${emailAddress} after ${timeout}ms` +
(diagnosis ? ` — ${diagnosis}` : '') +
(lastPollError ? ` (last testmail.app poll error: ${lastPollError})` : ''),
);
},
/**
@@ -0,0 +1,38 @@
import { test, expect } from '@playwright/test';
import { URLS } from '../helpers/constants';
/**
* Production E2E: translated-lyrics preview.
*
* The "Add translated lyrics" option at job creation shows a real rendered karaoke
* frame (default theme, sample lyrics + translation beneath each line). This checks
* the public preview endpoint serves a JPEG for LTR, RTL and CJK target languages and
* rejects unsupported ones.
*
* Run:
* npx playwright test e2e/production/translated-lyrics.spec.ts --config=playwright.production.config.ts
*/
const API_URL = URLS.production.api;
// API-only: the prod config's always-on trace hangs on the large image responses
test.use({ trace: 'off', video: 'off', screenshot: 'off' });
test.describe('Translated lyrics preview', () => {
for (const language of ['es', 'he', 'ja']) {
test(`renders a preview frame for ${language}`, async ({ request }) => {
test.setTimeout(60_000);
const res = await request.get(`${API_URL}/api/themes/translation-preview?language=${language}`);
expect(res.status()).toBe(200);
const { image } = await res.json();
expect(image).toMatch(/^data:image\/jpeg;base64,/);
// A real 1280x720 frame, not an empty image
expect(Buffer.from(image.split(',')[1], 'base64').length).toBeGreaterThan(20_000);
});
}
test('rejects an unsupported language', async ({ request }) => {
const res = await request.get(`${API_URL}/api/themes/translation-preview?language=xx`);
expect(res.status()).toBe(400);
});
});
+63
View File
@@ -896,3 +896,66 @@ describe("extractErrorMessage", () => {
expect(result).toBe('{"some":"object"}')
})
})
describe("translated lyrics — job creation + preview", () => {
beforeEach(() => {
jest.clearAllMocks()
})
function mockOk(json: unknown = { status: "success", job_id: "j1", message: "ok" }) {
;(global.fetch as jest.Mock).mockResolvedValueOnce({ ok: true, json: async () => json })
}
const lastBody = () => {
const calls = (global.fetch as jest.Mock).mock.calls
return calls[calls.length - 1][1].body
}
it("uploadJob sends translation_language as a form field only when set", async () => {
const file = new File(["x"], "a.mp3", { type: "audio/mpeg" })
mockOk()
await api.uploadJob(file, "A", "T", { translation_language: "es" })
expect((lastBody() as FormData).get("translation_language")).toBe("es")
mockOk()
await api.uploadJob(file, "A", "T", {})
expect((lastBody() as FormData).get("translation_language")).toBeNull()
})
it("createJobFromUrl sends translation_language in the JSON body only when set", async () => {
mockOk()
await api.createJobFromUrl("https://youtube.com/watch?v=1", "A", "T", { translation_language: "ja" })
expect(JSON.parse(lastBody()).translation_language).toBe("ja")
mockOk()
await api.createJobFromUrl("https://youtube.com/watch?v=1", "A", "T", {})
expect(JSON.parse(lastBody())).not.toHaveProperty("translation_language")
})
it("createJobWithUploadUrls sends translation_language in the JSON body", async () => {
mockOk({ status: "success", job_id: "j1", message: "ok", upload_urls: [], server_version: "1" })
await api.createJobWithUploadUrls("A", "T", [], { translation_language: "fr" })
expect(JSON.parse(lastBody()).translation_language).toBe("fr")
})
it("createJobFromSearch sends translation_language in the JSON body", async () => {
mockOk()
await api.createJobFromSearch({
search_session_id: "s", selection_index: 0, artist: "A", title: "T", translation_language: "de",
})
expect(JSON.parse(lastBody()).translation_language).toBe("de")
})
it("getTranslationPreview requests the preview for the language and returns the image", async () => {
mockOk({ image: "data:image/jpeg;base64,abc" })
const result = await api.getTranslationPreview("pt")
expect(result).toEqual({ image: "data:image/jpeg;base64,abc" })
expect((global.fetch as jest.Mock).mock.calls[0][0]).toContain("/api/themes/translation-preview?language=pt")
})
it("getTranslationPreview throws ApiError on an unsupported language", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false, status: 400, json: async () => ({ detail: "Unsupported language" }),
})
await expect(api.getTranslationPreview("xx")).rejects.toThrow(ApiError)
})
})
+31
View File
@@ -148,6 +148,8 @@ export interface Job {
// Theme and branding
theme_id?: string;
brand_prefix?: string;
// Translated lyrics: language code shown beneath the synced lyrics (null/absent = off)
translation_language?: string | null;
// Customer order fields
customer_email?: string;
made_for_you?: boolean;
@@ -958,6 +960,8 @@ export const api = {
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}
): Promise<UploadJobResponse> {
const formData = new FormData();
@@ -998,6 +1002,9 @@ export const api = {
if (options?.backing_preference) {
formData.append('backing_preference', options.backing_preference);
}
if (options?.translation_language) {
formData.append('translation_language', options.translation_language);
}
const response = await apiFetch(`${API_BASE_URL}/api/jobs/upload`, {
method: 'POST',
@@ -1025,6 +1032,8 @@ export const api = {
upload_mode?: 'signed_put' | 'resumable';
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}
): Promise<CreateJobWithUploadUrlsResponse> {
const body: Record<string, any> = { artist, title, files };
@@ -1035,6 +1044,7 @@ export const api = {
if (options?.upload_mode) body.upload_mode = options.upload_mode;
if (options?.review_mode) body.review_mode = options.review_mode;
if (options?.backing_preference) body.backing_preference = options.backing_preference;
if (options?.translation_language) body.translation_language = options.translation_language;
const response = await apiFetch(`${API_BASE_URL}/api/jobs/create-with-upload-urls`, {
method: 'POST',
@@ -1135,6 +1145,8 @@ export const api = {
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
instrumentalFile?: File | null;
},
onProgress?: (progress: UploadProgress) => void,
@@ -1200,6 +1212,8 @@ export const api = {
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}
): Promise<{ status: string; job_id: string; message: string }> {
const body: Record<string, any> = { url };
@@ -1216,6 +1230,7 @@ export const api = {
if (options?.requires_audio_edit) body.requires_audio_edit = options.requires_audio_edit;
if (options?.review_mode) body.review_mode = options.review_mode;
if (options?.backing_preference) body.backing_preference = options.backing_preference;
if (options?.translation_language) body.translation_language = options.translation_language;
const response = await apiFetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
method: 'POST',
@@ -1640,6 +1655,8 @@ export const api = {
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}): Promise<{ status: string; job_id: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/create-from-search`, {
method: 'POST',
@@ -1917,6 +1934,18 @@ export const api = {
return data.description;
},
/**
* Get a rendered sample frame of the default theme's karaoke video showing
* the translated-lyrics row in the given language. Returns a data: URL.
*/
async getTranslationPreview(language: string): Promise<{ image: string }> {
const response = await apiFetch(
`${API_BASE_URL}/api/themes/translation-preview?language=${encodeURIComponent(language)}`,
{ headers: getAuthHeaders() }
);
return handleResponse<{ image: string }>(response);
},
// ==========================================================================
// Auth API endpoints (Magic Link)
// ==========================================================================
@@ -3965,6 +3994,8 @@ export interface JobUpdateRequest {
non_interactive?: boolean;
prep_only?: boolean;
is_private?: boolean;
/** Translated lyrics language code; "" turns translated lyrics off. */
translation_language?: string;
}
export interface JobUpdateResponse {
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "سيُستخدم {name} ({size} ميغابايت) كمقطع موسيقي",
"ownInstrumentalTitle": "مقطعك الموسيقي (اختياري)",
"submitTrack": "إرسال المسار",
"ownInstrumentalRemove": "إزالة"
"ownInstrumentalRemove": "إزالة",
"translatedLyricsHint": "بعد مراجعة كلمات الأغنية، يتولى الذكاء الاصطناعي ترجمة كل سطر إلى {language} وعرضه بخط أصغر أسفل كلمات الأغنية في الفيديو. لا يمكن تعديل الترجمات.",
"translatedLyricsLanguageLabel": "ترجمة كلمات الأغنية إلى",
"translatedLyricsPreviewAlt": "إطار تجريبي لفيديو كاريوكي مع كلمات مترجمة إلى {language}",
"translatedLyricsPreviewError": "تعذر تحميل المعاينة.",
"translatedLyricsPreviewLoading": "جارٍ إنشاء المعاينة...",
"translatedLyricsToggle": "إضافة كلمات مترجمة",
"translatedLyricsToggleHint": "عرض ترجمة بالذكاء الاصطناعي لكل سطر بخط أصغر أسفل كلمات الأغنية. ميزة رائعة لتعلم اللغات.",
"translatedLyricsPreviewRetry": "حاول مرة أخرى"
},
"jobStatus": {
"settingUp": "جاري الإعداد",
@@ -986,7 +994,8 @@
"editSegment": "تعديل المقطع {index}",
"untimedSegment": "لا توجد توقيتات للكلمات — انقر للتعديل",
"waveforms": "الأشكال الموجية",
"missingLyricsMarker": "كلمات مفقودة محتملة {start}–{end}"
"missingLyricsMarker": "كلمات مفقودة محتملة {start}–{end}",
"waveformsSeparating": "جارٍ فصل صوت الغناء عن الموسيقى. ستظهر الموجات الصوتية تلقائيًا خلال دقيقة أو دقيقتين."
},
"editActionBar": {
"reset": "إعادة تعيين",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "الأصوات الخلفية التي تزيلها النسخة الموسيقية الصافية — انقر لسماع ما ستستغني عنه.",
"playingWhileEncoding": "جاري التشغيل: {stem}",
"stopAudio": "إيقاف الصوت",
"loadingAudio": "جاري التحميل: {stem}…"
"loadingAudio": "جاري التحميل: {stem}…",
"previewDiffersNote": "هذه المعاينة هي تصيير سريع للتحقق من مزامنة الكلمات. وتستخدم خلفية سوداء بسيطة لتسريع العملية، لذا لن تبدو تمامًا كالفيديو النهائي الذي سيعتمد خلفيتك وتصميمك بالكامل.",
"previewNoTranslationNote": "تُضاف الكلمات المترجمة ({language}) بعد المراجعة، لذا ستظهر في الفيديو النهائي وليس في هذه المعاينة."
},
"gapNavigator": {
"previousGap": "الفجوة السابقة (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Fent servir {name} ({size} MB) com a instrumental",
"ownInstrumentalTitle": "El teu propi instrumental (opcional)",
"submitTrack": "Envia la pista",
"ownInstrumentalRemove": "Elimina"
"ownInstrumentalRemove": "Elimina",
"translatedLyricsHint": "Un cop revisada la lletra, la IA tradueix cada línia a {language} i la mostra en un text més petit a sota de la lletra al teu vídeo. Les traduccions no es poden editar.",
"translatedLyricsLanguageLabel": "Tradueix la lletra a",
"translatedLyricsPreviewAlt": "Fotograma d'exemple de vídeo de karaoke amb la lletra traduïda a {language}",
"translatedLyricsPreviewError": "No s'ha pogut carregar la previsualització.",
"translatedLyricsPreviewLoading": "Renderitzant la previsualització...",
"translatedLyricsToggle": "Afegeix la lletra traduïda",
"translatedLyricsToggleHint": "Mostra una traducció amb IA de cada línia en un text més petit a sota de la lletra. Ideal per aprendre un idioma.",
"translatedLyricsPreviewRetry": "Torna-ho a provar"
},
"jobStatus": {
"settingUp": "Configurant",
@@ -986,7 +994,8 @@
"editSegment": "Edita el segment {index}",
"untimedSegment": "Sense sincronització de paraules — fes clic per editar",
"waveforms": "Formes d'ona",
"missingLyricsMarker": "Possible falta de lletra {start}–{end}"
"missingLyricsMarker": "Possible falta de lletra {start}–{end}",
"waveformsSeparating": "Separant la veu de la música. Les formes d'ona apareixeran automàticament d'aquí a un minut o dos."
},
"editActionBar": {
"reset": "Restableix",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Cors que l'instrumental net elimina — fes clic per escoltar què deixaries fora.",
"playingWhileEncoding": "Reproduint: {stem}",
"stopAudio": "Atura l'àudio",
"loadingAudio": "S'està carregant: {stem}…"
"loadingAudio": "S'està carregant: {stem}…",
"previewDiffersNote": "Aquesta previsualització és una renderització ràpida per comprovar la sincronització de la lletra. Utilitza un fons negre llis per anar més ràpid, així que no es veurà exactament com el teu vídeo final, que utilitza el teu fons i estil complets.",
"previewNoTranslationNote": "La lletra traduïda ({language}) s'afegeix després de la revisió, així que apareixerà al vídeo final, però no en aquesta previsualització."
},
"gapNavigator": {
"previousGap": "Buit anterior (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Jako instrumentální stopa se použije {name} ({size} MB)",
"ownInstrumentalTitle": "Vlastní instrumentální stopa (volitelné)",
"submitTrack": "Odeslat stopu",
"ownInstrumentalRemove": "Odstranit"
"ownInstrumentalRemove": "Odstranit",
"translatedLyricsHint": "Po kontrole textu AI přeloží každý řádek do {language} a zobrazí ho menším písmem pod textem ve tvém videu. Překlady nelze upravovat.",
"translatedLyricsLanguageLabel": "Přeložit text písně do",
"translatedLyricsPreviewAlt": "Ukázkový snímek karaoke videa s textem přeloženým do {language}",
"translatedLyricsPreviewError": "Nepodařilo se načíst náhled.",
"translatedLyricsPreviewLoading": "Generování náhledu...",
"translatedLyricsToggle": "Přidat přeložený text",
"translatedLyricsToggleHint": "Zobrazí AI překlad každého řádku menším písmem pod textem písně. Skvělé pro učení cizích jazyků.",
"translatedLyricsPreviewRetry": "Zkusit znovu"
},
"jobStatus": {
"settingUp": "Nastavování",
@@ -986,7 +994,8 @@
"editSegment": "Upravit segment {index}",
"untimedSegment": "Bez časování slov — klikni pro úpravu",
"waveforms": "Zvukové křivky",
"missingLyricsMarker": "Možný chybějící text {start}–{end}"
"missingLyricsMarker": "Možný chybějící text {start}–{end}",
"waveformsSeparating": "Oddělujeme vokály od hudby. Zvukové křivky se automaticky zobrazí za minutu nebo dvě."
},
"editActionBar": {
"reset": "Resetovat",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Doprovodné vokály, které čistá instrumentálka odstraní — klikni a poslechni si, o co přijdeš.",
"playingWhileEncoding": "Přehrává se: {stem}",
"stopAudio": "Zastavit zvuk",
"loadingAudio": "Načítání: {stem}…"
"loadingAudio": "Načítání: {stem}…",
"previewDiffersNote": "Tento náhled je rychlý render pro kontrolu synchronizace textu. Kvůli rychlosti využívá jen jednoduché černé pozadí, takže nebude vypadat přesně jako finální video, které použije tvé plné pozadí i styl.",
"previewNoTranslationNote": "Přeložený text ({language}) se přidává až po kontrole, takže se objeví ve finálním videu, ale ne v tomto náhledu."
},
"gapNavigator": {
"previousGap": "Předchozí mezera (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Bruger {name} ({size} MB) som instrumentalnummer",
"ownInstrumentalTitle": "Dit eget instrumentalnummer (valgfrit)",
"submitTrack": "Indsend nummer",
"ownInstrumentalRemove": "Fjern"
"ownInstrumentalRemove": "Fjern",
"translatedLyricsHint": "Når sangteksten er blevet gennemgået, oversætter AI hver linje til {language} og viser den med mindre skrift under sangteksten i din video. Oversættelser kan ikke redigeres.",
"translatedLyricsLanguageLabel": "Oversæt sangtekst til",
"translatedLyricsPreviewAlt": "Eksempel på et karaokevideobillede med sangtekst oversat til {language}",
"translatedLyricsPreviewError": "Kunne ikke indlæse forhåndsvisningen.",
"translatedLyricsPreviewLoading": "Genererer forhåndsvisning...",
"translatedLyricsToggle": "Tilføj oversat sangtekst",
"translatedLyricsToggleHint": "Vis en AI-oversættelse af hver linje med mindre skrift under sangteksten. Godt til at lære et sprog.",
"translatedLyricsPreviewRetry": "Prøv igen"
},
"jobStatus": {
"settingUp": "Sætter op",
@@ -986,7 +994,8 @@
"editSegment": "Rediger segment {index}",
"untimedSegment": "Ingen tidsangivelser for ord — klik for at redigere",
"waveforms": "Bølgeformer",
"missingLyricsMarker": "Muligvis manglende sangtekst {start}–{end}"
"missingLyricsMarker": "Muligvis manglende sangtekst {start}–{end}",
"waveformsSeparating": "Adskiller vokalen fra musikken. Bølgeformerne vises automatisk om et minut eller to."
},
"editActionBar": {
"reset": "Nulstil",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Baggrundsvokaler, som den rene instrumental fjerner — klik for at høre, hvad du udelader.",
"playingWhileEncoding": "Afspiller: {stem}",
"stopAudio": "Stop lyd",
"loadingAudio": "Indlæser: {stem}…"
"loadingAudio": "Indlæser: {stem}…",
"previewDiffersNote": "Denne forhåndsvisning er en hurtig rendering til at tjekke tekstsynkroniseringen. Den bruger en helt sort baggrund af hensyn til hastigheden, så den ser ikke helt ud som din endelige video, der bruger din fulde baggrund og stil.",
"previewNoTranslationNote": "Oversatte sangtekster ({language}) tilføjes efter gennemgang, så de vises i den endelige video, men ikke i denne forhåndsvisning."
},
"gapNavigator": {
"previousGap": "Forrige hul (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "{name} ({size} MB) wird als Instrumental verwendet",
"ownInstrumentalTitle": "Dein eigenes Instrumental (optional)",
"submitTrack": "Track einreichen",
"ownInstrumentalRemove": "Entfernen"
"ownInstrumentalRemove": "Entfernen",
"translatedLyricsHint": "Nach der Textüberprüfung übersetzt die KI jede Zeile in {language} und zeigt sie in kleinerer Schrift unter dem Text in deinem Video an. Übersetzungen können nicht bearbeitet werden.",
"translatedLyricsLanguageLabel": "Text übersetzen in",
"translatedLyricsPreviewAlt": "Beispiel-Frame eines Karaoke-Videos mit in {language} übersetztem Text",
"translatedLyricsPreviewError": "Die Vorschau konnte nicht geladen werden.",
"translatedLyricsPreviewLoading": "Vorschau wird gerendert...",
"translatedLyricsToggle": "Übersetzten Text hinzufügen",
"translatedLyricsToggleHint": "Zeigt eine KI-Übersetzung jeder Zeile in kleinerer Schrift unter dem Text an. Ideal zum Sprachenlernen.",
"translatedLyricsPreviewRetry": "Erneut versuchen"
},
"jobStatus": {
"settingUp": "Richte ein",
@@ -986,7 +994,8 @@
"editSegment": "Bearbeite Segment {index}",
"untimedSegment": "Keine Wort-Timings — klicke zum Bearbeiten",
"waveforms": "Wellenformen",
"missingLyricsMarker": "Möglicherweise fehlender Text {start}–{end}"
"missingLyricsMarker": "Möglicherweise fehlender Text {start}–{end}",
"waveformsSeparating": "Der Gesang wird von der Musik getrennt. Die Wellenformen erscheinen automatisch in ein bis zwei Minuten."
},
"editActionBar": {
"reset": "Zurücksetzen",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Hintergrundgesang, den das reine Instrumental entfernt — klicke, um zu hören, was du weglassen würdest.",
"playingWhileEncoding": "Wiedergabe: {stem}",
"stopAudio": "Audio stoppen",
"loadingAudio": "Lade: {stem}…"
"loadingAudio": "Lade: {stem}…",
"previewDiffersNote": "Diese Vorschau ist ein schneller Renderdurchlauf, um deine Textsynchronisation zu überprüfen. Aus Geschwindigkeitsgründen wird ein einfacher schwarzer Hintergrund verwendet, daher sieht sie nicht genau wie dein finales Video aus, das deinen vollständigen Hintergrund und Stil nutzt.",
"previewNoTranslationNote": "Der übersetzte Text ({language}) wird nach der Überprüfung hinzugefügt, daher erscheint er im finalen Video, aber nicht in dieser Vorschau."
},
"gapNavigator": {
"previousGap": "Vorherige Lücke (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Χρήση του {name} ({size} MB) ως instrumental",
"ownInstrumentalTitle": "Το δικό σου instrumental (προαιρετικό)",
"submitTrack": "Υποβολή κομματιού",
"ownInstrumentalRemove": "Αφαίρεση"
"ownInstrumentalRemove": "Αφαίρεση",
"translatedLyricsHint": "Αφού ελεγχθούν οι στίχοι, το AI μεταφράζει κάθε γραμμή στα {language} και την εμφανίζει με μικρότερα γράμματα κάτω από τους στίχους στο βίντεό σου. Δεν είναι δυνατή η επεξεργασία των μεταφράσεων.",
"translatedLyricsLanguageLabel": "Μετάφραση στίχων στα",
"translatedLyricsPreviewAlt": "Παράδειγμα καρέ βίντεο καραόκε με στίχους μεταφρασμένους στα {language}",
"translatedLyricsPreviewError": "Δεν ήταν δυνατή η φόρτωση της προεπισκόπησης.",
"translatedLyricsPreviewLoading": "Απόδοση προεπισκόπησης...",
"translatedLyricsToggle": "Προσθήκη μεταφρασμένων στίχων",
"translatedLyricsToggleHint": "Εμφάνισε μια μετάφραση μέσω AI για κάθε γραμμή με μικρότερα γράμματα κάτω από τους στίχους. Ιδανικό για την εκμάθηση μιας γλώσσας.",
"translatedLyricsPreviewRetry": "Δοκίμασε ξανά"
},
"jobStatus": {
"settingUp": "Ρύθμιση",
@@ -986,7 +994,8 @@
"editSegment": "Επεξεργασία τμήματος {index}",
"untimedSegment": "Χωρίς χρονισμό λέξεων — κάνε κλικ για επεξεργασία",
"waveforms": "Κυματομορφές",
"missingLyricsMarker": "Πιθανώς λείπουν στίχοι {start}–{end}"
"missingLyricsMarker": "Πιθανώς λείπουν στίχοι {start}–{end}",
"waveformsSeparating": "Γίνεται διαχωρισμός των φωνητικών από τη μουσική. Οι κυματομορφές θα εμφανιστούν αυτόματα σε ένα ή δύο λεπτά."
},
"editActionBar": {
"reset": "Επαναφορά",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Δεύτερα φωνητικά που αφαιρεί το καθαρό ορχηστρικό — κάνε κλικ για να ακούσεις τι αφήνεις απ' έξω.",
"playingWhileEncoding": "Αναπαραγωγή: {stem}",
"stopAudio": "Διακοπή ήχου",
"loadingAudio": "Φόρτωση: {stem}…"
"loadingAudio": "Φόρτωση: {stem}…",
"previewDiffersNote": "Αυτή η προεπισκόπηση είναι μια γρήγορη απόδοση για να ελέγξεις τον συγχρονισμό των στίχων σου. Χρησιμοποιεί ένα απλό μαύρο φόντο για μεγαλύτερη ταχύτητα, οπότε δεν θα φαίνεται ακριβώς όπως το τελικό σου βίντεο, το οποίο χρησιμοποιεί το πλήρες φόντο και το στυλ σου.",
"previewNoTranslationNote": "Οι μεταφρασμένοι στίχοι ({language}) προστίθενται μετά τον έλεγχο, οπότε εμφανίζονται στο τελικό βίντεο, αλλά όχι σε αυτήν την προεπισκόπηση."
},
"gapNavigator": {
"previousGap": "Προηγούμενο κενό (P)",
+12 -1
View File
@@ -579,6 +579,14 @@
"backingPrefAuto": "Keep where possible",
"backingPrefClean": "Remove (clean)",
"backingPrefReview": "Let me choose",
"translatedLyricsToggle": "Add translated lyrics",
"translatedLyricsToggleHint": "Show an AI translation of each line in smaller text beneath the lyrics. Great for learning a language.",
"translatedLyricsLanguageLabel": "Translate lyrics into",
"translatedLyricsHint": "After the lyrics are reviewed, AI translates each line into {language} and shows it in smaller text beneath the lyrics in your video. Translations can't be edited.",
"translatedLyricsPreviewAlt": "Example karaoke video frame with lyrics translated into {language}",
"translatedLyricsPreviewLoading": "Rendering preview...",
"translatedLyricsPreviewError": "Couldn't load the preview.",
"translatedLyricsPreviewRetry": "Try again",
"missingAudioSource": "Missing audio source. Please go back and try again.",
"searchExpired": "Your search results expired. Please search again — your song info is still saved.",
"failedToStartProcessing": "Failed to start processing. Please try again.",
@@ -998,7 +1006,8 @@
"longWordWarning": "This word lasts {seconds}s — unusually long. Play the line and check its end time hasn't run into the instrumental.",
"longGapWarning": "{seconds}s gap before the next word — often a stray early word (e.g. a phantom \"and\"). Click to play from here.",
"playFromGap": "Play from the end of this gap",
"missingLyricsMarker": "Possible missing lyrics {start}–{end}"
"missingLyricsMarker": "Possible missing lyrics {start}–{end}",
"waveformsSeparating": "Separating vocals from the music. Waveforms will appear automatically in a minute or two."
},
"editActionBar": {
"reset": "Reset",
@@ -1082,6 +1091,8 @@
"timedOut": "The preview video is taking longer than expected. Please try again.",
"retry": "Retry",
"unsupportedBrowser": "Your browser does not support the video tag.",
"previewDiffersNote": "This preview is a quick render to check your lyrics sync. It uses a plain black background for speed, so it won't look exactly like your final video, which uses your full background and style.",
"previewNoTranslationNote": "Translated lyrics ({language}) are added after review, so they appear in the final video but not in this preview.",
"audioLabel": "Preview audio:",
"audioOriginal": "Original (with vocals)",
"audioInstrumental": "Instrumental",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Usando {name} ({size} MB) como instrumental",
"ownInstrumentalTitle": "Tu propio instrumental (opcional)",
"submitTrack": "Enviar pista",
"ownInstrumentalRemove": "Quitar"
"ownInstrumentalRemove": "Quitar",
"translatedLyricsHint": "Después de la revisión de letras, la IA traduce cada línea al {language} y la muestra en un texto más pequeño debajo de las letras en tu video. Las traducciones no se pueden editar.",
"translatedLyricsLanguageLabel": "Traducir letras al",
"translatedLyricsPreviewAlt": "Fotograma de ejemplo de un video de karaoke con letras traducidas al {language}",
"translatedLyricsPreviewError": "No se pudo cargar la vista previa.",
"translatedLyricsPreviewLoading": "Renderizando vista previa...",
"translatedLyricsToggle": "Agregar letras traducidas",
"translatedLyricsToggleHint": "Muestra una traducción por IA de cada línea en un texto más pequeño debajo de las letras. Ideal para aprender un idioma.",
"translatedLyricsPreviewRetry": "Intentar de nuevo"
},
"jobStatus": {
"settingUp": "Configurando",
@@ -986,7 +994,8 @@
"editSegment": "Editar segmento {index}",
"untimedSegment": "Sin tiempos por palabra — haz clic para editar",
"waveforms": "Formas de onda",
"missingLyricsMarker": "Posible letra faltante {start}–{end}"
"missingLyricsMarker": "Posible letra faltante {start}–{end}",
"waveformsSeparating": "Separando la voz de la música. Las formas de onda aparecerán automáticamente en uno o dos minutos."
},
"editActionBar": {
"reset": "Restablecer",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Coros que elimina el instrumental limpio — haz clic para escuchar lo que estarías dejando fuera.",
"playingWhileEncoding": "Reproduciendo: {stem}",
"stopAudio": "Detener audio",
"loadingAudio": "Cargando: {stem}…"
"loadingAudio": "Cargando: {stem}…",
"previewDiffersNote": "Esta vista previa es un renderizado rápido para revisar tu sincronización de letras. Usa un fondo negro liso para mayor velocidad, por lo que no se verá exactamente igual que tu video final, que usa tu fondo y estilo completos.",
"previewNoTranslationNote": "Las letras traducidas ({language}) se agregan después de la revisión, por lo que aparecerán en el video final, pero no en esta vista previa."
},
"gapNavigator": {
"previousGap": "Hueco anterior (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Käytetään tiedostoa {name} ({size} MB) taustaraitana",
"ownInstrumentalTitle": "Oma taustaraita (valinnainen)",
"submitTrack": "Lähetä raita",
"ownInstrumentalRemove": "Poista"
"ownInstrumentalRemove": "Poista",
"translatedLyricsHint": "Kun sanoitukset on tarkistettu, tekoäly kääntää jokaisen rivin kielelle {language} ja näyttää sen pienemmällä tekstillä sanoitusten alla videossasi. Käännöksiä ei voi muokata.",
"translatedLyricsLanguageLabel": "Käännä sanoitukset kielelle",
"translatedLyricsPreviewAlt": "Esimerkkikuva karaokevideosta, jonka sanoitukset on käännetty kielelle {language}",
"translatedLyricsPreviewError": "Esikatselua ei voitu ladata.",
"translatedLyricsPreviewLoading": "Luodaan esikatselua...",
"translatedLyricsToggle": "Lisää käännetyt sanoitukset",
"translatedLyricsToggleHint": "Näytä jokaisen rivin tekoälykäännös pienemmällä tekstillä sanoitusten alla. Erinomainen kielen opetteluun.",
"translatedLyricsPreviewRetry": "Yritä uudelleen"
},
"jobStatus": {
"settingUp": "Asetetaan",
@@ -986,7 +994,8 @@
"editSegment": "Muokkaa segmenttiä {index}",
"untimedSegment": "Ei sana-ajoituksia — muokkaa klikkaamalla",
"waveforms": "Aaltomuodot",
"missingLyricsMarker": "Mahdollisesti puuttuvia sanoituksia {start}–{end}"
"missingLyricsMarker": "Mahdollisesti puuttuvia sanoituksia {start}–{end}",
"waveformsSeparating": "Erotetaan laulu musiikista. Aaltomuodot ilmestyvät automaattisesti minuutin tai parin kuluessa."
},
"editActionBar": {
"reset": "Nollaa",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Taustalaulut, jotka puhdas instrumentaaliversio poistaa — klikkaa kuullaksesi, mitä jäisi pois.",
"playingWhileEncoding": "Toistetaan: {stem}",
"stopAudio": "Pysäytä ääni",
"loadingAudio": "Ladataan: {stem}…"
"loadingAudio": "Ladataan: {stem}…",
"previewDiffersNote": "Tämä esikatselu on nopea renderöinti sanoitusten synkronoinnin tarkistamiseen. Siinä käytetään nopeuden vuoksi pelkkää mustaa taustaa, joten se ei näytä aivan samalta kuin lopullinen videosi, jossa käytetään valitsemaasi taustaa ja tyyliä.",
"previewNoTranslationNote": "Käännetyt sanoitukset ({language}) lisätään tarkistuksen jälkeen, joten ne näkyvät lopullisessa videossa, mutta eivät tässä esikatselussa."
},
"gapNavigator": {
"previousGap": "Edellinen aukko (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Utilisation de {name} ({size} Mo) comme instrumental",
"ownInstrumentalTitle": "Ton propre instrumental (facultatif)",
"submitTrack": "Soumettre le morceau",
"ownInstrumentalRemove": "Retirer"
"ownInstrumentalRemove": "Retirer",
"translatedLyricsHint": "Une fois les paroles vérifiées, l'IA traduit chaque ligne en {language} et l'affiche en plus petit sous les paroles dans ta vidéo. Les traductions ne peuvent pas être modifiées.",
"translatedLyricsLanguageLabel": "Traduire les paroles en",
"translatedLyricsPreviewAlt": "Exemple d'image de vidéo karaoké avec les paroles traduites en {language}",
"translatedLyricsPreviewError": "Impossible de charger l'aperçu.",
"translatedLyricsPreviewLoading": "Génération de l'aperçu...",
"translatedLyricsToggle": "Ajouter les paroles traduites",
"translatedLyricsToggleHint": "Affiche une traduction par IA de chaque ligne en plus petit sous les paroles. Idéal pour apprendre une langue.",
"translatedLyricsPreviewRetry": "Réessayer"
},
"jobStatus": {
"settingUp": "Configuration",
@@ -986,7 +994,8 @@
"editSegment": "Modifier le segment {index}",
"untimedSegment": "Aucune synchronisation des mots — clique pour modifier",
"waveforms": "Formes d'onde",
"missingLyricsMarker": "Paroles potentiellement manquantes {start}–{end}"
"missingLyricsMarker": "Paroles potentiellement manquantes {start}–{end}",
"waveformsSeparating": "Séparation de la voix et de la musique. Les formes d'onde apparaîtront automatiquement d'ici une minute ou deux."
},
"editActionBar": {
"reset": "Réinitialiser",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Chœurs que l'instrumental pur supprime — clique pour écouter ce qui sera retiré.",
"playingWhileEncoding": "Lecture : {stem}",
"stopAudio": "Arrêter l'audio",
"loadingAudio": "Chargement : {stem}…"
"loadingAudio": "Chargement : {stem}…",
"previewDiffersNote": "Cet aperçu est un rendu rapide pour vérifier la synchronisation de tes paroles. Il utilise un fond noir uni pour plus de rapidité, il ne ressemblera donc pas exactement à ta vidéo finale, qui intégrera ton arrière-plan complet et ton style.",
"previewNoTranslationNote": "Les paroles traduites ({language}) sont ajoutées après vérification, elles apparaîtront donc dans la vidéo finale mais pas dans cet aperçu."
},
"gapNavigator": {
"previousGap": "Écart précédent (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "משתמשים ב-{name} ({size} MB) כפלייבק",
"ownInstrumentalTitle": "פלייבק משלך (אופציונלי)",
"submitTrack": "שליחת רצועה",
"ownInstrumentalRemove": "הסרה"
"ownInstrumentalRemove": "הסרה",
"translatedLyricsHint": "לאחר בדיקת מילות השיר, ה-AI יתרגם כל שורה ל-{language} ויציג אותה בטקסט קטן יותר מתחת למילים בסרטון שלך. לא ניתן לערוך את התרגומים.",
"translatedLyricsLanguageLabel": "תרגום מילות השיר ל-",
"translatedLyricsPreviewAlt": "דוגמה לפריים מתוך סרטון קריוקי עם מילים מתורגמות ל-{language}",
"translatedLyricsPreviewError": "לא הצלחנו לטעון את התצוגה המקדימה.",
"translatedLyricsPreviewLoading": "יוצר תצוגה מקדימה...",
"translatedLyricsToggle": "הוספת מילים מתורגמות",
"translatedLyricsToggleHint": "הצגת תרגום AI של כל שורה בטקסט קטן יותר מתחת למילות השיר. מעולה ללימוד שפות.",
"translatedLyricsPreviewRetry": "נסה שוב"
},
"jobStatus": {
"settingUp": "מגדיר",
@@ -986,7 +994,8 @@
"editSegment": "עריכת מקטע {index}",
"untimedSegment": "ללא תזמון מילים — לחצו לעריכה",
"waveforms": "צורות גל",
"missingLyricsMarker": "ייתכן שחסרות מילים {start}–{end}"
"missingLyricsMarker": "ייתכן שחסרות מילים {start}–{end}",
"waveformsSeparating": "מפרידים את השירה מהמוזיקה. גלי הקול יופיעו אוטומטית תוך דקה או שתיים."
},
"editActionBar": {
"reset": "אפס",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "קולות רקע שהפלייבק הנקי מסיר — לחצו כדי לשמוע על מה אתם מוותרים.",
"playingWhileEncoding": "מתנגן: {stem}",
"stopAudio": "עצירת שמע",
"loadingAudio": "טוען: {stem}…"
"loadingAudio": "טוען: {stem}…",
"previewDiffersNote": "תצוגה מקדימה זו היא עיבוד מהיר לבדיקת סנכרון המילים שלך. היא כוללת רקע שחור חלק כדי שהעיבוד יהיה מהיר, ולכן היא לא תיראה בדיוק כמו הסרטון הסופי שלך, שיכלול את הרקע והסגנון המלאים.",
"previewNoTranslationNote": "מילים מתורגמות ({language}) מתווספות לאחר הבדיקה, ולכן הן יופיעו בסרטון הסופי אך לא בתצוגה המקדימה הזו."
},
"gapNavigator": {
"previousGap": "פער קודם (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "इंस्ट्रुमेंटल के रूप में {name} ({size} MB) का इस्तेमाल किया जा रहा है",
"ownInstrumentalTitle": "तुम्हारा अपना इंस्ट्रुमेंटल (वैकल्पिक)",
"submitTrack": "ट्रैक सबमिट करो",
"ownInstrumentalRemove": "हटाओ"
"ownInstrumentalRemove": "हटाओ",
"translatedLyricsHint": "बोल की समीक्षा होने के बाद, AI हर पंक्ति का {language} में अनुवाद करता है और तुम्हारे वीडियो में बोल के नीचे छोटे टेक्स्ट में दिखाता है। अनुवाद एडिट नहीं किए जा सकते।",
"translatedLyricsLanguageLabel": "बोल का अनुवाद इस भाषा में करें",
"translatedLyricsPreviewAlt": "कराओके वीडियो फ्रेम का उदाहरण जिसमें बोल का अनुवाद {language} में है",
"translatedLyricsPreviewError": "पूर्वावलोकन लोड नहीं किया जा सका।",
"translatedLyricsPreviewLoading": "प्रीव्यू रेंडर किया जा रहा है...",
"translatedLyricsToggle": "अनुवादित बोल जोड़ें",
"translatedLyricsToggleHint": "बोल के नीचे छोटे टेक्स्ट में हर पंक्ति का AI अनुवाद दिखाएं। नई भाषा सीखने के लिए बहुत बढ़िया।",
"translatedLyricsPreviewRetry": "फिर से कोशिश करो"
},
"jobStatus": {
"settingUp": "सेटअप हो रहा है",
@@ -986,7 +994,8 @@
"editSegment": "सेगमेंट {index} एडिट करो",
"untimedSegment": "शब्दों की टाइमिंग नहीं है — एडिट करने के लिए क्लिक करो",
"waveforms": "वेवफॉर्म",
"missingLyricsMarker": "संभवतः छूटे हुए लिरिक्स {start}–{end}"
"missingLyricsMarker": "संभवतः छूटे हुए लिरिक्स {start}–{end}",
"waveformsSeparating": "संगीत से वोकल्स अलग किए जा रहे हैं। वेवफ़ॉर्म एक या दो मिनट में अपने आप दिखाई देंगे।"
},
"editActionBar": {
"reset": "रीसेट करो",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "बैकिंग वोकल्स जिन्हें क्लीन इंस्ट्रुमेंटल हटा देता है — यह सुनने के लिए क्लिक करो कि तुम क्या छोड़ रहे हो।",
"playingWhileEncoding": "प्ले हो रहा है: {stem}",
"stopAudio": "ऑडियो रोको",
"loadingAudio": "लोड हो रहा है: {stem}…"
"loadingAudio": "लोड हो रहा है: {stem}…",
"previewDiffersNote": "यह प्रीव्यू तुम्हारे लिरिक्स सिंक को चेक करने के लिए एक क्विक रेंडर है। तेज़ी के लिए इसमें सादे काले बैकग्राउंड का इस्तेमाल किया गया है, इसलिए यह बिल्कुल तुम्हारे फाइनल वीडियो जैसा नहीं दिखेगा, जिसमें तुम्हारा पूरा बैकग्राउंड और स्टाइल होगा।",
"previewNoTranslationNote": "अनुवादित लिरिक्स ({language}) रिव्यू के बाद जोड़े जाते हैं, इसलिए वे फाइनल वीडियो में दिखाई देंगे लेकिन इस प्रीव्यू में नहीं।"
},
"gapNavigator": {
"previousGap": "पिछला गैप (P)",
+14 -3
View File
@@ -584,7 +584,15 @@
"ownInstrumentalSelected": "Kao instrumental koristi se {name} ({size} MB)",
"ownInstrumentalTitle": "Tvoj vlastiti instrumental (neobavezno)",
"submitTrack": "Pošalji pjesmu",
"ownInstrumentalRemove": "Ukloni"
"ownInstrumentalRemove": "Ukloni",
"translatedLyricsHint": "Nakon pregleda teksta pjesme, AI prevodi svaki redak na {language} i prikazuje ga manjim slovima ispod teksta pjesme u tvom videu. Prijevodi se ne mogu uređivati.",
"translatedLyricsLanguageLabel": "Prevedi tekst pjesme na",
"translatedLyricsPreviewAlt": "Primjer kadra karaoke videa s tekstom prevedenim na {language}",
"translatedLyricsPreviewError": "Nije uspjelo učitavanje pretpregleda.",
"translatedLyricsPreviewLoading": "Generiranje pretpregleda...",
"translatedLyricsToggle": "Dodaj prevedeni tekst pjesme",
"translatedLyricsToggleHint": "Prikaži AI prijevod svakog retka manjim slovima ispod teksta pjesme. Odlično za učenje jezika.",
"translatedLyricsPreviewRetry": "Pokušaj ponovno"
},
"jobStatus": {
"settingUp": "Postavljanje",
@@ -986,7 +994,8 @@
"editSegment": "Uredi segment {index}",
"untimedSegment": "Nema vremenskih oznaka riječi — klikni za uređivanje",
"waveforms": "Valni oblici",
"missingLyricsMarker": "Možda nedostaje tekst {start}–{end}"
"missingLyricsMarker": "Možda nedostaje tekst {start}–{end}",
"waveformsSeparating": "Odvajanje vokala od glazbe. Valni oblici pojavit će se automatski za minutu ili dvije."
},
"editActionBar": {
"reset": "Poništi",
@@ -1081,7 +1090,9 @@
"backingVocalsWaveformRemoved": "Prateći vokali koje čisti instrumental uklanja — klikni da čuješ što izostavljaš.",
"playingWhileEncoding": "Svira: {stem}",
"stopAudio": "Zaustavi zvuk",
"loadingAudio": "Učitavanje: {stem}…"
"loadingAudio": "Učitavanje: {stem}…",
"previewDiffersNote": "Ovaj je pretpregled brzi render za provjeru sinkronizacije teksta. Radi brzine koristi običnu crnu pozadinu, pa neće izgledati točno kao tvoj konačni video koji koristi tvoju punu pozadinu i stil.",
"previewNoTranslationNote": "Prevedeni tekst ({language}) dodaje se nakon pregleda, pa će se prikazati u konačnom videu, ali ne i u ovom pretpregledu."
},
"gapNavigator": {
"previousGap": "Prethodna praznina (P)",
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more