Compare commits

...
12 Commits
Author SHA1 Message Date
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
Andrew Beveridge ☄️andClaude Opus 5.5 b7a3864a37 Missing-lyrics insert: keep synced-reference timings inside the gap (v0.259.1) (#1099)
## Summary
Follow-up to #1098, found while fixing job 5710831e.

LRCLIB references are line-synced, and the last reference line in a gap
can end **after** the next transcribed line starts. On 5710831e it ends
at 33.07s while the next line starts at 32.40s. "Insert these lines"
copied those timings verbatim, so the inserted words overlapped the
following line.

`fitTimedLinesToWindow` clamps each inserted timed line to the window
between the neighbouring lines' words, with a 0.05s pad:
- A line that fits keeps its exact reference timing.
- An overflowing line is compressed affinely, keeping its word
proportions.
- A line with no room left falls back to **untimed**, so the existing
submit guard forces a Tap To Sync.

## Testing
- 4 new unit tests, including a 5710831e regression using the real
numbers: inserted words never overlap the next line, lines that fit keep
exact timing, push-after-previous, the untimed fallback, and untimed
lines passing through unchanged.
- Jest: 1561/1561.
- Playwright missing-lyrics scenarios: 4/4.

No local CodeRabbit review (the CLI has no seat for this org), so this
is left open for 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

* **Bug Fixes**
* Timed lyrics inserted into gaps now stay within the available interval
and avoid overlapping neighboring lyrics. Timings are preserved when
they already fit; overflowing lines are adjusted to fit when there is
enough room.
* If there isn’t enough room to assign valid timings, or the original
timing has no duration, inserted lyrics are left untimed instead. Lyrics
that are already untimed continue to pass through unchanged.
<!-- 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 11:47:52 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 08b574a86c Review UI: flag possible missing lyrics and insert the reference lines; mount sonner toasts (v0.259.0) (#1098)
## Summary
Phase 2b of the missing-lyrics work (#1095 detector, #1097 gate). When
the job's `vocal_gaps` analysis has an **evidenced** gap (the lead vocal
is singing, there are no lyrics, and the reference lyrics place lines
there), the lyrics review UI now shows:

- **An amber callout:** "Possible missing lyrics at 0:20–0:32 — the lead
vocal is singing here but there are no lyrics." It lists the expected
lines and their source (synced reference lines first), with **Play** and
**Insert these lines** buttons.
- **A marker row** at the gap's position in Synced Lyrics (Simple,
Advanced and Waveforms views).

**Insert these lines:**
- Adds one segment per reference line, at the right point in time.
- If the gap falls inside a segment, that segment is split.
- In duets, the singer follows Add Segment's rule.
- It's one undo step, logged in the edit log with `origin:
missing_lyrics_gap`.

**Timing of inserted words:**
- If a **synced reference** (e.g. LRCLIB) has the same line starting
inside the gap, its word timings are used.
- Otherwise the words go in **untimed**, so the existing "words have no
timing" submit guard forces a Tap To Sync. Timings are never invented.
- A re-sync hint lists inserted lines with **Sync timing** buttons that
open the existing Edit modal / Tap To Sync. It accumulates across gaps.

**When the marker hides:**
- When words exist inside the gap, with a 0.05s edge tolerance for the
backend's rounding.
- When the analysis doesn't match the lyrics as loaded (stale guard).
- For audio-only gaps, which are too noisy to show.
- In read-only/replay mode, the marker shows but Insert is disabled,
with an accessible explanation.
- The displayed range and Play use the review's timing offset.

**Also fixed (pre-existing bug):** sonner's `<Toaster>` was never
mounted, so **every sonner toast was silently dropped**. That covers
lyrics and instrumental review and the admin pages, and includes the
untimed-words submit guard this feature relies on. It's now mounted in
the root layout, and the guard message is translated (it was hardcoded
English).

## Testing
- Jest: 51 tests for the feature (gap detection with tolerance,
ordering/split, untimed vs synced timing, submit guard counting, duet
singer, offset, stale guard, read-only tooltip, memoisation, re-sync
hint).
- Playwright (`e2e/regression/lyrics-review.spec.ts`), 4 scenarios:
untimed insert → pending sync → undo; Sync timing opens Tap To Sync;
LRCLIB-timed insert closes the gap → undo; **blocked submit shows the
toast** (verified to fail without the Toaster mount).
- `make test`: frontend 1557/1557 plus all backend stages.
- i18n: all new strings in 33 locales.
- Two local code-review rounds; findings addressed.

No local CodeRabbit review (the CLI has no seat for this org), so this
is left open for 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**
* Lyrics review now highlights vocal gaps that may be missing lyrics,
with time ranges and available reference lines.
* Insert suggested lines into the transcript, undo the change, and open
inserted lyrics in the timing editor. Playback and timing-sync options
help review each gap.
* **Bug Fixes**
* Video submission now warns when lyrics contain untimed words that need
synchronization.
  * Improved accessibility labels for undo and redo controls.

<!-- 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 00:41:53 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 777daaf25f Missing-lyrics gate: block auto-approval when singing has no lyrics and the reference has lines there (v0.258.0) (#1097)
## Summary
Phase 2a of the missing-lyrics work (phase 1: #1095, shadow detector +
backfill).

**Audit** (262 completed jobs, 60 days, server-side
`scripts/audit_vocal_gaps.py`):
- Longest unlyricked vocal run per job: p50 0.7s, p90 5.1s, p99 22.4s.
47 jobs (18%) have a run of 3s or more, far too many to gate on audio
alone.
- Cross-checked against **synced** reference lyrics (LRCLIB line
timestamps): of 57 suspect gaps that have a synced reference, only 15
contain a reference line. Audio-only is ~25% precise. The rest are vocal
chops, samples, ad-libs and synth bleed, mostly in drum & bass tracks.
- **Evidence-based rule:** a gap is reliable when the reference lyrics
place lines in it.

**Changes**
- `vocal_gaps` 0.2.0: records the synced reference lines inside each
gap. `evidenced` = suspect vocal run AND reference lines, either synced
or between the neighbouring anchors.
- Scorer 0.5.0: new never-auto `missing-lyrics-gate` with a readable
reason, e.g. *"possible missing lyrics: ~10s of singing at 0:20-0:32 has
no transcribed words, and the reference lyrics have 3 line(s) there"*.
Audio-only gaps don't gate.
- The executor analyzes vocal gaps *before* scoring (off the event loop,
fingerprinted cache) and passes them to both scoring passes. It fails
open on pending audio or analysis errors.
- `GET /api/review/{id}/correction-data` now includes `vocal_gaps`, for
the upcoming review-UI marker (phase 2b).

On job 5710831e, the synced LRCLIB lines inside the gap are exactly the
three dropped lines. The genuine instrumentals have none.

## Testing
- `test_vocal_gaps.py`: synced lines with edge tolerance; section
headers ignored; evidence requires both singing and reference
(instrumental with misplaced reference lines doesn't gate; singing
without reference doesn't gate).
- `test_scorer.py`: reasons only for evidenced gaps; the gate overrides
confident lyrics; non-evidenced gaps don't gate.
- `test_executor.py`: evidenced gaps block auto-approval with the reason
and skip the timing check; cached evidenced gaps still gate.
- `test_combined_review_flow.py`: `vocal_gaps` is included in
correction-data.
- Full backend suite: 5211 passed.

Versioned 0.258.0 to follow #1096 (0.257.0).

No local CodeRabbit review (the CLI has no seat for this org), so this
is left open for the CodeRabbit bot.

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

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 23:56:48 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 f89de165cc Admin: re-render any completed job without review (v0.257.0) (#1096)
## Summary

An admin-only **Re-render** button on completed jobs in the `/app` jobs
list. It regenerates title/end cards, the karaoke video, all encoded
formats, packaging and distribution from the job's existing reviewed
lyrics, instrumental selection and style snapshot, **with no
lyrics/instrumental review**. Motivating case: re-rendering
already-delivered videos after a renderer fix (RTL/Hebrew, v0.255.0).

`POST /api/admin/jobs/{job_id}/rerender` with body `{"notify_customer":
false}`.

**Behaviour (decided with Andrew)**
- Works for consumer and tenant jobs, public or private. Uses the job's
existing style; no theme re-snapshot.
- **Published outputs are deleted up front, like Edit (YouTube, GDrive,
Dropbox), but the brand code is kept, not recycled.** The pipeline
re-publishes under the same NOMAD-xxxx. YouTube gets a new upload and
therefore a new URL.
- Outputs are only deleted for destinations the re-render will actually
re-publish (`plan_republish` uses the same conditions as the video
worker). Anything else is kept, with a warning shown to the admin.
- **No customer email/push/Discord by default.** The confirm dialog has
an "Email the customer when done" checkbox. Already-notified
requests-board voters aren't re-emailed; voter emails still owed from
the original publish do go out.
- A failed admin re-render is set to FAILED with an in-progress marker
(scoped to `review_token`, so it can't leak into later runs). It can be
retried by **admins only**; `/retry` returns 403 to customers while the
marker is active.
- **Mutual exclusion with the YouTube upload queue:** the claim and the
queue's `mark_processing` are Firestore transactions that each read both
documents. A re-render is refused with 409 while an upload is in flight.
A queued or failed deferred upload is cancelled atomically when YouTube
will be re-published. The queue never starts an upload for a job that is
mid re-render.
- After a successful upload, the queue never re-queues an entry, so a
later error can't cause a duplicate upload.
- Admin re-render completions don't increment the customer's
completed-jobs count.

**Refactors**
- New `backend/services/published_outputs_cleanup.py`, shared by Edit,
admin delete-outputs and the re-render.
- The Dropbox folder delete now uses the uploader's sanitised name and
also tries the legacy raw name. This is a deliberate fix for titles with
special characters.
- Remaining duplicate copies (`jobs.py` ~2440,
`visibility_change_service`) are listed as follow-ups in the design doc.

## Testing
- 173 tests in `test_admin_rerender.py` +
`test_published_outputs_cleanup.py`, built through three local
code-review rounds. They cover:
  - claim and validation
  - retry gating
  - marker scoping
  - publish planning (each mismatch case)
- queue exclusion in both directions, no starvation, and that the
re-render's own later upload is never cancelled
  - the no-re-queue-after-upload rule
  - notification gating on both pipelines
  - community voter cases plus reconcile
  - restart atomicity
  - legacy Dropbox naming
  - tenant re-render and Edit unchanged
- Frontend Jest: button visibility (admin vs non-admin, complete vs
not), dialog, payload, and warnings toast.
- `make test`: backend 1972 + 5372 + 150, frontend 1506.
- i18n: new strings in all 33 locales (frontend) plus backend
translations.

Docs: `docs/API.md`,
`docs/archive/2026-10-01-admin-rerender-any-job.md`.

No local CodeRabbit review (the CLI has no seat for this org), so this
is left open for the CodeRabbit bot. Three local code-review rounds ran;
their findings are addressed in the fix commits.

🤖 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**
* Administrators can re-render eligible completed tracks without another
review, retaining existing track settings and brand code.
* Choose whether to notify the customer; notifications are off by
default. Published outputs are replaced when applicable, and warnings
identify outputs that remain unchanged.
* Administrators can resume eligible failed or cancelled re-renders.
Re-render controls and status messages are available in multiple
languages.
* **Bug Fixes**
* Improved cleanup and handling of published files and queued YouTube
uploads during re-renders, with safer retries and clearer failure
reporting.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 23:37:51 -04:00
Andrew Beveridge ☄️andClaude Opus 5.5 e2f7dbd13c Detect sung stretches with no transcribed lyrics (shadow) + backfill endpoint (v0.256.0) (#1095)
## Summary

Transcription can silently **drop whole sung lines**. On job 5710831e
(Hebrew), the words stop at 20.66s and resume at 32.40s while the lead
vocal is ~96% active, and both reference sources have three pre-chorus
lines there. `SectionDetector` (gap ≥ 10s, no audio check) then rendered
"♪ INSTRUMENTAL ♪" over the singing. Nothing caught it:
- the scorer's anchor coverage measures how much of the *transcribed*
text matches the reference, so omissions don't lower it (98.8% here);
- `timing_check` G3 (`max_unclaimed_run_s`) does fire on this job but is
shadow-only and only computed for AUTO-bound jobs;
- the review UI shows nothing at the gap.

This PR is **phase 1: a shadow signal plus server-side backfill for
calibration**. It changes no verdicts or rendering.

- `backend/services/auto_approval/vocal_gaps.py`: for every
transcription gap ≥ 3s, records the lead-vocal active fraction, the
longest breath-bridged vocal run (with a 1.5s allowance for a held note
carried over from the previous word), and the reference lines between
the neighbouring words' reference positions. Section headers are dropped
and ±1-word anchor drift at line boundaries is snapped. `suspect` = run
≥ 3s.
- The executor analyzes every job once stems exist (any verdict), off
the event loop, and stores `state_data.vocal_gaps` keyed by an
`input_key` fingerprint so resets/edits recompute. A summary goes in
`processing_metadata.auto_approval.vocal_gaps`.
- `POST /api/internal/jobs/{id}/vocal-gaps[?dry_run=true]` (admin) plus
`scripts/audit_vocal_gaps.py` for backfill/calibration. Cloud Run does
the stem work.

**On the real job:** one suspect gap, 20.66–32.40s (10.26s run after the
allowance), whose reference lines are exactly the three missing Genius
lines. The three genuine instrumentals have ≤ 0.16s runs.

## Testing
- `test_vocal_gaps.py` (25 tests, synthesized audio + synthetic
correction data):
  - dropped lines vs instrumental vs ad-lib vs held note
  - a short dropped line diluted by a long gap
  - breath bridging
  - silent stem = error
  - malformed reference data
- reference snapping (off-by-one, single-word line, headers, reversed
chorus mapping)
- Executor tests: stored without changing the outcome; analyzed for
review-bound jobs; cache hit only for the same `input_key`, stale
recompute; pending audio / no stem / error / exception all non-fatal;
backfill uses the reviewed lyrics + original references; dry run.
- Internal endpoint tests (store / dry_run / admin).
- Full backend suite: 5199 passed.
- A local code review's findings were addressed in the second commit:
event loop, stale cache, silent stem, held notes, reference robustness,
audit ordering.

## Next (after deploy)
Run the audit → hand-check suspects → choose thresholds → phase 2:
scorer REVIEW gate with an explicit reason, no fake INSTRUMENTAL over
vocals, review-UI marker with one-click insert of the reference lines.
Also noted: anchor reference ids look shifted by one word at `[Section]`
header boundaries. Separate issue, documented in the plan doc.

No local CodeRabbit review (the CLI has no seat for this org), so this
is left open for 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**
* Added vocal-gap analysis to identify stretches of missing lyrics that
overlap with lead vocals. Results are saved with job data and can be
requested through an admin-only internal API.
* Analysis also runs automatically during auto-approval when vocal stems
are available. It does not change job status or approval decisions.
* **Documentation**
* Documented the internal API, its dry-run option, and the analysis
result statuses.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 22:10:47 -04:00
181 changed files with 12847 additions and 817 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"
+146 -226
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
# ============================================
@@ -2243,8 +2164,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
+128 -86
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",
@@ -1310,6 +1323,9 @@ async def reset_job(
# backend/workers/supersede.py. Atomic with the clears above so an in-flight
# worker can never observe a half-applied reset.
clear_updates["state_data.worker_generation"] = Increment(1)
# A reset starts a new run: drop any failed admin re-render's marker.
from backend.services.admin_rerender_service import clear_admin_rerender_update
clear_updates.update(clear_admin_rerender_update(job))
# Add timeline event
clear_updates["timeline"] = ArrayUnion([timeline_event])
@@ -1685,7 +1701,6 @@ async def delete_job_outputs(
Returns:
Deletion results for each service
"""
import re
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
admin_email = auth_data.user_email or "unknown"
@@ -1711,97 +1726,29 @@ async def delete_job_outputs(
)
state_data = job.state_data or {}
results = {
"youtube": {"status": "skipped", "reason": "no youtube_url in state_data"},
"dropbox": {"status": "skipped", "reason": "no brand_code or dropbox_path"},
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
}
from backend.services.published_outputs_cleanup import (
delete_dropbox_folder,
delete_gdrive_files,
delete_youtube_video,
snapshot_published_outputs,
)
# Snapshot current outputs before cleanup (preserved in timeline metadata)
deleted_outputs = {}
if state_data.get('youtube_url'):
deleted_outputs['youtube_url'] = state_data['youtube_url']
if state_data.get('dropbox_link'):
deleted_outputs['dropbox_link'] = state_data['dropbox_link']
if state_data.get('brand_code'):
deleted_outputs['brand_code'] = state_data['brand_code']
if state_data.get('gdrive_files'):
deleted_outputs['gdrive_files'] = state_data['gdrive_files']
deleted_outputs = snapshot_published_outputs(state_data)
log_to_job(job_id, "admin", "INFO", f"Output deletion initiated by {admin_email}", {"deleted_outputs": deleted_outputs})
# Clean up YouTube
youtube_url = state_data.get('youtube_url')
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False,
non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
success = finalise.delete_youtube_video(video_id)
results["youtube"] = {
"status": "success" if success else "failed",
"video_id": video_id
}
else:
results["youtube"] = {"status": "skipped", "reason": "YouTube credentials not configured"}
else:
results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
except Exception as e:
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
results["youtube"] = {"status": "error", "error": str(e)}
# Clean up Dropbox
# Shared helpers (same as Edit / admin re-render): the Dropbox folder name is
# sanitised exactly like the uploader names it.
brand_code = state_data.get('brand_code')
dropbox_path = getattr(job, 'dropbox_path', None)
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
base_name = f"{job.artist} - {job.title}"
folder_name = f"{brand_code} - {base_name}"
full_path = f"{dropbox_path}/{folder_name}"
success = dropbox.delete_folder(full_path)
results["dropbox"] = {
"status": "success" if success else "failed",
"path": full_path
}
else:
results["dropbox"] = {"status": "skipped", "reason": "Dropbox credentials not configured"}
except Exception as e:
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
results["dropbox"] = {"status": "error", "error": str(e)}
# Clean up Google Drive
gdrive_files = state_data.get('gdrive_files')
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results
}
else:
results["gdrive"] = {"status": "skipped", "reason": "Google Drive credentials not configured"}
except Exception as e:
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
results["gdrive"] = {"status": "error", "error": str(e)}
results = {
"youtube": delete_youtube_video(job_id, state_data.get('youtube_url')),
"dropbox": delete_dropbox_folder(
job_id, getattr(job, 'dropbox_path', None), brand_code, job.artist, job.title
),
# Mirror cleanup happens below for any brand_code, Drive files or not.
"gdrive": delete_gdrive_files(job_id, state_data.get('gdrive_files'), brand_code, cleanup_mirror=False),
}
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too (prefix-keyed
# by brand_code, covers renames). Non-fatal, Nomad-only, no-op otherwise.
@@ -1861,6 +1808,9 @@ async def delete_job_outputs(
if key in state_data:
update_payload[f"state_data.{key}"] = DELETE_FIELD
cleared_keys.append(key)
# Outputs are gone; a failed admin re-render's marker no longer applies.
from backend.services.admin_rerender_service import clear_admin_rerender_update
update_payload.update(clear_admin_rerender_update(job))
# Add timeline event with structured metadata
timeline_event = {
@@ -2448,6 +2398,86 @@ async def regenerate_screens(
)
# =============================================================================
# Admin Re-render Endpoint
# =============================================================================
class AdminRerenderRequest(BaseModel):
"""Request body for POST /api/admin/jobs/{job_id}/rerender."""
notify_customer: bool = Field(
False,
description="Email/push the customer when the re-render completes (default: no notification)",
)
class AdminRerenderResponse(BaseModel):
"""Response from the admin re-render endpoint."""
status: str
job_id: str
message: str
brand_code: Optional[str] = None
notify_customer: bool
previous_outputs: Dict[str, Any]
cleanup_results: Dict[str, Any]
warnings: List[str] = []
@router.post("/jobs/{job_id}/rerender", response_model=AdminRerenderResponse)
async def admin_rerender_job(
job_id: str,
body: Optional[AdminRerenderRequest] = None,
auth_data: AuthResult = Depends(require_admin),
):
"""
Re-render a completed job end to end without review (admin only).
Regenerates title/end screens, the karaoke video, every encoded format and
the CDG/TXT packages from the job's existing reviewed lyrics and
instrumental selection, with the job's existing style snapshot. Published
outputs (YouTube video, Google Drive files, Dropbox folder) the re-render
will re-publish are deleted up front and re-published under the SAME brand
code when the pipeline finishes (the YouTube URL changes); outputs for
destinations no longer configured are left in place (see ``warnings``).
The customer (and Discord / community voters) are only notified on
completion when ``notify_customer`` is true.
Works for tenant and consumer, public and private jobs in ``complete``
status (or ``failed`` after a previous admin re-render).
"""
from backend.services.admin_rerender_service import AdminRerenderService
from backend.services.theme_rerender_service import RerenderError
body = body or AdminRerenderRequest()
admin_email = auth_data.user_email or "unknown"
job_manager = JobManager()
job = await asyncio.to_thread(job_manager.get_job, job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
try:
result = await AdminRerenderService(job_manager).start(
job, requested_by=admin_email, notify_customer=body.notify_customer
)
except RerenderError as e:
logger.warning(f"Admin {admin_email} re-render of job {job_id} rejected ({e.status_code}): {e}")
raise HTTPException(status_code=e.status_code, detail=str(e))
logger.info(
f"Admin {admin_email} started re-render of job {job_id} "
f"(notify_customer={body.notify_customer}, brand_code={result['brand_code']})"
)
return AdminRerenderResponse(
status="processing",
job_id=job_id,
message="Re-render started. Published outputs will be replaced when it completes.",
brand_code=result["brand_code"],
notify_customer=body.notify_customer,
previous_outputs=result["previous_outputs"],
cleanup_results=result["cleanup_results"],
warnings=result.get("warnings") or [],
)
# =============================================================================
# Restart Job Endpoint
# =============================================================================
@@ -2538,6 +2568,12 @@ async def restart_job(
workers_triggered = []
error_msg = None
# A restart starts a new run: drop any failed admin re-render's marker —
# folded into the restart's own atomic update below, so a restart that is
# rejected (e.g. 400 on preserve_audio_stems) keeps the marker.
from backend.services.admin_rerender_service import clear_admin_rerender_update
marker_clear = clear_admin_rerender_update(job)
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
db = job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
@@ -2590,6 +2626,9 @@ async def restart_job(
]
update_payload = {}
update_payload.update(marker_clear)
if marker_clear:
cleared_keys.append("admin_rerender")
for key in keys_to_clear:
if key in state_data:
update_payload[f"state_data.{key}"] = DELETE_FIELD
@@ -2643,6 +2682,9 @@ async def restart_job(
]
update_payload = {}
update_payload.update(marker_clear)
if marker_clear:
cleared_keys.append("admin_rerender")
for key in keys_to_clear:
if key in state_data:
update_payload[f"state_data.{key}"] = DELETE_FIELD
+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 "",
+20
View File
@@ -204,6 +204,26 @@ async def trigger_auto_approval_eval(
return {"job_id": job_id, **result}
@router.post("/jobs/{job_id}/vocal-gaps")
async def analyze_vocal_gaps_endpoint(
job_id: str,
dry_run: bool = False,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""
Find sung stretches with no transcribed lyrics for a job (admin only).
Shadow-mode calibration/backfill for the missing-lyrics detector: downloads the
lead-vocal stem server-side, analyzes the job's current lyrics and stores
``state_data.vocal_gaps`` (unless ``dry_run``). Never changes job status.
"""
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
logger.info(f"[job:{job_id}] vocal gap analysis requested (dry_run={dry_run})")
result = await asyncio.to_thread(analyze_job_vocal_gaps, job_id, not dry_run)
return {"job_id": job_id, **result}
@router.post("/workers/lyrics", response_model=WorkerResponse)
async def trigger_lyrics_worker(
request: WorkerRequest,
+54 -80
View File
@@ -293,7 +293,6 @@ async def edit_completed_track(
No additional credits are consumed — the original credit covers re-edits.
"""
locale = get_locale_from_request(http_request)
import re
from datetime import timezone
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
@@ -324,94 +323,30 @@ async def edit_completed_track(
cleanup_results = {}
# Snapshot current outputs before cleanup (preserved in timeline metadata)
previous_outputs = {}
if state_data.get('youtube_url'):
previous_outputs['youtube_url'] = state_data['youtube_url']
if state_data.get('dropbox_link'):
previous_outputs['dropbox_link'] = state_data['dropbox_link']
if state_data.get('brand_code'):
previous_outputs['brand_code'] = state_data['brand_code']
if state_data.get('gdrive_files'):
previous_outputs['gdrive_files'] = state_data['gdrive_files']
from backend.services.published_outputs_cleanup import (
delete_dropbox_folder,
delete_gdrive_files,
delete_youtube_video,
snapshot_published_outputs,
)
previous_outputs = snapshot_published_outputs(state_data)
log_to_job(job_id, "edit", "INFO", f"Edit initiated by {user_email}", {"previous_outputs": previous_outputs})
# --- Phase 1: Clean up distributed outputs ---
# Delete YouTube video
youtube_url = state_data.get('youtube_url')
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False,
non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
success = finalise.delete_youtube_video(video_id)
cleanup_results["youtube"] = {"status": "success" if success else "failed", "video_id": video_id}
else:
cleanup_results["youtube"] = {"status": "skipped", "reason": "YouTube not configured"}
else:
cleanup_results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
except Exception as e:
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
cleanup_results["youtube"] = {"status": "error", "error": str(e)}
else:
cleanup_results["youtube"] = {"status": "skipped", "reason": "no youtube_url"}
cleanup_results["youtube"] = delete_youtube_video(job_id, state_data.get('youtube_url'))
log_to_job(job_id, "edit", "INFO", f"YouTube cleanup: {cleanup_results['youtube'].get('status')}", cleanup_results["youtube"])
# Delete Dropbox folder
brand_code = state_data.get('brand_code')
dropbox_path = getattr(job, 'dropbox_path', None)
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
base_name = f"{job.artist} - {job.title}"
folder_name = f"{brand_code} - {base_name}"
full_path = f"{dropbox_path}/{folder_name}"
success = dropbox.delete_folder(full_path)
cleanup_results["dropbox"] = {"status": "success" if success else "failed", "path": full_path}
else:
cleanup_results["dropbox"] = {"status": "skipped", "reason": "Dropbox not configured"}
except Exception as e:
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
cleanup_results["dropbox"] = {"status": "error", "error": str(e)}
else:
cleanup_results["dropbox"] = {"status": "skipped", "reason": "no brand_code or dropbox_path"}
cleanup_results["dropbox"] = delete_dropbox_folder(
job_id, getattr(job, 'dropbox_path', None), brand_code, job.artist, job.title
)
log_to_job(job_id, "edit", "INFO", f"Dropbox cleanup: {cleanup_results['dropbox'].get('status')}", cleanup_results["dropbox"])
# Delete Google Drive files
gdrive_files = state_data.get('gdrive_files')
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
# Also remove the Nomad 720p master from the GCS fast-sync mirror
# (prefix-keyed by brand_code, so it covers renames). Non-fatal,
# Nomad-brand only, no-op otherwise.
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
else:
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
except Exception as e:
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
cleanup_results["gdrive"] = {"status": "error", "error": str(e)}
else:
cleanup_results["gdrive"] = {"status": "skipped", "reason": "no gdrive_files"}
# Also removes the Nomad 720p master from the GCS fast-sync mirror (the
# brand code is recycled below, so the mirror copy must go).
cleanup_results["gdrive"] = delete_gdrive_files(job_id, state_data.get('gdrive_files'), brand_code)
log_to_job(job_id, "edit", "INFO", f"GDrive cleanup: {cleanup_results['gdrive'].get('status')}", cleanup_results["gdrive"])
# Delete GCS finals folder
@@ -468,6 +403,11 @@ async def edit_completed_track(
if key in state_data:
update_payload[f"state_data.{key}"] = DELETE_FIELD
# An earlier (failed) admin re-render's marker must not leak into the
# edited run (notification suppression, forced brand code).
from backend.services.admin_rerender_service import clear_admin_rerender_update
update_payload.update(clear_admin_rerender_update(job))
# Clear processing state so workers re-run from scratch
processing_keys = ["render_progress", "video_progress", "encoding_progress", "review_complete"]
for key in processing_keys:
@@ -2060,6 +2000,16 @@ async def retry_job(
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# A failed admin re-render is admin-only to resume: every retry path keeps
# its marker (brand code, deleted/re-published outputs, notification choice).
from backend.services.admin_rerender_service import active_admin_rerender
admin_rerender = active_admin_rerender(job)
if admin_rerender and not auth_result.is_admin:
raise HTTPException(
status_code=403,
detail=t(locale, "jobs.adminRerenderRetryAdminOnly"),
)
# Refuse if a Cloud Run Job auto-retry is already coming for this job.
# Otherwise the manual retry races with the automatic one and produces
# duplicate downloads and downstream worker triggers (see job 8a9c74ff).
@@ -2102,7 +2052,29 @@ async def retry_job(
"message": "Job retry: re-running the theme re-render",
"retry_stage": "theme_rerender",
}
# Same for an admin re-render (state_data.admin_rerender): re-run it,
# keeping the admin's notify_customer choice. Its published outputs were
# already removed on the first attempt (recorded in the marker).
if (admin_rerender and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
and not _has_title_screen(file_urls)):
from backend.services.admin_rerender_service import AdminRerenderService
from backend.services.theme_rerender_service import RerenderError
try:
await AdminRerenderService(job_manager).start(
job,
requested_by=auth_result.user_email or "unknown",
notify_customer=bool(admin_rerender.get('notify_customer', False)),
)
except RerenderError as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
return {
"status": "success",
"job_status": "lyrics_complete",
"message": "Job retry: re-running the admin re-render",
"retry_stage": "admin_rerender",
}
# If we have a video with vocals and instrumental selection, retry video generation
if (file_urls.get('videos', {}).get('with_vocals') and
state_data.get('instrumental_selection')):
@@ -2686,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):
@@ -2843,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),
)
+6
View File
@@ -802,6 +802,8 @@ async def get_correction_data(
- All lyrics correction data (segments, reference lyrics, anchors, etc.)
- instrumental_options: List of available instrumental tracks with audio URLs
- backing_vocals_analysis: Analysis data to help users choose instrumental
- vocal_gaps: sung stretches with no transcribed words (possible missing
lyrics) — see services/auto_approval/vocal_gaps.py
Replay mode (``?replay=true``, requires full auth — admin/owner, not a
review-token link): serves the SAME payload for a job in ANY status so the
@@ -899,6 +901,10 @@ async def get_correction_data(
backing_vocals_analysis = job.state_data.get('backing_vocals_analysis', {})
corrections_data['backing_vocals_analysis'] = backing_vocals_analysis
# Possible missing lyrics (auto-approval analysis): the review UI marks
# "evidenced" gaps and offers the reference lines for insertion.
corrections_data['vocal_gaps'] = job.state_data.get('vocal_gaps') or None
# Per-screen skip (C1): tell the frontend whether each review half is
# confidently auto-resolved, so it can skip the instrumental screen (or the
# lyrics screen). Derived from the stored auto-approval verdict + the job's
+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
View File
@@ -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()
+546
View File
@@ -0,0 +1,546 @@
"""
Admin re-render: rebuild ANY finished job end to end without a review step.
Use case: a renderer fix (e.g. RTL/Hebrew lyrics, v0.255.0) needs videos that
were already delivered regenerated. Unlike the tenant "Re-render with current
theme" (theme_rerender_service), this:
- works for every job (consumer or tenant, public or private);
- keeps the job's EXISTING style snapshot (``jobs/{id}/style/...``,
``style_params_gcs_path``, ``style_assets``) — no theme re-snapshot;
- deletes the published outputs (YouTube video, Google Drive files, Dropbox
folder) up front, like Edit — but only for destinations the re-render will
re-publish to (see ``plan_republish``); others are left in place with a
warning. The brand code is KEPT (never recycled): the video worker
re-publishes under the same code via ``rerender_brand_code``. YouTube gets a
new upload, so the YouTube URL changes;
- doesn't email/push the customer (or Discord / community voters) on
completion unless the admin opted in (``notify_customer``) — see
``suppress_customer_notifications``.
Mechanism (shared with the theme re-render and the private->public visibility
flow): atomically move the job COMPLETE -> LYRICS_COMPLETE with
``state_data.regen_restore_status = "review_complete"`` and trigger the screens
worker. The screens worker regenerates the screens, restores REVIEW_COMPLETE and
triggers the render worker, which renders from the existing
corrections_updated.json; the video worker then encodes, distributes and
completes using ``state_data.instrumental_selection``.
``state_data.admin_rerender`` is the in-progress marker. The video worker clears
it on success; a FAILED admin re-render keeps it, which lets an admin
``POST /api/jobs/{id}/retry`` (or another admin re-render) resume it. The marker
only applies to its own run: it records the job's ``review_token`` at claim
(a new token is minted whenever the job goes back through review), and the
admin reset/restart, Edit, visibility and delete-outputs flows clear it.
"""
import asyncio
import logging
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple
from google.cloud import firestore
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from backend.models.job import JobStatus
from backend.services.firestore_service import log_to_job
from backend.services.job_manager import JobManager
from backend.services.published_outputs_cleanup import (
delete_dropbox_folder,
delete_gdrive_files,
delete_youtube_video,
snapshot_published_outputs,
)
from backend.services.storage_service import StorageService
from backend.services.theme_rerender_service import (
RerenderConflictError,
RerenderError,
delete_regenerated_artifacts,
)
logger = logging.getLogger(__name__)
ADMIN_RERENDER_MARKER = "admin_rerender"
_LOG_SOURCE = "admin-rerender"
# destination -> state_data keys that reference its published output
_DESTINATION_KEYS = {
"youtube": ("youtube_url", "youtube_video_id", "youtube_upload_queued"),
"dropbox": ("dropbox_link",),
"gdrive": ("gdrive_files",),
}
# state_data link a destination's output is recorded under (kept_outputs keys)
_DESTINATION_LINK = {"youtube": "youtube_url", "dropbox": "dropbox_link", "gdrive": "gdrive_files"}
# --- Marker helpers ------------------------------------------------------------
def raw_admin_rerender_marker(job) -> Dict[str, Any]:
"""The stored marker, regardless of whether it belongs to the current run."""
state_data = getattr(job, "state_data", None)
marker = state_data.get(ADMIN_RERENDER_MARKER) if isinstance(state_data, dict) else None
return marker if isinstance(marker, dict) else {}
def active_admin_rerender(job) -> Dict[str, Any]:
"""The marker if it belongs to the job's current run, else ``{}``.
A job that has since gone back through review (admin reset, Edit, ...) has a
new ``review_token``, so a stale marker from a failed admin re-render no
longer suppresses notifications or forces the brand code.
"""
marker = raw_admin_rerender_marker(job)
if marker and "review_token" in marker:
if marker["review_token"] != getattr(job, "review_token", None):
return {}
return marker
def admin_rerender_blocks_upload(job_data: Dict[str, Any]) -> bool:
"""True if a queued YouTube upload must not start for this job (raw job doc).
An ACTIVE (review_token-scoped) admin re-render on a job that isn't complete
is rebuilding (or failed while rebuilding) the finals. Used inside the
queue's claim transaction, which reads the job doc.
"""
from types import SimpleNamespace
view = SimpleNamespace(
state_data=job_data.get("state_data") or {},
review_token=job_data.get("review_token"),
)
return bool(active_admin_rerender(view)) and job_data.get("status") != JobStatus.COMPLETE.value
UPLOAD_IN_PROGRESS_MESSAGE = (
"A YouTube upload for this track is in progress — try again in a few minutes."
)
def claim_with_youtube_queue(
db, job_id: str, update: Dict[str, Any], allowed_statuses: set,
cancel_deferred_upload: bool, keep_reason: Optional[str] = None,
) -> Dict[str, Any]:
"""Atomically claim the job for an admin re-render, reading its YouTube queue doc too.
- job status not claimable → RerenderConflictError (409);
- a deferred upload is ``processing`` → RerenderConflictError (409): an
upload of the old finals must never overlap the re-render;
- a ``queued``/``failed`` entry is cancelled in the same transaction when
the re-render will re-publish YouTube, otherwise left in place (warning).
The queue's ``mark_processing`` transaction reads the job doc and refuses
while an admin re-render is active, so the two can never interleave.
Returns the queue outcome, e.g. ``{"status": "cancelled", "previous_status": "queued"}``.
"""
from backend.services.youtube_upload_queue_service import (
PACIFIC_TZ,
YOUTUBE_UPLOAD_QUEUE_COLLECTION,
)
from backend.config import get_settings
# Same collection the YouTube queue's mark_processing transaction reads, so
# the two claims always contend on the same job document.
job_ref = db.collection(get_settings().firestore_collection).document(job_id)
queue_ref = db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
marker_key = f"state_data.{ADMIN_RERENDER_MARKER}"
@firestore.transactional
def claim(transaction):
snapshot = job_ref.get(transaction=transaction)
queue_snapshot = queue_ref.get(transaction=transaction)
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
if status not in allowed_statuses:
return "not_claimable", None
queue_status = (queue_snapshot.to_dict() or {}).get("status") if queue_snapshot.exists else None
if queue_status == "processing":
return "uploading", None
payload = dict(update) # fresh copy per transaction attempt
if queue_status in ("queued", "failed"):
if cancel_deferred_upload:
transaction.update(queue_ref, {
"status": "cancelled",
"last_error": "Cancelled: admin re-render will re-upload",
"updated_at": datetime.now(PACIFIC_TZ),
})
outcome = {"status": "cancelled", "previous_status": queue_status}
else:
warning = f"pending deferred YouTube upload left queued (YouTube not re-published: {keep_reason})"
marker = dict(payload[marker_key])
marker["warnings"] = [*marker.get("warnings", []), warning]
payload[marker_key] = marker
outcome = {"status": "kept", "previous_status": queue_status, "reason": keep_reason,
"warning": warning}
else:
outcome = {"status": "skipped",
"reason": "no queue entry" if queue_status is None else f"entry is {queue_status}"}
transaction.update(job_ref, payload)
return "ok", outcome
result, outcome = claim(db.transaction())
if result == "uploading":
raise RerenderConflictError(UPLOAD_IN_PROGRESS_MESSAGE)
if result != "ok":
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
return outcome
def clear_admin_rerender_update(job) -> Dict[str, Any]:
"""Firestore update that drops the marker (empty if there is none)."""
if raw_admin_rerender_marker(job):
return {f"state_data.{ADMIN_RERENDER_MARKER}": DELETE_FIELD}
return {}
def suppress_customer_notifications(job) -> bool:
"""True if this run's customer-facing notifications must be skipped.
Only an active admin re-render the admin didn't opt into announcing
suppresses them; normal jobs and the tenant theme re-render always notify.
"""
marker = active_admin_rerender(job)
return bool(marker) and not marker.get("notify_customer", False)
def admin_rerender_brand_code(job) -> Optional[str]:
return active_admin_rerender(job).get("brand_code") or None
def admin_rerender_kept_outputs(job) -> Dict[str, Any]:
"""Published outputs left in place (not re-published) by the active re-render."""
return active_admin_rerender(job).get("kept_outputs") or {}
# --- Validation / planning -----------------------------------------------------
def _claimable_statuses(job) -> set:
"""COMPLETE, plus FAILED/CANCELLED when that was an admin re-render (resume)."""
statuses = {JobStatus.COMPLETE.value}
if active_admin_rerender(job):
statuses.update({JobStatus.FAILED.value, JobStatus.CANCELLED.value})
return statuses
def validate_admin_rerender(job) -> Optional[str]:
"""Return a reason the job can't be re-rendered, or None if it can."""
if job.status not in _claimable_statuses(job):
return f"Only completed jobs can be re-rendered (current status: {job.status})."
if getattr(job, "outputs_deleted_at", None):
return "This job's outputs were deleted, so it can't be re-rendered."
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
return "Prep-only / finalise-only jobs can't be re-rendered."
state_data = job.state_data or {}
if state_data.get("visibility_change_in_progress"):
return "A visibility change is in progress for this job."
if not state_data.get("instrumental_selection"):
return "This job has no instrumental selection to re-render with."
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
return "This job has no reviewed lyrics to re-render with."
return None
def plan_republish(job) -> Dict[str, Tuple[bool, Optional[str]]]:
"""Which destinations the re-render's distribution step will publish to.
Mirrors the video worker: YouTube needs ``enable_youtube_upload`` on a
non-private job (effective distribution) and configured YouTube credentials;
Dropbox needs an effective ``dropbox_path`` and ``brand_prefix``; Google
Drive needs an effective ``gdrive_folder_id``. Returns
``{destination: (will_republish, reason_if_not)}``. Does blocking I/O
(YouTube credential lookup) — call off the event loop.
"""
from backend.services.job_defaults_service import get_effective_distribution_for_job
dist = get_effective_distribution_for_job(job)
plan: Dict[str, Tuple[bool, Optional[str]]] = {}
if getattr(job, "is_private", False) or not dist.enable_youtube_upload:
plan["youtube"] = (False, "YouTube upload is disabled for this job")
else:
try:
from backend.services.youtube_service import get_youtube_service
configured = get_youtube_service().is_configured
reason = "YouTube credentials are not configured"
except Exception as e:
# Can't plan → don't delete or cancel anything YouTube; warn instead.
logger.warning(f"[job:{job.job_id}] YouTube credential check failed: {e}")
configured = False
reason = f"couldn't verify YouTube credentials ({e})"
plan["youtube"] = (True, None) if configured else (False, reason)
if dist.dropbox_path and dist.brand_prefix:
plan["dropbox"] = (True, None)
else:
plan["dropbox"] = (False, "Dropbox upload is not configured for this job")
if dist.gdrive_folder_id:
plan["gdrive"] = (True, None)
else:
plan["gdrive"] = (False, "Google Drive upload is not configured for this job")
return plan
def _has_output(state_data: dict, destination: str) -> bool:
return bool(state_data.get(_DESTINATION_LINK[destination]))
# --- Service ---------------------------------------------------------------------
class AdminRerenderService:
def __init__(
self,
job_manager: Optional[JobManager] = None,
storage: Optional[StorageService] = None,
):
self.job_manager = job_manager or JobManager()
self.storage = storage or StorageService()
async def start(self, job, requested_by: str, notify_customer: bool = False) -> Dict[str, Any]:
"""Claim the job, delete its re-publishable outputs and kick off the re-render.
Blocking Firestore/GCS/YouTube/Dropbox/GDrive work runs in worker
threads. Any failure after the claim marks the job FAILED with the
marker kept (so it can be retried) and raises RerenderError.
Returns ``{"brand_code", "previous_outputs", "cleanup_results", "warnings"}``.
Raises RerenderError (400/500/503) or RerenderConflictError (409).
"""
reason = validate_admin_rerender(job)
if reason:
raise RerenderError(reason)
plan = await asyncio.to_thread(plan_republish, job)
update, context = self._build_claim(job, requested_by, notify_customer, plan)
queue_outcome = await asyncio.to_thread(
claim_with_youtube_queue, self.job_manager.firestore.db, job.job_id, update,
_claimable_statuses(job), plan["youtube"][0], plan["youtube"][1],
)
context["youtube_queue"] = queue_outcome
if queue_outcome.get("warning"):
context["warnings"].append(queue_outcome["warning"])
job_id = job.job_id
try:
cleanup_results = await asyncio.to_thread(self._after_claim, job, context, plan)
from backend.services.worker_service import get_worker_service
triggered = await get_worker_service().trigger_screens_worker(job_id)
except Exception as e:
logger.exception(f"[job:{job_id}] Admin re-render failed after claim")
await asyncio.to_thread(self._fail_run, job_id, f"Admin re-render failed to start: {e}", "start_error")
raise RerenderError(
f"The re-render failed to start ({e}). The job was marked failed; retry it to continue.",
status_code=500,
) from e
if not triggered:
await asyncio.to_thread(
self._fail_run, job_id,
"Admin re-render couldn't start the screens worker. Retry the job to continue.",
"screens_trigger_failed",
)
raise RerenderError("Couldn't start the re-render. Please retry the job.", status_code=503)
await asyncio.to_thread(log_to_job, job_id, _LOG_SOURCE, "INFO",
"Re-render started (screens worker triggered)",
{"cleanup_results": cleanup_results})
return {
"brand_code": context["brand_code"],
"previous_outputs": context["previous_outputs"],
"cleanup_results": cleanup_results,
"warnings": context["warnings"],
}
def _build_claim(self, job, requested_by: str, notify_customer: bool, plan) -> Tuple[dict, dict]:
state_data = job.state_data or {}
# Only the ACTIVE (same-run) marker carries over: a stale one from an
# earlier run must not leak its brand code / history into this run.
previous_marker = active_admin_rerender(job)
# On a retry the re-published outputs were already removed (and cleared
# from state_data) by the first attempt — keep that attempt's record.
previous_outputs = {
**(previous_marker.get("previous_outputs") or {}),
**snapshot_published_outputs(state_data),
}
brand_code = state_data.get("brand_code") or previous_marker.get("brand_code")
is_retry = bool(previous_marker)
warnings: List[str] = []
kept_outputs: Dict[str, Any] = {}
for destination, (republish, why) in plan.items():
if not republish and _has_output(state_data, destination):
link_key = _DESTINATION_LINK[destination]
kept_outputs[link_key] = state_data[link_key]
warnings.append(f"{destination} output left in place (not re-published): {why}")
republish_youtube = plan["youtube"][0]
now = datetime.now(timezone.utc)
message = (
f"Admin re-render requested by {requested_by} "
f"(existing style, no review; brand code {brand_code or 'n/a'} kept; "
f"customer notification {'on' if notify_customer else 'off'})"
)
update: Dict[str, Any] = {
"status": JobStatus.LYRICS_COMPLETE.value,
"progress": 50,
"error_message": None,
"error_details": None,
"state_data.regen_restore_status": "review_complete",
"state_data.audio_complete": True,
"state_data.lyrics_complete": True,
"state_data.screens_progress": DELETE_FIELD,
"state_data.render_progress": DELETE_FIELD,
"state_data.video_progress": DELETE_FIELD,
"state_data.encoding_progress": DELETE_FIELD,
"state_data.distribution_warnings": DELETE_FIELD,
f"state_data.{ADMIN_RERENDER_MARKER}": {
"requested_by": requested_by,
"requested_at": now.isoformat(),
"notify_customer": bool(notify_customer),
"brand_code": brand_code,
"previous_outputs": previous_outputs,
"kept_outputs": kept_outputs,
"warnings": warnings,
"republish_youtube": republish_youtube,
# Run identity: a later trip through review mints a new token,
# which retires this marker (see active_admin_rerender).
"review_token": getattr(job, "review_token", None),
},
# Old screens are deleted after the claim; drop their file_urls so
# nothing (e.g. a later retry) reuses them.
"file_urls.screens": DELETE_FIELD,
"file_urls.videos.with_vocals": DELETE_FIELD,
"updated_at": now,
"timeline": ArrayUnion([{
"status": JobStatus.LYRICS_COMPLETE.value,
"timestamp": now.isoformat(),
"message": message,
"metadata": {
"action": "admin_rerender_initiated",
"initiated_by": requested_by,
"notify_customer": bool(notify_customer),
"brand_code": brand_code,
"previous_outputs": previous_outputs,
"kept_outputs": kept_outputs,
"warnings": warnings,
"retry": is_retry,
},
}]),
}
# Drop the links of outputs about to be deleted and re-published (dead
# links otherwise). brand_code stays — it's reused.
for destination, (republish, _) in plan.items():
if republish:
for key in _DESTINATION_KEYS[destination]:
update[f"state_data.{key}"] = DELETE_FIELD
# youtube_upload_queued is only cleared (and the deferred upload
# cancelled) when YouTube will be re-published — it's in
# _DESTINATION_KEYS["youtube"] above.
context = {
"message": message,
"brand_code": brand_code,
"previous_outputs": previous_outputs,
"warnings": warnings,
"notify_customer": bool(notify_customer),
"is_retry": is_retry,
"republish_youtube": republish_youtube,
}
return update, context
def _after_claim(self, job, context: dict, plan) -> Dict[str, Any]:
"""Blocking post-claim work: audit log, stale artifacts, published outputs."""
job_id = job.job_id
logger.info(
f"[job:{job_id}] Admin re-render claimed: brand_code={context['brand_code']} "
f"notify_customer={context['notify_customer']} retry={context['is_retry']} "
f"previous_outputs={sorted(context['previous_outputs'])} warnings={context['warnings']}"
)
log_to_job(job_id, _LOG_SOURCE, "INFO", context["message"], {
"previous_outputs": context["previous_outputs"],
"notify_customer": context["notify_customer"],
"retry": context["is_retry"],
})
for warning in context["warnings"]:
log_to_job(job_id, _LOG_SOURCE, "WARNING", warning)
delete_regenerated_artifacts(self.storage, job_id)
return self._delete_published_outputs(
job, job.state_data or {}, context["brand_code"], plan, context.get("youtube_queue")
)
def _fail_run(self, job_id: str, error: str, reason: str) -> None:
"""Mark the run FAILED, keeping the marker so it can be retried."""
logger.error(f"[job:{job_id}] {error}")
try:
self.job_manager.update_job(job_id, {
"status": JobStatus.FAILED.value,
"error_message": error,
"error_details": {"stage": "admin_rerender", "reason": reason},
"state_data.regen_restore_status": DELETE_FIELD,
})
log_to_job(job_id, _LOG_SOURCE, "ERROR", error)
except Exception:
logger.exception(f"[job:{job_id}] Failed to mark admin re-render as failed")
def _delete_published_outputs(
self, job, state_data: dict, brand_code: Optional[str], plan,
youtube_queue: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Delete outputs the re-render will re-publish; keep the rest. Best-effort.
Failures don't abort the re-render: the re-publish targets the same
names (same brand code), and the server-side YouTube upload and GDrive
upload both replace a same-named leftover, while Dropbox uploads overwrite.
"""
job_id = job.job_id
from backend.services.job_defaults_service import get_effective_distribution_for_job
def kept(destination):
return {"status": "kept", "reason": plan[destination][1]}
results: Dict[str, Any] = {}
results["youtube"] = (
delete_youtube_video(job_id, state_data.get("youtube_url"))
if plan["youtube"][0] else kept("youtube")
)
# Private jobs publish to the private Dropbox path, not job.dropbox_path.
results["dropbox"] = (
delete_dropbox_folder(
job_id, get_effective_distribution_for_job(job).dropbox_path,
brand_code, job.artist, job.title,
)
if plan["dropbox"][0] else kept("dropbox")
)
# Same brand code is re-published, so the kjbox GCS mirror copy is
# overwritten in place rather than removed.
results["gdrive"] = (
delete_gdrive_files(job_id, state_data.get("gdrive_files"), brand_code, cleanup_mirror=False)
if plan["gdrive"][0] else kept("gdrive")
)
# Handled atomically by the claim transaction (claim_with_youtube_queue).
results["youtube_queue"] = youtube_queue or {"status": "skipped", "reason": "no queue entry"}
results["brand_code"] = {"status": "kept", "code": brand_code}
for service in ("youtube", "dropbox", "gdrive", "youtube_queue"):
status = results[service].get("status")
level = "WARNING" if status in ("failed", "partial", "error", "kept", "processing") else "INFO"
log_to_job(job_id, _LOG_SOURCE, level, f"{service} cleanup: {status}", results[service])
logger.info(
f"[job:{job_id}] Admin re-render cleanup: "
+ ", ".join(f"{k}={v.get('status')}" for k, v in results.items())
)
try:
now = datetime.now(timezone.utc)
self.job_manager.update_job(job_id, {
f"state_data.{ADMIN_RERENDER_MARKER}.cleanup_results": results,
"timeline": ArrayUnion([{
"status": JobStatus.LYRICS_COMPLETE.value,
"timestamp": now.isoformat(),
"message": "Admin re-render: previous published outputs removed",
"metadata": {"action": "admin_rerender_cleanup", "cleanup_results": results},
}]),
})
except Exception as e: # audit only — never block the re-render
logger.warning(f"[job:{job_id}] Failed to record admin re-render cleanup results: {e}")
return results
+147 -9
View File
@@ -33,9 +33,12 @@ review. Auto-approval must never be the reason a job fails.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Tuple
from backend.models.job import JobStatus
from backend.services.auto_approval.instrumental import (
@@ -125,7 +128,16 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
audio_complete = bool(state_data.get("audio_complete", False))
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
verdict = score_job(corrections, backing_analysis, ai_suggestions)
# Missing-lyrics gate input: sung stretches the transcription has no words
# for. Gates only when reference lyrics put lines in the gap ("evidenced");
# fail-OPEN on pending audio / analysis errors (recorded below). Stem
# download + decode: keep it off the event loop.
vocal_gaps_info, vocal_gaps = await asyncio.to_thread(
_vocal_gaps_shadow,
job_id, job, corrections, ai_suggestions, stems, audio_complete, storage, job_manager,
)
verdict = score_job(corrections, backing_analysis, ai_suggestions, vocal_gaps=vocal_gaps)
# Timing-plausibility gate: word timing vs the lead-vocal stem. Audio
# IO (~15MB stem + a few seconds of numpy), so it runs only when the
@@ -154,7 +166,7 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
if signals.fired:
verdict = score_job(
corrections, backing_analysis, ai_suggestions,
timing_signals=signals,
timing_signals=signals, vocal_gaps=vocal_gaps,
)
blockers = _enforcement_blockers(job, settings)
@@ -216,6 +228,7 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
"trigger": trigger,
"enforcement_blockers": blockers,
"timing": timing_info,
"vocal_gaps": vocal_gaps_info,
"audio_complete_at_scoring": audio_complete,
"backing_analysis_available": backing_analysis is not None,
"ai_suggestions_available": ai_suggestions is not None,
@@ -324,6 +337,136 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
return {"outcome": "error", "error": str(e)}
def _published_segments(corrections, ai_suggestions):
"""The segments auto-ship would publish: raw + auto-applied AI suggestions."""
from backend.services.auto_approval.apply import build_applied_segments
segments = corrections.get("corrected_segments") or []
if ai_suggestions:
applied = build_applied_segments(corrections, ai_suggestions)
if not applied.get("aborted"):
segments = applied["segments"]
return segments
def analyze_vocal_gaps(job_id, corrections, segments, stems, storage):
"""Download the lead-vocal stem and find sung stretches with no transcribed words.
Returns ``None`` when no lead/vocals stem is registered, else a
``VocalGapsResult`` (``.error`` set on analysis failure). Never raises.
"""
import os
import tempfile
from backend.services.auto_approval.vocal_gaps import VocalGapsResult, compute_vocal_gaps
stem_path = stems.get("lead_vocals") or stems.get("vocals_clean")
if not stem_path:
return None
try:
with tempfile.TemporaryDirectory() as temp_dir:
local = os.path.join(temp_dir, "lead_vocals.flac")
storage.download_file(stem_path, local)
result = compute_vocal_gaps(segments, local, corrections)
logger.info(
f"[job:{job_id}] vocal gaps: {len(result.gaps)} gap(s), "
f"suspect={result.suspect_count} max_run={result.max_suspect_run_s}s error={result.error}"
)
return result
except Exception as e: # noqa: BLE001 — shadow analysis is best-effort
logger.warning(f"[job:{job_id}] vocal gap analysis failed non-fatally: {e}")
return VocalGapsResult(error=str(e))
def vocal_gaps_input_key(segments, stems) -> str:
"""Fingerprint of what a vocal-gap analysis looked at: word timings, stem, detector
version. A reset, re-transcription, audio edit or new AI suggestions changes it."""
from backend.services.auto_approval.vocal_gaps import VOCAL_GAPS_VERSION
words = [(w.get("id"), round(w.get("start_time") or 0, 2), round(w.get("end_time") or 0, 2))
for seg in segments for w in (seg.get("words") or [])]
stem = stems.get("lead_vocals") or stems.get("vocals_clean")
blob = json.dumps([VOCAL_GAPS_VERSION, stem, words], ensure_ascii=False)
return hashlib.sha1(blob.encode("utf-8")).hexdigest()[:16]
def _vocal_gaps_shadow(job_id, job, corrections, ai_suggestions, stems, audio_complete,
storage, job_manager) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]:
"""Analyze when stems exist and store ``state_data.vocal_gaps``; reuse a stored
result only if it was computed from the same lyrics + stem (``input_key``).
Returns ``(summary for the payload, full vocal-gaps dict or None)``. Never raises.
Blocking (stem download + decode): call via ``asyncio.to_thread``.
"""
try:
if not audio_complete:
return {"status": "pending_audio"}, None
segments = _published_segments(corrections, ai_suggestions)
input_key = vocal_gaps_input_key(segments, stems)
existing = (job.state_data or {}).get("vocal_gaps")
if existing and existing.get("input_key") == input_key:
return {"status": "cached", "suspect_count": existing.get("suspect_count"),
"evidenced_count": existing.get("evidenced_count", 0),
"max_suspect_run_s": existing.get("max_suspect_run_s")}, existing
result = analyze_vocal_gaps(job_id, corrections, segments, stems, storage)
if result is None:
return {"status": "no_lead_stem"}, None
if result.error:
return {"status": "error", "error": result.error}, None
stored = {**result.to_dict(), "analyzed_at": datetime.now(timezone.utc).isoformat(),
"source": "auto_approval", "input_key": input_key}
job_manager.update_state_data(job_id, "vocal_gaps", stored)
return {"status": "checked", "suspect_count": result.suspect_count,
"evidenced_count": result.evidenced_count,
"max_suspect_run_s": result.max_suspect_run_s}, stored
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] vocal gap analysis failed non-fatally: {e}")
return {"status": "error", "error": str(e)}, None
def analyze_job_vocal_gaps(job_id: str, store: bool = True) -> Dict[str, Any]:
"""Backfill/inspect: vocal gaps for the lyrics a job actually has now.
Uses the reviewed ``corrections_updated.json`` segments when present (what was
rendered), with reference lyrics + anchors from ``corrections.json``. Runs
synchronously (stem download + numpy, a few seconds). Never raises.
"""
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
try:
job_manager, storage = JobManager(), StorageService()
job = job_manager.get_job(job_id)
if not job:
return {"status": "no_job"}
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
if not storage.file_exists(corrections_path):
return {"status": "no_corrections"}
corrections = storage.download_json(corrections_path)
segments = corrections.get("corrected_segments") or []
lyrics_source = "corrections"
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
if storage.file_exists(updated_path):
updated = storage.download_json(updated_path)
if updated.get("corrected_segments"):
segments, lyrics_source = updated["corrected_segments"], "corrections_updated"
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
result = analyze_vocal_gaps(job_id, corrections, segments, stems, storage)
if result is None:
return {"status": "no_lead_stem"}
if result.error:
return {"status": "error", "error": result.error}
payload = {**result.to_dict(), "analyzed_at": datetime.now(timezone.utc).isoformat(),
"source": "backfill", "lyrics_source": lyrics_source,
"input_key": vocal_gaps_input_key(segments, stems)}
if store:
job_manager.update_state_data(job_id, "vocal_gaps", payload)
return {"status": "checked", "stored": store, "vocal_gaps": payload}
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] vocal gap backfill failed: {e}")
return {"status": "error", "error": str(e)}
def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage):
"""Download the lead-vocal stem and run the timing-plausibility analysis
on the POST-AI word stream (the state auto-ship would publish).
@@ -335,7 +478,6 @@ def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage)
import os
import tempfile
from backend.services.auto_approval.apply import build_applied_segments
from backend.services.auto_approval.timing_check import (
TimingSignals,
compute_timing_signals,
@@ -348,11 +490,7 @@ def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage)
# The published state is raw + auto-applied suggestions; on an apply
# abort the executor falls back to human review anyway, so analyzing
# the raw segments there is only shadow data.
segments = corrections.get("corrected_segments") or []
if ai_suggestions:
applied = build_applied_segments(corrections, ai_suggestions)
if not applied.get("aborted"):
segments = applied["segments"]
segments = _published_segments(corrections, ai_suggestions)
with tempfile.TemporaryDirectory() as temp_dir:
local = os.path.join(temp_dir, "lead_vocals.flac")
storage.download_file(stem_path, local)
+38 -2
View File
@@ -41,7 +41,7 @@ from backend.services.auto_approval.models import (
LyricsVerdict,
)
SCORER_VERSION = "0.4.0"
SCORER_VERSION = "0.5.0"
# --- Lyrics thresholds (deliberately conservative; the safe intersection first) ---
# The AUTO tier requires a synced reference the transcription matches with ZERO
@@ -373,13 +373,43 @@ def extract_lyrics_signals(
)
def _fmt_time(seconds: float) -> str:
return f"{int(seconds // 60)}:{int(seconds % 60):02d}"
def missing_lyrics_reasons(vocal_gaps: Optional[Dict[str, Any]]) -> List[str]:
"""Human-readable reasons for each evidenced vocal gap (sung, no lyrics, and the
reference lyrics put lines there). Empty when there's nothing to flag."""
reasons = []
for gap in (vocal_gaps or {}).get("gaps") or []:
if not gap.get("evidenced"):
continue
lines = max(
[len(v) for v in (gap.get("synced_reference_lines") or {}).values()]
+ [len(v) for v in (gap.get("reference_lines") or {}).values()] + [0]
)
reasons.append(
f"possible missing lyrics: ~{gap['longest_run_s']:.0f}s of singing at "
f"{_fmt_time(gap['start'])}-{_fmt_time(gap['end'])} has no transcribed words, and the "
f"reference lyrics have {lines} line(s) there"
)
return reasons
def score_lyrics(
correction_data: Dict[str, Any],
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
timing_signals: Optional[Any] = None,
vocal_gaps: Optional[Dict[str, Any]] = None,
) -> LyricsResult:
"""Decide whether the lyrics look safe to auto-approve.
``vocal_gaps`` (a stored ``VocalGapsResult`` dict) is a never-auto gate when any
gap is *evidenced*: the lead vocal sings for >=3s with no transcribed words AND
the reference lyrics place lines there (transcription dropped them — anchor
coverage can't see omissions). Audio-only gaps don't gate (2026-10 audit:
~25% precision without reference evidence).
``timing_signals`` (a ``timing_check.TimingSignals``) is optional because
computing it needs the lead-vocal stem (audio IO the executor performs only
when the text signals would otherwise be AUTO). When provided and fired,
@@ -416,6 +446,11 @@ def score_lyrics(
)
return LyricsResult(LyricsVerdict.REVIEW, "phantom-gate", s, reasons)
missing = missing_lyrics_reasons(vocal_gaps)
if missing:
reasons.extend(missing)
return LyricsResult(LyricsVerdict.REVIEW, "missing-lyrics-gate", s, reasons)
if timing_signals is not None and getattr(timing_signals, "fired", None):
sig = timing_signals
reasons.append(
@@ -635,13 +670,14 @@ def score_job(
backing_analysis: Optional[Dict[str, Any]],
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
timing_signals: Optional[Any] = None,
vocal_gaps: Optional[Dict[str, Any]] = None,
) -> AutoApprovabilityVerdict:
"""Produce the combined shadow verdict for a job.
``overall_auto`` is the narrow safe intersection: confident lyrics AND a
non-subjective (no-audible-backing) backing decision.
"""
lyrics = score_lyrics(correction_data, ai_suggestions, timing_signals)
lyrics = score_lyrics(correction_data, ai_suggestions, timing_signals, vocal_gaps)
backing = score_backing(backing_analysis)
overall_auto = lyrics.verdict == LyricsVerdict.AUTO and backing.non_subjective
return AutoApprovabilityVerdict(
@@ -0,0 +1,293 @@
"""Vocal gaps: stretches where the lead vocal is singing but the transcription has no words.
Transcription can silently drop whole sung lines (job 5710831e: 11.7s of a Hebrew
pre-chorus, three lines, no words at all). Nothing downstream notices:
- the scorer's anchor coverage is the fraction of *transcribed* words that match the
reference, so omitted lines don't lower it;
- ``SectionDetector`` labels any >=10s gap between segments "INSTRUMENTAL" without
looking at the audio, so the video shows "♪ INSTRUMENTAL ♪" over singing;
- a reviewer who doesn't read the language can't see that lines are missing.
For every transcription gap of at least ``MIN_GAP_S`` this measures how much of it the
lead-vocal stem is active (short breaths bridged), and which reference lyrics sit
between the reference positions of the words either side of the gap. Lines in the
reference there are the strongest evidence that lyrics were dropped rather than the gap
being ad-libs or a vocal sample.
Shadow-only for now: results are stored on the job (``state_data.vocal_gaps``) for
calibration before anything gates on them.
"""
from __future__ import annotations
import logging
from dataclasses import asdict, dataclass, field
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from backend.services.auto_approval.timing_check import _load_mono, _rms_activity
logger = logging.getLogger(__name__)
VOCAL_GAPS_VERSION = "0.2.0"
MIN_GAP_S = 3.0 # shorter gaps are normal phrasing
BREATH_BRIDGE_S = 0.5 # silences this short inside singing don't end a vocal run
# Shadow "suspect" threshold — calibrate on the backfill audit. Keyed on the longest
# continuous (breath-bridged) vocal run, NOT the gap's active fraction: dropped lines
# followed by an instrumental inside one transcription gap dilute the fraction (a 4s
# dropped line in a 20s gap is only 20% active). On job 5710831e genuine
# instrumentals peaked at 0.16s runs vs 11.76s for the dropped lines.
SUSPECT_MIN_RUN_S = 3.0
# A vocal run that starts at the gap's first frame is usually the previous word's held
# note (transcribed end_time under-extended — a known AudioShake failure). Don't count
# its first seconds as "unlyricked"; dropped lines run far longer (11.76s on 5710831e).
# Held notes up to ALLOWANCE + SUSPECT_MIN_RUN_S (4.5s) past the word's end are tolerated.
HELD_NOTE_ALLOWANCE_S = 1.5 # calibrate with the audit; 2.0 hid a single 4s dropped line
MAX_REFERENCE_LINES = 12 # more than this between anchors = misaligned anchors, not a gap
@dataclass
class VocalGap:
start: float
end: float
duration: float
active_fraction: float # share of the gap where the lead vocal is active
longest_run_s: float # longest vocal run inside the gap, breaths bridged
reference_lines: Dict[str, List[str]] = field(default_factory=dict) # source -> lines
# Synced reference lines (e.g. LRCLIB) whose timestamp falls inside the gap
synced_reference_lines: Dict[str, List[str]] = field(default_factory=dict)
suspect: bool = False # sung run long enough to be dropped lyrics (audio only)
evidenced: bool = False # suspect AND reference lyrics place lines in this gap
@dataclass
class VocalGapsResult:
version: str = VOCAL_GAPS_VERSION
gaps: List[VocalGap] = field(default_factory=list)
suspect_count: int = 0
evidenced_count: int = 0
max_suspect_run_s: float = 0.0
error: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
# ---- transcription gaps ---------------------------------------------------------
def _words(segments: List[dict]) -> List[dict]:
words = [w for seg in segments for w in (seg.get("words") or [])
if w.get("start_time") is not None and w.get("end_time") is not None]
return sorted(words, key=lambda w: w["start_time"])
def transcription_gaps(segments: List[dict], audio_duration: float,
min_gap_s: float = MIN_GAP_S) -> List[Tuple[float, float, Optional[dict], Optional[dict]]]:
"""(start, end, word_before, word_after) for every gap >= ``min_gap_s``.
Includes the stretch before the first word and after the last one.
"""
words = _words(segments)
gaps = []
cursor, prev = 0.0, None
for w in words:
if w["start_time"] - cursor >= min_gap_s:
gaps.append((cursor, w["start_time"], prev, w))
cursor = max(cursor, w["end_time"])
prev = w
if audio_duration - cursor >= min_gap_s:
gaps.append((cursor, audio_duration, prev, None))
return gaps
# ---- vocal activity -------------------------------------------------------------
def _bridge(active: np.ndarray, max_gap_frames: int) -> np.ndarray:
"""Fill inactive runs of <= ``max_gap_frames`` that sit between active frames."""
out = active.copy()
idx = np.flatnonzero(active)
if len(idx) < 2:
return out
for a, b in zip(idx[:-1], idx[1:]):
if 1 < b - a <= max_gap_frames + 1:
out[a:b] = True
return out
def _longest_run(mask: np.ndarray) -> int:
best = run = 0
for v in mask:
run = run + 1 if v else 0
best = max(best, run)
return best
# ---- reference lines in a gap ---------------------------------------------------
def _reference_index(correction_data: Dict[str, Any]) -> Dict[str, Dict[str, Tuple[int, int, int]]]:
"""source -> reference word id -> (line index, word index within line, line length)."""
index: Dict[str, Dict[str, Tuple[int, int, int]]] = {}
for source, ref in (correction_data.get("reference_lyrics") or {}).items():
ids: Dict[str, Tuple[int, int, int]] = {}
for li, seg in enumerate((ref or {}).get("segments") or []):
seg_words = seg.get("words") or []
for wi, w in enumerate(seg_words):
if w.get("id"):
ids[w["id"]] = (li, wi, len(seg_words))
index[source] = ids
return index
def _transcribed_to_reference(correction_data: Dict[str, Any]) -> Dict[str, Dict[str, List[str]]]:
"""transcribed word id -> source -> reference word ids (anchors + gap sequences)."""
mapping: Dict[str, Dict[str, List[str]]] = {}
for seq in (correction_data.get("anchor_sequences") or []) + (correction_data.get("gap_sequences") or []):
t_ids = seq.get("transcribed_word_ids") or []
r_ids = seq.get("reference_word_ids") or {}
for source, refs in r_ids.items():
if len(refs) == len(t_ids): # anchors: 1:1 by position
for t, r in zip(t_ids, refs):
mapping.setdefault(t, {})[source] = [r]
else: # gap sequences: not aligned word-for-word
for t in t_ids:
mapping.setdefault(t, {})[source] = list(refs)
return mapping
def reference_lines_between(correction_data: Dict[str, Any], word_before: Optional[dict],
word_after: Optional[dict], _indexes=None) -> Dict[str, List[str]]:
"""Reference lines strictly between the reference positions of the words around a gap.
Only whole reference lines are returned, and only when both neighbours map to the
same source in increasing order (repeated choruses can anchor to a different
occurrence; those cases return nothing rather than a misleading span).
"""
if not word_before or not word_after:
return {}
ref_index, t2r = _indexes or (_reference_index(correction_data), _transcribed_to_reference(correction_data))
before = t2r.get(word_before.get("id"), {})
after = t2r.get(word_after.get("id"), {})
out: Dict[str, List[str]] = {}
for source in set(before) & set(after):
ids = ref_index.get(source, {})
b = [ids[r] for r in before[source] if r in ids]
a = [ids[r] for r in after[source] if r in ids]
if not b or not a:
continue
b_line, b_word, _ = max(b, key=lambda x: (x[0], x[1]))
a_line, a_word, a_len = min(a, key=lambda x: (x[0], x[1]))
# Anchor reference ids can be off by one word at line boundaries (section
# headers like "[Chorus]" tokenised differently): a gap's preceding word
# "landing" on the first word of a line really ended the previous line, and
# a following word landing on the last word of a line starts the next one.
b_len = len(correction_data["reference_lyrics"][source]["segments"][b_line].get("words") or [])
if b_word == 0 and b_len > 1:
b_line -= 1
if a_word == a_len - 1 and a_len > 1:
a_line += 1
# Whole lines only: after the line holding word_before, before the line of word_after
first, last = b_line + 1, a_line - 1
if first > last or last - first + 1 > MAX_REFERENCE_LINES:
continue
segs = correction_data["reference_lyrics"][source]["segments"]
lines = [(segs[i].get("text") or "").strip() for i in range(first, last + 1)]
lines = [l for l in lines if l and not (l.startswith("[") and l.endswith("]"))] # drop [Chorus] headers
if lines:
out[source] = lines
return out
# ---- synced reference lines in a gap ---------------------------------------------
SYNCED_EDGE_S = 0.5 # line must start this far inside the gap (tolerates small offsets)
def _synced_reference_lines(correction_data: Dict[str, Any]) -> Dict[str, List[Tuple[float, str]]]:
"""source -> [(line start time, text)] for reference sources with word timings."""
out: Dict[str, List[Tuple[float, str]]] = {}
for source, ref in (correction_data.get("reference_lyrics") or {}).items():
lines = []
for seg in (ref or {}).get("segments") or []:
starts = [w.get("start_time") for w in seg.get("words") or [] if w.get("start_time") is not None]
text = (seg.get("text") or "").strip()
if starts and text and not (text.startswith("[") and text.endswith("]")):
lines.append((float(starts[0]), text))
if lines:
out[source] = lines
return out
def synced_lines_in_gap(synced: Dict[str, List[Tuple[float, str]]], start: float, end: float) -> Dict[str, List[str]]:
"""Synced reference lines that start inside (start, end), with an edge tolerance.
On the 2026-10 audit this was the most reliable evidence of dropped lyrics: only ~25%
of audio-only suspect gaps had a synced reference line inside them.
"""
found = {src: [t for ts, t in lines if start + SYNCED_EDGE_S <= ts <= end - SYNCED_EDGE_S]
for src, lines in synced.items()}
return {src: lines for src, lines in found.items() if lines}
# ---- entry point ----------------------------------------------------------------
def compute_vocal_gaps(segments: List[dict], lead_vocals_path: str,
correction_data: Optional[Dict[str, Any]] = None) -> VocalGapsResult:
"""Never raises: failures return ``VocalGapsResult(error=...)``."""
try:
samples, sr = _load_mono(lead_vocals_path)
active, frame_s = _rms_activity(samples, sr)
if len(active) == 0 or not active.any():
# A failed separation must not be recorded as a clean "no gaps" pass
return VocalGapsResult(error="empty or silent lead-vocal audio")
bridged = _bridge(active, int(round(BREATH_BRIDGE_S / frame_s)))
duration = len(active) * frame_s
allowance = int(round(HELD_NOTE_ALLOWANCE_S / frame_s))
correction_data = correction_data or {}
try:
indexes = (_reference_index(correction_data), _transcribed_to_reference(correction_data))
except Exception as e: # noqa: BLE001 — reference evidence is secondary
logger.warning("vocal gaps: reference index failed: %s", e)
indexes = None
try:
synced = _synced_reference_lines(correction_data)
except Exception as e: # noqa: BLE001
logger.warning("vocal gaps: synced reference parse failed: %s", e)
synced = {}
result = VocalGapsResult()
for start, end, before, after in transcription_gaps(segments, duration):
i0, i1 = int(start / frame_s), min(len(active), int(np.ceil(end / frame_s)))
if i1 <= i0:
continue
frac = float(active[i0:i1].mean())
window = bridged[i0:i1].copy()
# Discount a held note carried over from the word before the gap
if before is not None and window[0]:
window[:allowance] = False
run_s = _longest_run(window) * frame_s
try:
refs = reference_lines_between(correction_data, before, after, indexes) if indexes else {}
except Exception as e: # noqa: BLE001 — never lose the audio result to bad reference data
logger.warning("vocal gaps: reference lookup failed: %s", e)
refs = {}
gap = VocalGap(
start=round(start, 2), end=round(end, 2), duration=round(end - start, 2),
active_fraction=round(frac, 3), longest_run_s=round(run_s, 2),
reference_lines=refs,
)
gap.synced_reference_lines = synced_lines_in_gap(synced, start, end)
gap.suspect = run_s >= SUSPECT_MIN_RUN_S
gap.evidenced = gap.suspect and bool(gap.reference_lines or gap.synced_reference_lines)
result.gaps.append(gap)
suspects = [g for g in result.gaps if g.suspect]
result.suspect_count = len(suspects)
result.evidenced_count = sum(1 for g in suspects if g.evidenced)
result.max_suspect_run_s = max((g.longest_run_s for g in suspects), default=0.0)
return result
except Exception as e: # noqa: BLE001 — shadow analysis is best-effort
logger.warning("vocal gap analysis failed: %s", e, exc_info=True)
return VocalGapsResult(error=str(e))
@@ -305,6 +305,9 @@ class CreditEvaluationService:
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
+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 ""
+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"
+35 -3
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,
@@ -494,6 +496,9 @@ class JobManager:
state_data_updates: Optional[Dict[str, Any]] = None,
raise_on_invalid: bool = True,
timeline_metadata: Optional[Dict[str, Any]] = None,
notify: bool = True,
extra_updates: Optional[Dict[str, Any]] = None,
count_completion: bool = True,
) -> bool:
"""
Transition job to new state with validation.
@@ -507,6 +512,14 @@ class JobManager:
raise_on_invalid: If True (default), raise InvalidStateTransitionError
on invalid transitions. If False, return False silently.
timeline_metadata: Optional structured metadata to attach to the timeline event
notify: If False, skip the user email/push notifications for this
transition (e.g. an admin re-render the admin didn't opt
into announcing to the customer).
extra_updates: Additional Firestore field updates (dot paths allowed,
e.g. ``{"state_data.admin_rerender": DELETE_FIELD}``) written
in the SAME update as the status change.
count_completion: If False, don't increment the user's completed-jobs
counter on COMPLETE (an admin re-render isn't a new job).
Returns:
True if transition succeeded, False if failed (only when raise_on_invalid=False)
@@ -514,6 +527,17 @@ class JobManager:
Raises:
InvalidStateTransitionError: If transition is invalid and raise_on_invalid=True
"""
if state_data_updates and any(
key == "state_data" or key.startswith("state_data.") for key in (extra_updates or {})
):
# state_data_updates rewrites the whole state_data map; a dot-path
# write to state_data.* in the same Firestore update is a
# conflicting-path error (and would be ambiguous anyway).
raise ValueError(
"transition_to_state: pass state_data changes via state_data_updates OR "
"extra_updates['state_data.*'], not both"
)
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
return False
@@ -542,6 +566,7 @@ class JobManager:
merged_state_data = {**job.state_data, **state_data_updates}
# Update job status (includes timeline event), passing state_data if present
extra = dict(extra_updates or {})
if merged_state_data is not None:
self.update_job_status(
job_id=job_id,
@@ -549,7 +574,8 @@ class JobManager:
progress=progress,
message=message,
timeline_metadata=timeline_metadata,
state_data=merged_state_data
state_data=merged_state_data,
**extra,
)
else:
self.update_job_status(
@@ -558,6 +584,7 @@ class JobManager:
progress=progress,
message=message,
timeline_metadata=timeline_metadata,
**extra,
)
# Apply review token update separately if generated
@@ -570,7 +597,9 @@ class JobManager:
logger.info(f"Job {job_id} transitioned to {new_status}")
# Increment user's completed jobs counter on terminal success states
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE) and not count_completion:
logger.info(f"Job {job_id}: completion not counted towards the user's jobs_completed")
elif new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
try:
job = self.get_job(job_id)
if job and job.user_email:
@@ -581,7 +610,10 @@ class JobManager:
logger.exception(f"Failed to increment jobs_completed for job {job_id}")
# Trigger notifications asynchronously (fire-and-forget)
self._trigger_state_notifications(job_id, new_status)
if notify:
self._trigger_state_notifications(job_id, new_status)
else:
logger.info(f"Job {job_id}: notifications suppressed for transition to {new_status}")
return True
+341
View File
@@ -0,0 +1,341 @@
"""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 import genai
from google.genai import types
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=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:
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)
+3
View File
@@ -169,6 +169,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)
@@ -219,6 +219,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)
+3
View File
@@ -143,6 +143,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)
@@ -0,0 +1,158 @@
"""
Delete a job's published (distributed) outputs: YouTube video, Dropbox folder,
Google Drive files.
Shared by the track Edit flow (``POST /api/jobs/{id}/edit``) and the admin
re-render (``POST /api/admin/jobs/{id}/rerender``). Each helper returns a small
result dict (``{"status": "success" | "failed" | "partial" | "skipped" |
"error", ...}``) suitable for the job timeline and API responses, and never
raises — the caller decides which failures are fatal.
Brand-code recycling is deliberately NOT done here: Edit recycles the code,
the admin re-render keeps it and re-publishes under the same code.
"""
import logging
import re
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
_YOUTUBE_ID_RE = re.compile(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)')
# state_data keys that point at published outputs.
PUBLISHED_OUTPUT_KEYS = ("youtube_url", "dropbox_link", "brand_code", "gdrive_files")
def snapshot_published_outputs(state_data: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""The job's current published-output references (for the timeline/audit)."""
state_data = state_data or {}
return {key: state_data[key] for key in PUBLISHED_OUTPUT_KEYS if state_data.get(key)}
def youtube_video_id(youtube_url: Optional[str]) -> Optional[str]:
match = _YOUTUBE_ID_RE.search(youtube_url or "")
return match.group(1) if match else None
def delete_youtube_video(job_id: str, youtube_url: Optional[str]) -> Dict[str, Any]:
"""Delete the job's YouTube video (via the server-side YouTube credentials)."""
if not youtube_url:
return {"status": "skipped", "reason": "no youtube_url"}
video_id = None
try:
# Inside the try: a malformed (e.g. non-string) URL must not raise.
video_id = youtube_video_id(youtube_url)
if not video_id:
return {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if not youtube_service.is_configured:
return {"status": "skipped", "reason": "YouTube not configured"}
finalise = KaraokeFinalise(
dry_run=False,
non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict(),
)
success = finalise.delete_youtube_video(video_id)
return {"status": "success" if success else "failed", "video_id": video_id}
except Exception as e:
logger.error(f"[job:{job_id}] Error deleting YouTube video {video_id}: {e}", exc_info=True)
return {"status": "error", "error": str(e), "video_id": video_id}
def legacy_dropbox_folder_path(
dropbox_path: str, brand_code: str, artist: Optional[str], title: Optional[str]
) -> str:
"""Raw-name folder (no sanitisation) that older Edit/delete code assumed."""
return f"{dropbox_path}/{brand_code} - {artist or 'Unknown'} - {title or 'Unknown'}"
def dropbox_folder_path(dropbox_path: str, brand_code: str, artist: Optional[str], title: Optional[str]) -> str:
"""The Dropbox folder the distribution step uploads to (same sanitisation)."""
from karaoke_gen.utils import sanitize_filename
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
return f"{dropbox_path}/{brand_code} - {safe_artist} - {safe_title}"
def delete_dropbox_folder(
job_id: str,
dropbox_path: Optional[str],
brand_code: Optional[str],
artist: Optional[str],
title: Optional[str],
) -> Dict[str, Any]:
"""Delete the job's ``{dropbox_path}/{brand_code} - {Artist} - {Title}`` folder.
The uploader sanitises artist/title; older code paths assumed the raw names.
When the two differ, both are checked and whichever exists is deleted.
``success`` (which lets callers recycle the brand code) only when no folder
remains; ``deleted`` lists what was removed.
"""
if not (brand_code and dropbox_path):
return {"status": "skipped", "reason": "no brand_code or dropbox_path"}
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if not dropbox.is_configured:
return {"status": "skipped", "reason": "Dropbox not configured"}
full_path = dropbox_folder_path(dropbox_path, brand_code, artist, title)
legacy_path = legacy_dropbox_folder_path(dropbox_path, brand_code, artist, title)
candidates = [full_path] if legacy_path == full_path else [full_path, legacy_path]
deleted, failed = [], []
for path in candidates:
if len(candidates) > 1:
try:
if not dropbox.file_exists(path):
continue
except Exception as e: # unknown → attempt the delete anyway
logger.warning(f"[job:{job_id}] Dropbox existence check failed for {path}: {e}")
# delete_folder is True when deleted OR already absent.
(deleted if dropbox.delete_folder(path) else failed).append(path)
result = {"status": "failed" if failed else "success", "path": full_path, "deleted": deleted}
if failed:
result["failed"] = failed
return result
except Exception as e:
logger.error(f"[job:{job_id}] Error deleting Dropbox folder: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
def delete_gdrive_files(
job_id: str,
gdrive_files: Optional[Dict[str, str]],
brand_code: Optional[str] = None,
cleanup_mirror: bool = True,
) -> Dict[str, Any]:
"""Delete the job's Google Drive public-share files.
``cleanup_mirror`` also removes the Nomad 720p master from the GCS
fast-sync mirror (kjbox). A re-render that re-publishes under the same brand
code skips it: the new upload overwrites the same mirror object, so kjbox
keeps the old master until the new one lands instead of losing the song.
"""
if not gdrive_files:
return {"status": "skipped", "reason": "no gdrive_files"}
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if not gdrive.is_configured:
return {"status": "skipped", "reason": "Google Drive not configured"}
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
if cleanup_mirror:
# Prefix-keyed by brand_code, so it covers renames. Non-fatal,
# Nomad-brand only, no-op otherwise.
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
return {"status": "success" if all_success else "partial", "files": delete_results}
except Exception as e:
logger.error(f"[job:{job_id}] Error deleting Google Drive files: {e}", exc_info=True)
return {"status": "error", "error": str(e)}
+3
View File
@@ -475,6 +475,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,
+65 -45
View File
@@ -96,15 +96,71 @@ def validate_rerender(job) -> Optional[str]:
def rerender_brand_code(job) -> Optional[str]:
"""Brand code a theme re-render must reuse, if one is in progress.
"""Brand code a re-render (theme or admin) must reuse, if one is in progress.
A re-render refreshes the job's existing Dropbox folder (uploads overwrite)
instead of allocating a new code. Scoped to the re-render marker (cleared on
success) rather than the job's ``keep_brand_code`` field so a later Edit,
which recycles the code, can't reuse it.
A re-render refreshes the job's existing Dropbox folder / re-publishes under
the same code instead of allocating a new one. Scoped to the re-render
marker (cleared on success) rather than the job's ``keep_brand_code`` field
so a later Edit, which recycles the code, can't reuse it.
"""
marker = (getattr(job, "state_data", None) or {}).get("theme_rerender") or {}
return marker.get("brand_code") or None
state_data = getattr(job, "state_data", None) or {}
code = (state_data.get("theme_rerender") or {}).get("brand_code")
if code:
return code
# Admin re-render (only while its marker belongs to the current run).
from backend.services.admin_rerender_service import admin_rerender_brand_code
return admin_rerender_brand_code(job)
def delete_regenerated_artifacts(storage: StorageService, job_id: str) -> None:
"""Best-effort removal of everything a re-render regenerates.
The GCE encoder looks up the title/end MOV with ``**/*Title*.mov`` /
``**/*End*.mov`` across everything it downloaded from ``jobs/{id}/``, so
once ``screens/title.mov`` is gone it would pick up the OLD
``finals/<Artist> - <Title> (Title).mov`` (or ``finals/title_mov.mov``)
and splice the old intro/outro around the new lyrics video.
finals/ only holds MOVs for those title/end cards, so drop every MOV there.
The MP4/MKV/zip finals stay (overwritten by the re-render).
"""
paths = [f"jobs/{job_id}/{rel}" for rel in _REGENERATED_ARTIFACTS]
try:
paths += [
p for p in storage.list_files(f"jobs/{job_id}/finals/")
if p.lower().endswith(".mov")
]
except Exception as e:
logger.warning(f"[job:{job_id}] Re-render: failed to list finals: {e}")
for path in paths:
try:
storage.delete_file(path, ignore_missing=True)
except Exception as e: # best-effort, like the visibility flow
logger.warning(f"[job:{job_id}] Re-render: failed to delete {path}: {e}")
def claim_for_rerender(db, job_id: str, update: dict, allowed_statuses: set) -> None:
"""Atomically apply ``update`` iff the job's status is still claimable.
Raises RerenderConflictError otherwise (e.g. a double-click already
started a re-render).
"""
from backend.config import get_settings
# Same collection the YouTube queue's mark_processing transaction reads, so
# the two claims always contend on the same job document.
job_ref = db.collection(get_settings().firestore_collection).document(job_id)
@firestore.transactional
def claim(transaction):
snapshot = job_ref.get(transaction=transaction)
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
if status not in allowed_statuses:
return False
transaction.update(job_ref, update)
return True
if not claim(db.transaction()):
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
class ThemeRerenderService:
@@ -190,43 +246,7 @@ class ThemeRerenderService:
logger.info(f"[job:{job_id}] Re-render with theme '{theme_id}' started by {requested_by}")
def _delete_stale_artifacts(self, job_id: str) -> None:
"""Best-effort removal of everything the re-render regenerates.
The GCE encoder looks up the title/end MOV with ``**/*Title*.mov`` /
``**/*End*.mov`` across everything it downloaded from ``jobs/{id}/``, so
once ``screens/title.mov`` is gone it would pick up the OLD
``finals/<Artist> - <Title> (Title).mov`` (or ``finals/title_mov.mov``)
and splice the old theme's intro/outro around the new lyrics video.
finals/ only holds MOVs for those title/end cards, so drop every MOV there.
The MP4/MKV/zip finals stay (overwritten by the re-render).
"""
paths = [f"jobs/{job_id}/{rel}" for rel in _REGENERATED_ARTIFACTS]
try:
paths += [
p for p in self.storage.list_files(f"jobs/{job_id}/finals/")
if p.lower().endswith(".mov")
]
except Exception as e:
logger.warning(f"[job:{job_id}] Re-render: failed to list finals: {e}")
for path in paths:
try:
self.storage.delete_file(path, ignore_missing=True)
except Exception as e: # best-effort, like the visibility flow
logger.warning(f"[job:{job_id}] Re-render: failed to delete {path}: {e}")
delete_regenerated_artifacts(self.storage, job_id)
def _claim(self, job_id: str, update: dict, allowed_statuses: set) -> None:
"""Atomically apply ``update`` iff the job's status is still claimable."""
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
@firestore.transactional
def claim(transaction):
snapshot = job_ref.get(transaction=transaction)
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
if status not in allowed_statuses:
return False
transaction.update(job_ref, update)
return True
if not claim(db.transaction()):
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
claim_for_rerender(self.job_manager.firestore.db, job_id, update, allowed_statuses)
+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': ['每晚我都跟着唱', '灯光暗下,这是我的歌', '握紧麦克风,登上舞台', '翻过这一页,翻过这一页']}}
@@ -194,6 +194,8 @@ class VisibilityChangeService:
job_id=job_id, theme_id="nomad"
)
from backend.services.admin_rerender_service import clear_admin_rerender_update
# Step 4: Reset styles and update job fields
# Step 5: Set status to LYRICS_COMPLETE with regen_restore_status
# Step 6: Clear progress keys and set guard flag
@@ -215,6 +217,9 @@ class VisibilityChangeService:
"outputs_deleted_at": None,
"outputs_deleted_by": None,
"updated_at": datetime.now(timezone.utc),
# New run (new theme, new brand code): drop any failed admin
# re-render's marker so it can't suppress notifications here.
**clear_admin_rerender_update(job),
"timeline": ArrayUnion([{
"status": "lyrics_complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
+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()
@@ -14,7 +14,6 @@ from google.cloud import firestore
from backend.config import settings
logger = logging.getLogger(__name__)
YOUTUBE_UPLOAD_QUEUE_COLLECTION = "youtube_upload_queue"
@@ -43,6 +42,7 @@ class YouTubeUploadQueueService:
title: str,
brand_code: Optional[str],
reason: str = "quota_exceeded",
notify_user: bool = True,
) -> None:
"""
Queue a YouTube upload for later processing.
@@ -54,6 +54,8 @@ class YouTubeUploadQueueService:
title: Song title
brand_code: Release ID (e.g., "NOMAD-1287")
reason: Why the upload was deferred
notify_user: Email the user when the deferred upload completes
(False for an admin re-render without customer notification)
"""
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
now = datetime.now(PACIFIC_TZ)
@@ -72,6 +74,7 @@ class YouTubeUploadQueueService:
"last_error": None,
"youtube_url": None,
"notification_sent": False,
"notify_user": notify_user,
"updated_at": now,
})
@@ -127,10 +130,15 @@ class YouTubeUploadQueueService:
True if successfully claimed, False if already processing/completed
"""
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
job_ref = self.db.collection(settings.firestore_collection).document(job_id)
@firestore.transactional
def claim_in_transaction(transaction, doc_ref):
doc = doc_ref.get(transaction=transaction)
# Read the job in the same transaction: an admin re-render claims the
# job only if no upload is processing (and reads this queue doc), so
# with both transactions reading both docs they can never overlap.
job_doc = job_ref.get(transaction=transaction)
if not doc.exists:
return False
@@ -138,6 +146,12 @@ class YouTubeUploadQueueService:
if data.get("status") != "queued":
return False
if job_doc.exists:
from backend.services.admin_rerender_service import admin_rerender_blocks_upload
if admin_rerender_blocks_upload(job_doc.to_dict() or {}):
logger.info(f"YouTube upload for job {job_id} deferred: admin re-render in progress")
return False # leave queued; picked up once the re-render completes
attempts = data.get("attempts", 0)
max_attempts = data.get("max_attempts", 5)
if attempts >= max_attempts:
@@ -208,6 +222,22 @@ class YouTubeUploadQueueService:
f"for job {job_id} (attempt {attempts}/{max_attempts}): {error}"
)
def mark_post_upload_error(self, job_id: str, youtube_url: str, error: str) -> None:
"""The video was uploaded but a follow-up step failed.
Terminal "completed" (never re-queued — that would upload it twice) with
the URL and a ``needs_attention`` flag + error for an operator.
"""
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
doc_ref.update({
"status": "completed",
"youtube_url": youtube_url,
"needs_attention": True,
"post_upload_error": error,
"updated_at": datetime.now(PACIFIC_TZ),
})
logger.error(f"YouTube upload for job {job_id} succeeded ({youtube_url}) but a follow-up step failed: {error}")
def retry_upload(self, job_id: str) -> bool:
"""
Admin manual retry: reset a failed upload back to queued.
@@ -472,3 +472,237 @@ async def test_gated_lyrics_skip_timing_compute() -> None:
compute.assert_not_called()
payload = job_manager.update_processing_metadata.call_args[0][2]
assert payload["timing"]["status"] == "not_needed"
# ---------------------------------------------------------------- vocal gaps (shadow)
def _vocal_gaps_result(suspect_count=1, error=None, evidenced=False):
from backend.services.auto_approval.vocal_gaps import VocalGap, VocalGapsResult
gaps = [VocalGap(start=20.66, end=32.4, duration=11.74, active_fraction=0.96,
longest_run_s=11.76, suspect=True, evidenced=evidenced,
reference_lines={"genius": ["line one", "line two"]})] if suspect_count else []
return VocalGapsResult(gaps=gaps, suspect_count=suspect_count,
evidenced_count=1 if (evidenced and suspect_count) else 0,
max_suspect_run_s=11.76 if suspect_count else 0.0, error=error)
def _stored_vocal_gaps(job_manager):
calls = [c for c in job_manager.update_state_data.call_args_list if c[0][1] == "vocal_gaps"]
return calls[0][0][2] if calls else None
@pytest.mark.asyncio
async def test_vocal_gaps_analyzed_and_stored_without_changing_outcome() -> None:
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result()) as analyze, \
patch("backend.services.auto_approval.executor._compute_timing_signals",
return_value=_timing_signals(fired=False)):
result, job_manager, _, _ = await _run(_job_with_lead_stem())
analyze.assert_called_once()
# Shadow only: a suspect gap must not demote a confident job (yet)
assert result["outcome"] == "auto_completed"
stored = _stored_vocal_gaps(job_manager)
assert stored["suspect_count"] == 1
assert stored["gaps"][0]["reference_lines"] == {"genius": ["line one", "line two"]}
assert stored["source"] == "auto_approval" and "analyzed_at" in stored
payload = job_manager.update_processing_metadata.call_args[0][2]
assert payload["vocal_gaps"] == {"status": "checked", "suspect_count": 1, "evidenced_count": 0,
"max_suspect_run_s": 11.76}
@pytest.mark.asyncio
async def test_evidenced_missing_lyrics_block_auto_approval() -> None:
"""Singing with no words where the reference lyrics have lines = dropped lyrics:
a confident job must go to review with an explicit reason."""
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result(evidenced=True)), \
patch("backend.services.auto_approval.executor._compute_timing_signals") as timing:
result, job_manager, _, worker = await _run(_job_with_lead_stem())
assert result["outcome"] == "review"
worker.trigger_render_video_worker.assert_not_called()
timing.assert_not_called() # lyrics no longer AUTO, so the timing check is skipped
payload = job_manager.update_processing_metadata.call_args[0][2]
assert payload["lyrics"]["tier"] == "missing-lyrics-gate"
assert any("possible missing lyrics" in r and "0:20-0:32" in r and "2 line(s)" in r
for r in payload["lyrics"]["reasons"])
assert payload["vocal_gaps"]["evidenced_count"] == 1
@pytest.mark.asyncio
async def test_cached_evidenced_gaps_still_gate() -> None:
job = _job_with_lead_stem()
gaps = _vocal_gaps_result(evidenced=True).to_dict()
job.state_data["vocal_gaps"] = {**gaps, "input_key": _input_key_for(job)}
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps") as analyze:
result, job_manager, _, _ = await _run(job)
analyze.assert_not_called()
assert result["outcome"] == "review"
assert job_manager.update_processing_metadata.call_args[0][2]["lyrics"]["tier"] == "missing-lyrics-gate"
@pytest.mark.asyncio
async def test_vocal_gaps_analyzed_for_review_bound_jobs_too() -> None:
"""Unlike the timing gate, gaps are analyzed whatever the lyrics verdict."""
corrections = _confident_corrections()
corrections["gap_sequences"] = [{"id": "g0", "transcribed_word_ids": ["w1", "w2", "w3"]}]
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result()) as analyze:
result, job_manager, _, _ = await _run(_job_with_lead_stem(), corrections=corrections)
assert result["outcome"] == "review"
analyze.assert_called_once()
assert _stored_vocal_gaps(job_manager)["suspect_count"] == 1
def _input_key_for(job, corrections=None):
from backend.services.auto_approval.executor import vocal_gaps_input_key
corrections = corrections or _confident_corrections()
return vocal_gaps_input_key(corrections["corrected_segments"], job.file_urls["stems"])
@pytest.mark.asyncio
async def test_vocal_gaps_not_recomputed_when_cached_for_same_inputs() -> None:
job = _job_with_lead_stem()
job.state_data["vocal_gaps"] = {"suspect_count": 0, "max_suspect_run_s": 0.0,
"input_key": _input_key_for(job)}
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps") as analyze, \
patch("backend.services.auto_approval.executor._compute_timing_signals",
return_value=_timing_signals(fired=False)):
_, job_manager, _, _ = await _run(job)
analyze.assert_not_called()
assert _stored_vocal_gaps(job_manager) is None
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"]["status"] == "cached"
@pytest.mark.asyncio
async def test_stale_vocal_gaps_recomputed_when_lyrics_changed() -> None:
"""A stored result from different lyrics/stem (reset, edit, re-transcription) is
not reused — it would corrupt the calibration data."""
job = _job_with_lead_stem()
job.state_data["vocal_gaps"] = {"suspect_count": 5, "max_suspect_run_s": 9.0, "input_key": "stale"}
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result(suspect_count=0)) as analyze, \
patch("backend.services.auto_approval.executor._compute_timing_signals",
return_value=_timing_signals(fired=False)):
_, job_manager, _, _ = await _run(job)
analyze.assert_called_once()
stored = _stored_vocal_gaps(job_manager)
assert stored["suspect_count"] == 0 and stored["input_key"] == _input_key_for(job)
def test_input_key_changes_with_word_timing_and_stem() -> None:
from backend.services.auto_approval.executor import vocal_gaps_input_key
segs = _confident_corrections()["corrected_segments"]
stems = {"lead_vocals": "a.flac"}
key = vocal_gaps_input_key(segs, stems)
moved = [{**segs[0], "words": [{**segs[0]["words"][0], "start_time": 9.0}] + segs[0]["words"][1:]}]
assert vocal_gaps_input_key(moved, stems) != key
assert vocal_gaps_input_key(segs, {"lead_vocals": "b.flac"}) != key
assert vocal_gaps_input_key(segs, stems) == key
@pytest.mark.asyncio
async def test_vocal_gaps_wait_for_audio() -> None:
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps") as analyze:
_, job_manager, _, _ = await _run(_job_with_lead_stem(audio_complete=False))
analyze.assert_not_called()
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"] == {"status": "pending_audio"}
@pytest.mark.asyncio
async def test_vocal_gaps_without_lead_stem() -> None:
with patch("backend.services.auto_approval.executor._compute_timing_signals", return_value=None):
_, job_manager, _, _ = await _run(_job(backing=_clean_backing()))
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"] == {"status": "no_lead_stem"}
@pytest.mark.asyncio
async def test_vocal_gaps_error_is_nonfatal_and_not_stored() -> None:
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result(error="decode failed")), \
patch("backend.services.auto_approval.executor._compute_timing_signals",
return_value=_timing_signals(fired=False)):
result, job_manager, _, _ = await _run(_job_with_lead_stem())
assert result["outcome"] == "auto_completed"
assert _stored_vocal_gaps(job_manager) is None
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"]["status"] == "error"
@pytest.mark.asyncio
async def test_vocal_gaps_exception_is_nonfatal() -> None:
with patch("backend.services.auto_approval.executor.analyze_vocal_gaps", side_effect=RuntimeError("boom")), \
patch("backend.services.auto_approval.executor._compute_timing_signals",
return_value=_timing_signals(fired=False)):
result, job_manager, _, _ = await _run(_job_with_lead_stem())
assert result["outcome"] == "auto_completed"
assert job_manager.update_processing_metadata.call_args[0][2]["vocal_gaps"]["status"] == "error"
# ---------------------------------------------------------------- backfill
def _backfill(job, files: Dict[str, Any], analyze_result):
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
job_manager = MagicMock()
job_manager.get_job.return_value = job
storage = MagicMock()
storage.file_exists.side_effect = lambda p: p in files
storage.download_json.side_effect = lambda p: files[p]
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService", return_value=storage), \
patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=analyze_result) as analyze:
return analyze_job_vocal_gaps, job_manager, analyze
def test_backfill_uses_reviewed_lyrics_and_stores() -> None:
original = _confident_corrections()
updated = {"corrected_segments": [{"id": "s9", "words": []}]}
files = {"jobs/j1/lyrics/corrections.json": original,
"jobs/j1/lyrics/corrections_updated.json": updated}
fn, job_manager, analyze = _backfill(_job_with_lead_stem(), files, _vocal_gaps_result())
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService") as storage_cls, \
patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result()) as analyze:
storage = storage_cls.return_value
storage.file_exists.side_effect = lambda p: p in files
storage.download_json.side_effect = lambda p: files[p]
out = fn("j1", store=True)
assert out["status"] == "checked" and out["stored"] is True
corrections_arg, segments_arg = analyze.call_args[0][1], analyze.call_args[0][2]
assert corrections_arg is original # reference + anchors from the original
assert segments_arg == updated["corrected_segments"] # words as reviewed/rendered
assert out["vocal_gaps"]["lyrics_source"] == "corrections_updated"
assert _stored_vocal_gaps(job_manager)["source"] == "backfill"
def test_backfill_dry_run_does_not_store() -> None:
files = {"jobs/j1/lyrics/corrections.json": _confident_corrections()}
fn, job_manager, _ = _backfill(_job_with_lead_stem(), files, _vocal_gaps_result())
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService") as storage_cls, \
patch("backend.services.auto_approval.executor.analyze_vocal_gaps",
return_value=_vocal_gaps_result()):
storage_cls.return_value.file_exists.side_effect = lambda p: p in files
storage_cls.return_value.download_json.side_effect = lambda p: files[p]
out = fn("j1", store=False)
assert out["status"] == "checked" and out["vocal_gaps"]["lyrics_source"] == "corrections"
assert _stored_vocal_gaps(job_manager) is None
@pytest.mark.parametrize("files,job,expected", [
({}, "job", "no_corrections"),
({"jobs/j1/lyrics/corrections.json": {}}, None, "no_job"),
])
def test_backfill_missing_inputs(files, job, expected) -> None:
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
job_manager = MagicMock()
job_manager.get_job.return_value = _job_with_lead_stem() if job else None
with patch("backend.services.job_manager.JobManager", return_value=job_manager), \
patch("backend.services.storage_service.StorageService") as storage_cls:
storage_cls.return_value.file_exists.side_effect = lambda p: p in files
assert analyze_job_vocal_gaps("j1")["status"] == expected
@@ -445,3 +445,38 @@ def test_timing_gate_flows_through_score_job() -> None:
verdict = score_job(_corrections_json(), None, None, timing_signals=sig)
assert verdict.lyrics.tier == "timing-gate"
assert verdict.overall_auto is False
# ---------------------------------------------------------------- missing-lyrics gate
def _gap(evidenced, start=20.66, end=32.4, run=10.26, synced=None, refs=None):
return {"start": start, "end": end, "longest_run_s": run, "suspect": True, "evidenced": evidenced,
"synced_reference_lines": synced or {}, "reference_lines": refs or {}}
class TestMissingLyricsGate:
def test_reasons_only_for_evidenced_gaps(self):
from backend.services.auto_approval.scorer import missing_lyrics_reasons
gaps = {"gaps": [_gap(True, synced={"lrclib": ["a", "b", "c"]}, refs={"genius": ["a", "b"]}),
_gap(False, start=60, end=80)]}
reasons = missing_lyrics_reasons(gaps)
assert len(reasons) == 1
assert "~10s of singing at 0:20-0:32" in reasons[0] and "3 line(s)" in reasons[0]
def test_no_gaps_no_reasons(self):
from backend.services.auto_approval.scorer import missing_lyrics_reasons
assert missing_lyrics_reasons(None) == []
assert missing_lyrics_reasons({"gaps": []}) == []
def test_evidenced_gap_overrides_confident_lyrics(self):
from backend.services.auto_approval.scorer import score_lyrics
from backend.services.auto_approval.models import LyricsVerdict
data = _corrections_json(anchor_words=20, gap_words=0, synced=True)
assert score_lyrics(data).verdict == LyricsVerdict.AUTO
gated = score_lyrics(data, vocal_gaps={"gaps": [_gap(True, synced={"lrclib": ["x"]})]})
assert gated.verdict == LyricsVerdict.REVIEW and gated.tier == "missing-lyrics-gate"
assert score_lyrics(data, vocal_gaps={"gaps": [_gap(False)]}).verdict == LyricsVerdict.AUTO
@@ -0,0 +1,320 @@
"""Tests for vocal-gap detection (sung stretches with no transcribed words).
Motivating case: job 5710831e — the transcription dropped three sung lines (11.7s,
lead vocal ~96% active) and the video showed "INSTRUMENTAL" over the singing, while
genuine instrumentals measured 1-2% active. These tests build that situation on
synthesized audio plus synthetic correction data with the same structure (including
the off-by-one anchor reference ids seen at "[Section]" header boundaries).
"""
from __future__ import annotations
import json
import os
import numpy as np
import pytest
from backend.services.auto_approval.vocal_gaps import (
MIN_GAP_S,
VocalGapsResult,
_bridge,
_longest_run,
compute_vocal_gaps,
reference_lines_between,
transcription_gaps,
)
def _synth_stem(tmp_path, sung_regions, duration_s=40.0):
"""WAV 'vocal stem': silence with a 440Hz tone over ``sung_regions``."""
from pydub import AudioSegment
from pydub.generators import Sine
audio = AudioSegment.silent(duration=int(duration_s * 1000), frame_rate=22050)
for start_s, end_s in sung_regions:
tone = Sine(440, sample_rate=22050).to_audio_segment(
duration=int((end_s - start_s) * 1000)
).apply_gain(-6)
audio = audio.overlay(tone, position=int(start_s * 1000))
path = os.path.join(str(tmp_path), "lead_vocals.wav")
audio.export(path, format="wav")
return path
def _word(wid, text, start, end):
return {"id": wid, "text": text, "start_time": start, "end_time": end}
def _segments(*lines):
return [{"id": f"s{i}", "text": " ".join(w["text"] for w in ws), "words": ws,
"start_time": ws[0]["start_time"], "end_time": ws[-1]["end_time"]}
for i, ws in enumerate(lines)]
# --------------------------------------------------------------- gap finding
class TestTranscriptionGaps:
def test_finds_leading_inner_and_trailing_gaps(self):
segs = _segments([_word("a", "a", 5.0, 6.0), _word("b", "b", 6.2, 7.0)],
[_word("c", "c", 15.0, 16.0)])
gaps = transcription_gaps(segs, audio_duration=30.0)
assert [(s, e) for s, e, _, _ in gaps] == [(0.0, 5.0), (7.0, 15.0), (16.0, 30.0)]
assert gaps[1][2]["id"] == "b" and gaps[1][3]["id"] == "c"
assert gaps[0][2] is None and gaps[2][3] is None
def test_short_gaps_ignored(self):
segs = _segments([_word("a", "a", 0.5, 1.0), _word("b", "b", 1.0 + MIN_GAP_S - 0.1, 5.0)])
assert transcription_gaps(segs, audio_duration=5.5) == []
def test_overlapping_words_do_not_create_negative_gaps(self):
segs = _segments([_word("a", "a", 0.0, 10.0), _word("b", "b", 2.0, 3.0), _word("c", "c", 11.0, 12.0)])
assert [(s, e) for s, e, _, _ in transcription_gaps(segs, 12.0)] == []
def test_words_without_timing_are_skipped(self):
segs = _segments([_word("a", "a", 0.0, 1.0), {"id": "x", "text": "x", "start_time": None, "end_time": None}])
assert [(s, e) for s, e, _, _ in transcription_gaps(segs, 10.0)] == [(1.0, 10.0)]
class TestRunHelpers:
def test_bridge_fills_short_breaths_only(self):
a = np.array([1, 0, 0, 1, 0, 0, 0, 0, 1], dtype=bool)
assert _bridge(a, 2).tolist() == [1, 1, 1, 1, 0, 0, 0, 0, 1]
def test_longest_run(self):
assert _longest_run(np.array([1, 1, 0, 1, 1, 1, 0], dtype=bool)) == 3
assert _longest_run(np.zeros(4, dtype=bool)) == 0
# --------------------------------------------------------------- end to end (audio)
class TestComputeVocalGaps:
def test_dropped_sung_lines_are_suspect_and_instrumental_is_not(self, tmp_path):
# Words 2-8s; singing continues 8-20s with no words (dropped lines, with
# short breaths); a silent instrumental 20-30s; words again 30-34s.
sung = [(2.0, 8.0), (8.3, 12.0), (12.4, 16.0), (16.3, 20.0), (30.0, 34.0)]
stem = _synth_stem(tmp_path, sung)
segs = _segments([_word("a", "a", 2.0, 5.0), _word("b", "b", 5.0, 8.0)],
[_word("c", "c", 30.0, 32.0), _word("d", "d", 32.0, 34.0)])
result = compute_vocal_gaps(segs, stem)
assert result.error is None
by_start = {g.start: g for g in result.gaps}
dropped = by_start[8.0]
assert dropped.suspect
# Diluted by the instrumental sharing the gap — the run, not the fraction, decides
assert 0.4 < dropped.active_fraction < 0.6
# 12s of bridged singing, minus the held-note allowance at the gap start
assert dropped.longest_run_s >= 10.0, "breaths inside singing must be bridged"
assert result.suspect_count == 1
assert result.max_suspect_run_s == dropped.longest_run_s
def test_genuine_instrumental_is_not_suspect(self, tmp_path):
stem = _synth_stem(tmp_path, [(2.0, 8.0), (25.0, 30.0)])
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
result = compute_vocal_gaps(segs, stem)
assert [(g.start, g.suspect) for g in result.gaps] == [(8.0, False), (30.0, False)] # middle, outro
assert result.suspect_count == 0
def test_short_dropped_line_in_long_gap_is_still_suspect(self, tmp_path):
"""A 4s dropped line followed by a long instrumental in the same gap."""
stem = _synth_stem(tmp_path, [(2.0, 8.0), (8.5, 12.5), (28.0, 30.0)])
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 28.0, 30.0)])
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
assert gap.active_fraction < 0.25
assert gap.suspect
def test_held_note_past_last_word_is_not_suspect(self, tmp_path):
"""The word's transcribed end is 3.5s before the singer stops (held note)."""
stem = _synth_stem(tmp_path, [(2.0, 11.5), (25.0, 30.0)])
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
assert not gap.suspect
assert gap.longest_run_s == pytest.approx(2.0, abs=0.1)
def test_singing_after_a_pause_gets_no_allowance(self, tmp_path):
"""A dropped line that starts after a real pause is counted in full."""
stem = _synth_stem(tmp_path, [(2.0, 8.0), (10.0, 14.0), (25.0, 30.0)])
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
assert gap.suspect
assert gap.longest_run_s == pytest.approx(4.0, abs=0.1)
def test_silent_stem_is_an_error_not_a_clean_pass(self, tmp_path):
stem = _synth_stem(tmp_path, [], duration_s=20.0)
result = compute_vocal_gaps(_segments([_word("a", "a", 2.0, 4.0)]), stem)
assert result.error and "silent" in result.error
assert result.gaps == []
def test_malformed_reference_does_not_lose_audio_result(self, tmp_path):
stem = _synth_stem(tmp_path, [(2.0, 20.0)], duration_s=25.0)
bad = {"reference_lyrics": {"genius": {"segments": [{"words": [{"text": "no id"}]}]}},
"anchor_sequences": [{"transcribed_word_ids": ["a"], "reference_word_ids": {"genius": ["zz"]}}]}
result = compute_vocal_gaps(_segments([_word("a", "a", 2.0, 4.0)]), stem, bad)
assert result.error is None
assert result.suspect_count == 1
def test_brief_ad_lib_in_gap_is_not_suspect(self, tmp_path):
stem = _synth_stem(tmp_path, [(2.0, 8.0), (14.0, 15.5), (25.0, 30.0)])
segs = _segments([_word("a", "a", 2.0, 8.0)], [_word("b", "b", 25.0, 30.0)])
gap = next(g for g in compute_vocal_gaps(segs, stem).gaps if g.start == 8.0)
assert not gap.suspect
assert 1.0 < gap.longest_run_s < 2.0
def test_missing_stem_returns_error_not_raise(self, tmp_path):
result = compute_vocal_gaps(_segments([_word("a", "a", 0.0, 1.0)]), str(tmp_path / "nope.flac"))
assert isinstance(result, VocalGapsResult)
assert result.error
def test_result_is_json_serializable(self, tmp_path):
stem = _synth_stem(tmp_path, [(2.0, 20.0)], duration_s=25.0)
result = compute_vocal_gaps(_segments([_word("a", "a", 2.0, 4.0)]), stem)
json.dumps(result.to_dict())
# --------------------------------------------------------------- reference lines
def _ref(lines):
"""Reference lyrics source: list of line strings -> segments with word ids."""
segs = []
for li, line in enumerate(lines):
segs.append({"text": line, "words": [{"id": f"r{li}_{wi}", "text": t}
for wi, t in enumerate(line.split())]})
return {"segments": segs}
REFERENCE = [
"[Verse]",
"come run far away",
"[Pre-Chorus]",
"like two crazy people",
"we kept moments close", # dropped
"you were pretty as a flower", # dropped
"[Chorus]",
"like two crazy people",
]
def _correction_data(before_ref_ids, after_ref_ids):
return {
"reference_lyrics": {"genius": _ref(REFERENCE)},
"anchor_sequences": [
{"transcribed_word_ids": ["t_before"], "reference_word_ids": {"genius": before_ref_ids}},
{"transcribed_word_ids": ["t_after"], "reference_word_ids": {"genius": after_ref_ids}},
],
"gap_sequences": [],
}
class TestReferenceLinesBetween:
before, after = {"id": "t_before"}, {"id": "t_after"}
def test_lines_between_neighbouring_anchors(self):
data = _correction_data(["r3_3"], ["r7_0"]) # "people" ... "like"
assert reference_lines_between(data, self.before, self.after) == {
"genius": ["we kept moments close", "you were pretty as a flower"]
}
def test_off_by_one_anchor_at_line_start_is_snapped(self):
# Real job: the word before the gap mapped to the FIRST word of the next line
# ("people" -> "we") because "[Section]" headers shift anchor ids by one.
data = _correction_data(["r4_0"], ["r7_0"])
assert reference_lines_between(data, self.before, self.after)["genius"][0] == "we kept moments close"
def test_off_by_one_anchor_at_line_end_is_snapped(self):
data = _correction_data(["r3_3"], ["r6_0"]) # "like" landed on the "[Chorus]" header's last word
assert reference_lines_between(data, self.before, self.after) == {
"genius": ["we kept moments close", "you were pretty as a flower"]
}
def test_single_word_line_before_gap_is_not_reported_missing(self):
lines = ["intro words here", "Yeah", "dropped line one", "after the gap"]
data = {"reference_lyrics": {"genius": _ref(lines)},
"anchor_sequences": [
{"transcribed_word_ids": ["t_before"], "reference_word_ids": {"genius": ["r1_0"]}},
{"transcribed_word_ids": ["t_after"], "reference_word_ids": {"genius": ["r3_0"]}}],
"gap_sequences": []}
assert reference_lines_between(data, self.before, self.after) == {"genius": ["dropped line one"]}
def test_section_headers_are_dropped(self):
data = _correction_data(["r1_3"], ["r7_0"])
lines = reference_lines_between(data, self.before, self.after)["genius"]
assert not any(l.startswith("[") for l in lines)
def test_reversed_order_from_repeated_chorus_returns_nothing(self):
data = _correction_data(["r7_3"], ["r3_0"])
assert reference_lines_between(data, self.before, self.after) == {}
def test_gap_at_song_edge_has_no_reference_lines(self):
data = _correction_data(["r3_3"], ["r7_0"])
assert reference_lines_between(data, None, self.after) == {}
assert reference_lines_between(data, self.before, None) == {}
def test_unmapped_words_return_nothing(self):
data = _correction_data(["r3_3"], ["r7_0"])
assert reference_lines_between(data, {"id": "other"}, self.after) == {}
def test_compute_includes_reference_lines(self, tmp_path):
stem = _synth_stem(tmp_path, [(2.0, 20.0), (30.0, 34.0)])
segs = _segments([_word("t_before", "people", 2.0, 8.0)], [_word("t_after", "like", 30.0, 34.0)])
gap = next(g for g in compute_vocal_gaps(segs, stem, _correction_data(["r3_3"], ["r7_0"])).gaps
if g.start == 8.0)
assert gap.suspect
assert gap.reference_lines == {"genius": ["we kept moments close", "you were pretty as a flower"]}
# --------------------------------------------------------------- synced reference evidence
class TestSyncedEvidence:
def _synced_ref(self, lines):
"""[(start, text)] -> reference source with word timings (like LRCLIB)."""
segs = []
for li, (start, text) in enumerate(lines):
segs.append({"text": text, "words": [
{"id": f"s{li}_{wi}", "text": t, "start_time": start + wi * 0.3, "end_time": start + wi * 0.3 + 0.25}
for wi, t in enumerate(text.split())]})
return {"segments": segs}
def test_lines_inside_gap_with_edge_tolerance(self):
from backend.services.auto_approval.vocal_gaps import _synced_reference_lines, synced_lines_in_gap
data = {"reference_lyrics": {"lrclib": self._synced_ref(
[(5.0, "before gap"), (8.2, "at the edge"), (12.0, "dropped one"), (18.0, "dropped two"),
(19.8, "too close to end"), (25.0, "after gap")]),
"genius": _ref(["unsynced line"])}}
synced = _synced_reference_lines(data)
assert set(synced) == {"lrclib"} # unsynced sources ignored
assert synced_lines_in_gap(synced, 8.0, 20.0) == {"lrclib": ["dropped one", "dropped two"]}
assert synced_lines_in_gap(synced, 30.0, 40.0) == {}
def test_section_headers_ignored(self):
from backend.services.auto_approval.vocal_gaps import _synced_reference_lines
data = {"reference_lyrics": {"lrclib": self._synced_ref([(1.0, "[Chorus]"), (2.0, "real line")])}}
assert _synced_reference_lines(data) == {"lrclib": [(2.0, "real line")]}
def test_evidenced_requires_suspect_and_reference(self, tmp_path):
# singing 2-20s, words only 2-4s; synced reference has lines at 10s and 15s
stem = _synth_stem(tmp_path, [(2.0, 20.0), (30.0, 34.0)])
segs = _segments([_word("a", "a", 2.0, 4.0)], [_word("b", "b", 30.0, 34.0)])
data = {"reference_lyrics": {"lrclib": self._synced_ref([(10.0, "dropped line"), (15.0, "another")])}}
result = compute_vocal_gaps(segs, stem, data)
gap = next(g for g in result.gaps if g.start == 4.0)
assert gap.suspect and gap.evidenced
assert gap.synced_reference_lines == {"lrclib": ["dropped line", "another"]}
assert result.evidenced_count == 1
def test_reference_lines_without_singing_are_not_evidenced(self, tmp_path):
"""An instrumental where the reference (mis)places lines must not gate."""
stem = _synth_stem(tmp_path, [(2.0, 4.0), (30.0, 34.0)])
segs = _segments([_word("a", "a", 2.0, 4.0)], [_word("b", "b", 30.0, 34.0)])
data = {"reference_lyrics": {"lrclib": self._synced_ref([(10.0, "misplaced line")])}}
gap = next(g for g in compute_vocal_gaps(segs, stem, data).gaps if g.start == 4.0)
assert gap.synced_reference_lines and not gap.suspect and not gap.evidenced
def test_singing_without_reference_is_suspect_but_not_evidenced(self, tmp_path):
stem = _synth_stem(tmp_path, [(2.0, 20.0), (30.0, 34.0)])
segs = _segments([_word("a", "a", 2.0, 4.0)], [_word("b", "b", 30.0, 34.0)])
result = compute_vocal_gaps(segs, stem, {})
gap = next(g for g in result.gaps if g.start == 4.0)
assert gap.suspect and not gap.evidenced
assert result.evidenced_count == 0
File diff suppressed because it is too large. Load diff
@@ -148,6 +148,25 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
# Verify the returned data is the original
assert result["corrected_segments"][0]["text"] == "Hello world"
@pytest.mark.parametrize("stored", [None, {"gaps": [{"start": 20.66, "end": 32.4, "evidenced": True}],
"evidenced_count": 1}])
def test_includes_vocal_gaps_for_missing_lyrics_marker(self, mock_job, original_corrections, stored):
"""The review UI marks possible missing lyrics from state_data.vocal_gaps."""
from backend.api.routes.review import get_correction_data
if stored:
mock_job.state_data = {"vocal_gaps": stored}
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
patch("backend.api.routes.review.StorageService") as MockStorageService:
MockJobManager.return_value.get_job.return_value = mock_job
storage = MockStorageService.return_value
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
storage.download_json.return_value = original_corrections.copy()
storage.generate_signed_url.return_value = "https://signed-url.com"
import asyncio
result = asyncio.run(get_correction_data("test-job-123", ("user@test.com", "job_owner")))
assert result["vocal_gaps"] == stored
def test_returns_proxy_audio_urls_and_omits_waveform_without_signing(
self, mock_job, original_corrections
):
+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"
+32
View File
@@ -364,3 +364,35 @@ class TestAutoApprovalEval:
def test_eval_requires_admin(self, client):
response = client.post("/api/internal/jobs/test123/auto-approval-eval")
assert response.status_code == 401
class TestVocalGapsEndpoint:
"""POST /api/internal/jobs/{job_id}/vocal-gaps — missing-lyrics backfill/inspect."""
def test_stores_by_default(self, client):
with patch(
'backend.services.auto_approval.executor.analyze_job_vocal_gaps',
return_value={"status": "checked", "stored": True},
) as analyze:
response = client.post(
"/api/internal/jobs/test123/vocal-gaps",
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
assert response.json() == {"job_id": "test123", "status": "checked", "stored": True}
analyze.assert_called_once_with("test123", True)
def test_dry_run_does_not_store(self, client):
with patch(
'backend.services.auto_approval.executor.analyze_job_vocal_gaps',
return_value={"status": "checked", "stored": False},
) as analyze:
client.post(
"/api/internal/jobs/test123/vocal-gaps?dry_run=true",
headers={"Authorization": "Bearer test-admin-token"},
)
analyze.assert_called_once_with("test123", False)
def test_requires_admin(self, client):
response = client.post("/api/internal/jobs/test123/vocal-gaps")
assert response.status_code == 401
+303
View File
@@ -0,0 +1,303 @@
"""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():
transient = Exception("429 RESOURCE_EXHAUSTED")
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_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,108 @@
"""Unit tests for backend.services.published_outputs_cleanup (shared by Edit + admin re-render)."""
from unittest.mock import MagicMock, patch
from backend.services import published_outputs_cleanup as cleanup
class TestSnapshot:
def test_only_present_published_keys(self):
state = {"youtube_url": "https://youtu.be/a", "brand_code": "NOMAD-1", "dropbox_link": None,
"instrumental_selection": "clean"}
assert cleanup.snapshot_published_outputs(state) == {"youtube_url": "https://youtu.be/a",
"brand_code": "NOMAD-1"}
def test_none(self):
assert cleanup.snapshot_published_outputs(None) == {}
class TestYouTube:
def test_video_id_parsing(self):
assert cleanup.youtube_video_id("https://www.youtube.com/watch?v=abc123&t=3") == "abc123"
assert cleanup.youtube_video_id("https://youtu.be/xyz") == "xyz"
assert cleanup.youtube_video_id("https://example.com") is None
def test_skipped_without_url(self):
assert cleanup.delete_youtube_video("j", None)["status"] == "skipped"
def test_unparseable_url_fails(self):
assert cleanup.delete_youtube_video("j", "https://example.com/v")["status"] == "failed"
def _patched(self, configured=True, delete_ok=True, raises=None):
yt = MagicMock(is_configured=configured)
yt.get_credentials_dict.return_value = {"token": "t"}
finalise = MagicMock()
finalise.return_value.delete_youtube_video.return_value = delete_ok
if raises:
finalise.return_value.delete_youtube_video.side_effect = raises
return (patch("backend.services.youtube_service.get_youtube_service", return_value=yt),
patch("karaoke_gen.karaoke_finalise.karaoke_finalise.KaraokeFinalise", finalise), finalise)
def test_deletes(self):
p1, p2, finalise = self._patched()
with p1, p2:
result = cleanup.delete_youtube_video("j", "https://www.youtube.com/watch?v=abc123")
assert result == {"status": "success", "video_id": "abc123"}
finalise.return_value.delete_youtube_video.assert_called_once_with("abc123")
def test_not_configured(self):
p1, p2, _ = self._patched(configured=False)
with p1, p2:
assert cleanup.delete_youtube_video("j", "https://youtu.be/a")["status"] == "skipped"
def test_error_never_raises(self):
p1, p2, _ = self._patched(raises=RuntimeError("quotaExceeded"))
with p1, p2:
result = cleanup.delete_youtube_video("j", "https://youtu.be/a")
assert result["status"] == "error" and "quotaExceeded" in result["error"]
class TestDropbox:
def test_folder_path_matches_distribution_sanitisation(self):
with patch("karaoke_gen.utils.sanitize_filename", side_effect=lambda s: s.replace("/", "_")):
assert cleanup.dropbox_folder_path("/K", "NOMAD-1", "AC/DC", "T") == "/K/NOMAD-1 - AC_DC - T"
def test_skipped_without_brand_code_or_path(self):
assert cleanup.delete_dropbox_folder("j", None, "NOMAD-1", "A", "T")["status"] == "skipped"
assert cleanup.delete_dropbox_folder("j", "/K", None, "A", "T")["status"] == "skipped"
def test_deletes(self):
dropbox = MagicMock(is_configured=True)
dropbox.delete_folder.return_value = True
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=dropbox):
result = cleanup.delete_dropbox_folder("j", "/K", "NOMAD-1", "Artist", "Title")
assert result == {"status": "success", "path": "/K/NOMAD-1 - Artist - Title",
"deleted": ["/K/NOMAD-1 - Artist - Title"]}
dropbox.file_exists.assert_not_called() # names identical: no probing
def test_error(self):
dropbox = MagicMock(is_configured=True)
dropbox.delete_folder.side_effect = RuntimeError("boom")
with patch("backend.services.dropbox_service.get_dropbox_service", return_value=dropbox):
assert cleanup.delete_dropbox_folder("j", "/K", "NOMAD-1", "A", "T")["status"] == "error"
class TestGDrive:
def test_skipped_without_files(self):
assert cleanup.delete_gdrive_files("j", None)["status"] == "skipped"
def _gdrive(self, results):
gdrive = MagicMock(is_configured=True)
gdrive.delete_files.return_value = results
return gdrive
def test_deletes_and_cleans_mirror_by_default(self):
gdrive = self._gdrive({"g1": True, "g2": True})
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=gdrive), \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mirror:
result = cleanup.delete_gdrive_files("j", {"mp4": "g1", "mp4_720p": "g2"}, "NOMAD-1")
assert result["status"] == "success"
gdrive.delete_files.assert_called_once_with(["g1", "g2"])
mirror.assert_called_once_with("NOMAD-1")
def test_keeps_mirror_when_asked(self):
gdrive = self._gdrive({"g1": False})
with patch("backend.services.gdrive_service.get_gdrive_service", return_value=gdrive), \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mirror:
result = cleanup.delete_gdrive_files("j", {"mp4": "g1"}, "NOMAD-1", cleanup_mirror=False)
assert result["status"] == "partial"
mirror.assert_not_called()
@@ -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
@@ -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")
+46 -4
View File
@@ -267,15 +267,57 @@ class TestUpdateJobYouTubeUrl:
# (which would clobber a concurrently-changed sibling like brand_code).
assert "state_data" not in payload
def test_handles_missing_job(self):
"""Should not raise when job not found."""
def test_missing_job_raises(self):
"""A missing job must surface as a failure, so the processor flags the
queue entry needs_attention instead of silently losing the URL."""
from backend.workers.youtube_queue_processor import _update_job_youtube_url
mock_job_manager = Mock()
mock_job_manager.get_job.return_value = None
with patch('backend.workers.youtube_queue_processor.JobManager', return_value=mock_job_manager):
# Should not raise
_update_job_youtube_url("nonexistent", "https://youtube.com/watch?v=abc")
with pytest.raises(RuntimeError, match="not found"):
_update_job_youtube_url("nonexistent", "https://youtube.com/watch?v=abc")
mock_job_manager.update_job.assert_not_called()
def test_update_failure_propagates(self):
from backend.workers.youtube_queue_processor import _update_job_youtube_url
mock_job_manager = Mock()
mock_job_manager.get_job.return_value = Mock(state_data={})
mock_job_manager.update_job.side_effect = RuntimeError("firestore down")
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)")
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "We couldn't find your uploaded instrumental. The upload may not have finished. Please try again.",
"uploadDurationMismatchCancelled": "The instrumental ({instrumental_duration}s) doesn't line up with the song audio ({audio_duration}s), so it may be the wrong file for this song. This job has been cancelled and your credit refunded. Please check the files and submit again.",
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead.",
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment."
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment.",
"adminRerenderRetryAdminOnly": "This track is being re-rendered by our team, so it can only be retried by an admin. Please contact support and we'll finish it for you."
},
"review": {
"jobNotFound": "Job not found",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "تعذر العثور على ملف الموسيقى الآلية الذي قمت برفعه. قد لا يكون الرفع قد اكتمل بعد. يُرجى المحاولة مرة أخرى.",
"uploadDurationMismatchCancelled": "لا تتطابق مدة المسار الموسيقي ({instrumental_duration} ثانية) مع مدة صوت الأغنية ({audio_duration} ثانية)، لذا قد يكون الملف غير صحيح لهذه الأغنية. تم إلغاء هذه المهمة واسترداد رصيدك. يُرجى التحقق من الملفات وإعادة المحاولة.",
"instrumentalUploadTooLarge": "حجم هذا الملف الموسيقي هو {size_mb} ميجابايت، وهو ما يتجاوز الحد المسموح به البالغ {max_mb} ميجابايت. يُرجى رفع نسخة بصيغة FLAC أو MP3 بدلاً من ذلك.",
"instrumentalConformUnavailable": "لم نتمكن من معالجة المقطع الموسيقي الخاص بك الآن. يُرجى محاولة الإرسال مجدداً بعد لحظات."
"instrumentalConformUnavailable": "لم نتمكن من معالجة المقطع الموسيقي الخاص بك الآن. يُرجى محاولة الإرسال مجدداً بعد لحظات.",
"adminRerenderRetryAdminOnly": "يعمل فريقنا على إعادة تصيير هذا المسار، لذا لا يمكن إعادة المحاولة إلا من قِبل مسؤول. يُرجى التواصل مع الدعم وسنكمله لك."
},
"review": {
"jobNotFound": "المهمة غير موجودة",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "No hem pogut trobar l'instrumental que has pujat. És possible que la pujada no s'hagi completat. Si us plau, torna-ho a intentar.",
"uploadDurationMismatchCancelled": "L'instrumental ({instrumental_duration}s) no coincideix amb l'àudio de la cançó ({audio_duration}s), per la qual cosa podria ser el fitxer equivocat per a aquesta cançó. Aquesta tasca s'ha cancel·lat i se t'ha reemborsat el crèdit. Comprova els fitxers i torna-ho a enviar.",
"instrumentalUploadTooLarge": "Aquest fitxer instrumental fa {size_mb} MB, que supera el límit de {max_mb} MB. Si us plau, penja una versió en FLAC o MP3 en comptes d'això.",
"instrumentalConformUnavailable": "No hem pogut processar el teu instrumental ara mateix. Si us plau, torna-ho a enviar d'aquí a un moment."
"instrumentalConformUnavailable": "No hem pogut processar el teu instrumental ara mateix. Si us plau, torna-ho a enviar d'aquí a un moment.",
"adminRerenderRetryAdminOnly": "Aquesta pista l'està tornant a renderitzar el nostre equip, així que només la pot reintentar un administrador. Posa't en contacte amb el servei de suport i te l'acabarem."
},
"review": {
"jobNotFound": "Tasca no trobada",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nepodařilo se najít tvůj nahraný instrumentál. Nahrávání možná nebylo dokončeno. Zkus to prosím znovu.",
"uploadDurationMismatchCancelled": "Instrumentální stopa ({instrumental_duration}s) časově nesedí se zvukem skladby ({audio_duration}s), takže může jít o nesprávný soubor pro tuto skladbu. Tato úloha byla zrušena a tvůj kredit byl vrácen. Zkontroluj prosím soubory a odešli je znovu.",
"instrumentalUploadTooLarge": "Tento instrumentální soubor má {size_mb} MB, což překračuje limit {max_mb} MB. Nahraj prosím místo toho verzi ve formátu FLAC nebo MP3.",
"instrumentalConformUnavailable": "Právě se nám nepodařilo zpracovat tvůj instrumentál. Zkus to prosím za chvíli odeslat znovu."
"instrumentalConformUnavailable": "Právě se nám nepodařilo zpracovat tvůj instrumentál. Zkus to prosím za chvíli odeslat znovu.",
"adminRerenderRetryAdminOnly": "Tuto skladbu právě znovu renderuje náš tým, takže ji může znovu spustit pouze administrátor. Kontaktuj prosím podporu a my to pro tebe dokončíme."
},
"review": {
"jobNotFound": "Úloha nebyla nalezena",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Vi kunne ikke finde din uploadede instrumental. Uploaden blev muligvis ikke fuldført. Prøv venligst igen.",
"uploadDurationMismatchCancelled": "Instrumentalsporet ({instrumental_duration}s) stemmer ikke overens med sangens lydspor ({audio_duration}s), så det er muligvis den forkerte fil til denne sang. Denne opgave er blevet annulleret, og din kredit er blevet refunderet. Tjek venligst filerne, og indsend igen.",
"instrumentalUploadTooLarge": "Denne instrumentalfil er på {size_mb} MB, hvilket overskrider grænsen på {max_mb} MB. Upload venligst en FLAC- eller MP3-version i stedet.",
"instrumentalConformUnavailable": "Vi kunne ikke behandle dit instrumentalspor lige nu. Prøv venligst at indsende igen om et øjeblik."
"instrumentalConformUnavailable": "Vi kunne ikke behandle dit instrumentalspor lige nu. Prøv venligst at indsende igen om et øjeblik.",
"adminRerenderRetryAdminOnly": "Dette track bliver renderet igen af vores team, så det kun kan genstartes af en administrator. Kontakt venligst support, så gør vi det færdigt for dig."
},
"review": {
"jobNotFound": "Jobbet blev ikke fundet",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Wir konnten dein hochgeladenes Instrumental nicht finden. Der Upload wurde möglicherweise nicht abgeschlossen. Bitte versuche es erneut.",
"uploadDurationMismatchCancelled": "Das Instrumental ({instrumental_duration}s) stimmt zeitlich nicht mit dem Song-Audio ({audio_duration}s) überein, daher handelt es sich möglicherweise um die falsche Datei für diesen Song. Dieser Auftrag wurde abgebrochen und dein Guthaben erstattet. Bitte überprüfe die Dateien und reiche den Auftrag erneut ein.",
"instrumentalUploadTooLarge": "Diese Instrumental-Datei ist {size_mb} MB groß, was über dem Limit von {max_mb} MB liegt. Bitte lade stattdessen eine FLAC- oder MP3-Version hoch.",
"instrumentalConformUnavailable": "Wir konnten dein Instrumental gerade nicht verarbeiten. Bitte versuche es in einem Moment noch einmal einzureichen."
"instrumentalConformUnavailable": "Wir konnten dein Instrumental gerade nicht verarbeiten. Bitte versuche es in einem Moment noch einmal einzureichen.",
"adminRerenderRetryAdminOnly": "Dieser Track wird von unserem Team neu gerendert, daher kann er nur von einem Admin erneut gestartet werden. Bitte kontaktiere den Support, und wir stellen ihn für dich fertig."
},
"review": {
"jobNotFound": "Auftrag nicht gefunden",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Δεν μπορέσαμε να βρούμε το ορχηστρικό που μεταφόρτωσες. Η μεταφόρτωση ενδέχεται να μην έχει ολοκληρωθεί. Δοκίμασε ξανά.",
"uploadDurationMismatchCancelled": "Το ορχηστρικό ({instrumental_duration}s) δεν ταιριάζει σε διάρκεια με τον ήχο του τραγουδιού ({audio_duration}s), οπότε μπορεί να είναι λάθος αρχείο για αυτό το τραγούδι. Αυτή η εργασία ακυρώθηκε και η πίστωσή σου επιστράφηκε. Παρακαλούμε έλεγξε τα αρχεία και υπόβαλε ξανά.",
"instrumentalUploadTooLarge": "Αυτό το ορχηστρικό αρχείο είναι {size_mb} MB, το οποίο υπερβαίνει το όριο των {max_mb} MB. Παρακαλώ ανέβασε μια έκδοση FLAC ή MP3 αντ' αυτού.",
"instrumentalConformUnavailable": "Δεν μπορέσαμε να επεξεργαστούμε το ορχηστρικό σου αυτή τη στιγμή. Δοκίμασε να υποβάλεις ξανά σε λίγο."
"instrumentalConformUnavailable": "Δεν μπορέσαμε να επεξεργαστούμε το ορχηστρικό σου αυτή τη στιγμή. Δοκίμασε να υποβάλεις ξανά σε λίγο.",
"adminRerenderRetryAdminOnly": "Αυτό το κομμάτι υποβάλλεται σε εκ νέου απόδοση από την ομάδα μας, επομένως μόνο ένας διαχειριστής μπορεί να επαναλάβει τη διαδικασία. Επικοινώνησε με την υποστήριξη και θα το ολοκληρώσουμε για εσένα."
},
"review": {
"jobNotFound": "Η εργασία δεν βρέθηκε",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "We couldn't find your uploaded instrumental. The upload may not have finished. Please try again.",
"uploadDurationMismatchCancelled": "The instrumental ({instrumental_duration}s) doesn't line up with the song audio ({audio_duration}s), so it may be the wrong file for this song. This job has been cancelled and your credit refunded. Please check the files and submit again.",
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead.",
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment."
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment.",
"adminRerenderRetryAdminOnly": "This track is being re-rendered by our team, so it can only be retried by an admin. Please contact support and we'll finish it for you."
},
"review": {
"jobNotFound": "Job not found",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "No pudimos encontrar el instrumental que subiste. Es posible que la subida no haya finalizado. Por favor, inténtalo de nuevo.",
"uploadDurationMismatchCancelled": "El instrumental ({instrumental_duration}s) no coincide con el audio de la canción ({audio_duration}s), por lo que podría ser el archivo incorrecto para esta canción. Este trabajo ha sido cancelado y tu crédito ha sido reembolsado. Por favor, revisa los archivos y vuelve a enviarlos.",
"instrumentalUploadTooLarge": "Este archivo instrumental tiene {size_mb} MB, lo que supera el límite de {max_mb} MB. Por favor, sube una versión en FLAC o MP3 en su lugar.",
"instrumentalConformUnavailable": "No pudimos procesar tu instrumental en este momento. Por favor, intenta enviarlo de nuevo en un momento."
"instrumentalConformUnavailable": "No pudimos procesar tu instrumental en este momento. Por favor, intenta enviarlo de nuevo en un momento.",
"adminRerenderRetryAdminOnly": "Esta pista está siendo rerenderizada por nuestro equipo, por lo que solo un administrador puede reintentarla. Por favor, contacta con soporte y la terminaremos por ti."
},
"review": {
"jobNotFound": "Trabajo no encontrado",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Emme löytäneet lataamaasi instrumentaaliraitaa. Lataus ei ehkä ole valmistunut. Yritä uudelleen.",
"uploadDurationMismatchCancelled": "Taustaraita ({instrumental_duration}s) ei täsmää kappaleen ääniraidan ({audio_duration}s) kanssa, joten se saattaa olla väärä tiedosto tälle kappaleelle. Tämä työ on peruutettu ja krediittisi on palautettu. Tarkista tiedostot ja lähetä uudelleen.",
"instrumentalUploadTooLarge": "Tämä instrumentaalitiedosto on {size_mb} MB, mikä ylittää {max_mb} MB:n rajan. Lataa sen sijaan FLAC- tai MP3-versio.",
"instrumentalConformUnavailable": "Emme voineet käsitellä taustaraitaasi juuri nyt. Yritä lähettää uudelleen hetken kuluttua."
"instrumentalConformUnavailable": "Emme voineet käsitellä taustaraitaasi juuri nyt. Yritä lähettää uudelleen hetken kuluttua.",
"adminRerenderRetryAdminOnly": "Tiimimme renderöi tätä kappaletta uudelleen, joten vain ylläpitäjä voi käynnistää sen uudelleen. Ota yhteyttä tukeen, niin viimeistelemme sen puolestasi."
},
"review": {
"jobNotFound": "Työtä ei löytynyt",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nous n'avons pas trouvé ton instrumentale téléversée. Le téléversement n'est peut-être pas terminé. Réessaie.",
"uploadDurationMismatchCancelled": "L'instrumental ({instrumental_duration}s) ne correspond pas à l'audio du morceau ({audio_duration}s), il s'agit donc peut-être du mauvais fichier pour cette chanson. Cette tâche a été annulée et ton crédit a été remboursé. Vérifie les fichiers et réessaie.",
"instrumentalUploadTooLarge": "Ce fichier instrumental fait {size_mb} Mo, ce qui dépasse la limite de {max_mb} Mo. Téléverse plutôt une version FLAC ou MP3.",
"instrumentalConformUnavailable": "Nous n'avons pas pu traiter ton instrumental à l'instant. Réessaie de le soumettre dans un instant."
"instrumentalConformUnavailable": "Nous n'avons pas pu traiter ton instrumental à l'instant. Réessaie de le soumettre dans un instant.",
"adminRerenderRetryAdminOnly": "Cette piste fait l'objet d'un nouveau rendu par notre équipe, elle ne peut donc être relancée que par un administrateur. Contacte le support et nous la terminerons pour toi."
},
"review": {
"jobNotFound": "Tâche introuvable",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "לא הצלחנו למצוא את הפלייבק שהעליתם. ייתכן שההעלאה לא הושלמה. אנא נסו שוב.",
"uploadDurationMismatchCancelled": "הפלייבק ({instrumental_duration} שניות) אינו תואם לקובץ השמע של השיר ({audio_duration} שניות), ולכן ייתכן שמדובר בקובץ שגוי עבור שיר זה. משימה זו בוטלה והקרדיט שלך הוחזר. נא לבדוק את הקבצים ולשלוח שוב.",
"instrumentalUploadTooLarge": "קובץ הפלייבק הזה הוא בגודל {size_mb} MB, שחורג מהמגבלה של {max_mb} MB. נא להעלות גרסת FLAC או MP3 במקום זאת.",
"instrumentalConformUnavailable": "לא הצלחנו לעבד את הפלייבק שלך כרגע. אנא נסה לשלוח שוב בעוד רגע."
"instrumentalConformUnavailable": "לא הצלחנו לעבד את הפלייבק שלך כרגע. אנא נסה לשלוח שוב בעוד רגע.",
"adminRerenderRetryAdminOnly": "הרצועה הזו מרונדרת מחדש על ידי הצוות שלנו, ולכן רק מנהל מערכת יכול לנסות שוב. אנא צרו קשר עם התמיכה ונסיים זאת עבורכם."
},
"review": {
"jobNotFound": "המשימה לא נמצאה",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "हमें तुम्हारा अपलोड किया गया इंस्ट्रूमेंटल नहीं मिला। हो सकता है कि अपलोड पूरा न हुआ हो। कृपया फिर से कोशिश करो।",
"uploadDurationMismatchCancelled": "इंस्ट्रुमेंटल ({instrumental_duration}s) गाने के ऑडियो ({audio_duration}s) से मेल नहीं खा रहा है, इसलिए हो सकता है कि यह इस गाने के लिए गलत फ़ाइल हो। यह जॉब रद्द कर दिया गया है और तुम्हारा क्रेडिट रिफ़ंड कर दिया गया है। कृपया फ़ाइलों की जाँच करो और फिर से सबमिट करो।",
"instrumentalUploadTooLarge": "यह इंस्ट्रुमेंटल फ़ाइल {size_mb} MB की है, जो {max_mb} MB की सीमा से ज़्यादा है। कृपया इसके बजाय FLAC या MP3 वर्शन अपलोड करो।",
"instrumentalConformUnavailable": "हम अभी तुम्हारा इंस्ट्रुमेंटल प्रोसेस नहीं कर पाए। कृपया थोड़ी देर बाद फिर से सबमिट करने की कोशिश करो।"
"instrumentalConformUnavailable": "हम अभी तुम्हारा इंस्ट्रुमेंटल प्रोसेस नहीं कर पाए। कृपया थोड़ी देर बाद फिर से सबमिट करने की कोशिश करो।",
"adminRerenderRetryAdminOnly": "यह ट्रैक हमारी टीम द्वारा री-रेंडर किया जा रहा है, इसलिए इसे केवल एडमिन ही री-ट्राई कर सकता है। कृपया सपोर्ट से संपर्क करो और हम इसे तुम्हारे लिए पूरा कर देंगे।"
},
"review": {
"jobNotFound": "जॉब नहीं मिली",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nismo uspjeli pronaći tvoj preneseni instrumental. Prijenos možda nije dovršen. Pokušaj ponovno.",
"uploadDurationMismatchCancelled": "Instrumental ({instrumental_duration}s) se ne podudara s audiozapisom pjesme ({audio_duration}s), pa je možda riječ o pogrešnoj datoteci za ovu pjesmu. Ovaj je zadatak otkazan, a tvoj je kredit vraćen. Provjeri datoteke i pošalji ponovno.",
"instrumentalUploadTooLarge": "Ova instrumentalna datoteka ima {size_mb} MB, što premašuje ograničenje od {max_mb} MB. Umjesto toga učitaj FLAC ili MP3 verziju.",
"instrumentalConformUnavailable": "Trenutačno nismo uspjeli obraditi tvoj instrumental. Pokušaj ponovno poslati za koji trenutak."
"instrumentalConformUnavailable": "Trenutačno nismo uspjeli obraditi tvoj instrumental. Pokušaj ponovno poslati za koji trenutak.",
"adminRerenderRetryAdminOnly": "Ovu pjesmu ponovno renderira naš tim, pa je može ponovno pokrenuti samo administrator. Javi se podršci i dovršit ćemo je za tebe."
},
"review": {
"jobNotFound": "Zadatak nije pronađen",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nem találtuk a feltöltött hangszeres sávot. Lehet, hogy a feltöltés nem fejeződött be. Kérlek, próbáld újra.",
"uploadDurationMismatchCancelled": "Az instrumentális sáv ({instrumental_duration} mp) nem vág egybe a dal hanganyagával ({audio_duration} mp), ezért előfordulhat, hogy nem a megfelelő fájl tartozik ehhez a dalhoz. A feladat törölve lett, és a kreditedet visszatérítettük. Kérjük, ellenőrizd a fájlokat, és küldd be újra.",
"instrumentalUploadTooLarge": "Ez az instrumentális fájl {size_mb} MB méretű, ami meghaladja a {max_mb} MB-os limitet. Kérlek, tölts fel helyette egy FLAC vagy MP3 verziót.",
"instrumentalConformUnavailable": "Nem sikerült most feldolgozni a zenei alapodat. Kérlek, próbáld meg újra beküldeni egy pillanat múlva."
"instrumentalConformUnavailable": "Nem sikerült most feldolgozni a zenei alapodat. Kérlek, próbáld meg újra beküldeni egy pillanat múlva.",
"adminRerenderRetryAdminOnly": "Ezt a számot a csapatunk éppen újrarendereli, ezért csak egy adminisztrátor indíthatja újra. Kérjük, lépj kapcsolatba az ügyfélszolgálattal, és befejezzük neked."
},
"review": {
"jobNotFound": "A feladat nem található",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Kami tidak dapat menemukan instrumental yang Anda unggah. Pengunggahan mungkin belum selesai. Silakan coba lagi.",
"uploadDurationMismatchCancelled": "Audio instrumental ({instrumental_duration} detik) tidak selaras dengan audio lagu ({audio_duration} detik), sehingga mungkin ini bukan file yang tepat untuk lagu ini. Proses ini telah dibatalkan dan kredit Anda telah dikembalikan. Silakan periksa file Anda dan kirimkan kembali.",
"instrumentalUploadTooLarge": "File instrumental ini berukuran {size_mb} MB, yang melebihi batas {max_mb} MB. Silakan unggah versi FLAC atau MP3 sebagai gantinya.",
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental Anda barusan. Silakan coba kirimkan lagi beberapa saat lagi."
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental Anda barusan. Silakan coba kirimkan lagi beberapa saat lagi.",
"adminRerenderRetryAdminOnly": "Trek ini sedang dirender ulang oleh tim kami, sehingga hanya dapat dicoba ulang oleh admin. Silakan hubungi tim dukungan dan kami akan menyelesaikannya untuk Anda."
},
"review": {
"jobNotFound": "Tugas tidak ditemukan",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Non siamo riusciti a trovare la base strumentale caricata. Il caricamento potrebbe non essere stato completato. Riprova.",
"uploadDurationMismatchCancelled": "La base strumentale ({instrumental_duration}s) non coincide con l'audio del brano ({audio_duration}s), quindi potrebbe trattarsi del file sbagliato per questo brano. Questo lavoro è stato annullato e il tuo credito è stato rimborsato. Controlla i file e invia di nuovo.",
"instrumentalUploadTooLarge": "Questo file strumentale è di {size_mb} MB, che supera il limite di {max_mb} MB. Carica invece una versione in FLAC o MP3.",
"instrumentalConformUnavailable": "Non siamo riusciti a elaborare la tua base strumentale in questo momento. Riprova a inviarla tra qualche istante."
"instrumentalConformUnavailable": "Non siamo riusciti a elaborare la tua base strumentale in questo momento. Riprova a inviarla tra qualche istante.",
"adminRerenderRetryAdminOnly": "Questa traccia è in fase di re-rendering da parte del nostro team, quindi può essere riavviata solo da un amministratore. Contatta l'assistenza e la completeremo per te."
},
"review": {
"jobNotFound": "Lavoro non trovato",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "アップロードされたインスト音源が見つかりませんでした。アップロードが完了していない可能性があります。もう一度お試しください。",
"uploadDurationMismatchCancelled": "インスト音源({instrumental_duration}秒)の長さが楽曲音源({audio_duration}秒)と一致しないため、この曲とは異なるファイルの可能性があります。このジョブはキャンセルされ、クレジットは返却されました。ファイルをご確認のうえ、再度送信してください。",
"instrumentalUploadTooLarge": "このインスト音源ファイルは{size_mb} MBで、上限の{max_mb} MBを超えています。代わりにFLACまたはMP3形式のファイルをアップロードしてください。",
"instrumentalConformUnavailable": "インスト音源を処理できませんでした。少し時間をおいてから、もう一度送信してください。"
"instrumentalConformUnavailable": "インスト音源を処理できませんでした。少し時間をおいてから、もう一度送信してください。",
"adminRerenderRetryAdminOnly": "このトラックは現在当チームにて再レンダリング中のため、管理者のみ再試行できます。サポートまでお問い合わせいただければ、こちらで処理を完了いたします。"
},
"review": {
"jobNotFound": "ジョブが見つかりません",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "업로드한 반주 파일을 찾을 수 없습니다. 업로드가 완료되지 않았을 수 있습니다. 다시 시도해 주세요.",
"uploadDurationMismatchCancelled": "반주({instrumental_duration}초)의 길이가 원곡 오디오({audio_duration}초)와 일치하지 않아 이 곡에 맞는 파일이 아닐 수 있습니다. 해당 작업은 취소되었으며 크레딧이 환불되었습니다. 파일을 확인하신 후 다시 제출해 주세요.",
"instrumentalUploadTooLarge": "이 반주 파일의 용량은 {size_mb} MB로 제한 용량인 {max_mb} MB를 초과했습니다. 대신 FLAC 또는 MP3 버전으로 업로드해 주세요.",
"instrumentalConformUnavailable": "방금 반주 음원을 처리하지 못했습니다. 잠시 후 다시 제출해 주세요."
"instrumentalConformUnavailable": "방금 반주 음원을 처리하지 못했습니다. 잠시 후 다시 제출해 주세요.",
"adminRerenderRetryAdminOnly": "이 트랙은 현재 저희 팀에서 재렌더링 중이므로 관리자만 다시 시도할 수 있습니다. 지원팀에 문의해 주시면 저희가 작업을 마무리해 드리겠습니다."
},
"review": {
"jobNotFound": "작업을 찾을 수 없습니다",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Kami tidak dapat mencari instrumental yang anda muat naik. Proses muat naik mungkin belum selesai. Sila cuba lagi.",
"uploadDurationMismatchCancelled": "Instrumental ({instrumental_duration}s) tidak sepadan dengan audio lagu ({audio_duration}s), jadi ia mungkin fail yang salah untuk lagu ini. Tugasan ini telah dibatalkan dan kredit anda telah dikembalikan. Sila semak fail tersebut dan hantar semula.",
"instrumentalUploadTooLarge": "Fail instrumental ini bersaiz {size_mb} MB, iaitu melebihi had {max_mb} MB. Sila muat naik versi FLAC atau MP3 sebagai ganti.",
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental anda sebentar tadi. Sila cuba hantar semula sebentar lagi."
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental anda sebentar tadi. Sila cuba hantar semula sebentar lagi.",
"adminRerenderRetryAdminOnly": "Trek ini sedang dirender semula oleh pasukan kami, jadi ia hanya boleh dicuba semula oleh pentadbir. Sila hubungi pihak sokongan dan kami akan menyelesaikannya untuk anda."
},
"review": {
"jobNotFound": "Tugasan tidak dijumpai",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Vi fant ikke den opplastede instrumentalen din. Det kan hende opplastingen ikke ble fullført. Prøv igjen.",
"uploadDurationMismatchCancelled": "Instrumentalsporet ({instrumental_duration}s) stemmer ikke overens med sanglyden ({audio_duration}s), så det kan være feil fil for denne sangen. Denne jobben har blitt kansellert og kreditten din er refundert. Vennligst sjekk filene og send inn på nytt.",
"instrumentalUploadTooLarge": "Denne instrumentalfilen er på {size_mb} MB, noe som er over grensen på {max_mb} MB. Vennligst last opp en FLAC- eller MP3-versjon i stedet.",
"instrumentalConformUnavailable": "Vi kunne ikke behandle instrumentalen din akkurat nå. Prøv å sende inn på nytt om et øyeblikk."
"instrumentalConformUnavailable": "Vi kunne ikke behandle instrumentalen din akkurat nå. Prøv å sende inn på nytt om et øyeblikk.",
"adminRerenderRetryAdminOnly": "Dette sporet rendres på nytt av teamet vårt, så det kan kun prøves på nytt av en administrator. Ta kontakt med kundestøtte, så fullfører vi det for deg."
},
"review": {
"jobNotFound": "Jobben ble ikke funnet",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "We konden je geüploade instrumentale track niet vinden. De upload is mogelijk niet voltooid. Probeer het opnieuw.",
"uploadDurationMismatchCancelled": "De instrumentale track ({instrumental_duration}s) komt niet overeen met de audio van het nummer ({audio_duration}s), dus het is mogelijk het verkeerde bestand voor dit nummer. Deze opdracht is geannuleerd en je tegoed is teruggestort. Controleer de bestanden en dien de aanvraag opnieuw in.",
"instrumentalUploadTooLarge": "Dit instrumentale bestand is {size_mb} MB, wat de limiet van {max_mb} MB overschrijdt. Upload in plaats daarvan een FLAC- of MP3-versie.",
"instrumentalConformUnavailable": "We konden je instrumental zojuist niet verwerken. Probeer het over een ogenblik opnieuw in te dienen."
"instrumentalConformUnavailable": "We konden je instrumental zojuist niet verwerken. Probeer het over een ogenblik opnieuw in te dienen.",
"adminRerenderRetryAdminOnly": "Dit nummer wordt opnieuw gerenderd door ons team, dus alleen een beheerder kan dit opnieuw proberen. Neem contact op met support en we maken het voor je af."
},
"review": {
"jobNotFound": "Taak niet gevonden",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nie udało się znaleźć Twojego przesłanego podkładu instrumentalnego. Przesyłanie mogło się nie zakończyć. Spróbuj ponownie.",
"uploadDurationMismatchCancelled": "Wersja instrumentalna ({instrumental_duration}s) nie zgadza się z plikiem audio utworu ({audio_duration}s), więc może to być niewłaściwy plik dla tej piosenki. To zadanie zostało anulowane, a Twój kredyt zwrócony. Sprawdź pliki i prześlij je ponownie.",
"instrumentalUploadTooLarge": "Ten plik instrumentalny ma {size_mb} MB, co przekracza limit {max_mb} MB. Prześlij zamiast tego wersję FLAC lub MP3.",
"instrumentalConformUnavailable": "Nie udało nam się teraz przetworzyć Twojego podkładu instrumentalnego. Spróbuj przesłać go ponownie za chwilę."
"instrumentalConformUnavailable": "Nie udało nam się teraz przetworzyć Twojego podkładu instrumentalnego. Spróbuj przesłać go ponownie za chwilę.",
"adminRerenderRetryAdminOnly": "Ten utwór jest ponownie renderowany przez nasz zespół, więc tylko administrator może ponowić próbę. Skontaktuj się ze wsparciem, a dokończymy to dla Ciebie."
},
"review": {
"jobNotFound": "Nie znaleziono zadania",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Não conseguimos encontrar o instrumental enviado. O upload pode não ter sido concluído. Tente novamente.",
"uploadDurationMismatchCancelled": "O instrumental ({instrumental_duration}s) não coincide com o áudio da música ({audio_duration}s), portanto pode ser o arquivo errado para esta música. Esta tarefa foi cancelada e seu crédito foi reembolsado. Por favor, verifique os arquivos e envie novamente.",
"instrumentalUploadTooLarge": "Este arquivo instrumental tem {size_mb} MB, o que ultrapassa o limite de {max_mb} MB. Por favor, envie uma versão em FLAC ou MP3 em vez disso.",
"instrumentalConformUnavailable": "Não conseguimos processar seu instrumental agora. Por favor, tente enviar novamente em alguns instantes."
"instrumentalConformUnavailable": "Não conseguimos processar seu instrumental agora. Por favor, tente enviar novamente em alguns instantes.",
"adminRerenderRetryAdminOnly": "Esta faixa está sendo renderizada novamente pela nossa equipe, então só um administrador pode tentar novamente. Entre em contato com o suporte e nós a finalizaremos para você."
},
"review": {
"jobNotFound": "Job não encontrado",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nu am putut găsi instrumentalul încărcat. Este posibil ca încărcarea să nu se fi finalizat. Te rugăm să încerci din nou.",
"uploadDurationMismatchCancelled": "Instrumentalul ({instrumental_duration}s) nu se potrivește cu fișierul audio al melodiei ({audio_duration}s), așa că este posibil să fie fișierul greșit pentru această melodie. Această sarcină a fost anulată, iar creditul tău a fost rambursat. Te rugăm să verifici fișierele și să trimiți din nou.",
"instrumentalUploadTooLarge": "Acest fișier instrumental are {size_mb} MB, ceea ce depășește limita de {max_mb} MB. Te rugăm să încarci în schimb o versiune FLAC sau MP3.",
"instrumentalConformUnavailable": "Nu am putut procesa instrumentalul tău chiar acum. Te rugăm să încerci să trimiți din nou peste câteva momente."
"instrumentalConformUnavailable": "Nu am putut procesa instrumentalul tău chiar acum. Te rugăm să încerci să trimiți din nou peste câteva momente.",
"adminRerenderRetryAdminOnly": "Această piesă este randată din nou de echipa noastră, așa că poate fi reîncercată doar de un administrator. Te rugăm să contactezi echipa de asistență și o vom finaliza pentru tine."
},
"review": {
"jobNotFound": "Jobul nu a fost găsit",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Мы не смогли найти твой загруженный инструментал. Возможно, загрузка не завершилась. Попробуй ещё раз.",
"uploadDurationMismatchCancelled": "Длительность инструментала ({instrumental_duration} с) не совпадает с длительностью аудио песни ({audio_duration} с), поэтому, возможно, для этой песни выбран не тот файл. Задача отменена, а твой кредит возвращен. Пожалуйста, проверь файлы и отправь снова.",
"instrumentalUploadTooLarge": "Этот файл инструментала весит {size_mb} МБ, что превышает лимит в {max_mb} МБ. Пожалуйста, загрузи вместо него версию в формате FLAC или MP3.",
"instrumentalConformUnavailable": "Нам не удалось обработать твой инструментал прямо сейчас. Пожалуйста, попробуй отправить снова чуть позже."
"instrumentalConformUnavailable": "Нам не удалось обработать твой инструментал прямо сейчас. Пожалуйста, попробуй отправить снова чуть позже.",
"adminRerenderRetryAdminOnly": "Этот трек сейчас повторно рендерится нашей командой, поэтому перезапустить его может только администратор. Пожалуйста, свяжись с поддержкой, и мы всё доделаем."
},
"review": {
"jobNotFound": "Задача не найдена",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Nenašli sme tvoj nahraný inštrumentál. Nahrávanie sa pravdepodobne nedokončilo. Skús to, prosím, znova.",
"uploadDurationMismatchCancelled": "Inštrumentálna stopa ({instrumental_duration}s) sa nezhoduje so zvukom skladby ({audio_duration}s), takže môže ísť o nesprávny súbor pre túto skladbu. Táto úloha bola zrušená a tvoj kredit bol vrátený. Prosím, skontroluj súbory a odošli ich znova.",
"instrumentalUploadTooLarge": "Tento inštrumentálny súbor má {size_mb} MB, čo prekračuje limit {max_mb} MB. Namiesto toho prosím nahraj verziu vo formáte FLAC alebo MP3.",
"instrumentalConformUnavailable": "Nepodarilo sa nám práve spracovať tvoj inštrumentál. Skús to, prosím, o chvíľu odoslať znova."
"instrumentalConformUnavailable": "Nepodarilo sa nám práve spracovať tvoj inštrumentál. Skús to, prosím, o chvíľu odoslať znova.",
"adminRerenderRetryAdminOnly": "Túto skladbu práve nanovo renderuje náš tím, takže ju môže znova spustiť iba administrátor. Kontaktuj, prosím, podporu a my to pre teba dokončíme."
},
"review": {
"jobNotFound": "Úloha sa nenašla",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Vi kunde inte hitta ditt uppladdade instrumentala spår. Uppladdningen slutfördes eventuellt inte. Försök igen.",
"uploadDurationMismatchCancelled": "Instrumentalspåret ({instrumental_duration}s) stämmer inte överens med låtens ljud ({audio_duration}s), så det kan vara fel fil för den här låten. Det här jobbet har avbrutits och din kredit har återbetalats. Kontrollera filerna och skicka in igen.",
"instrumentalUploadTooLarge": "Den här instrumentalfilen är på {size_mb} MB, vilket överskrider gränsen på {max_mb} MB. Ladda upp en FLAC- eller MP3-version istället.",
"instrumentalConformUnavailable": "Vi kunde inte bearbeta ditt instrumentalspår just nu. Försök att skicka in igen om en stund."
"instrumentalConformUnavailable": "Vi kunde inte bearbeta ditt instrumentalspår just nu. Försök att skicka in igen om en stund.",
"adminRerenderRetryAdminOnly": "Det här spåret renderas om av vårt team, så det kan endast köras om av en administratör. Kontakta supporten så slutför vi det åt dig."
},
"review": {
"jobNotFound": "Jobbet hittades inte",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "เราไม่พบไฟล์เสียงดนตรีที่คุณอัปโหลด การอัปโหลดอาจยังไม่เสร็จสมบูรณ์ โปรดลองอีกครั้ง",
"uploadDurationMismatchCancelled": "ไฟล์ดนตรี ({instrumental_duration} วินาที) มีความยาวไม่ตรงกับไฟล์เสียงเพลง ({audio_duration} วินาที) จึงอาจเป็นไฟล์ที่ไม่ถูกต้องสำหรับเพลงนี้ รายการนี้ถูกยกเลิกแล้วและระบบได้คืนเครดิตของคุณเรียบร้อยแล้ว โปรดตรวจสอบไฟล์และส่งใหม่อีกครั้ง",
"instrumentalUploadTooLarge": "ไฟล์เสียงดนตรีนี้มีขนาด {size_mb} MB ซึ่งเกินขีดจำกัด {max_mb} MB โปรดอัปโหลดเป็นเวอร์ชัน FLAC หรือ MP3 แทน",
"instrumentalConformUnavailable": "เราไม่สามารถประมวลผลไฟล์ดนตรีของคุณได้ในขณะนี้ โปรดลองส่งใหม่อีกครั้งในอีกสักครู่"
"instrumentalConformUnavailable": "เราไม่สามารถประมวลผลไฟล์ดนตรีของคุณได้ในขณะนี้ โปรดลองส่งใหม่อีกครั้งในอีกสักครู่",
"adminRerenderRetryAdminOnly": "เพลงนี้ทีมงานของเรากำลังเรนเดอร์ใหม่อยู่ จึงมีเพียงผู้ดูแลระบบเท่านั้นที่สามารถลองใหม่อีกครั้งได้ โปรดติดต่อฝ่ายสนับสนุน แล้วเราจะจัดการให้เสร็จเรียบร้อย"
},
"review": {
"jobNotFound": "ไม่พบงาน",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Hindi namin mahanap ang na-upload mong instrumental. Maaaring hindi natapos ang pag-upload. Pakisubukan muli.",
"uploadDurationMismatchCancelled": "Hindi tumutugma ang instrumental ({instrumental_duration}s) sa audio ng kanta ({audio_duration}s), kaya maaaring maling file ito para sa kantang ito. Kinansela ang job na ito at na-refund ang iyong credit. Pakisuri ang mga file at i-submit muli.",
"instrumentalUploadTooLarge": "Ang instrumental file na ito ay {size_mb} MB, na lampas sa {max_mb} MB na limitasyon. Mangyaring mag-upload na lang ng bersyong FLAC o MP3.",
"instrumentalConformUnavailable": "Hindi namin naproseso ang iyong instrumental sa ngayon. Pakisubukang isumite muli sa ilang sandali."
"instrumentalConformUnavailable": "Hindi namin naproseso ang iyong instrumental sa ngayon. Pakisubukang isumite muli sa ilang sandali.",
"adminRerenderRetryAdminOnly": "Kasalukuyang nire-render muli ng aming team ang track na ito, kaya admin lamang ang maaaring sumubok muli nito. Mangyaring makipag-ugnayan sa support at tatapusin namin ito para sa iyo."
},
"review": {
"jobNotFound": "Hindi nahanap ang job",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Yüklediğin enstrümantali bulamadık. Yükleme tamamlanmamış olabilir. Lütfen tekrar dene.",
"uploadDurationMismatchCancelled": "Enstrümantal ({instrumental_duration} sn.) şarkı sesiyle ({audio_duration} sn.) uyuşmuyor, bu yüzden bu şarkı için yanlış dosya olabilir. Bu işlem iptal edildi ve kredin iade edildi. Lütfen dosyaları kontrol edip tekrar gönder.",
"instrumentalUploadTooLarge": "Bu enstrümantal dosya {size_mb} MB ve {max_mb} MB sınırını aşıyor. Lütfen bunun yerine bir FLAC veya MP3 sürümü yükle.",
"instrumentalConformUnavailable": "Enstrümantal parçanı şu anda işleyemedik. Lütfen birazdan tekrar göndermeyi dene."
"instrumentalConformUnavailable": "Enstrümantal parçanı şu anda işleyemedik. Lütfen birazdan tekrar göndermeyi dene.",
"adminRerenderRetryAdminOnly": "Bu parça ekibimiz tarafından yeniden işleniyor, bu nedenle yalnızca bir yönetici tarafından yeniden denenebilir. Lütfen destek ekibiyle iletişime geç, senin için tamamlayalım."
},
"review": {
"jobNotFound": "İş bulunamadı",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Нам не вдалося знайти твій завантажений інструментал. Можливо, завантаження не завершилося. Будь ласка, спробуй ще раз.",
"uploadDurationMismatchCancelled": "Інструментал ({instrumental_duration} с) не збігається з аудіо пісні ({audio_duration} с), тому, можливо, це неправильний файл для цієї пісні. Це завдання скасовано, а твій кредит повернено. Будь ласка, перевір файли та надішли знову.",
"instrumentalUploadTooLarge": "Цей інструментальний файл має розмір {size_mb} МБ, що перевищує ліміт у {max_mb} МБ. Будь ласка, завантаж натомість версію у форматі FLAC або MP3.",
"instrumentalConformUnavailable": "Нам щойно не вдалося обробити твій інструментал. Будь ласка, спробуй надіслати ще раз за мить."
"instrumentalConformUnavailable": "Нам щойно не вдалося обробити твій інструментал. Будь ласка, спробуй надіслати ще раз за мить.",
"adminRerenderRetryAdminOnly": "Цей трек зараз повторно рендерить наша команда, тому повторити спробу може лише адміністратор. Будь ласка, звернися до служби підтримки, і ми все завершимо для тебе."
},
"review": {
"jobNotFound": "Завдання не знайдено",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "Chúng tôi không tìm thấy bản nhạc nền bạn đã tải lên. Quá trình tải lên có thể chưa hoàn tất. Vui lòng thử lại.",
"uploadDurationMismatchCancelled": "Bản nhạc không lời ({instrumental_duration}s) không khớp với âm thanh bài hát ({audio_duration}s), do đó có thể đây không phải là tệp chính xác cho bài hát này. Tác vụ này đã bị hủy và credit của bạn đã được hoàn lại. Vui lòng kiểm tra lại các tệp và gửi lại.",
"instrumentalUploadTooLarge": "Tệp nhạc nền này có dung lượng {size_mb} MB, vượt quá giới hạn {max_mb} MB. Vui lòng tải lên phiên bản FLAC hoặc MP3 thay thế.",
"instrumentalConformUnavailable": "Hiện tại chúng tôi không thể xử lý bản nhạc nền của bạn. Vui lòng thử gửi lại sau giây lát."
"instrumentalConformUnavailable": "Hiện tại chúng tôi không thể xử lý bản nhạc nền của bạn. Vui lòng thử gửi lại sau giây lát.",
"adminRerenderRetryAdminOnly": "Bài hát này đang được đội ngũ của chúng tôi kết xuất lại, nên chỉ có quản trị viên mới có thể thử lại. Vui lòng liên hệ với bộ phận hỗ trợ và chúng tôi sẽ hoàn tất giúp bạn."
},
"review": {
"jobNotFound": "Không tìm thấy công việc",
+2 -1
View File
@@ -55,7 +55,8 @@
"instrumentalUploadMissing": "未找到您上传的伴奏。上传可能尚未完成,请重试。",
"uploadDurationMismatchCancelled": "伴奏时长({instrumental_duration} 秒)与歌曲音频时长({audio_duration} 秒)不匹配,可能不是该歌曲对应的正确文件。该任务已取消,您的点数已退还。请检查文件后重新提交。",
"instrumentalUploadTooLarge": "此伴奏文件大小为 {size_mb} MB,已超出 {max_mb} MB 的限制。请改为上传 FLAC 或 MP3 版本。",
"instrumentalConformUnavailable": "我们刚才无法处理您的伴奏。请稍后重新尝试提交。"
"instrumentalConformUnavailable": "我们刚才无法处理您的伴奏。请稍后重新尝试提交。",
"adminRerenderRetryAdminOnly": "这首歌曲正由我们的团队重新渲染,因此只能由管理员重试。请联系客服,我们会为您完成制作。"
},
"review": {
"jobNotFound": "未找到任务",
+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:
+54 -13
View File
@@ -37,9 +37,15 @@ from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.admin_rerender_service import (
active_admin_rerender,
admin_rerender_kept_outputs,
suppress_customer_notifications,
)
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
@@ -385,12 +391,15 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# visibility-change flow or the worker_generation supersession fence
# (an Increment reverted by a stale full-map write). Dot-path writes
# touch only the distribution-result keys.
# An admin re-render leaves outputs it doesn't re-publish in place
# (e.g. YouTube now disabled) — keep their links.
kept_outputs = admin_rerender_kept_outputs(job)
state_updates: Dict[str, Any] = {
'state_data.brand_code': result.brand_code,
'state_data.youtube_url': result.youtube_url,
'state_data.youtube_url': result.youtube_url or kept_outputs.get('youtube_url'),
'state_data.youtube_upload_queued': result.youtube_upload_queued,
'state_data.dropbox_link': result.dropbox_link,
'state_data.gdrive_files': result.gdrive_files,
'state_data.dropbox_link': result.dropbox_link or kept_outputs.get('dropbox_link'),
'state_data.gdrive_files': result.gdrive_files or kept_outputs.get('gdrive_files'),
# Clear the visibility-change guard flag (previously popped from the map).
'state_data.visibility_change_in_progress': DELETE_FIELD,
# Fresh finals were just uploaded, so any earlier "outputs deleted"
@@ -398,9 +407,11 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# this job distributes anywhere (tenant jobs never do).
'outputs_deleted_at': None,
'outputs_deleted_by': None,
# A theme re-render (if any) finished; only a FAILED re-render
# keeps this marker (it lets the retry re-run the re-render).
# A theme/admin re-render (if any) finished; only a FAILED
# re-render keeps its marker (it lets the retry re-run it).
'state_data.theme_rerender': DELETE_FIELD,
# The admin re-render marker is cleared atomically WITH the
# COMPLETE transition below, so a failed transition keeps it.
}
if result.distribution_warnings:
state_updates['state_data.distribution_warnings'] = result.distribution_warnings
@@ -432,12 +443,26 @@ async def generate_video_orchestrated(job_id: str) -> bool:
}
if result.distribution_warnings:
completion_metadata["distribution_warnings"] = result.distribution_warnings
# An admin re-render only emails/pushes the customer if the admin
# opted in (read from the snapshot taken at worker start — the
# marker itself was just cleared above).
notify_customer = not suppress_customer_notifications(job)
is_admin_rerender = bool(active_admin_rerender(job))
if is_admin_rerender:
completion_metadata["admin_rerender"] = True
completion_metadata["customer_notified"] = notify_customer
if not notify_customer:
job_log.info("Admin re-render: completion email/push suppressed (notify_customer=False)")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.COMPLETE,
progress=100,
message="Karaoke generation complete!",
timeline_metadata=completion_metadata,
notify=notify_customer,
extra_updates={'state_data.admin_rerender': DELETE_FIELD},
# An admin re-render isn't a newly completed job for the user.
count_completion=not is_admin_rerender,
)
# If this was a requests-board community pick published directly here
@@ -448,6 +473,9 @@ async def generate_video_orchestrated(job_id: str) -> bool:
if result.youtube_url and not result.youtube_upload_queued:
try:
from backend.services.community_publish import notify_community_publish
# Idempotent: voters already fully notified are never
# re-emailed, so a quiet admin re-render only completes an
# OWED fan-out (voters are owed "it's live").
await notify_community_publish(job_id, result.youtube_url)
except Exception:
logger.exception(f"[job:{job_id}] Community publish fan-out failed (non-fatal)")
@@ -597,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),
@@ -948,7 +977,11 @@ async def generate_video_legacy(job_id: str) -> bool:
organised_dir_rclone_root=getattr(job, 'organised_dir_rclone_root', None),
public_share_dir=None, # Not used in cloud
# Notifications
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
# A quiet admin re-render doesn't announce the new video.
discord_webhook_url=(
None if suppress_customer_notifications(job)
else getattr(job, 'discord_webhook_url', None)
),
# YouTube upload (server-side with pre-loaded credentials)
youtube_client_secrets_file=None, # Not used with pre-stored credentials
youtube_description_file=youtube_desc_path,
@@ -1015,14 +1048,20 @@ async def generate_video_legacy(job_id: str) -> bool:
# _handle_native_distribution already saved them but job.state_data
# is stale (fetched before distribution ran)
logger.info(f"[job:{job_id}] Video generation complete")
notify_customer = not suppress_customer_notifications(job)
kept_outputs = admin_rerender_kept_outputs(job)
new_state_data = {
**job.state_data,
'brand_code': result.get('brand_code'),
'youtube_url': result.get('youtube_url') or kept_outputs.get('youtube_url'),
'dropbox_link': result.get('dropbox_link') or kept_outputs.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files') or kept_outputs.get('gdrive_files'),
}
# A theme/admin re-render finished — drop its marker.
new_state_data.pop('theme_rerender', None)
new_state_data.pop('admin_rerender', None)
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': result.get('brand_code'),
'youtube_url': result.get('youtube_url'),
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
},
'state_data': new_state_data,
'outputs_deleted_at': None,
'outputs_deleted_by': None,
})
@@ -1044,6 +1083,8 @@ async def generate_video_legacy(job_id: str) -> bool:
progress=100,
message="Karaoke generation complete!",
timeline_metadata=completion_metadata,
notify=notify_customer,
count_completion=not active_admin_rerender(job),
)
# Advance a requests-board community pick to `published` + fan out
+24 -5
View File
@@ -27,9 +27,11 @@ 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
from backend.services.admin_rerender_service import suppress_customer_notifications
from backend.services.original_audio import (
original_audio_gcs_path,
original_audio_output_filename,
@@ -67,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
@@ -81,6 +85,11 @@ class OrchestratorConfig:
# Keep existing brand code (for re-processing)
keep_brand_code: Optional[str] = None
# Whether this run may be announced (False for an admin re-render the admin
# didn't opt into announcing). Gates the Discord "new video" post and the
# follow-up email of a quota-deferred YouTube upload.
notify_customer: bool = True
# Instrumental selection (clean, with_backing, or custom)
instrumental_selection: str = "clean"
@@ -806,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
@@ -873,6 +885,7 @@ class VideoWorkerOrchestrator:
title=self.config.title,
brand_code=self.result.brand_code,
reason=reason,
notify_user=self.config.notify_customer,
)
self.result.youtube_upload_queued = True
self.job_log.info(f"YouTube upload queued for later processing (reason: {reason})")
@@ -1077,6 +1090,10 @@ class VideoWorkerOrchestrator:
self.job_log.debug("No Discord webhook configured, skipping notification")
return
if not self.config.notify_customer:
self.job_log.info("Admin re-render without notification: skipping Discord post")
return
if not self.result.youtube_url:
self.job_log.info("No YouTube URL available, skipping Discord notification")
return
@@ -1234,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)
@@ -1246,6 +1264,7 @@ def create_orchestrator_config_from_job(
# Keep existing brand code
keep_brand_code=getattr(job, 'keep_brand_code', None) or rerender_brand_code(job),
notify_customer=not suppress_customer_notifications(job),
# Instrumental selection (for GCE encoding)
instrumental_selection=instrumental_selection,
+130 -36
View File
@@ -4,6 +4,7 @@ YouTube upload queue processor.
Processes deferred YouTube uploads when quota is available.
Called by Cloud Scheduler via an internal endpoint (hourly).
"""
import asyncio
import logging
import os
import shutil
@@ -20,6 +21,12 @@ from backend.services.youtube_upload_queue_service import get_youtube_upload_que
logger = logging.getLogger(__name__)
# Uploads attempted per run (quota-bound anyway) vs entries fetched: the fetch
# is larger so entries whose claim is refused (job mid admin re-render) can't
# fill the page and starve everything behind them.
MAX_UPLOADS_PER_RUN = 20
QUEUE_FETCH_LIMIT = 100
async def process_youtube_upload_queue() -> Dict[str, Any]:
"""
@@ -48,8 +55,9 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
"remaining": len(queue_service.get_queued_uploads()),
}
# Get queued uploads
queued = queue_service.get_queued_uploads(limit=20)
# Get queued uploads. Fetch more than we'll upload so entries whose claim is
# refused (job mid admin re-render) can't fill the page and starve others.
queued = queue_service.get_queued_uploads(limit=QUEUE_FETCH_LIMIT)
if not queued:
logger.info("YouTube queue processor: no uploads queued")
return {
@@ -62,11 +70,18 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
logger.info(f"YouTube queue processor: processing {len(queued)} queued uploads")
# One batched read of the jobs (for the admin re-render notification
# choice) instead of a Firestore round-trip per entry.
jobs = await asyncio.to_thread(_get_jobs_batch, queue_service.db, [e["job_id"] for e in queued])
processed = 0
failed = 0
attempted = 0
for entry in queued:
job_id = entry["job_id"]
if attempted >= MAX_UPLOADS_PER_RUN:
break
# Re-check quota before each upload
allowed, remaining, message = quota_service.check_quota_available()
@@ -74,26 +89,23 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
logger.info(f"YouTube queue processor: quota exhausted after {processed} uploads")
break
# Claim the entry
# Claim the entry. The claim transaction also reads the job and refuses
# while an admin re-render is active on it (the re-render's claim in turn
# refuses while an upload is processing), so the two never overlap.
if not queue_service.mark_processing(job_id):
logger.info(f"YouTube queue processor: could not claim job {job_id}, skipping")
continue
attempted += 1
uploaded_url = None
try:
youtube_url = await _process_single_upload(job_id, entry, quota_service, settings)
if youtube_url:
uploaded_url = youtube_url
# Record completion FIRST: from here on the entry must never go
# back to "queued" (that would upload the video a second time).
queue_service.mark_completed(job_id, youtube_url)
# Update job state_data with the YouTube URL
_update_job_youtube_url(job_id, youtube_url)
# Send follow-up email
await _send_youtube_upload_notification(job_id, entry, youtube_url)
# If this was a requests-board community pick, mark it published
# and fan out "your track is live" emails to everyone who voted.
await notify_community_publish(job_id, youtube_url)
await _after_successful_upload(job_id, entry, youtube_url, jobs.get(job_id), queue_service)
processed += 1
else:
queue_service.mark_failed(job_id, "Upload returned no URL")
@@ -103,6 +115,13 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
error_str = str(e)
logger.exception(f"YouTube queue processor: failed to process job {job_id}: {e}")
if uploaded_url:
# The video IS on YouTube; only recording it failed. Never
# re-queue — flag for attention instead.
_flag_post_upload_error(queue_service, job_id, uploaded_url, error_str)
processed += 1
continue
# If quota exceeded, stop processing entirely
if "quotaExceeded" in error_str:
queue_service.mark_failed(job_id, f"Quota exceeded: {error_str}")
@@ -126,6 +145,74 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
}
async def _after_successful_upload(job_id: str, entry: Dict[str, Any], youtube_url: str, job, queue_service) -> None:
"""Post-upload side effects. Each is isolated: a failure is logged and the
entry flagged for attention, never re-queued (the upload already happened)."""
try:
# Update job state_data with the YouTube URL
_update_job_youtube_url(job_id, youtube_url)
except Exception as e:
logger.exception(f"YouTube queue processor: failed to record URL for job {job_id}")
_flag_post_upload_error(queue_service, job_id, youtube_url, f"update job: {e}")
# Send follow-up email — unless queued by (or processed during) an admin
# re-render that wasn't meant to notify the customer.
from backend.services.admin_rerender_service import suppress_customer_notifications
if entry.get("notify_user", True) and not (job is not None and suppress_customer_notifications(job)):
await _send_youtube_upload_notification(job_id, entry, youtube_url)
else:
logger.info(f"YouTube queue processor: skipping follow-up email for job {job_id} (notifications suppressed)")
# If this was a requests-board community pick, mark it published and fan out
# "your track is live" emails to everyone who voted (idempotent: voters
# already notified are never re-emailed).
try:
await notify_community_publish(job_id, youtube_url)
except Exception as e:
logger.exception(f"YouTube queue processor: community publish failed for job {job_id}")
_flag_post_upload_error(queue_service, job_id, youtube_url, f"community publish: {e}")
def _flag_post_upload_error(queue_service, job_id: str, youtube_url: str, error: str) -> None:
"""Mark an uploaded entry as needing attention — terminal, never re-queued."""
try:
queue_service.mark_post_upload_error(job_id, youtube_url, error)
except Exception:
logger.exception(f"YouTube queue processor: could not flag post-upload error for job {job_id}")
def _get_jobs_batch(db, job_ids) -> Dict[str, Any]:
"""Read the given jobs in one ``get_all`` call; returns ``{job_id: job view}``.
The view carries only what the notification check needs (status,
review_token, state_data). Best-effort: on error, returns ``{}`` (the
authoritative admin re-render check is in the claim transaction).
"""
from types import SimpleNamespace
unique_ids = list(dict.fromkeys(job_ids))
if not unique_ids:
return {}
try:
collection = db.collection(get_settings().firestore_collection)
refs = [collection.document(job_id) for job_id in unique_ids]
jobs = {}
for snapshot in db.get_all(refs):
if not snapshot.exists:
continue
data = snapshot.to_dict() or {}
jobs[snapshot.id] = SimpleNamespace(
job_id=snapshot.id,
status=data.get("status"),
review_token=data.get("review_token"),
state_data=data.get("state_data") or {},
)
return jobs
except Exception as e:
logger.warning(f"YouTube queue processor: batch job read failed: {e}")
return {}
async def _process_single_upload(
job_id: str,
entry: Dict[str, Any],
@@ -170,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
@@ -288,21 +380,23 @@ def _create_youtube_service(settings):
def _update_job_youtube_url(job_id: str, youtube_url: str) -> None:
"""Update job state_data with the YouTube URL after deferred upload."""
try:
job_manager = JobManager()
job = job_manager.get_job(job_id)
if job:
# Atomic per-field writes: this deferred upload can land while other
# state_data is being written, so rewriting the whole map from a
# snapshot could clobber a sibling key.
job_manager.update_job(job_id, {
"state_data.youtube_url": youtube_url,
"state_data.youtube_upload_queued": False, # No longer queued
})
logger.info(f"Updated job {job_id} state_data with YouTube URL")
except Exception as e:
logger.error(f"Failed to update job {job_id} with YouTube URL: {e}")
"""Update job state_data with the YouTube URL after deferred upload.
Raises on failure (including a missing job) so the caller records the queue
entry as completed-with-``needs_attention`` instead of silently losing the URL.
"""
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise RuntimeError(f"job {job_id} not found while recording YouTube URL {youtube_url}")
# Atomic per-field writes: this deferred upload can land while other
# state_data is being written, so rewriting the whole map from a
# snapshot could clobber a sibling key.
job_manager.update_job(job_id, {
"state_data.youtube_url": youtube_url,
"state_data.youtube_upload_queued": False, # No longer queued
})
logger.info(f"Updated job {job_id} state_data with YouTube URL")
async def _send_youtube_upload_notification(
+84
View File
@@ -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
@@ -1464,6 +1485,37 @@ POST /api/internal/jobs/{job_id}/trigger-render-video
POST /api/internal/jobs/{job_id}/trigger-video
```
#### Vocal gaps (missing-lyrics detector, shadow mode)
```http
POST /api/internal/jobs/{job_id}/vocal-gaps[?dry_run=true]
```
Finds sung stretches with no transcribed words — transcription can silently drop whole
lines, which then render as a fake "INSTRUMENTAL" section. Downloads the job's lead-vocal
stem server-side, analyzes the job's current lyrics (`corrections_updated.json` if present)
and stores `state_data.vocal_gaps` (skipped with `dry_run=true`). Never changes job status.
The same analysis runs automatically in the auto-approval executor once stems exist.
```json
{
"job_id": "5710831e",
"status": "checked",
"stored": true,
"vocal_gaps": {
"version": "0.1.0",
"gaps": [{"start": 20.66, "end": 32.4, "duration": 11.74, "active_fraction": 0.96,
"longest_run_s": 11.76, "suspect": true,
"reference_lines": {"genius": ["…", "…", "…"]}}],
"suspect_count": 1, "max_suspect_run_s": 11.76,
"source": "backfill", "lyrics_source": "corrections_updated", "analyzed_at": "…"
}
}
```
`status` is one of `checked`, `no_job`, `no_corrections`, `no_lead_stem`, `error`.
Bulk calibration: `scripts/audit_vocal_gaps.py`.
## Job States
| State | Description |
@@ -2398,6 +2450,38 @@ Response:
Screen generation takes 30-60 seconds. Monitor progress via job timeline or logs.
#### Re-render Any Completed Job (Admin)
```http
POST /api/admin/jobs/{job_id}/rerender
Authorization: Bearer ADMIN_TOKEN
Content-Type: application/json
{"notify_customer": false}
```
Rebuilds a completed job end to end with the **current renderer** (e.g. after a renderer bug fix): title/end screens, the karaoke video, every encoded format, CDG/TXT packages, then distribution. It reuses the reviewed `corrections_updated.json`, `state_data.instrumental_selection` and the job's **existing style snapshot** (`style_params_gcs_path` / `style_assets` — no theme re-snapshot), so there is no review step. Works for consumer and tenant, public and private jobs. Surfaced as the admin-only "Re-render" button on job cards in `/app`.
- **Body** (optional): `notify_customer` (default `false`). When false, the completion email + push, the follow-up email of a quota-deferred YouTube upload, and the Discord "new video" post are skipped. Community-pick voters who were already notified aren't re-emailed; an owed (never/partially sent) "it's live" fan-out still goes out. The community request gets the new YouTube URL.
- **Published outputs** are deleted up front (YouTube video, Google Drive files, Dropbox folder `{dropbox_path}/{brand_code} - {Artist} - {Title}`; private jobs use the private Dropbox path) and re-published at the end of the pipeline — but only for destinations the job will still publish to (YouTube: `enable_youtube_upload`, not private, credentials configured; Dropbox: `dropbox_path` + `brand_prefix`; GDrive: `gdrive_folder_id`). Others are left in place (`cleanup_results.<dest>.status = "kept"`, listed in `warnings`) and keep their link. A pending quota-deferred YouTube upload for the job is cancelled (atomically with the claim) only when YouTube will be re-published (otherwise it stays queued, with a warning); if that upload is currently in progress the request is refused with **409** — retry in a few minutes. While the re-render runs, the YouTube queue won't start an upload for the job. Admin re-render completions don't count towards the user's completed-jobs total. The **brand code is kept** (not recycled): `state_data.admin_rerender.brand_code` → orchestrator `keep_brand_code`. YouTube gets a new upload, so the **YouTube URL changes**. Cleanup failures are logged but don't abort (re-uploads replace same-named leftovers).
- Marker `state_data.admin_rerender` (`requested_by`, `requested_at`, `notify_customer`, `brand_code`, `previous_outputs`, `cleanup_results`) is cleared on success; it also records the job's `review_token` and stops applying once the job goes back through review (and admin reset/restart/delete-outputs, Edit and private→public visibility clear it). A failed admin re-render keeps it: an **admin** `POST /api/jobs/{id}/retry` (customers get 403 while the marker is active) re-runs the re-render (`retry_stage: "admin_rerender"`) while screens are missing, otherwise the normal render/video retry resumes it, still keeping the brand code and the notification choice.
Response:
```json
{
"status": "processing",
"job_id": "abc123",
"message": "Re-render started. Published outputs will be replaced when it completes.",
"brand_code": "NOMAD-1234",
"notify_customer": false,
"previous_outputs": {"youtube_url": "https://www.youtube.com/watch?v=...", "brand_code": "NOMAD-1234", "dropbox_link": "...", "gdrive_files": {"mp4": "..."}},
"cleanup_results": {"youtube": {"status": "success", "video_id": "..."}, "dropbox": {"status": "success", "path": "..."}, "gdrive": {"status": "success", "files": {}}, "youtube_queue": {"status": "skipped", "reason": "no queue entry"}, "brand_code": {"status": "kept", "code": "NOMAD-1234"}},
"warnings": []
}
```
Errors: **403** non-admin; **404** unknown job; **400** not `complete` (or `failed`/`cancelled` after an admin re-render), outputs deleted, prep/finalise-only, visibility change in progress, or missing reviewed lyrics / instrumental selection; **409** the job left `complete` meanwhile (double-click) or a YouTube upload for it is in progress; **500** something failed after the claim (output deletion etc.) / **503** the screens worker couldn't be triggered — in both cases the job is set `failed` with the marker kept, so an admin can retry it.
#### Prepare Review Audio
```http
+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
+1
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)
+7
View File
@@ -57,6 +57,13 @@
## Recent Changes
- **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`).
+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,154 @@
# Missing lyrics: sung sections the transcription dropped ("vocals but no lyrics")
## Trigger
Job `5710831e` (Omer Adam – שני משוגעים, KaraokeHunt batch, reviewed by Andrew):
the transcription has **no words from 20.66s to 32.40s** while the lead-vocal stem is
active the whole time. Both references (Genius, LRCLIB) put three pre-chorus lines there:
- שמרנו רגעים בלב, שתינו ת'נוף
- ואת היית יפה כמו פרח שאסור היה לקטוף
- רציתי רק לקטוף אותך, רציתי לקטוף
`SectionDetector` (gap ≥ 10s between segments, no audio check) then rendered
"♪ INSTRUMENTAL (6 seconds) ♪" over clearly sung vocals. Not caused by the RTL work
(PR #1094): shipped and re-rendered ASS have identical sections.
## Why nothing caught it
- **Scorer** said REVIEW only because anchor coverage was 98.8% (< AUTO bar). Anchor
coverage = fraction of *transcribed* words matching the reference; skipped reference
lines don't lower it. Naive reference-side coverage is noisy for repeated choruses
(anchors map each transcribed chorus to one reference occurrence) — 18–23 "missing"
lines reported vs 3 real.
- **timing_check G3** (`max_unclaimed_run_s`, longest lead-vocal activity not covered by
any word) DOES fire on this job (`unclaimed-vocal`, 5.84s run; 23% of activity
unclaimed) — but it is shadow-only and only computed when lyrics would otherwise be
AUTO, so it never ran here. Known false-positive class: ad-libs / vocal samples
deliberately absent from lyrics.
- **Review UI** shows nothing for a gap; a reviewer who doesn't read the language can't spot it.
## Plan
1. **Signal**: compute untranscribed-vocal runs for every job once stems exist (reuse
`timing_check._rms_activity`; output a list of runs `{start, end, active_fraction}`
merged across short breaths, plus the reference lines that fall between the
neighbouring anchors). Store in `state_data` / corrections metadata.
2. **Audit / calibration** (run on GCP, not the Mac): run the signal over completed jobs
(KaraokeHunt batch + recent prod) → distribution of merged-run lengths, manual check
of top hits → threshold that separates dropped lines from ad-libs (likely: merged run
≥ ~6s AND reference lines unaccounted for between the neighbouring anchors).
3. **Gate**: scorer REVIEW with an explicit reason ("~11s of vocals at 0:20 with no
lyrics; reference has 3 lines there"); compute regardless of tier.
4. **Section detection**: don't label a gap INSTRUMENTAL when vocal activity covers most
of it (carrier: corrections metadata, already downloaded by both render paths).
5. **Review UI**: mark the gap ("vocals detected, no lyrics") and offer the reference
lines between the neighbouring anchors for one-click insert → Tap To Sync.
6. Later: auto-fill (re-transcribe the chunk / align reference lines).
## Fix for this job
Insert the three lines in review (Tap To Sync) and re-render after PR #1094 deploys.
## Phase 1 built (shadow signal + backfill)
- `backend/services/auto_approval/vocal_gaps.py`: every transcription gap ≥3s →
lead-vocal active fraction, longest breath-bridged (≤0.5s) vocal run, and the reference
lines between the reference positions of the words either side (section headers
dropped, ±1-word anchor drift at line boundaries snapped, reversed/huge spans → none).
`suspect` = longest run ≥3s (NOT active fraction: a dropped line followed by an
instrumental in the same gap dilutes the fraction), after a 1.5s held-note allowance
for a run touching the gap start. Silent/empty stems → error, never a clean pass.
Stored results are keyed by `input_key` (word timings + stem + version) so resets /
edits recompute.
- On 5710831e: one suspect gap 20.66–32.40s (96% active, 11.76s run) with exactly the 3
missing Genius lines; the three real instrumentals have ≤0.16s runs.
- Executor computes it once per job when stems exist (any verdict), stores
`state_data.vocal_gaps`, summary in `processing_metadata.auto_approval.vocal_gaps`.
- Backfill: `POST /api/internal/jobs/{id}/vocal-gaps` + `scripts/audit_vocal_gaps.py`
(server-side; nothing bulky through the Mac).
### Upstream oddity found
Anchor `reference_word_ids` can be shifted one word at "[Section]" header boundaries
(Genius "[קדם-פזמון]": the anchor for "כמו איזה שני משוגעים בחוף" maps its last word to the
next line's first word). Worth a separate look — it probably mis-highlights reference words
in the review UI too.
## Known overlap
`timing_check` G3 (`max_unclaimed_run_s`) is a whole-song version of the same idea. Once the
audit shows which formulation separates dropped lines from ad-libs/held notes best, fold
them into one detector (one stem download/decode; currently AUTO jobs decode twice).
## Next
Deploy → run the audit (needs `gcloud auth login` for the admin token) → hand-check
suspects → pick the gate threshold → Phase 2: scorer gate + SectionDetector + review UI.
## Audit results (2026-10-01, v0.256.0, 262 completed jobs, last 60 days)
Server-side via `scripts/audit_vocal_gaps.py` (results stored on each job).
- Longest unlyricked vocal run per job: p50 0.7s, p75 2.4s, p90 5.1s, p95 7.4s, p99 22.4s.
- Jobs with a run ≥3s: 47 (18%); ≥6s: 21; ≥10s: 8 — far too many for an audio-only gate.
- Cross-check against **synced** reference lyrics (LRCLIB line timestamps): of 57 suspect
gaps on jobs with a synced reference, only **15** have a reference line timestamped
inside the gap (~25% precision at 3s; ~60% at ≥6s). The rest are vocal chops / samples /
ad-libs / synth bleed (DnB-heavy: Etherwood, London Elektricity, Danny Byrd, …).
- Reference lines between the neighbouring anchors appeared on only 3 suspect gaps
(5710831e, XTC, Etherwood) — high precision when present, low recall (repeated choruses
break the anchor-span method).
### Phase 2 decision: evidence-based gate
- **REVIEW gate** (explicit reason) when a vocal run ≥3s AND reference lyrics place
lines inside the gap — synced reference timestamps inside the gap, or reference lines
between the neighbouring anchors.
- Audio-only runs: record + soft note in review, no gate (precision too low).
- `SectionDetector`: don't label a gap INSTRUMENTAL when the evidence rule fires.
- Review UI: marker at the gap + the reference lines (from either method) offered for insert.
## Phase 2b built: review UI marker + insert
- `GET /api/review/{job_id}/correction-data` → `vocal_gaps` (typed as `VocalGapsResult` in
`frontend/lib/lyrics-review/types.ts`). Only **evidenced** gaps are shown; audio-only
suspects stay hidden (precision too low). Nothing shows when `vocal_gaps` is null/empty.
- Open gaps are derived from the reviewer's CURRENT segments
(`lib/lyrics-review/utils/missingLyrics.ts`): a gap is open while no timed word starts in
`[start, end)`. `vocal_gaps` is never mutated, so inserting/typing lines hides the marker
and undo brings it back. Taken from the loaded data so restored sessions still show it.
- `MissingLyricsCallout` (above Synced Lyrics): "Possible missing lyrics at m:ss–m:ss", the
expected lines (synced reference lines preferred, else anchor-bounded reference lines,
with the source name), Play, and **Insert these lines**. `TranscriptionView` draws a
dashed amber marker row at the gap's chronological position (all three view modes);
clicking it scrolls to the callout.
- Insert (`hooks/useMissingLyrics.ts`): one segment per line, words split on whitespace,
provisional timings spread evenly per word across `[start+0.1, end-0.1]`, inserted before
the first segment starting after the gap midpoint, singer inherited from the neighbour.
Goes through `updateDataWithHistory` (one undo step) and logs one `segment_add` edit-log
entry per line (`details.origin = "missing_lyrics_gap"`).
- Re-sync guidance: `MissingLyricsResyncHint` lists the inserted lines (while they exist)
with a **Sync timing** button each, opening the existing Edit modal (Tap To Sync). No
new timing system.
- Read-only/replay: marker + lines shown, insert disabled.
- Tests: Jest (`missingLyrics.test.ts`, `useMissingLyrics.test.tsx`,
`MissingLyricsCallout.test.tsx`, `TranscriptionView.missingLyrics.test.tsx`) + Playwright
regression (`lyrics-review.spec.ts` › "Possible Missing Lyrics": insert, order, undo, Sync
timing → Edit modal).
- Found while building: sonner's `<Toaster />` isn't mounted anywhere (root layout mounts
the shadcn `ui/toaster`), so `toast` from `sonner` in the review UI is silently invisible.
The hint is therefore inline rather than a toast. Worth a separate fix.
### Phase 2b review fixes (code review)
- **Edge tolerance:** words starting within 0.05s of a gap edge are its neighbours (backend
rounds gap bounds to 2dp and `end` = next word's start, e.g. 19.996 vs 20.0).
- **Stale-analysis guard:** a gap is only shown if, in the segments AS LOADED, it holds no
words and the neighbouring words sit within 1s of both edges (or it touches the song
start / has no words after it). The frontend can't recompute `input_key`, so this is the
proxy for "the analysis matches this transcription".
- **Insert position by word times:** a gap inside one segment (words 5–9s + a word at 22s)
splits that segment — earlier words keep the id, later words get a fresh id — with the
lines inserted between (logged as `segment_split` + `segment_add`).
- **No fabricated timing:** lines take word timings from the synced reference source
(`reference_lyrics[source].segments`, matched by text inside the gap, all words timed);
otherwise words are inserted UNTIMED (segment bounds = the gap, so Play/Edit open there)
and the existing "N lyric word(s) have no timing yet" submit guard forces a Tap To Sync.
- **Pending state:** untimed words between the gap's neighbouring timed words (inserted
here, typed via Edit/Add Lyrics, or Replace All) → no Insert (no duplicates); the callout
shows a "not timed yet" note + Sync timing instead. Timed words inside close the gap.
- Re-sync hint appends across inserts; a line leaves it once re-synced or deleted.
- Duet singer: following segment's, then preceding (as `addSegmentBefore`).
- Display timing offset applied to the callout range, Play time and markers.
- Read-only tooltip moved to a focusable wrapper (disabled buttons get no hover).
- Caveat: the submit guard reports via a sonner toast, and sonner's `<Toaster />` isn't
mounted, so a blocked submit is currently silent (pre-existing; fix separately).
@@ -0,0 +1,198 @@
# Admin "Re-render" for any completed job (v0.256.0)
## Why
Renderer fixes (first case: RTL/Hebrew rendering, v0.255.0) need already-delivered
videos regenerated. Edit sends the customer back through review and recycles the
brand code; the tenant "Re-render with current theme" (v0.253.0/#1091) only covers
unpublished tenant jobs and re-snapshots the theme. This adds an admin-only button
that rebuilds any completed job end to end with no review.
## What
- `POST /api/admin/jobs/{job_id}/rerender` (`require_admin`), body
`{"notify_customer": false}`. See `docs/API.md`.
- Service: `backend/services/admin_rerender_service.py` (`AdminRerenderService`,
`validate_admin_rerender`, `suppress_customer_notifications`).
- Frontend: admin-only "Re-render" button on completed job cards
(`components/job/OutputLinks.tsx`) with a confirm dialog (explains: current
renderer, no review, YouTube deleted + re-uploaded with a new URL, GDrive/Dropbox
replaced, brand code kept) and an "Email the customer when done" checkbox (default
off). Strings in `messages/*.json` (33 locales).
## Flow
1. Validate: `complete` (or `failed` with `state_data.admin_rerender`), outputs not
deleted, not prep/finalise-only, no visibility change in progress, reviewed lyrics
+ instrumental selection present.
2. Firestore transaction claims `complete → lyrics_complete` with
`regen_restore_status = review_complete` (shared `claim_for_rerender`, same as the
theme re-render), sets the `admin_rerender` marker (`notify_customer`,
`brand_code`, `previous_outputs`), clears the dead links (`youtube_url`,
`dropbox_link`, `gdrive_files`, ...) but **not** `brand_code`, and drops
`file_urls.screens` / `videos.with_vocals`. Style fields are untouched.
3. Deletes regenerated artifacts (screens, with_vocals, `finals/*.mov` — the encoder
globs `**/*Title*.mov`) via the shared `delete_regenerated_artifacts`.
4. Deletes published outputs (only for destinations it will re-publish to — see
review fix 6) via the new shared
`backend/services/published_outputs_cleanup.py` (also now used by Edit): YouTube,
Dropbox (effective dist path, so private jobs hit the private folder), GDrive (with
`cleanup_mirror=False` — same brand code, so the kjbox GCS mirror object is
overwritten in place instead of disappearing for ~20 min). Results go to the
marker, the timeline and `log_to_job`. Failures don't abort.
5. Triggers the screens worker → render → video worker (encode + distribute). Worker
ids are generation-keyed, so the encoder cache can't return the old render.
6. Video worker: `rerender_brand_code()` now also reads `admin_rerender.brand_code` →
`keep_brand_code` (no new allocation). On success it clears the marker and
transitions to COMPLETE with `notify=not suppress_customer_notifications(job)`.
## Decisions
- **Existing style**, not current theme (tenant endpoint unchanged).
- **Delete up front, keep brand code** (Andrew). Distribution re-publishes under the
same code; YouTube URL changes.
- **No customer notification by default.** `JobManager.transition_to_state(...,
notify=False)` skips the completion email + push. The orchestrator also passes
`notify_user=False` to a quota-deferred YouTube queue entry so the "your video is on
YouTube" follow-up is skipped. Normal jobs and the tenant theme re-render always
notify (covered by tests). The community voter fan-out (`notify_community_publish`)
still runs: it's idempotent (voters already notified aren't re-emailed) and it
updates the request's YouTube URL.
- **Trigger failure → `failed`** (marker kept) rather than restoring `complete`, since
the published outputs may already be gone. `/retry` re-runs the admin re-render
while screens are missing; after that the normal render/video retry ladder resumes
it (marker → same brand code and notification choice).
## Caveats
- YouTube cost per re-render: delete (50) + duplicate search (100) + upload (1600) +
thumbnail (50) units. With quota exhausted the upload is queued, so the track is off
YouTube until the queue drains.
- If the up-front YouTube delete fails, the server-side upload's duplicate-by-title
check deletes the old video before uploading; GDrive uploads replace same-named
files; Dropbox uploads overwrite.
- `jobs_completed` on the user is incremented again on completion (same as Edit and
the tenant re-render).
## Review fixes (second commit)
1. **Stale deferred YouTube upload.** The re-render cancels the job's
`youtube_upload_queue` entry (`cancel_upload`: `queued`/`failed` → `cancelled`;
a `processing` entry is reported, not stopped). The queue processor defers any
entry while the job has an active admin re-render and isn't `complete` (the
finals are being rebuilt), and suppresses the follow-up + voter emails while a
silent re-render's marker is present, even for legacy entries without
`notify_user`.
2. **Retry is admin-only** while an active `admin_rerender` marker exists: a
customer's `POST /api/jobs/{id}/retry` gets 403 `jobs.adminRerenderRetryAdminOnly`
("contact support"), for every retry branch, not just the re-run one.
3. **Marker scoped to its run.** The marker records the job's `review_token` at
claim; `active_admin_rerender()` ignores it once the token changes (any trip back
through review mints a new one). `suppress_customer_notifications`,
`rerender_brand_code`, kept outputs and retry eligibility all go through it. The
admin reset, admin restart, admin delete-outputs, Edit and private→public
visibility flows also delete the marker outright.
4. **Legacy video worker path** drops `admin_rerender`/`theme_rerender` from the
state_data map it rewrites and applies the same notification/kept-output rules.
5. **No stuck LYRICS_COMPLETE.** Everything after the claim (audit log, artifact
deletes, output deletes, queue cancel, screens trigger) is wrapped: any exception
marks the job `failed` (`error_details.stage = "admin_rerender"`) with the marker
kept, and the endpoint returns 500 "retry it".
6. **Only delete what will be re-published.** `plan_republish()` mirrors the video
worker: YouTube needs `enable_youtube_upload` on a non-private job plus configured
credentials; Dropbox needs effective `dropbox_path` + `brand_prefix`; GDrive needs
effective `gdrive_folder_id`. Outputs for other destinations are left in place:
`cleanup_results[dest] = {"status": "kept", reason}`, a warning in the response /
marker / timeline / job log, their state_data link isn't cleared, and the video
worker keeps that link (`kept_outputs`) instead of overwriting it with `None`.
7. **Discord + community voters.** The orchestrator's Discord "new video" post is
skipped when `notify_customer` is false. `notify_community_publish(...,
notify_voters=False)` still marks the request published with the new URL but
emails no voters.
8. **Edit's Dropbox folder name changed.** Edit now uses the shared
`dropbox_folder_path()`, which sanitises artist/title like the uploader does
(`sanitize_filename`). Before, Edit built the raw `"{brand} - {Artist} - {Title}"`
and silently missed folders for names with special characters (`/`, `?`, `"`,
curly quotes, ...). Deliberate fix; covered by a test.
9. **No blocking I/O on the event loop.** The publish plan (YouTube credential
lookup), the Firestore claim transaction and all post-claim GCS/YouTube/Dropbox/
GDrive work run via `asyncio.to_thread`; deletions still complete before the
screens worker is triggered (so before distribution).
## Second review pass
1. **Admin restart** folds the marker deletion into the restart's own atomic
update, so a rejected restart (e.g. 400 on `preserve_audio_stems`) keeps it.
2. ~~Community reconcile suppression~~ — replaced in the final round (C).
3. ~~Post-upload reconciliation of an in-flight upload~~ — replaced in the final
round by mutual exclusion (A).
4. **Marker cleared atomically with COMPLETE.** `transition_to_state(...,
extra_updates={"state_data.admin_rerender": DELETE_FIELD})` writes it in the
same Firestore update as the status; a failed transition keeps the marker.
5. **Completion counter.** Admin re-render completions pass
`count_completion=False`, so `users.total_jobs_completed` (which gates feedback
prompts) isn't inflated. Edit and the tenant theme re-render still increment on
their re-completion (unchanged; arguably also double counting, left as is).
6. **Queue starvation.** The processor fetches 100 queued entries and attempts at
most 20 uploads, so deferred entries can't fill the page. Only jobs actively in
the pipeline are deferred; for a failed/cancelled admin re-render the entry is
cancelled when the re-render re-publishes YouTube (resuming it re-queues),
otherwise kept queued (it's the original run's owed upload). Job reads use one
`JobManager` via `asyncio.to_thread`.
7. **Deferred upload only cancelled when YouTube is re-published.** Otherwise the
queue entry and `youtube_upload_queued` are kept and a warning is emitted. A
YouTube credential-check exception plans "don't touch YouTube" with a
"couldn't verify YouTube credentials" warning.
8. **Legacy (KaraokeFinalise) path** gets `discord_webhook_url=None` on a quiet
admin re-render. Brand code: both paths distribute via
`_handle_native_distribution`, which already applies `rerender_brand_code` (tested).
9. **Admin delete-outputs** now uses the shared cleanup helpers (sanitised Dropbox
folder name, like Edit / re-render); mirror cleanup unchanged.
10. **Frontend:** fixed the orphaned `regenerateScreens` JSDoc; `warnings` added to
`AdminRerenderResponse` and shown in a toast after starting (33 locales).
11. **Claim uses the active marker** (a stale one can't leak brand code / history /
retry flag), and a **CANCELLED** admin re-render can be resumed by the admin
endpoint and `/retry`, like FAILED.
## Final review round (simplification)
A. **Mutual exclusion instead of reconciliation.** Two Firestore transactions that
each read BOTH docs (`jobs/{id}` + `youtube_upload_queue/{id}`):
- the admin re-render claim (`claim_with_youtube_queue`) aborts with 409 "A YouTube
upload for this track is in progress — try again in a few minutes." if the
entry is `processing`; a `queued`/`failed` entry is cancelled inside the same
transaction when YouTube will be re-published, otherwise left with a warning;
- the queue's `mark_processing` refuses (entry stays `queued`) while the job has an
ACTIVE admin re-render and isn't `complete` (`admin_rerender_blocks_upload`).
An in-flight upload and a re-render can therefore never overlap, so the round-2
post-upload re-read / stale-video deletion / `kept_outputs.youtube_url` write and
the processor's halted-cancel logic are gone, as is `cancel_upload` — nothing but
the claim transaction cancels entries, so the re-render's own later
`queue_upload` entry is never cancelled. Refused claims don't count towards the
20-uploads-per-run cap and the fetch page is 100, so they can't starve the queue.
B. **Never re-queue after a successful upload.** `mark_completed` is recorded first;
failures in follow-up steps (job URL write, community publish) or in
`mark_completed` itself flag the entry `needs_attention` / `post_upload_error`
(terminal `completed`) instead of `mark_failed` (which re-queued → double upload).
C. **Community voters: only re-notification is suppressed.** The round-2
`notify_voters` / `voter_fanout_suppressed` mechanism is removed;
`notify_community_publish` is back to main's behaviour: voters already fully
notified are never re-emailed, an owed (unnotified / partially notified) fan-out
is completed, and `voters_notified` is only set when it actually completed.
D. `transition_to_state` raises `ValueError` if `state_data_updates` and
`extra_updates['state_data.*']` are combined (Firestore conflicting-path trap).
E. `delete_dropbox_folder` also checks the legacy raw-name folder
(`{brand} - {Artist} - {Title}` unsanitised) when it differs from the sanitised
one, deletes whichever exist, reports `deleted` / `failed`, and only reports
`success` (which allows brand-code recycling) when no folder remains.
F. `delete_youtube_video` extracts the video id inside the try — a malformed
(non-string) URL returns `{"status": "error"}` instead of raising.
G. The queue processor reads the fetched jobs in one `db.get_all` batch.
## Follow-ups
- Two other copies of published-output deletion remain and should move onto
`published_outputs_cleanup.py` (admin delete-outputs was migrated in the second
review pass): `backend/api/routes/jobs.py` (~L2440-2545), and
`backend/services/visibility_change_service.py` `_delete_public_outputs` /
`_delete_distributed_outputs` (~L280-410).
@@ -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>
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more