Compare commits

...
24 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 c94a5b8754 fix(audioshake): remux user audio with leading null padding before transcription (#826)
@coderabbitai ignore

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 03:22:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fea6ebec1a fix(tenant): make white-label B2B portals attribute jobs to the tenant (Vocal Star + Singa) (#824)
@coderabbitai ignore

## Problem

The white-label tenant portals (`vocalstar.nomadkaraoke.com`,
`singa.nomadkaraoke.com`) looked "done" but **had never worked
end-to-end**: 0 of the last 484 production jobs carried a `tenant_id`.
No tenant job had ever run.

**Root cause:** the frontend API client never sent the `X-Tenant-ID`
header. Tenant portals call the shared `api.nomadkaraoke.com`, whose
Host isn't the tenant subdomain, and the `?tenant=` query param is
disabled in prod — so the backend could never detect the tenant. Every
tenant sign-in and job submission silently fell back to consumer
behavior (default theme, no tenant Dropbox, etc.). The
`getTenantHeaders()` helper existed and was unit-tested, but was never
wired into requests.

## Changes

**Frontend** (`lib/api.ts`, `lib/tenant.ts`)
- Attach `X-Tenant-ID` on all authenticated requests **and** the
magic-link request, sourced from `window.__TENANT_CONFIG__`
(edge-injected by the Cloudflare function; mirrored from the tenant
store for dev/preview). Consumer build resolves no tenant → no header →
**behavior unchanged**.

**Backend** (`_apply_tenant_overrides` in `file_upload.py`)
- Make tenant config **authoritative** over global distribution
defaults. Prod sets `DEFAULT_DROPBOX_PATH` / `DEFAULT_GDRIVE_FOLDER_ID`
/ `DEFAULT_BRAND_PREFIX` globally; these seed `dist`, and the old "fill
only when unset" overlay let them leak — so every tenant job would have
landed in the **shared consumer Dropbox folder** and uploaded to the
**global Google Drive**. Now Dropbox/GDrive routing is gated by the
tenant feature flags and cleared when disabled.

**Tenant configs** (GCS + setup scripts, Vocal Star + Singa)
- Disable Google Drive (`gdrive_upload=false`, `gdrive_folder_id=null`),
keep YouTube off, enable Dropbox to each tenant's own folder. B2B =
locked theme, no YouTube/GDrive, Dropbox + portal download only.

## Why it's consumer-safe
- Frontend: header only attached when a tenant is resolved (never on
`gen.nomadkaraoke.com`).
- Backend: `_apply_tenant_overrides` early-returns when `tenant_config
is None` (all consumer jobs).

## Testing
- New: frontend header-attachment tests (tenant build vs consumer);
backend authoritative-override + feature-flag-gating regression guards
(incl. the global-default-leak case).
- Full suites green: **3466 backend**, **1013 frontend**.
- Verified live tenant configs via API after update.

Manual prod E2E (real track through each portal) + a daily per-tenant
E2E workflow follow in a second PR, once this deploys and is verified in
prod.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 02:40:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fd331a643f infra: GCP cost reductions (artifact cleanup, NAT egress, weekly backup) (#823)
Part of the June 2026 cost-reduction effort
(`docs/archive/2026-06-14-gcp-cost-reduction-plan.md`). Targets the
post-credit-expiry (2026-09-19) bill.

## Changes
- **Item 4 — Artifact Registry cleanup** (~$6/mo + caps growth): keep 10
most-recent versions + delete untagged digests >7d, on all 3 repos
(karaoke-repo, karaoke-backend-gpu, audio-separator; 92 GiB, previously
no policy). In-place update.
- **Item 5 — NAT egress** (~$26/mo): ephemeral GHA runners now always
get an external IP, so egress bypasses the Cloud NAT data-processing
charge (runners were the NAT's only user; us-central1 IN_USE_ADDRESSES
quota is 69, usage 1).
- **Item 6 — backup cadence** (~$15/mo): Firestore export stays nightly
to GCS (1-day local restore point) but uploads to S3 only on Sundays
(1-week off-site RPO) — Firestore is the bulk of the cross-cloud egress.
Staging keeps only the latest export so the weekly upload ships exactly
one.
- **Item 1 — encoding disks** (~$35/mo): pinned the 4 worker hyperdisks
to the free baseline (3000 IOPS / 140 MB/s) **live via `gcloud`**, not
IaC — setting it in IaC forces a capacity-risky VM replacement. A code
comment documents this.

## Deploy status
- `pulumi up` (artifact policies + runner function): **applied** locally
(prod, update 751).
- Backup function source: shipped via
`functions/backup_to_aws/deploy.sh` (pulumi doesn't manage the source
zip).
- Encoding disks: tuned live via gcloud.

## Tests
- `backup_to_aws`: 13 pass (added firestore-cleanup + s3-exclude
coverage).
- `runner_manager/ephemeral`: 32 pass (updated external-IP assertion).

Item 7 (fallback disks on-demand) intentionally deferred — reliability
tradeoff not worth ~$20/mo. See plan doc.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 17:11:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 39fb93653f fix(auto-correct): switch active model from Fable 5 to Opus 4.8 (#822)
## Summary

Claude **Fable 5** (`claude-fable-5`) is no longer available on the
Anthropic API. Verified live against `api.anthropic.com`:

```
404 not_found_error: "Claude Fable 5 is not available. Please use Opus 4.8.
Learn more: https://www.anthropic.com/news/fable-mythos-access"
```

`claude-opus-4-8` responds normally and is the API's own prescribed
replacement. Opus 4.8 was also ≈ Gemini 3.1 Pro in our 30-job offline
eval, so switching to it preserves the two-model compare quality.

## Changes

- **`.github/workflows/ci.yml`** (load-bearing):
`AUTO_CORRECT_MODEL=claude-opus-4-8` and
`AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview`.
Compare mode now runs **Opus 4.8 + Gemini 3.1 Pro** instead of Fable +
Gemini.
- **`scripts/measure_autocorrect_cost.py`**: default models + docstring
example → Opus, so the cost tool measures what prod runs.
- **`docs/API.md`**: example auto-correct response reflects Opus.
- **`pyproject.toml`**: `0.182.1` → `0.182.2`.

## Re-enable path

Fable is **disabled, not deleted** — its pricing entry in `pricing.py`
and all Fable unit tests are intentionally left intact. If access
returns, flip it back by reverting the two env-var values in `ci.yml`.

## Testing

- Auto-correct suite: 73 passed (`backend/tests/services/auto_correct/`
+ `test_proactive_auto_correct.py`).
- Live API probe confirmed Fable 404s and Opus 4.8 works.
- CodeRabbit (uncommitted): 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 10:27:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 dfdbf60dc5 docs(monitoring): document email-channel verification gap (Pulumi vs Console) (#785)
## Summary

Followup to PR #783. The PR claimed Cloud Monitoring would deliver a
verification email to `andrew@beveridge.uk` automatically after `pulumi
up`. It didn't — the channel sat in `UNVERIFIED` state silently, exactly
as if no channel had been created.

The actual GCP behaviour: the auto-send only fires when a channel is
created through the **Cloud Console**. Channels created through the
**API/Pulumi** require an explicit call to the `:sendVerificationCode`
REST endpoint to trigger the email.

I discovered this when running `getVerificationCode` against the channel
and getting `"Cannot generate a verification code from an unverified
channel."` despite `enabled: true`. The right endpoint is
`sendVerificationCode` (no admin-flow restrictions), which returned `{}`
(success) and the email arrived shortly after.

## Change

Rewrite the "Gotcha" callout in `infrastructure/monitoring/README.md` to
explain this, with a copy-paste-ready curl invocation for triggering the
email after any future `pulumi up` that adds a new email channel.

No code change.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-12 16:03:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 9f25ae4c4c feat(divebar): on-demand pipeline refresh trigger (refresh action) (#821)
## Why

A track made via gen.nomadkaraoke.com is uploaded to the Nomad Google
Drive immediately, but the Divebar/GCS community mirror only ingests it
on the nightly schedule (mirror index 2 AM, GCS file sync 3 AM, xref
rebuild 6 AM ET). Until then, kjbox's link flow can't find a mirror copy
and falls back to a YouTube download.

This adds an **on-demand "refresh now"** path so a freshly-published
track can be pulled into the catalog within minutes.

## What

New `refresh` action on the **public `divebar-lookup`** Cloud Function:

- Force-runs the three existing scheduler jobs in pipeline order —
`divebar-mirror-daily` (Drive→BigQuery index, makes the track appear) →
`divebar-sync-vm-daily` (Drive→GCS, fast URL) →
`divebar-xref-rebuild-daily` — via `CloudSchedulerClient.run_job`.
Reuses each job's own OIDC identity/target.
- **Least privilege:** the function SA gets a custom
`divebarSchedulerRunner` role (`cloudscheduler.jobs.run` + `.get`) only
— no new function-invoke or compute perms.
- **Token-gated:** the endpoint is public, so the action requires a
shared bearer token (constant-time compare). The token is read from the
`divebar-refresh-token` Secret Manager secret **at runtime** (not
injected as a secret env var) so the function deploys cleanly before the
secret has a version — it just returns a uniform `403` until one is
added, and picks up rotations without a redeploy. Fails closed.

Consumed by kjbox's new "Refresh catalog" button (kjbox#107).

## Tests

`infrastructure/functions/divebar_lookup/test_main.py` — 8 tests: token
gate (wrong/empty/unconfigured), all-jobs-triggered-in-order,
partial-failure tolerance, dispatch 200/403. All green.

## Deploy status — ✅ applied to prod

Applied locally (provider pinned to prod's 9.22.0 so the apply contained
only these 5 resources — no unrelated provider-upgrade churn): `4
created, 1 updated, 262 unchanged`. Function source rebuilt from the new
zip. Secret version set. Verified live: no/wrong token → 403; valid
token → 200 triggering all three jobs.

**Remaining (kjbox#107):** put the same token in the kjbox device
`config.json` as `divebar_refresh_token`, then deploy kjbox.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 00:53:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 cf79da79ab fix: honor "use official formatting" correction on search-created jobs (#820)
## Problem

When a user searches for a song, selects **"Use the official
formatting"** (e.g. picks `Hard-Fi — Hard to Beat` over their typed
`hard-fi - hard to beat`), and creates the job, the job was still named
with their raw lowercase query. The official-formatting selection was
silently discarded.

## Root cause

`create_job_from_search` (`backend/api/routes/jobs.py`) derived the
display name from the **original search query stored in the session**,
not from the corrected `artist`/`title` the frontend sends in the
request body:

```python
session_artist = session.get('artist', body.artist)   # always the raw query
effective_display_artist = body.display_artist or session_artist  # body.artist never used
```

Since the session always has an `artist` key, `body.artist` was only
ever an unreachable fallback. The frontend's "Use official formatting"
click correctly updates its state and sends the corrected values — they
were just ignored server-side.

## Fix

Prefer `body.artist`/`body.title` (the wizard's current,
possibly-corrected values) over the stored query, with an explicit
display override still winning above all. Whitespace-only body values
are stripped and fall back to the stored query so a stray `" "` can't
become the job name. The original query is preserved for
`audio_search_artist`/`audio_search_title` matching metadata.

## Tests

- New regression test: corrected artist/title wins over the session
query (fails on old code: `'hard-fi' == 'Hard-Fi'`).
- New test: whitespace-only body artist/title falls back to the stored
query.
- `test_standalone_search.py`: **33 passed**; broader job
route/api/regression suites: **123 passed**.
- Existing `test_display_overrides_applied_when_provided` still passes
(override precedence intact).

Version bumped `0.181.0 → 0.181.1`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 22:44:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 eccf77a626 fix(audio-editor): always show Trim/Fade buttons, disable off-edge (#819)
## Summary
- The Trim Start/End and Fade In/Out buttons in the input audio editor
were **conditionally rendered** — only visible when the selection
touched the very start or end of the track. A mid-track selection showed
only Cut/Mute/Clear, so users couldn't discover the Fade actions at all.
- Reported on a 9:11 track with a 3:02–3:55 selection: the Fade buttons
(shipped in #813) appeared to be "missing in prod" when they were
actually just hidden by the edge-gating.
- Now all four edge-actions **always render** when a selection exists
but are `disabled` off-edge, with a tooltip hint explaining how to
enable them.

## Changes
- `AudioEditor.tsx`: derive `atStartEdge`/`atEndEdge` (1s tolerance,
matching the server-side `afade` anchoring in
`audio_edit_service.fade_region`); render Trim Start, Fade In, Trim End,
Fade Out always, `disabled` off-edge with context-aware `title`
tooltips.
- 6 new i18n keys (`trimStart/EndSelection`, `trim*/fade*DisabledHint`)
added to `en.json` and translated to all 33 locales.
- New jest test asserting a mid-track selection renders the four buttons
disabled.
- Version bump `0.181.0 → 0.182.0`.

## Testing
- [x] `AudioEditor.test.tsx` — 26/26 pass (incl. new disabled-state
test)
- [x] i18n completeness — 33/33 locales at 100%
- [x] No new `tsc` errors in changed files

## Review
- [x] CodeRabbit CLI review completed locally
- [x] In-scope findings addressed (only i18n loanword nits, consistent
with existing convention)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 22:04:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a7bb338703 feat(auto-correct): enable proactive pre-generation (runs on API service) (#818)
## Summary

Enables the proactive pre-generation that PR #816 intended but couldn't
deploy (the lyrics-job `--update-secrets` crashed on Cloud Run secret
aliases). Per the chosen approach, the work now runs **on the API
service** — which already has a working `ANTHROPIC_API_KEY` +
`AUTO_CORRECT_COMPARE_MODELS` — instead of the lyrics job, sidestepping
the secret-alias problem entirely.

## How it works

1. Lyrics worker finishes transcription → after `mark_lyrics_complete`,
fires `WorkerService.trigger_auto_correct(job_id)` — a direct, awaited
HTTP call (no Cloud Tasks / new queue). Best-effort: never blocks or
fails the job.
2. New internal endpoint `POST /api/internal/workers/auto-correct`
(admin auth) runs `process_proactive_auto_correct(job_id)` synchronously
on the service: loads `corrections.json`, runs the multi-model
`suggest()` with default settings (cache-aligned with the UI), caches
it. Gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, 180s timeout, swallows
all errors.
3. `ci.yml`: `AUTO_CORRECT_PROACTIVE_ENABLED=true` added to the
**service** env (deploys cleanly — the broken lyrics-job secret path is
gone).

Result: when a reviewer opens the lyrics UI, the auto-run-on-load
request is an instant cache hit.

## Testing
- Backend: **3462 passing** (emulator excluded), incl. rewritten
`test_proactive_auto_correct.py` covering the service worker (flag
gating, no-references skip, happy path multi-model, error-swallow) and
the lyrics-worker trigger (fires / swallows errors).
- CodeRabbit: trace-context propagation + defensive endpoint guard
applied.

## Notes
- Failure modes unchanged & graceful: flaky AI / out of credits /
timeout → endpoint returns a status, job proceeds; UI falls back to
on-demand generation.
- Version bumped 0.180.0 → 0.181.0.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 19:42:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 32dfd9fbdc fix(ci): revert lyrics-transcription-job to image-only deploy (#817)
## Why

PR #816's deploy **failed** at the "Update Cloud Run Jobs" step:

```
ERROR: gcloud crashed (ValueError): Invalid secret path 'projects/nomadkaraoke/secrets/audioshake-api-key' in annotation
```

The `--update-secrets ANTHROPIC_API_KEY=…` I added to
`lyrics-transcription-job` made gcloud re-validate the job's *existing*
secrets, which are stored via Cloud Run **secret aliases**
(`secret-alias-N`) in a format `--update-secrets` rejects. That crash
stranded **lyrics + audio jobs on the previous image** (the API service
deployed fine and is healthy; the video-encoding-job updated fine).

## Fix

Revert the lyrics-job step to **image-only** (proven to work — same form
the video/audio job steps use). This makes deploys succeed and brings
lyrics + audio jobs onto the current image, so prod is consistent again.

Proactive auto-correct ships dormant: the worker's
`_run_proactive_auto_correct()` is gated by
`AUTO_CORRECT_PROACTIVE_ENABLED`, which is unset, so it returns early
(no-op, zero risk). Wiring that env + the Anthropic secret onto the job
via an alias-safe method is a tracked follow-up.

## Testing
- No code change; CI-only. The reverted step matches the working
video-encoding-job step exactly.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 18:48:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 364e4ebd5f feat(auto-correct): proactive multi-model suggestions + cost logging + de-AI-ified review UI (#816)
## Summary

Makes AI lyrics auto-correction run **automatically on every job**
(multi-model), so suggestions are cached and ready the moment the
reviewer opens the lyrics UI — plus token/cost instrumentation and a UI
cleanup that removes all "AI"/"model" wording.

Measured cost first (`scripts/measure_autocorrect_cost.py`):
**~$0.13/track** multi-model on normal songs — cheap enough to run
proactively.

## Changes

**Cost instrumentation**
- Capture per-model `usage` from Anthropic + Gemini; log greppable
`auto-correct usage` / `auto-correct cost … total_est_cost_usd=…` lines
from `suggest()`.
- `backend/services/auto_correct/pricing.py` (Anthropic rates
authoritative; Gemini estimated) + `scripts/measure_autocorrect_cost.py`
offline harness.

**Proactive generation (every job)**
- `lyrics_worker._run_proactive_auto_correct()` runs the multi-model
path after `mark_lyrics_complete` (downstream already triggered →
non-blocking), gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, bounded by a
180s timeout, and **swallows every error** — it never blocks or fails
the karaoke job (flaky AI / out of credits / timeout all degrade
gracefully).
- Cache-key aligned with the UI request, so the review page's on-load
call is an instant cache hit (no double spend).
- `ci.yml`: wires `AUTO_CORRECT_*` env + the `anthropic-api-key` secret
onto `lyrics-transcription-job` (same SA as the API service — no IAM
change).

**Review UI**
- Always multi-model (removed the model-selection toggle); button
renamed **"Auto-correct"**; stripped model/consensus/cached attribution
badges; reworded strings to drop "AI"/"model" (translated to all 32
locales).
- Auto-runs once on review load so suggestions are ready without a
click; the button stays for the paste-references-later flow.

## Testing
- Backend: **3460 passed** (`backend/tests/`, emulator excluded) — incl.
new `test_pricing.py` + `test_proactive_auto_correct.py` (gating,
graceful failure, cache alignment).
- Frontend: **1006 jest tests pass**; type-clean; 33-locale key parity
verified.

## Notes / follow-ups
- Proactive activates on the **next deploy** (the lyrics-job env/secret
apply via this PR's ci.yml on merge).
- Left "AI" wording in two *separate* features untouched (different
subsystems): `lyricsReview.agenticMetrics` and
`lyricsReview.modals.correctionAnnotation` — flagged for a separate
decision.
- The production E2E spec's click-to-open flow may want a tweak now that
suggestions auto-run on load.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 18:22:51 -04:00
Andrew Beveridge ☄️andClaude Fable 5 0dd5d404e5 feat: cache AI auto-correct suggestions per job (free re-runs on unmodified lyrics) (#815)
@coderabbitai ignore

Per Andrew: clicking AI Suggest twice on the same unmodified lyrics
shouldn't spend AI tokens twice.

Suggestions are now cached per job in GCS
(`jobs/{job_id}/lyrics/auto_correct_cache/{hash}.json`), keyed on the
exact input — word ids + texts, reference lyrics texts, settings knobs,
and the resolved model list. A repeat run on byte-identical input
returns the previous suggestions instantly with `cached: true` (teal
"cached" badge in the panel) and incurs no LLM cost. Any edit to the
lyrics, references, or settings produces a new key and a fresh run; word
ids in the key guarantee cached suggestions always reference words that
still exist.

Cache reads/writes are strictly best-effort — any storage failure
degrades to a normal uncached run (tested). 7 new backend tests (hit
skips model call, miss writes cache, key stability/sensitivity, payload
round-trip, corrupt entry = miss, storage failure never breaks the
request).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 18:03:44 +00:00
Andrew Beveridge ☄️andClaude Fable 5 5bf8de3730 fix: AI suggestions list overflows panel instead of scrolling (#814)
@coderabbitai ignore

The suggestions list in the auto-correct panel rendered past the panel
border over the content below (screenshot from Andrew on job b9adb5b4
with 39 suggestions). Root cause: the repo's `ScrollArea` Radix root has
no `overflow-hidden`, so `max-h-64` on it never clips the viewport.
Replaced with a plain `max-h-64 overflow-y-auto` div — native scroll,
guaranteed containment.

Test-impact: none (tsc clean, auto-correct suites pass; pure
CSS/structure change).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 17:32:22 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 a0e61d9e21 feat(audio-editor): add Fade In / Fade Out buttons for selected region (#813)
## Summary

Adds **Fade In** and **Fade Out** action buttons to the audio editor
toolbar so users can ramp the volume of a selected region gracefully
instead of an abrupt hard cut.

**Primary use case:** after trimming a long intro off a song, the track
otherwise begins at full volume at the trim point. Selecting the first
few seconds and clicking **Fade In** makes it come in gracefully.
Likewise **Fade Out** for a trimmed outro.

## UX

The buttons are **edge-gated**, mirroring the existing `Trim Start` /
`Trim End` behaviour:
- **Fade In** appears when the selection starts near the beginning
(`start < 1s`)
- **Fade Out** appears when the selection ends near the end (`end >
duration - 1s`)

This matches the real workflow and `afade`'s semantics (fades only make
sense at clip edges — a mid-clip fade-in would silence everything before
it). Mid-track fades are noted as out-of-scope future work.

## Changes

**Backend** (`audio_edit_service.py`, `review.py`)
- New `fade_region()` using FFmpeg's `afade` filter (lossless FLAC,
duration-preserving).
- **Anchoring + bounds enforced server-side** (not just in the UI): a
fade-in is forced to begin at the clip start and a fade-out to finish at
the clip end, with a 1s tolerance matching the UI gating, so a
non-anchored API request can never silently mute the rest of the track.
- `fade_in` / `fade_out` dispatch in `apply_edit` + added to route
`valid_operations`.

**Frontend** (`AudioEditor.tsx`)
- `handleFadeIn` / `handleFadeOut` + edge-gated toolbar buttons
(`TrendingUp` / `TrendingDown` icons).
- i18n strings added and translated to all 33 locales.

## Testing

- **Backend unit** (`test_audio_edit_service.py`): fade in/out ffmpeg
args, invalid direction, inverted region, **unanchored start/end
rejection**, end-beyond-duration rejection, `apply_edit` dispatch for
both ops.
- **Backend route** (`test_audio_edit_routes.py`): `fade_in` /
`fade_out` accepted (parametrized).
- **Frontend** (`AudioEditor.test.tsx`): Fade In/Out buttons render for
start/end-anchored selections and call `applyAudioEdit` with the right
operation + params.
- Full suites green: 60 backend audio-edit + 45 review-route + 25
frontend AudioEditor tests pass. Lint clean on changed files.

Plan doc: `docs/archive/2026-06-11-audio-editor-fade-buttons-plan.md`

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 13:25:28 -04:00
Andrew Beveridge ☄️andClaude Fable 5 f5169bfaa1 test: harden auto-correct production E2E (session dialog + cold start) (#812)
@coderabbitai ignore

Test-only follow-up to #811. The production E2E for AI auto-correct
failed against a job that had a saved review session: the Saved Review
Sessions dialog aria-hides the rest of the app, so role-based locators
couldn't find the (visible) AI Suggest button. The spec now closes that
dialog without restoring, and allows 90s for the first review-page load
after a fresh deploy (cold Cloud Run + uncached correction payload).
Verified passing against live prod (19.5s).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 07:52:41 +00:00
Andrew Beveridge ☄️andClaude Fable 5 e4aad66a06 feat: Fable 5 default + multi-model compare for AI auto-correct (v0.178.0) (#811)
@coderabbitai ignore

## Summary

Follow-up to #809, per Andrew's direction: switch the auto-correct
default to the eval's best model, and add an opt-in **multi-model
compare mode** that queries several models in parallel, dedupes
identical suggestions with consensus counts, and lets the reviewer pick
between conflicting variants.

## Changes

**Fable 5 as production default**
- New Anthropic provider path in `AutoCorrectService` (structured
outputs + adaptive thinking — the exact configuration the 30-job eval
used). Eval rationale: strict precision 0.62 vs 0.56, strict recall 0.51
vs 0.46, 27s vs 35s median latency vs Gemini 3.1 Pro.
- `anthropic-api-key` secret: container added to Pulumi
(`infrastructure/modules/secrets.py`, **already applied** — preview was
exactly +1 create after pinning pulumi-gcp to 9.22.0 to avoid
provider-upgrade VM replaces), value added and verified against the live
API.
- Cloud Run deploy: `AUTO_CORRECT_MODEL=claude-fable-5`,
`AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview`,
`ANTHROPIC_API_KEY` secret mapping.
- No silent provider fallback: missing key → clear 502.
- `anthropic >=0.109` added as a direct dependency (lock updated).

**Multi-model compare mode**
- `compare_models` setting → all configured models queried in parallel;
identical suggestions deduped with `consensus`/`total_models` + `models`
attribution; overlapping disagreements share a `conflict_group`.
- UI: "Compare multiple AI models" toggle in the run modal; consensus
badges ("2/2 models") and variant badges in the panel; accepting one
variant of a conflict group auto-rejects its siblings; accept-all picks
the highest-consensus winner per group.
- Partial model failure (call error or malformed output) degrades to a
response warning; only all-fail returns 502.
- EditLog decisions now record models/consensus/conflict_group —
per-model accept-rate data accrues in prod.

**Cross-provider bug fixed**: google-genai mutates `response_schema`
dicts in place (injects `property_ordering`), which the Anthropic API
rejects — found via real-call smoke test of compare mode; schemas now
deep-copied per call, with a regression test.

## Testing

- 55 backend auto-correct tests (incl. 10 new multi-model
merge/conflict/degradation tests + schema-pollution regression) and
frontend conflict-util tests; full suite green (3,426 backend unit + 103
emulator + 1,004 frontend)
- Real-call smoke tests: single-model Fable (glory→chlorine, 0.98, 5.6s)
and compare mode (Fable + Gemini parallel, merged to one 2/2-consensus
suggestion, 5.8s)
- Secret value verified end-to-end against the Anthropic API
- CodeRabbit CLI: 12 findings — 5 fixed, 5 skipped with reasons, 2 in
files from another merged PR

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 06:52:14 +00:00
Andrew Beveridge ☄️andClaude Fable 5 6f8503a113 feat: opt-in AI auto-correct suggestions in lyrics review UI (v0.177.0) (#809)
@coderabbitai ignore

## Summary

Third take on lyrics auto-correction, redesigned around the failures
that led to disabling it in #321 (Jan 2026): **one whole-song LLM call**
instead of per-gap calls, **user-triggered from the review UI** instead
of blocking the pipeline, and a **pending-suggestion layer with
per-change accept/reject/undo** instead of silent application. Fully
opt-in — zero change to the default review journey.

## Changes

**Backend**
- `POST /api/review/{job_id}/auto-correct` — stateless; client posts its
current working segments + reference lyrics, gets back word-id-keyed
suggestions (`replace` / `delete` / `insert_after`) with reason,
category, confidence
- `backend/services/auto_correct/` — prompts (kept in sync with the
offline eval harness), settings knobs (adlib removal, insertions,
min-confidence), Vertex Gemini call with 120s timeout, strict
server-side validation of model output
- `AUTO_CORRECT_MODEL` env (default `gemini-3.1-pro-preview`); 422 when
no reference sources exist

**Frontend**
- "AI Suggest" button in the review header → settings modal →
suggestions panel: per-row accept/reject/undo, accept-all/reject-all,
click-to-scroll-and-flash, stale detection when targeted words were
edited since generation
- `useAutoCorrect` hook + pure `autoCorrectApply` utils (id-based
apply/revert, safe against concurrent edits)
- EditLog ops `ai_suggestion_run/accept/reject/undo` — real accept-rate
data accrues from day one
- i18n strings translated to all 33 locales

**Model choice** backed by an offline eval over 30 real production jobs
scored against actual human review edits (design doc:
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`): Fable
5 ≈ Gemini 3.1 Pro at the top; GPT-5.2 actively worsened lyrics (would
have repeated the 2025 failure). Gemini chosen for v1 (already on
Vertex, no new secret); switching models is one env var.

## Testing

- 42 backend unit/route tests (`backend/tests/services/auto_correct/`,
`backend/tests/api/test_review_auto_correct.py`)
- 15 frontend unit tests (`autoCorrectApply.test.ts`)
- Production E2E spec
(`frontend/e2e/production/auto-correct-suggestions.spec.ts`) — runs one
real suggestion cycle and dismisses without mutating review state
- Full `make test` green (unit + backend + emulator + frontend)
- CodeRabbit CLI review: 7 findings, 6 fixed, 1 skipped with reason

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 05:44:51 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 2b7d6bb5f0 fix(lyrics-review): validate & sanitize word timings during review (prevent overlap at source) (#810)
## Summary
Prevents the invalid-word-timing class that caused job `17f7c313`'s
overlapping rendered lyrics (`start=0`, `end=-0.005`) from being
**created or persisted** during lyrics review. The render-time net
(v0.176.2, #804) stays as the last resort; this fixes the source.

Root cause: `useManualSync` ("tap-to-time") assigned `start=0` when the
audio playhead sat at 0 and cascaded `end = 0 - 0.005`. Verified against
this job's data — not AudioShake; not in the edit log (manual-sync
timing edits aren't logged there).

## One shared invariant, four enforcement points
Each word stays within its segment's `[start, end]`; `end ≥ start`;
repaired words are placed at the previous word's end. All four
implementations now produce identical results:
1. **Frontend sanitizer**
`frontend/lib/lyrics-review/sanitizeWordTimings.ts` — pure function +
change report.
2. **Manual-sync clamp** `frontend/hooks/useManualSync.ts` — tap times
clamped to the segment window; `end_time` inversion-guarded (without
capping — holding a note still extends the segment); toast on clamp.
3. **Modal** `frontend/components/lyrics-review/modals/EditModal.tsx` —
sanitize-on-open + `role="status"` banner; Reset/Un-Correct also
sanitize (fixes the buggy 0/null editing surface).
4. **Backend safety net** `backend/services/timing_sanitizer.py` +
`submit_corrections` — clamps + logs before persisting
`corrections_updated.json`.

"Segment follows words" (the modal already derives bounds from word
min/max) means dragging a word earlier/later extends the segment — so
clamping is operation-specific and never traps the user.

## Changes
- 3 new sanitizers (FE lib, FE hook helper, BE service) + modal wiring +
route safety net.
- New unit tests anchored on the `17f7c313` fixture across all layers
(FE Jest + BE pytest).
- 2 new i18n strings, auto-translated to all 33 locales.
- Version `0.176.2 → 0.176.3`. Design + plan in
`docs/archive/2026-06-10-review-timing-validation-{design,plan}.md`.

## Testing
- [x] Backend unit (sanitizer + request-level submit test): 14 passed
- [x] Frontend lyrics-review/hooks/lib: 301 passed
- [x] Two-stage subagent review (spec + quality) per task; final
whole-impl review; CodeRabbit (1 doc fix; i18n nitpicks skipped)

## Review
- [x] Local CodeRabbit review completed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 01:15:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1b7b106c21 fix(lyrics): sanitize invalid word timings to prevent overlapping screens (#804)
## Summary
- Fixes overlapping rendered lyrics on job `17f7c313` ("Atmosphere -
Scalp") — two full screens of lyrics displayed on the same 4 vertical
slots for 7-12s.
- **Distinct root cause** from the earlier libass-wrap overlap (PR
#794), which is why it recurred. This one is a genuine same-Y /
same-time overlap caused by invalid word timestamps.

## Root cause
The transcription left the 4 leading words of a segment ("A whiskey and
a") with invalid timestamps (`start=0.0`, `end=-0.005`) while the
segment itself correctly started at 15.18s.
`SegmentResizer._create_segment_from_words` derives a split line's
`start_time` from `words[0].start_time`, so the split line `"A whiskey
and a beer,"` inherited `start_time=0.0`. A `LyricsScreen` sorts by
`min(line.segment.start_time)`, so the screen jumped ahead of the INTRO
section screen; the INTRO then wiped the active-line bookkeeping and the
next screen faded in (post-instrumental) over the still-displayed
previous screen.

## Changes
- Add `SegmentResizer._sanitize_segment_timings`, run at the top of
`resize_segments` (covers all output paths via `generator.py`).
- Clamps **only invalid** word timings into the segment's `[start, end]`
window and keeps them non-decreasing; valid words are left untouched so
the karaoke highlight sweep is preserved.
- New regression tests in
`tests/unit/lyrics_transcriber/output/test_segment_resizer_timing.py`.
- Bump version `0.176.1` → `0.176.2`.

## Testing
- [x] New timing regression tests + prior line-length regression tests
pass
- [x] Full `lyrics_transcriber` unit suite: 110 passed
- [x] End-to-end against job `17f7c313`: **4 same-Y overlaps before → 0
after**

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

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:24:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 bce87a37fb feat(ui): advertise multi-site URL support on create-from-URL input (#803)
## Summary

Phase 3 of the flacfetch-sole-downloader work. Now that **all** URLs
route through flacfetch and any yt-dlp-supported site works (Facebook,
SoundCloud, TikTok, Vimeo, …), tell users so on the create-from-URL
input.

## Changes (`frontend/components/job/steps/AudioSourceStep.tsx`)

- Broaden the button label **"YouTube URL" → "Paste a link"**.
- Add a hint under the URL field: *"Works with YouTube, Facebook,
SoundCloud, TikTok, Vimeo and hundreds of other sites."* with a link to
the yt-dlp [supported-sites
list](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md).
- Wire the URL section to i18n (`useTranslations('jobFlow')`) —
previously hardcoded — and add 4 new `jobFlow` keys (`pasteUrlButton`,
`useThisUrl`, `urlSupportedSitesHint`, `urlSupportedSitesLink`).
- Translated to **all 33 locales** via `translate.py` (key parity
verified; CI i18n validation will confirm).

## Testing

- i18n key parity verified across all 33 locale files (0 missing).
- Existing `AudioSourceStep.test.tsx` uses the global `next-intl` mock
that returns real en.json strings, and asserts none of the changed
literals — unaffected.
- Frontend `next build`/jest/E2E run in CI (node_modules isn't installed
in this worktree).

Depends on the already-shipped backend change (#802) that makes
non-YouTube URLs actually work.

Plan:
`nomadkaraoke/docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:51:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 11b3d30618 feat(downloads): route all URLs through flacfetch; remove Cloud Run yt-dlp (#802)
## Summary

Phase 2 of making **flacfetch the sole audio downloader** — no yt-dlp
ever runs on Cloud Run. Fixes the original Facebook-URL job failure and
removes a class of legacy silent-fallback behaviour.

**Root cause of the reported bug** (job `34e60208`,
`facebook.com/share/v/...`): non-YouTube URLs were downloaded by local
yt-dlp *inside the Cloud Run container*, which succeeded but then died
in `convert_to_wav` (ffmpeg given both `-y` and `-n`), surfacing as a
generic `Failed to download audio file`. Rather than patch the flags,
this removes the path entirely.

## Changes

- **`youtube_download_service.py`** — `download()` now handles **any**
yt-dlp-supported URL: YouTube via the existing video-id path; everything
else (Facebook, SoundCloud, TikTok, Vimeo, …) via flacfetch's generic
`URL` source (`download_by_id(source_name="URL", download_url=url)`).
**Deleted `_download_local`** (local yt-dlp fallback); with no flacfetch
configured it now **hard-fails with a clear error** instead of silently
falling back.
- **`file_upload.create_job_from_url`** — downloads audio up front via
the service for **all** URLs (not just YouTube), then
`start_job_processing`. Removed the non-YouTube branch that triggered
the GPU worker to download locally, and the now-dead
`_trigger_audio_worker_only`. (Keeps GPU idle until audio is in GCS.)
- **`audio_worker.py`** — deleted `download_from_url` (the buggy local
path) and `download_audio`'s URL-download fallback + the dead
`_trigger_lyrics_worker_after_url_download`. The worker now only
consumes a pre-downloaded GCS file; a URL job arriving without one fails
clearly.
- **Docs** — added
`docs/archive/2026-06-08-fallback-logic-audit-prompt.md` (a prompt for a
future session to audit all legacy "fallback" logic).

Net **−331 lines**.

## Testing

- Updated/replaced tests for the removed fallbacks; added tests for
generic-URL routing (`source_name="URL"`) and the no-flacfetch
hard-fail. Affected suites green (410 passed across the touched files);
full backend collection clean.
- Depends on **flacfetch ≥ 0.21.0** (generic `URL` source) — already
shipped & deployed (flacfetch #28), and verified end-to-end: the
original Facebook URL downloads through flacfetch to GCS.

Requires no infra change. Plan:
`nomadkaraoke/docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:15:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a319bf206a feat(lyrics-review): show song artist + title in header (#801)
## Summary

The Lyrics Transcription Review header showed only the static title
"Lyrics Transcription Review". The Instrumental Review header already
displays the song (artist + title). This adds the same song display to
the lyrics review header so reviewers can see which song they're working
on at a glance.

## Changes

- `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx`: render
`artist - title` (from the existing `job` prop) next to the header
title, mirroring the Instrumental Review pattern
(`InstrumentalSelector.tsx`). Uses `[job.artist,
job.title].filter(Boolean).join(" - ")` so it degrades cleanly when a
field is missing, with `truncate` to protect the layout.
- `pyproject.toml`: version bump 0.175.1 → 0.175.2.

## Testing

- ESLint clean on the changed file.
- `tsc` reports no new errors (the 39 pre-existing errors are all in
unrelated files).
- No new user-facing strings — only renders existing `job` data — so no
i18n/translation changes (won't trip CI's locale-completeness check).
- CodeRabbit reviewed locally (1 minor finding, fixed: cleaner
artist/title join).

## Notes

Display-only, low-risk change. No existing test covers either review
header's artist/title display (the instrumental review precedent has
none either); a meaningful test would require mocking the full lyrics
data-loading lifecycle, so none was added.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:31:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c1837c1086 fix(lyrics-review): gate audio playback until loaded + silence benign AbortError noise (#800)
## Summary
- Production error monitor flagged `AbortError: The fetching process for
the media resource was aborted...` from the lyrics-review page. Root
cause: the audio player started fetching a large file on mount but left
playback controls live before the media could play, so early clicks /
spacebar did nothing **and** the rejected `play()` promise was reported
as error noise.
- Fixes both the noise and the janky UX: playback is now gated until the
audio is fully ready, with a clear loading spinner + buffer progress
bar.

## Changes
- **AudioPlayer** is now the single source of truth for readiness:
tracks `canplaythrough` (+ fully-buffered fallback), publishes
`window.isAudioReady` and a `karaoke:audio-ready` event, and **guards
the `seekAndPlayAudio` / `toggleAudioPlayback` globals** so spacebar,
segment buttons, and the edit modal no-op until ready.
- While loading, shows a spinner + `<Progress>` bar ("Loading
audio..."); on failure shows an inline error.
- New `useAudioReady()` hook visually disables the segment play buttons
(`TranscriptionView`) and the edit-modal play button with an "Audio is
still loading..." tooltip.
- Added `.catch(() => {})` to the three bare `play()` calls and filter
benign `AbortError` in `crash-reporter` so this class of noise never
reaches the error monitor again.
- 3 new i18n strings, translated to all 33 locales (ASCII `...` to match
existing loading strings).

## Testing
- [x] Frontend unit suite green: **916 tests / 65 suites** (added
`AudioPlayer` readiness+gating, `useAudioReady`, `crash-reporter`
benign-abort cases)
- [x] Lint clean; typecheck clean on all touched files
- [ ] Manual: throttled-network check of spinner → controls transition
(recommended post-deploy)

## Review
- [x] CodeRabbit CLI review completed locally (1 finding fixed: ASCII
ellipsis; 1 pre-existing tl.json translation gap noted, out of scope)
- [x] Issues addressed

Plan doc: `docs/archive/2026-06-07-lyrics-review-audio-loading-plan.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:45:58 -04:00
139 changed files with 11263 additions and 842 deletions

No files matched your search

+10 -2
View File
@@ -1658,8 +1658,8 @@ jobs:
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
run: |
@@ -1676,6 +1676,14 @@ jobs:
--quiet
# Lyrics transcription job (CPU, us-central1)
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
# ("Invalid secret path ... in annotation") because this job's existing
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
# re-validates and rejects. Proactive auto-correct env/secret
# (AUTO_CORRECT_PROACTIVE_ENABLED + ANTHROPIC_API_KEY) must be wired by a
# method that handles the alias format (see proactive-autocorrect plan
# doc); until then the proactive flag stays unset and the worker's
# _run_proactive_auto_correct() returns early (no-op).
gcloud run jobs update lyrics-transcription-job \
--image "$IMAGE" \
--region us-central1 \
+72 -70
View File
@@ -10,12 +10,11 @@ Supports two upload flows:
- Client uploads files directly to GCS using signed URLs (no size limit)
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
"""
import asyncio
import json
import logging
import tempfile
import os
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
from pathlib import Path
from typing import Optional, List, Dict, Any, Tuple
@@ -58,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
router = APIRouter(tags=["jobs"])
def _select_mixed_audio_files(files):
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
the instrumental — so transcription would run on the backing track instead of the
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
"""
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
def _apply_tenant_overrides(
dist: EffectiveDistributionSettings,
tenant_config,
@@ -68,12 +80,20 @@ def _apply_tenant_overrides(
"""
Apply tenant-specific overrides to distribution settings and job options.
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
distribution settings, so tenant outputs never inherit the global consumer defaults
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
tenant job would land in the shared consumer Dropbox folder and upload to the global
Google Drive, regardless of the tenant's own config.
For tenant jobs:
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
(only when not already set in the request body / dist)
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
otherwise disables that channel entirely (no global-default leak)
- Forces is_private = True
- Applies locked_theme as effective theme
- Disables YouTube upload
- Disables YouTube upload (tenants never publish to YouTube)
Returns:
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
@@ -82,14 +102,12 @@ def _apply_tenant_overrides(
return dist, effective_theme_id, is_private, enable_youtube_upload
defaults = tenant_config.defaults
features = tenant_config.features
# Overlay tenant distribution defaults (request-level values take precedence)
if defaults.brand_prefix and not dist.brand_prefix:
dist.brand_prefix = defaults.brand_prefix
if defaults.dropbox_path and not dist.dropbox_path:
dist.dropbox_path = defaults.dropbox_path
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
dist.gdrive_folder_id = defaults.gdrive_folder_id
# Authoritative distribution routing (overrides any global defaults in `dist`).
dist.brand_prefix = defaults.brand_prefix
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
# Force private for all tenant jobs
is_private = True
@@ -338,16 +356,6 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
async def _trigger_audio_worker_only(job_id: str) -> None:
"""
Trigger only the audio worker.
Used for URL jobs where audio needs to be downloaded first.
The audio worker will trigger the lyrics worker after download completes.
"""
await worker_service.trigger_audio_worker(job_id)
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
@@ -1393,12 +1401,14 @@ async def mark_uploads_complete(
# List files with this prefix to find the actual uploaded file
files = storage_service.list_files(prefix)
if file_type == 'audio':
files = _select_mixed_audio_files(files)
if not files:
raise HTTPException(
status_code=400,
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
)
# Use the first (and should be only) file found
gcs_path = files[0]
@@ -1784,55 +1794,47 @@ async def create_job_from_url(
if title:
logger.info(f" Title: {title}")
# For YouTube URLs, download audio NOW using YouTubeDownloadService
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
if _is_youtube_url(body.url):
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
try:
youtube_service = get_youtube_download_service()
audio_gcs_path = await youtube_service.download(
url=body.url,
job_id=job_id,
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"YouTube download failed: {e}")
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
else:
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
# The audio worker will download the URL and trigger lyrics worker after
job_manager.transition_to_state(
# Download audio NOW via the flacfetch service for ALL URLs (YouTube and
# any other yt-dlp-supported site, e.g. Facebook/SoundCloud/TikTok).
# flacfetch is the sole downloader — no yt-dlp ever runs on Cloud Run.
# Downloading up front (before the GPU worker starts) also keeps the GPU
# idle until the audio is in GCS.
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
try:
download_service = get_youtube_download_service()
audio_gcs_path = await download_service.download(
url=body.url,
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=5,
message="Starting audio download from URL"
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"Audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"URL download failed: {e}")
job_manager.fail_job(job_id, f"Download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
background_tasks.add_task(_trigger_audio_worker_only, job_id)
return CreateJobFromUrlResponse(
status="success",
+43
View File
@@ -20,6 +20,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
from pydantic import BaseModel
from backend.workers.audio_worker import process_audio_separation
from backend.workers.auto_correct_worker import process_proactive_auto_correct
from backend.workers.lyrics_worker import process_lyrics_transcription
from backend.workers.screens_worker import generate_screens
from backend.workers.video_worker import generate_video
@@ -227,6 +228,48 @@ async def trigger_lyrics_worker(
)
@router.post("/workers/auto-correct", response_model=WorkerResponse)
async def trigger_auto_correct_worker(
request: WorkerRequest,
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""Proactively pre-generate + cache AI auto-correct suggestions for a job.
Called by the lyrics worker once transcription + references are ready, so
the suggestions are cached before the reviewer opens the lyrics UI. Runs
HERE (the API service) because the service has the working Anthropic key /
compare-models config; the lyrics job does not.
Best-effort and runs synchronously within the request (the caller awaits
with its own timeout): the work never fails the karaoke job, and the
response just reports what happened. Gated by AUTO_CORRECT_PROACTIVE_ENABLED.
"""
job_id = request.job_id
# Extract trace context from incoming request (propagated via the trigger).
trace_context = extract_trace_context(dict(http_request.headers))
logger.info(f"[job:{job_id}] WORKER_TRIGGER worker=auto-correct")
add_span_attribute("job_id", job_id)
add_span_attribute("worker", "auto-correct")
# process_proactive_auto_correct already swallows its own errors; the extra
# guard keeps the endpoint itself best-effort no matter what.
try:
result = await process_proactive_auto_correct(job_id)
add_span_event("auto_correct_proactive", {"result": result.get("status", "unknown")})
return WorkerResponse(
status=result.get("status", "unknown"),
job_id=job_id,
message=f"Proactive auto-correct: {result.get('status', 'unknown')}",
)
except Exception as e: # noqa: BLE001 — best-effort, never fail the caller
logger.warning(f"[job:{job_id}] auto-correct endpoint error (non-fatal): {e}")
add_span_event("auto_correct_proactive", {"result": "error"})
return WorkerResponse(status="error", job_id=job_id, message=f"error: {e}")
@router.post("/workers/screens", response_model=WorkerResponse)
async def trigger_screens_worker(
request: WorkerRequest,
+25 -3
View File
@@ -1112,6 +1112,18 @@ async def submit_corrections(
from backend.services.storage_service import StorageService
storage = StorageService()
# Safety net: never persist word timings that fall outside their segment.
# Frontend should already prevent this; this guarantees clean stored data
# (the render worker reads corrections_updated.json verbatim).
from backend.services.timing_sanitizer import sanitize_corrections
sanitized, clamp_count = sanitize_corrections(submission.corrections)
if clamp_count:
logger.warning(
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
f"in submitted corrections before persisting"
)
submission.corrections = sanitized
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, submission.corrections)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
@@ -2422,11 +2434,21 @@ async def create_job_from_search(
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
# Determine display values
# Determine display values.
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
# body.title carry whatever is currently in the wizard's artist/title fields,
# which reflect a "Use official formatting" correction the user may have applied
# after searching. The displayed job name must honour that correction, so prefer
# the request body over the stored query. An explicit display override wins above all.
session_artist = session.get('artist', body.artist)
session_title = session.get('title', body.title)
effective_display_artist = body.display_artist or session_artist
effective_display_title = body.display_title or session_title
# body.artist/body.title are required but unvalidated for whitespace, so strip
# them and fall back to the stored query if blank (display_* is pre-stripped to
# None by its validator). This keeps a stray " " from becoming the job name.
body_artist = (body.artist or "").strip()
body_title = (body.title or "").strip()
effective_display_artist = body.display_artist or body_artist or session_artist
effective_display_title = body.display_title or body_title or session_title
tenant_id = session.get('tenant_id') or ""
+119 -2
View File
@@ -44,6 +44,11 @@ from backend.services.custom_lyrics_service import (
CustomLyricsServiceError,
get_custom_lyrics_service,
)
from backend.services.auto_correct import (
AutoCorrectService,
AutoCorrectServiceError,
get_auto_correct_service,
)
class LineMetadataResponse(_PydBaseModel):
@@ -70,11 +75,49 @@ class CustomLyricsResponse(_PydBaseModel):
model: str
class AutoCorrectRequest(_PydBaseModel):
segments: list[dict] # client's current working corrected_segments
reference_lyrics: dict # client's reference sources (incl. user-added)
artist: Optional[str] = None
title: Optional[str] = None
settings: Optional[dict] = None # AutoCorrectSettings knobs
class AutoCorrectSuggestionResponse(_PydBaseModel):
id: str
op: str # "replace" | "delete" | "insert_after"
word_ids: list[str]
segment_ids: list[str]
original_text: str
new_text: str
reason: str
category: str
confidence: float
models: list[str]
consensus: int
total_models: int
conflict_group: Optional[str] = None
class AutoCorrectResponse(_PydBaseModel):
suggestions: list[AutoCorrectSuggestionResponse]
model: str
elapsed_seconds: float
settings_applied: dict
warnings: list[str]
cached: bool = False
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
"""FastAPI dependency wrapper around the singleton accessor."""
return get_custom_lyrics_service()
def _get_auto_correct_service_dep() -> AutoCorrectService:
"""FastAPI dependency wrapper around the singleton accessor."""
return get_auto_correct_service()
async def _load_target_segments_for_custom_lyrics(
job_id: str,
target_lines: list[str],
@@ -636,6 +679,79 @@ async def generate_custom_lyrics(
)
@router.post("/{job_id}/auto-correct", response_model=AutoCorrectResponse)
async def auto_correct_suggestions(
job_id: str,
body: AutoCorrectRequest,
auth_info: Tuple[str, str] = Depends(require_review_auth),
service: AutoCorrectService = Depends(_get_auto_correct_service_dep),
) -> AutoCorrectResponse:
"""Generate AI auto-correction suggestions for the lyrics review UI.
Stateless and strictly opt-in: one whole-song LLM call comparing the
client's current working transcription against the reference lyrics.
Returns word-id-keyed suggestions; nothing is applied server-side —
the reviewer accepts or rejects each suggestion individually and
persistence happens via the existing corrections/complete paths.
"""
from backend.services.auto_correct.settings import settings_from_dict
try:
settings = settings_from_dict(body.settings or {})
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
with job_log_context(job_id), create_span("auto_correct_suggestions"):
add_span_attribute("job_id", job_id)
add_span_attribute("segment_count", len(body.segments))
logger.info(
"auto-correct requested job=%s segments=%d sources=%d",
job_id, len(body.segments), len(body.reference_lyrics),
)
try:
result = await asyncio.to_thread(
service.suggest,
job_id=job_id,
segments=body.segments,
reference_lyrics=body.reference_lyrics,
artist=body.artist,
title=body.title,
settings=settings,
)
except AutoCorrectServiceError as exc:
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
logger.info(
"auto-correct completed job=%s suggestions=%d model=%s elapsed=%.1fs",
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
)
return AutoCorrectResponse(
suggestions=[
AutoCorrectSuggestionResponse(
id=s.id,
op=s.op,
word_ids=s.word_ids,
segment_ids=s.segment_ids,
original_text=s.original_text,
new_text=s.new_text,
reason=s.reason,
category=s.category,
confidence=s.confidence,
models=s.models,
consensus=s.consensus,
total_models=s.total_models,
conflict_group=s.conflict_group,
)
for s in result.suggestions
],
model=result.model,
elapsed_seconds=result.elapsed_seconds,
settings_applied=result.settings_applied.to_dict(),
warnings=result.warnings,
cached=result.cached,
)
@router.post("/{job_id}/handlers")
async def update_handlers(
job_id: str,
@@ -1817,7 +1933,8 @@ async def apply_audio_edit(
"""
Apply an edit operation to the input audio.
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
Supported operations: trim_start, trim_end, cut, mute, fade_in, fade_out,
join_start, join_end.
Returns updated waveform data and playback URL.
"""
import uuid
@@ -1831,7 +1948,7 @@ async def apply_audio_edit(
if not operation:
raise HTTPException(status_code=400, detail="Missing 'operation' field")
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
valid_operations = {"trim_start", "trim_end", "cut", "mute", "fade_in", "fade_out", "join_start", "join_end"}
if operation not in valid_operations:
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
+16
View File
@@ -88,6 +88,22 @@ 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"))
# 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.
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
# Models used by the multi-model "compare" mode (semicolon-separated —
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
# Proactively generate (and cache) auto-correct suggestions in the lyrics
# worker once transcription + references are ready, so the review UI has
# them instantly. Best-effort: failures never block or fail the job. Only
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
# (the lyrics-transcription-job, via ci.yml). Default off.
auto_correct_proactive_enabled: bool = os.getenv(
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
# Cloud Tasks (for scalable worker coordination)
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
# When disabled (default), workers are triggered via direct HTTP (for development)
+53
View File
@@ -106,6 +106,54 @@ class AudioEditService:
])
return self.get_metadata(output_path)
# Fades must be anchored to a clip edge — FFmpeg's afade silences audio outside
# the ramp, so a mid-clip fade would unexpectedly mute the rest of the track.
# The tolerance matches the editor UI's edge gating (start < 1s / end within 1s).
FADE_ANCHOR_TOLERANCE_SECONDS = 1.0
def fade_region(
self, input_path: str, start: float, end: float, direction: str, output_path: str
) -> AudioMetadata:
"""Apply a fade in or out anchored to a clip edge (preserves duration).
direction='in' ramps the volume from silence to full over [0, end];
direction='out' ramps from full to silence over [start, clip_end].
Anchoring is enforced server-side (not just in the UI) because FFmpeg's
afade filter silences audio outside the ramp window: a fade-in is forced
to begin at the clip start, and a fade-out to finish at the clip end, so a
non-anchored request can never silently mute the rest of the track.
"""
if direction not in ("in", "out"):
raise ValueError(f"Invalid fade direction: {direction}")
if start < 0 or end <= start:
raise ValueError(f"Invalid fade region: start={start}, end={end}")
total = self.get_metadata(input_path).duration_seconds
tol = self.FADE_ANCHOR_TOLERANCE_SECONDS
if end > total + tol:
raise ValueError(f"Fade region exceeds clip duration ({end} > {total})")
if direction == "in":
if start > tol:
raise ValueError(f"fade_in must be anchored to the clip start (got start={start})")
fade_start, fade_duration = 0.0, end
else:
if end < total - tol:
raise ValueError(f"fade_out must be anchored to the clip end (got end={end}, duration={total})")
fade_start, fade_duration = start, total - start
if fade_duration <= 0:
raise ValueError(f"Fade region must have positive duration (got {fade_duration})")
self._run_ffmpeg([
"-i", input_path,
"-af", f"afade=t={direction}:st={fade_start}:d={fade_duration}",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
if position == "start":
@@ -156,6 +204,11 @@ class AudioEditService:
metadata = self.mute_region(
local_input, params["start_seconds"], params["end_seconds"], local_output
)
elif operation in ("fade_in", "fade_out"):
direction = "in" if operation == "fade_in" else "out"
metadata = self.fade_region(
local_input, params["start_seconds"], params["end_seconds"], direction, local_output
)
elif operation in ("join_start", "join_end"):
# Download the upload file
upload_gcs_path = params["upload_gcs_path"]
+19
View File
@@ -0,0 +1,19 @@
"""AI auto-correction suggestions for the lyrics review UI.
Stateless suggestion generation: the client posts its current working
segments, the service returns word-level suggestions (replace / delete /
insert_after) referencing word ids. Nothing is applied server-side — the
reviewer accepts or rejects each suggestion in the UI.
"""
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
get_auto_correct_service,
)
__all__ = [
"AutoCorrectService",
"AutoCorrectServiceError",
"get_auto_correct_service",
]
+94
View File
@@ -0,0 +1,94 @@
"""Token pricing for auto-correct model calls.
Used to turn the per-call token usage we capture from each provider into an
estimated USD cost, for both the production usage logs and the offline
measurement script (``scripts/measure_autocorrect_cost.py``).
Prices are USD per 1,000,000 tokens.
- **Anthropic** prices are authoritative (published Claude API pricing).
``output`` is the billed output rate, which already includes adaptive
*thinking* tokens — they are billed as output and are not separable from
the final answer in the Anthropic usage object.
- **Gemini** prices are a best-known ESTIMATE for the Vertex preview tier and
are clearly marked below. Verify against current Vertex pricing before
relying on the dollar figure. Gemini thinking tokens ARE separable
(``thoughts_token_count``) and are billed at the output rate, so we fold
them into the output total.
The raw token counts are always logged alongside the dollar figure, so the
cost here is a derived convenience — if a rate is stale, recompute from the
logged tokens rather than trusting the historical USD value.
"""
from __future__ import annotations
from typing import Optional, TypedDict
class TokenUsage(TypedDict):
"""Normalized, provider-agnostic usage for one model call.
``output_tokens`` is the total billed output (final answer + thinking).
``thinking_tokens`` is informational only (None when the provider does
not report it separately) — it is already counted inside ``output_tokens``.
"""
input_tokens: int
output_tokens: int
cache_read_tokens: int
thinking_tokens: Optional[int]
class _Rate(TypedDict):
input: float
output: float
cache_read: float
# USD per 1,000,000 tokens.
MODEL_PRICING: dict[str, _Rate] = {
# --- Anthropic (authoritative) ---
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
# tier; confirm against current Google pricing before trusting USD) ---
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
}
def get_rate(model: str) -> Optional[_Rate]:
"""Return the rate card for ``model``, or None if we have no pricing.
Falls back to a prefix match on the model family (e.g. a dated
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
so a minor model-id change doesn't silently drop cost tracking.
"""
if model in MODEL_PRICING:
return MODEL_PRICING[model]
for known, rate in MODEL_PRICING.items():
if model.startswith(known):
return rate
return None
def estimate_cost_usd(model: str, usage: Optional[TokenUsage]) -> Optional[float]:
"""Estimate the USD cost of one model call from its token usage.
Returns None when usage is unavailable or the model has no known pricing,
so callers can distinguish "free/zero" from "unknown".
"""
if not usage:
return None
rate = get_rate(model)
if rate is None:
return None
input_tokens = usage.get("input_tokens") or 0
output_tokens = usage.get("output_tokens") or 0
cache_read = usage.get("cache_read_tokens") or 0
return (
input_tokens * rate["input"]
+ output_tokens * rate["output"]
+ cache_read * rate["cache_read"]
) / 1_000_000.0
+145
View File
@@ -0,0 +1,145 @@
"""Prompt construction for AI auto-correction suggestions.
Kept in sync with the offline eval harness
(lyrics-alignment-eval-dataset/auto-correct-eval/harness.py) — changes here
should be re-scored against the 30-job ground-truth dataset.
"""
from __future__ import annotations
from backend.services.auto_correct.settings import AutoCorrectSettings
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"suggestions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"op": {
"type": "string",
"enum": ["replace", "delete", "insert_after"],
},
"start_idx": {"type": "integer"},
"end_idx": {"type": "integer"},
"new_text": {"type": "string"},
"reason": {"type": "string"},
"category": {
"type": "string",
"enum": [
"mishearing",
"grammar",
"adlib_removal",
"repeated_chorus_fix",
"formatting",
"other",
],
},
"confidence": {"type": "number"},
},
"required": [
"op",
"start_idx",
"end_idx",
"new_text",
"reason",
"category",
"confidence",
],
},
}
},
"required": ["suggestions"],
}
_BASE_SYSTEM_PROMPT = """\
You are an expert lyrics transcription reviewer for a karaoke video company. \
You are given an automatic speech transcription of a song's vocals (already \
segmented into lines, each word tagged with a numeric index) plus lyrics for \
the same song from internet sources. Internet sources are usually (not always) \
closer to the true lyrics, but lack the transcription's timing and line layout.
Propose word-level corrections to the TRANSCRIPTION so its words match what is \
actually sung. A human reviewer who has listened to the song will accept or \
reject each suggestion individually, so precision matters far more than \
recall: only suggest a change when you are confident a careful human reviewer \
would make it. If reference sources disagree and you have no other evidence, \
make no suggestion.
Guidelines:
- Transcription errors are usually sound-alike mishearings: the wrong words \
sound similar to the true lyric (e.g. "glory" vs "chlorine", "ladder" vs \
"matter"). Prefer corrections that are phonetically plausible.
- The same mishearing often repeats in every chorus; correct every occurrence.
- Keep the transcription's line structure. NEVER suggest timing changes.
- Match the casing and punctuation style of the surrounding transcription.
- Do not censor or bowdlerise explicit lyrics.
- Do not rewrite lines wholesale unless the transcription is clearly garbled \
and a reference line is unambiguously what is sung at that point.
- new_text may contain multiple words, or differ in word count from the span \
it replaces.
"""
_ADLIB_ALLOWED = """\
- Parenthesised backing vocals / adlibs that the transcription contains but \
references omit may be real (references often drop them). Only suggest \
deleting them when they look like transcription hallucinations or the \
references make clear they are not sung lead lines; use category \
"adlib_removal" and lower confidence.
"""
_ADLIB_FORBIDDEN = """\
- NEVER suggest deleting backing vocals or adlibs solely because the \
references omit them; references often drop adlibs that are really sung.
"""
_INSERTIONS_FORBIDDEN = """\
- NEVER use the "insert_after" operation; only suggest "replace" and \
"delete" operations.
"""
_OUTPUT_SPEC = """\
Output JSON only, matching this shape exactly:
{"suggestions": [{"op": "replace"|"delete"|"insert_after",
"start_idx": <int>, "end_idx": <int>,
"new_text": "<replacement, empty for delete>",
"reason": "<short justification>",
"category": "mishearing"|"grammar"|"adlib_removal"|"repeated_chorus_fix"|"formatting"|"other",
"confidence": <0.0-1.0>}]}
start_idx and end_idx are inclusive word indices. For "insert_after", \
start_idx == end_idx == the index of the word the new text should follow. \
If nothing needs changing, return {"suggestions": []}.
"""
def build_system_prompt(settings: AutoCorrectSettings) -> str:
parts = [_BASE_SYSTEM_PROMPT]
parts.append(_ADLIB_ALLOWED if settings.suggest_adlib_removal else _ADLIB_FORBIDDEN)
if not settings.allow_insertions:
parts.append(_INSERTIONS_FORBIDDEN)
parts.append(_OUTPUT_SPEC)
return "\n".join(parts)
def build_user_prompt(
*,
segments: list[dict],
reference_lyrics: dict[str, dict],
artist: str | None,
title: str | None,
) -> str:
"""Render segments (with global word indices) + reference sources."""
lines = [f"ARTIST: {artist or 'unknown'}", f"TITLE: {title or 'unknown'}", "", "TRANSCRIPTION:"]
idx = 0
for li, seg in enumerate(segments):
toks = []
for w in seg.get("words") or []:
toks.append(f"{idx}:{w.get('text', '')}")
idx += 1
lines.append(f"[L{li:03d}] " + " ".join(toks))
for source, ref in (reference_lyrics or {}).items():
lines.append("")
lines.append(f"REFERENCE LYRICS ({source}):")
for seg in ref.get("segments") or []:
lines.append(seg.get("text", ""))
return "\n".join(lines)
+621
View File
@@ -0,0 +1,621 @@
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
from __future__ import annotations
import hashlib
import json
import logging
import time
import uuid
from dataclasses import asdict, dataclass, field
from typing import Any, Optional
from google import genai
from google.genai import types
from backend.config import get_settings
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
from backend.services.auto_correct.prompts import (
RESPONSE_SCHEMA,
build_system_prompt,
build_user_prompt,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
logger = logging.getLogger(__name__)
VALID_OPS = {"replace", "delete", "insert_after"}
VALID_CATEGORIES = {
"mishearing",
"grammar",
"adlib_removal",
"repeated_chorus_fix",
"formatting",
"other",
}
class AutoCorrectServiceError(Exception):
def __init__(self, message: str, *, status_code: int = 400) -> None:
super().__init__(message)
self.status_code = status_code
@dataclass
class Suggestion:
id: str
op: str # replace | delete | insert_after
word_ids: list[str] # targeted words (replace/delete); [anchor] for insert_after
segment_ids: list[str] # segments containing the targeted words
original_text: str # current text of the targeted span ("" for insert_after)
new_text: str # replacement text ("" for delete)
reason: str
category: str
confidence: float
# Multi-model compare metadata. In single-model mode models has one
# entry and consensus == total_models == 1.
models: list[str] = field(default_factory=list)
consensus: int = 1
total_models: int = 1
# Set when other suggestions target overlapping words with a different
# outcome — the UI lets the reviewer pick at most one per group.
conflict_group: Optional[str] = None
@dataclass
class AutoCorrectResult:
suggestions: list[Suggestion]
model: str # comma-joined when compare mode queried several models
elapsed_seconds: float
settings_applied: AutoCorrectSettings
warnings: list[str] = field(default_factory=list)
# True when served from the per-job GCS cache (no LLM call was made).
cached: bool = False
class AutoCorrectService:
def __init__(self) -> None:
self.settings = get_settings()
def suggest(
self,
*,
job_id: str,
segments: list[dict],
reference_lyrics: dict[str, dict],
artist: Optional[str],
title: Optional[str],
settings: AutoCorrectSettings,
) -> AutoCorrectResult:
if not segments:
raise AutoCorrectServiceError("segments is empty")
if not reference_lyrics:
raise AutoCorrectServiceError(
"no reference lyrics available — auto-correction needs at least "
"one internet/reference source to compare against",
status_code=422,
)
# Flat word list mirrors the prompt's global indices.
flat: list[tuple[str, str, str]] = [] # (word_id, word_text, segment_id)
for seg in segments:
if not seg.get("id"):
raise AutoCorrectServiceError("all segments must have ids")
for w in seg.get("words") or []:
if not w.get("id"):
raise AutoCorrectServiceError("all words must have ids")
flat.append((w["id"], w.get("text", ""), seg["id"]))
system_prompt = build_system_prompt(settings)
user_prompt = build_user_prompt(
segments=segments,
reference_lyrics=reference_lyrics,
artist=artist,
title=title,
)
models = self._models_for(settings)
# Re-running on byte-identical input (lyrics, references, settings,
# models) returns the previous result instead of paying for another
# LLM call. Word ids are part of the key, so cached suggestions
# always reference words that still exist.
cache_path = self._cache_path(
job_id, models, settings, flat, reference_lyrics, artist, title
)
cached = self._cache_get(cache_path)
if cached is not None:
logger.info(
"auto-correct cache hit job=%s suggestions=%d", job_id,
len(cached.suggestions),
)
return cached
t0 = time.time()
per_model: dict[str, list[Suggestion]] = {}
# Token usage per successful model call (None when the provider's
# usage object couldn't be read). Drives the cost log below.
per_model_usage: dict[str, Optional[TokenUsage]] = {}
warnings: list[str] = []
if len(models) == 1:
raw, usage = self._call_model(
models[0], system_prompt, user_prompt, job_id=job_id
)
suggestions, vw = self._validate(raw, flat, settings)
per_model[models[0]] = suggestions
per_model_usage[models[0]] = usage
warnings.extend(vw)
else:
import concurrent.futures as cf
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
futures = {
ex.submit(
self._call_model, m, system_prompt, user_prompt, job_id=job_id
): m
for m in models
}
for fut, m in futures.items():
try:
raw, usage = fut.result()
suggestions, vw = self._validate(raw, flat, settings)
except AutoCorrectServiceError as exc:
# One model failing (call OR malformed output) must not
# abort compare mode; the rest still return results.
warnings.append(f"model {m} failed: {exc}")
continue
per_model[m] = suggestions
per_model_usage[m] = usage
warnings.extend(f"[{m}] {w}" for w in vw)
if not per_model:
raise AutoCorrectServiceError(
"all AI models failed", status_code=502
)
merged = self._merge(per_model, flat)
elapsed = time.time() - t0
model_label = ", ".join(per_model.keys())
logger.info(
"auto-correct job=%s models=%s words=%d suggestions=%d dropped_warnings=%d elapsed=%.1fs",
job_id, model_label, len(flat), len(merged), len(warnings), elapsed,
)
self._log_usage(job_id, per_model_usage)
result = AutoCorrectResult(
suggestions=merged,
model=model_label,
elapsed_seconds=round(elapsed, 1),
settings_applied=settings,
warnings=warnings,
)
self._cache_put(cache_path, result)
return result
@staticmethod
def _log_usage(
job_id: str, per_model_usage: dict[str, Optional[TokenUsage]]
) -> None:
"""Emit greppable per-model and total cost lines for one suggest() call.
Token counts are ground truth; the USD figures are derived from
``pricing.MODEL_PRICING`` and use ESTIMATED Gemini rates (see that
module). Query in Cloud Logging via ``auto-correct usage`` /
``auto-correct cost``. Observability only — never raises.
"""
total_cost = 0.0
any_cost = False
for model, usage in per_model_usage.items():
cost = estimate_cost_usd(model, usage)
if cost is not None:
total_cost += cost
any_cost = True
if usage is None:
logger.info(
"auto-correct usage job=%s model=%s tokens=unavailable",
job_id, model,
)
continue
thinking = usage.get("thinking_tokens")
logger.info(
"auto-correct usage job=%s model=%s input_tokens=%d "
"output_tokens=%d thinking_tokens=%s cache_read_tokens=%d "
"est_cost_usd=%s",
job_id,
model,
usage.get("input_tokens", 0),
usage.get("output_tokens", 0),
"na" if thinking is None else thinking,
usage.get("cache_read_tokens", 0),
"unknown" if cost is None else f"{cost:.4f}",
)
logger.info(
"auto-correct cost job=%s models=%s total_est_cost_usd=%s",
job_id,
", ".join(per_model_usage.keys()),
f"{total_cost:.4f}" if any_cost else "unknown",
)
# ---- suggestion cache (GCS, best-effort) ----
def _get_storage(self):
if not hasattr(self, "_storage"):
from backend.services.storage_service import StorageService
self._storage = StorageService()
return self._storage
@staticmethod
def _cache_path(
job_id: str,
models: list[str],
settings: AutoCorrectSettings,
flat: list[tuple[str, str, str]],
reference_lyrics: dict[str, dict],
artist: Optional[str],
title: Optional[str],
) -> str:
payload = {
"v": 1,
"models": models,
"settings": settings.to_dict(),
"words": [[word_id, text] for word_id, text, _seg in flat],
"references": {
source: [seg.get("text", "") for seg in (ref.get("segments") or [])]
for source, ref in sorted((reference_lyrics or {}).items())
},
"artist": artist,
"title": title,
}
digest = hashlib.sha256(
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
).hexdigest()[:24]
return f"jobs/{job_id}/lyrics/auto_correct_cache/{digest}.json"
def _cache_get(self, path: str) -> Optional[AutoCorrectResult]:
"""Best-effort: any storage/shape problem is a cache miss, never an error."""
try:
storage = self._get_storage()
if not storage.bucket.blob(path).exists():
return None
data = storage.download_json(path)
return AutoCorrectResult(
suggestions=[Suggestion(**s) for s in data["suggestions"]],
model=data["model"],
elapsed_seconds=0.0,
settings_applied=AutoCorrectSettings(**data["settings_applied"]),
warnings=list(data.get("warnings") or []),
cached=True,
)
except Exception:
logger.warning("auto-correct cache read failed for %s", path, exc_info=True)
return None
def _cache_put(self, path: str, result: AutoCorrectResult) -> None:
"""Best-effort: a failed cache write never fails the request."""
try:
self._get_storage().upload_json(
path,
{
"suggestions": [asdict(s) for s in result.suggestions],
"model": result.model,
"settings_applied": result.settings_applied.to_dict(),
"warnings": result.warnings,
"elapsed_seconds": result.elapsed_seconds,
},
)
except Exception:
logger.warning("auto-correct cache write failed for %s", path, exc_info=True)
def _models_for(self, settings: AutoCorrectSettings) -> list[str]:
if settings.compare_models:
configured = [
m.strip()
for m in self.settings.auto_correct_compare_models.replace(",", ";").split(";")
if m.strip()
]
# De-dupe while preserving order.
seen: set[str] = set()
models = [m for m in configured if not (m in seen or seen.add(m))]
if len(models) >= 2:
return models
logger.warning(
"compare_models requested but AUTO_CORRECT_COMPARE_MODELS has "
"%d usable entries; falling back to single model", len(models),
)
return [self.settings.auto_correct_model]
@staticmethod
def _merge(
per_model: dict[str, list[Suggestion]],
flat: list[tuple[str, str, str]],
) -> list[Suggestion]:
"""Deduplicate identical suggestions across models, tag consensus,
assign conflict groups to overlapping non-identical suggestions, and
sort by document position."""
total = len(per_model)
merged: dict[tuple, Suggestion] = {}
for model, suggestions in per_model.items():
for s in suggestions:
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
existing = merged.get(key)
if existing is None:
s.models = [model]
s.consensus = 1
s.total_models = total
merged[key] = s
else:
existing.models.append(model)
existing.consensus += 1
existing.confidence = max(existing.confidence, s.confidence)
result = list(merged.values())
# Conflict groups: suggestions sharing any target word but not merged
# above disagree about the same span — reviewer picks at most one.
# (insert_after anchors are excluded: inserting after a word does not
# conflict with editing that word.)
by_word: dict[str, list[int]] = {}
for i, s in enumerate(result):
if s.op == "insert_after":
continue
for wid in s.word_ids:
by_word.setdefault(wid, []).append(i)
parent = list(range(len(result)))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for overlapping in by_word.values():
for other in overlapping[1:]:
parent[find(other)] = find(overlapping[0])
roots: dict[int, list[int]] = {}
for i in range(len(result)):
roots.setdefault(find(i), []).append(i)
for members in roots.values():
if len(members) < 2:
continue
group = str(uuid.uuid4())
for i in members:
result[i].conflict_group = group
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
return result
# ---- internals ----
def _call_model(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
if model.startswith("claude"):
return self._call_anthropic(model, system_prompt, user_prompt, job_id=job_id)
return self._call_gemini(model, system_prompt, user_prompt, job_id=job_id)
@staticmethod
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
"""Best-effort usage from an Anthropic response.
``output_tokens`` already includes adaptive thinking tokens (billed as
output); they are not separable here, so thinking_tokens is None.
Returns None on any shape problem — usage must never break the call.
"""
try:
u = response.usage
return TokenUsage(
input_tokens=int(getattr(u, "input_tokens", 0) or 0),
output_tokens=int(getattr(u, "output_tokens", 0) or 0),
cache_read_tokens=int(getattr(u, "cache_read_input_tokens", 0) or 0),
thinking_tokens=None,
)
except Exception:
logger.debug("auto-correct: could not read Anthropic usage", exc_info=True)
return None
@staticmethod
def _gemini_usage(response: Any) -> Optional[TokenUsage]:
"""Best-effort usage from a Gemini (Vertex) response.
Gemini reports thinking separately (``thoughts_token_count``); it is
billed at the output rate, so it's folded into output_tokens and also
reported separately for visibility. Returns None on any shape problem.
"""
try:
u = response.usage_metadata
prompt = int(getattr(u, "prompt_token_count", 0) or 0)
candidates = int(getattr(u, "candidates_token_count", 0) or 0)
thoughts = int(getattr(u, "thoughts_token_count", 0) or 0)
cached = int(getattr(u, "cached_content_token_count", 0) or 0)
return TokenUsage(
input_tokens=prompt,
output_tokens=candidates + thoughts,
cache_read_tokens=cached,
thinking_tokens=thoughts,
)
except Exception:
logger.debug("auto-correct: could not read Gemini usage", exc_info=True)
return None
def _call_anthropic(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
import os
import anthropic
if not os.environ.get("ANTHROPIC_API_KEY"):
# No silent fallback to another provider — surface the
# misconfiguration so it gets fixed, not masked.
logger.error(
"auto-correct model %s requires ANTHROPIC_API_KEY which is not set "
"(job=%s)", model, job_id,
)
raise AutoCorrectServiceError(
"AI model is not configured", status_code=502
)
# Structured outputs require additionalProperties: false on objects;
# the Vertex variant of the schema omits it, so inject here. Deep-copy
# because the google-genai SDK mutates schema dicts in place (it adds
# 'property_ordering', which the Anthropic API rejects).
import copy
base = copy.deepcopy(RESPONSE_SCHEMA)
for obj in (base, base["properties"]["suggestions"]["items"]):
obj.pop("property_ordering", None)
obj.pop("propertyOrdering", None)
obj["additionalProperties"] = False
strict_schema = base
client = anthropic.Anthropic(timeout=120.0)
try:
response = client.messages.create(
model=model,
max_tokens=16000,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
thinking={"type": "adaptive"},
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
)
except Exception as exc:
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
raise AutoCorrectServiceError(
"AI model call failed", status_code=502
) from exc
usage = self._anthropic_usage(response)
try:
text = next(b.text for b in response.content if b.type == "text")
return json.loads(text), usage
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
logger.exception(
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
)
raise AutoCorrectServiceError(
"AI returned non-JSON output", status_code=502
) from exc
def _call_gemini(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
# Milliseconds; bounds the call so a hung model never strands the UI.
http_options=types.HttpOptions(timeout=120_000),
)
# Deep-copy: the google-genai SDK mutates the schema dict in place,
# which would poison the shared module-level constant for other
# providers running in the same process.
import copy
try:
response = client.models.generate_content(
model=model,
contents=[user_prompt],
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
),
)
except Exception as exc: # surface as 502, never a stuck job
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
raise AutoCorrectServiceError(
"AI model call failed", status_code=502
) from exc
usage = self._gemini_usage(response)
try:
return json.loads(response.text), usage
except (json.JSONDecodeError, TypeError) as exc:
logger.exception(
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
)
raise AutoCorrectServiceError(
"AI returned non-JSON output", status_code=502
) from exc
def _validate(
self,
raw: Any,
flat: list[tuple[str, str, str]],
settings: AutoCorrectSettings,
) -> tuple[list[Suggestion], list[str]]:
if not isinstance(raw, dict) or not isinstance(raw.get("suggestions"), list):
raise AutoCorrectServiceError(
"AI response missing 'suggestions' list", status_code=502
)
n = len(flat)
out: list[Suggestion] = []
warnings: list[str] = []
for i, s in enumerate(raw["suggestions"]):
problem = self._check(s, n, settings)
if problem:
warnings.append(f"dropped suggestion {i}: {problem}")
continue
start, end = int(s["start_idx"]), int(s["end_idx"])
if s["op"] == "insert_after":
word_ids = [flat[start][0]]
segment_ids = [flat[start][2]]
original_text = ""
else:
span = flat[start : end + 1]
word_ids = [w[0] for w in span]
segment_ids = sorted({w[2] for w in span})
original_text = " ".join(w[1] for w in span)
out.append(
Suggestion(
id=str(uuid.uuid4()),
op=s["op"],
word_ids=word_ids,
segment_ids=segment_ids,
original_text=original_text,
new_text="" if s["op"] == "delete" else str(s["new_text"]).strip(),
reason=str(s.get("reason", "")),
category=s["category"] if s.get("category") in VALID_CATEGORIES else "other",
confidence=max(0.0, min(1.0, float(s["confidence"]))),
)
)
return out, warnings
@staticmethod
def _check(s: Any, n_words: int, settings: AutoCorrectSettings) -> Optional[str]:
if not isinstance(s, dict):
return "not an object"
op = s.get("op")
if op not in VALID_OPS:
return f"invalid op {op!r}"
try:
start, end = int(s["start_idx"]), int(s["end_idx"])
confidence = float(s["confidence"])
except (KeyError, TypeError, ValueError):
return "missing/invalid indices or confidence"
if not (0 <= start <= end < n_words):
return f"indices out of range ({start}..{end} of {n_words})"
if op == "insert_after" and not settings.allow_insertions:
return "insertions disabled by settings"
if op == "insert_after" and start != end:
return "insert_after requires start_idx == end_idx"
new_text = str(s.get("new_text", "")).strip()
if op in ("replace", "insert_after") and not new_text:
return f"{op} with empty new_text"
if op == "delete" and new_text:
return "delete with non-empty new_text"
if confidence < settings.min_confidence:
return f"confidence {confidence:.2f} below threshold"
if (
s.get("category") == "adlib_removal"
and not settings.suggest_adlib_removal
):
return "adlib removal disabled by settings"
return None
_service_instance: Optional[AutoCorrectService] = None
def get_auto_correct_service() -> AutoCorrectService:
global _service_instance
if _service_instance is None:
_service_instance = AutoCorrectService()
return _service_instance
+47
View File
@@ -0,0 +1,47 @@
"""User-facing knobs for AI auto-correction suggestions."""
from __future__ import annotations
from dataclasses import asdict, dataclass
@dataclass(frozen=True)
class AutoCorrectSettings:
"""Reviewer-tunable behaviour for a suggestion run.
suggest_adlib_removal: allow suggestions that delete transcribed
backing-vocal / adlib phrases absent from the references.
allow_insertions: allow suggestions that insert words the
transcription missed entirely.
min_confidence: drop suggestions below this confidence server-side
(the UI can filter further client-side).
compare_models: query every configured compare model in parallel,
deduplicate identical suggestions and report per-suggestion
model consensus (slower, costs one call per model).
"""
suggest_adlib_removal: bool = True
allow_insertions: bool = True
min_confidence: float = 0.0
compare_models: bool = False
def to_dict(self) -> dict:
return asdict(self)
def settings_from_dict(data: dict) -> AutoCorrectSettings:
known = {f for f in AutoCorrectSettings.__dataclass_fields__}
unknown = set(data) - known
if unknown:
raise ValueError(f"unknown settings: {sorted(unknown)}")
merged = {**AutoCorrectSettings().to_dict(), **data}
if not isinstance(merged["suggest_adlib_removal"], bool):
raise ValueError("suggest_adlib_removal must be a boolean")
if not isinstance(merged["allow_insertions"], bool):
raise ValueError("allow_insertions must be a boolean")
if not isinstance(merged["compare_models"], bool):
raise ValueError("compare_models must be a boolean")
mc = merged["min_confidence"]
if isinstance(mc, bool) or not isinstance(mc, (int, float)) or not 0.0 <= float(mc) <= 1.0:
raise ValueError("min_confidence must be a number between 0 and 1")
merged["min_confidence"] = float(mc)
return AutoCorrectSettings(**merged)
+64
View File
@@ -0,0 +1,64 @@
"""Sanitize submitted review corrections so word timings stay within their segment.
Mirrors the frontend sanitizeWordTimings.ts and the render-time
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
segment window or is inverted. Segments whose own bounds are non-finite are left
untouched (the editor derives bounds from words elsewhere). Mutates and returns the
same dict for caller convenience, plus the number of fields clamped."""
from __future__ import annotations
import math
from typing import Any, Dict, Tuple
def _finite(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
segments = corrections.get("corrected_segments")
if not isinstance(segments, list):
return corrections, 0
changes = 0
for seg in segments:
if not isinstance(seg, dict):
continue
seg_start = seg.get("start_time")
seg_end = seg.get("end_time")
# If the segment's own bounds aren't finite, don't touch its words.
if not _finite(seg_start) or not _finite(seg_end):
continue
seg_end = max(seg_end, seg_start)
prev_end = seg_start
for w in seg.get("words", []):
if not isinstance(w, dict):
continue
start = w.get("start_time")
end = w.get("end_time")
# Invalid start = missing/non-finite OR outside the segment window.
if _finite(start) and seg_start <= start <= seg_end:
new_start = start
else:
new_start = min(max(prev_end, seg_start), seg_end)
# Invalid end = missing/non-finite, before start, or past segment end.
if _finite(end) and new_start <= end <= seg_end:
new_end = end
else:
new_end = min(max(new_start, end if _finite(end) else new_start), seg_end)
if new_end < new_start:
new_end = new_start
if new_start != start:
w["start_time"] = new_start
changes += 1
if new_end != end:
w["end_time"] = new_end
changes += 1
prev_end = new_end
return corrections, changes
+28
View File
@@ -410,6 +410,34 @@ class WorkerService:
async def trigger_screens_worker(self, job_id: str) -> bool:
"""Trigger screen generation worker."""
return await self.trigger_worker("screens", job_id)
async def trigger_auto_correct(self, job_id: str, timeout_seconds: int = 200) -> bool:
"""Trigger proactive auto-correct generation on the API service.
Direct, awaited HTTP call (NOT Cloud Tasks): the endpoint runs the work
synchronously, so awaiting it keeps both the caller (lyrics job) and the
service instance alive until the cache is written. Best-effort — returns
False on any failure and never raises, so it can't affect the job.
"""
if not self._base_url:
logger.info(f"[job:{job_id}] auto-correct trigger skipped: no service base URL")
return False
url = f"{self._base_url}/api/internal/workers/auto-correct"
headers = {"Content-Type": "application/json"}
if self._admin_token:
headers["X-Admin-Token"] = self._admin_token
# Propagate trace context so the service-side span links to this job.
headers = inject_trace_context(headers)
try:
async with httpx.AsyncClient(timeout=timeout_seconds) as client:
resp = await client.post(url, json={"job_id": job_id}, headers=headers)
logger.info(
f"[job:{job_id}] auto-correct trigger -> HTTP {resp.status_code}"
)
return resp.status_code < 400
except Exception as e: # noqa: BLE001 — best-effort, never fatal
logger.warning(f"[job:{job_id}] auto-correct trigger failed (non-fatal): {e}")
return False
def _warmup_encoding_worker(self, job_id: str) -> None:
"""Fire-and-forget warmup of the encoding worker VM.
+64 -92
View File
@@ -13,16 +13,11 @@ The flow is:
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
"""
import asyncio
import logging
import mimetypes
import os
import re
import tempfile
from typing import Optional
from .flacfetch_client import get_flacfetch_client, FlacfetchServiceError
from .storage_service import StorageService
logger = logging.getLogger(__name__)
@@ -54,14 +49,13 @@ class YouTubeDownloadService:
def __init__(self):
self._flacfetch_client = get_flacfetch_client()
self._storage_service = StorageService()
if self._flacfetch_client:
logger.info("YouTubeDownloadService using REMOTE flacfetch (recommended)")
logger.info("YouTubeDownloadService using REMOTE flacfetch")
else:
logger.warning(
"YouTubeDownloadService using LOCAL yt_dlp - "
"downloads may fail due to YouTube bot detection on Cloud Run IPs"
"YouTubeDownloadService: remote flacfetch NOT configured "
"(FLACFETCH_API_URL) - URL downloads will fail until it is set"
)
def is_remote_enabled(self) -> bool:
@@ -121,20 +115,24 @@ class YouTubeDownloadService:
Raises:
YouTubeDownloadError: If download fails
"""
video_id = self._extract_video_id(url)
if not video_id:
raise YouTubeDownloadError(f"Could not extract video ID from URL: {url}")
logger.info(f"YouTube download: video_id={video_id}, job_id={job_id}")
if self._flacfetch_client:
return await self._download_remote(video_id, job_id, artist, title)
else:
logger.warning(
"Remote flacfetch not configured. Attempting local download, "
"but this may fail due to YouTube bot detection on Cloud Run IPs."
# flacfetch is the SOLE downloader — never run yt-dlp on Cloud Run.
# If it isn't configured, fail loudly rather than silently falling back
# to a local download (which is blocked by bot detection on Cloud Run
# IPs anyway).
if not self._flacfetch_client:
raise YouTubeDownloadError(
"Remote flacfetch is not configured (FLACFETCH_API_URL). "
"URL downloads require the flacfetch service."
)
return await self._download_local(url, job_id, artist, title)
video_id = self._extract_video_id(url)
if video_id:
logger.info(f"URL download (YouTube): video_id={video_id}, job_id={job_id}")
return await self._download_remote(video_id, job_id, artist, title)
# Any other yt-dlp-supported site (Facebook, SoundCloud, TikTok, ...).
logger.info(f"URL download (generic): url={url}, job_id={job_id}")
return await self._download_remote_url(url, job_id, artist, title)
async def download_by_id(
self,
@@ -265,7 +263,7 @@ class YouTubeDownloadService:
logger.error(f"Remote YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
async def _download_local(
async def _download_remote_url(
self,
url: str,
job_id: str,
@@ -273,92 +271,66 @@ class YouTubeDownloadService:
title: Optional[str] = None,
) -> str:
"""
Download using local yt_dlp (fallback when remote not configured).
Download an arbitrary yt-dlp-supported URL via remote flacfetch.
Warning: This may fail on Cloud Run due to YouTube bot detection.
Used for non-YouTube sites (Facebook, SoundCloud, TikTok, Vimeo, ...).
The URL is handed to flacfetch's generic "URL" source, which downloads
on the VM and uploads to GCS.
"""
temp_dir = tempfile.mkdtemp(prefix=f"youtube_{job_id}_")
gcs_destination = f"uploads/{job_id}/audio/"
output_filename = None
if artist and title:
from karaoke_gen.utils import sanitize_filename
output_filename = f"{sanitize_filename(artist)} - {sanitize_filename(title)}"
logger.info(
f"Remote URL download: url={url}, "
f"gcs_path={gcs_destination}, filename={output_filename}"
)
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
download_id = await self._flacfetch_client.download_by_id(
source_name="URL",
source_id=url,
download_url=url,
output_filename=output_filename,
gcs_path=gcs_destination,
)
# Build output filename
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(
temp_dir, f"{safe_artist} - {safe_title}"
logger.info(f"Remote URL download started: {download_id}")
def log_progress(status):
progress = status.get("progress", 0)
logger.debug(f"Download progress: {progress:.1f}%")
final_status = await self._flacfetch_client.wait_for_download(
download_id,
timeout=300,
progress_callback=log_progress,
)
# Get cookies from environment
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for local download")
# Download
logger.info(f"Local YouTube download: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if not downloaded_file or not os.path.exists(downloaded_file):
gcs_path = final_status.get("gcs_path")
if not gcs_path:
raise YouTubeDownloadError(
f"Local download failed - no file returned. "
"This is likely due to YouTube bot detection on Cloud Run IPs. "
"Configure FLACFETCH_API_URL for remote downloads."
"Remote download completed but no GCS path returned"
)
logger.info(f"Downloaded video: {downloaded_file}")
if gcs_path.startswith("gs://"):
parts = gcs_path.replace("gs://", "").split("/", 1)
if len(parts) == 2:
gcs_path = parts[1]
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if not wav_file or not os.path.exists(wav_file):
raise YouTubeDownloadError("WAV conversion failed")
logger.info(f"Converted to WAV: {wav_file}")
# Upload to GCS
filename = os.path.basename(wav_file)
gcs_path = f"uploads/{job_id}/audio/{filename}"
content_type, _ = mimetypes.guess_type(wav_file)
with open(wav_file, 'rb') as f:
self._storage_service.upload_fileobj(
f,
gcs_path,
content_type=content_type or 'audio/wav'
)
logger.info(f"Uploaded to GCS: {gcs_path}")
logger.info(f"Remote URL download complete: {gcs_path}")
return gcs_path
except FlacfetchServiceError as e:
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
except YouTubeDownloadError:
raise
except Exception as e:
logger.error(f"Local YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Local download failed: {e}") from e
finally:
# Cleanup temp directory
try:
import shutil
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
except Exception as cleanup_error:
logger.warning(f"Failed to cleanup temp dir: {cleanup_error}")
logger.error(f"Remote URL download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
# Singleton instance
+215
View File
@@ -0,0 +1,215 @@
"""Route-level tests for POST /api/jobs/{job_id}/corrections — timing sanitizer integration.
Verifies that out-of-bounds word timings submitted by the frontend are clamped
before corrections_updated.json is written to GCS.
"""
from __future__ import annotations
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, patch, call
from backend.models.job import Job, JobStatus
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def review_job():
"""A job in AWAITING_REVIEW state owned by the test admin user."""
job = Job(
job_id="review-job-001",
status=JobStatus.AWAITING_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
)
return job
@pytest.fixture
def mock_job_manager(review_job):
manager = MagicMock()
manager.get_job.return_value = review_job
manager.update_state_data.return_value = None
manager.update_file_url.return_value = None
manager.transition_to_state.return_value = None
return manager
@pytest.fixture
def mock_worker_service():
return MagicMock()
@pytest.fixture
def mock_theme_service():
svc = MagicMock()
svc.get_default_theme_id.return_value = "nomad"
svc.get_theme.return_value = None
return svc
@pytest.fixture
def client(mock_job_manager, mock_worker_service, mock_theme_service):
"""FastAPI TestClient with mocked dependencies."""
from fastapi.testclient import TestClient
mock_creds = MagicMock()
mock_creds.universe_domain = "googleapis.com"
def _jm_factory(*args, **kwargs):
return mock_job_manager
with patch("backend.api.routes.jobs.job_manager", mock_job_manager), \
patch("backend.api.routes.jobs.worker_service", mock_worker_service), \
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
patch("backend.services.job_manager.JobManager", _jm_factory), \
patch("backend.services.firestore_service.firestore"), \
patch("backend.services.storage_service.storage"), \
patch("google.auth.default", return_value=(mock_creds, "test-project")):
from backend.main import app
yield TestClient(app)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _bad_corrections():
"""Corrections payload whose words fall outside segment bounds (start=0, end<0).
Must include the 'lines' and 'metadata' keys required by CorrectionsSubmission
validation before the sanitizer runs.
"""
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": [
{
"id": "s1",
"text": "A whiskey and a beer,",
"start_time": 15.18,
"end_time": 18.04,
"words": [
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
],
}
]
}
def _good_corrections():
"""Corrections payload whose word timings are already valid."""
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": [
{
"id": "s1",
"text": "Filling up",
"start_time": 21.4,
"end_time": 22.1,
"words": [
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
],
}
]
}
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestSubmitCorrectionsTimingSanitizer:
"""Verify that submit_corrections clamps out-of-bounds word timings before GCS upload."""
def test_sanitized_timings_uploaded_to_gcs(self, client, auth_headers):
"""Words with start_time/end_time outside segment bounds must be clamped
before corrections_updated.json is written to GCS.
Patch StorageService at the class level in its source module so the local
import inside submit_corrections picks up the mock.
"""
uploaded_payload = {}
with patch("backend.services.storage_service.StorageService") as MockStorage:
storage_instance = MockStorage.return_value
# Capture what gets passed to upload_json
def capture_upload(path, data):
uploaded_payload.update(data)
storage_instance.upload_json.side_effect = capture_upload
response = client.post(
"/api/jobs/review-job-001/corrections",
json={"corrections": _bad_corrections()},
headers=auth_headers,
)
assert response.status_code == 200, response.text
assert uploaded_payload, "upload_json was never called — capture failed"
# All uploaded word timings must be within their segment bounds
words = uploaded_payload["corrected_segments"][0]["words"]
seg_start = 15.18
seg_end = 18.04
for w in words:
assert w["start_time"] >= seg_start, f"word start_time {w['start_time']} < seg start {seg_start}"
assert w["end_time"] >= w["start_time"], f"word end_time {w['end_time']} < start_time {w['start_time']}"
assert w["end_time"] <= seg_end + 1e-9, f"word end_time {w['end_time']} > seg end {seg_end}"
def test_valid_timings_uploaded_unchanged(self, client, auth_headers):
"""Word timings already within bounds must not be modified."""
uploaded_payload = {}
with patch("backend.services.storage_service.StorageService") as MockStorage:
storage_instance = MockStorage.return_value
def capture_upload(path, data):
uploaded_payload.update(data)
storage_instance.upload_json.side_effect = capture_upload
response = client.post(
"/api/jobs/review-job-001/corrections",
json={"corrections": _good_corrections()},
headers=auth_headers,
)
assert response.status_code == 200, response.text
assert uploaded_payload, "upload_json was never called — capture failed"
words = uploaded_payload["corrected_segments"][0]["words"]
assert words[0]["start_time"] == 21.4
assert words[0]["end_time"] == 21.82
assert words[1]["start_time"] == 21.86
assert words[1]["end_time"] == 22.1
class TestSubmitCorrectionsContract:
"""Minimal contract test — does not require the full FastAPI test harness."""
def test_sanitize_contract_bad_timings(self):
"""sanitize_corrections clamps words with start/end outside segment bounds."""
from backend.services.timing_sanitizer import sanitize_corrections
bad = {
"corrected_segments": [
{
"id": "s", "start_time": 15.18, "end_time": 18.04, "text": "A",
"words": [{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005}],
}
]
}
cleaned, count = sanitize_corrections(bad)
assert count >= 1
w = cleaned["corrected_segments"][0]["words"][0]
assert w["start_time"] >= 15.18
assert w["end_time"] >= w["start_time"]
@@ -0,0 +1,139 @@
"""Route tests for POST /api/review/{job_id}/auto-correct."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.services.auto_correct.service import (
AutoCorrectResult,
AutoCorrectServiceError,
Suggestion,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def bypass_auth(monkeypatch):
"""Bypass require_review_auth for these tests."""
from backend.api.dependencies import require_review_auth as real_dep
async def fake_dep():
return ("test-job", "full")
app.dependency_overrides[real_dep] = fake_dep
yield
app.dependency_overrides.pop(real_dep, None)
def _override_service(result_or_exc):
from backend.api.routes.review import _get_auto_correct_service_dep
mock_service = MagicMock()
if isinstance(result_or_exc, Exception):
mock_service.suggest.side_effect = result_or_exc
else:
mock_service.suggest.return_value = result_or_exc
app.dependency_overrides[_get_auto_correct_service_dep] = lambda: mock_service
return mock_service
def teardown_function(_): # noqa: ANN001
from backend.api.routes.review import _get_auto_correct_service_dep
app.dependency_overrides.pop(_get_auto_correct_service_dep, None)
def _make_result(suggestions=None) -> AutoCorrectResult:
return AutoCorrectResult(
suggestions=suggestions
if suggestions is not None
else [
Suggestion(
id="sug-1",
op="replace",
word_ids=["w3"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="matches reference",
category="mishearing",
confidence=0.95,
)
],
model="gemini-test",
elapsed_seconds=12.3,
settings_applied=AutoCorrectSettings(),
warnings=["dropped suggestion 3: out of range"],
)
BODY = {
"segments": [{"id": "seg-1", "words": [{"id": "w3", "text": "glory"}]}],
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
"artist": "Twenty One Pilots",
"title": "Chlorine",
}
def test_happy_path(client: TestClient) -> None:
mock = _override_service(_make_result())
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 200
data = resp.json()
assert data["model"] == "gemini-test"
assert len(data["suggestions"]) == 1
s = data["suggestions"][0]
assert s["op"] == "replace"
assert s["word_ids"] == ["w3"]
assert s["new_text"] == "chlorine"
assert data["warnings"] == ["dropped suggestion 3: out of range"]
assert data["settings_applied"]["suggest_adlib_removal"] is True
mock.suggest.assert_called_once()
def test_settings_passed_through(client: TestClient) -> None:
mock = _override_service(_make_result([]))
resp = client.post(
"/api/review/test-job/auto-correct",
json={**BODY, "settings": {"suggest_adlib_removal": False, "min_confidence": 0.8}},
)
assert resp.status_code == 200
settings = mock.suggest.call_args.kwargs["settings"]
assert settings.suggest_adlib_removal is False
assert settings.min_confidence == 0.8
def test_invalid_settings_400(client: TestClient) -> None:
_override_service(_make_result([]))
resp = client.post(
"/api/review/test-job/auto-correct",
json={**BODY, "settings": {"bogus_knob": True}},
)
assert resp.status_code == 400
assert "invalid settings" in resp.json()["detail"]
def test_no_references_422_propagates(client: TestClient) -> None:
_override_service(AutoCorrectServiceError("no reference lyrics", status_code=422))
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 422
def test_model_failure_502_propagates(client: TestClient) -> None:
_override_service(AutoCorrectServiceError("AI model call failed", status_code=502))
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 502
def test_missing_body_fields_422(client: TestClient) -> None:
_override_service(_make_result([]))
resp = client.post("/api/review/test-job/auto-correct", json={"segments": []})
assert resp.status_code == 422 # reference_lyrics is required
+21 -22
View File
@@ -241,10 +241,10 @@ class TestYouTubeDownloadErrorHandling:
assert "Remote download failed" in str(exc.value)
@pytest.mark.asyncio
async def test_invalid_youtube_url_raises_clear_error(self):
async def test_download_without_flacfetch_raises_clear_error(self):
"""
When given an invalid YouTube URL (no video ID extractable),
should raise a clear error.
With no flacfetch configured, download must fail clearly (no local
yt-dlp fallback on Cloud Run).
"""
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -261,11 +261,11 @@ class TestYouTubeDownloadErrorHandling:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="not-a-valid-youtube-url",
url="https://youtu.be/abcDEF12345",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
class TestRemoteVsLocalDownload:
@@ -306,13 +306,20 @@ class TestRemoteVsLocalDownload:
assert "uploads/job_test/audio/" in result
@pytest.mark.asyncio
async def test_local_download_when_remote_not_configured(self):
async def test_non_youtube_url_uses_generic_url_source(self):
"""
When FLACFETCH_API_URL is not configured, should fall back to local.
A non-YouTube URL is routed through flacfetch's generic 'URL' source.
"""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_test/audio/test.m4a",
})
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
return_value=mock_client
):
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -321,18 +328,10 @@ class TestRemoteVsLocalDownload:
reset_youtube_download_service()
service = YouTubeDownloadService()
assert service.is_remote_enabled() is False
sc_url = "https://soundcloud.com/forss/flickermood"
result = await service.download(url=sc_url, job_id="job_test")
# Mock the local download to avoid actually calling yt_dlp
with patch.object(
service, '_download_local',
new_callable=AsyncMock,
return_value="uploads/job/audio/test.wav"
) as mock_local:
result = await service.download(
url="https://youtu.be/abcDEF12345",
job_id="job_test",
)
mock_local.assert_called_once()
assert result == "uploads/job/audio/test.wav"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == sc_url
assert "uploads/job_test/audio/" in result
Whitespace-only changes.
@@ -0,0 +1,203 @@
"""Tests for the per-job auto-correct suggestion cache."""
from __future__ import annotations
from unittest.mock import patch
from backend.services.auto_correct.service import (
AutoCorrectResult,
AutoCorrectService,
Suggestion,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
SEGMENTS = [
{
"id": "seg-1",
"words": [
{"id": "w0", "text": "straight"},
{"id": "w1", "text": "glory"},
],
},
]
REFS = {"genius": {"segments": [{"text": "straight chlorine"}]}}
RAW = {
"suggestions": [
{
"op": "replace",
"start_idx": 1,
"end_idx": 1,
"new_text": "chlorine",
"reason": "r",
"category": "mishearing",
"confidence": 0.9,
}
]
}
FLAT = [("w0", "straight", "seg-1"), ("w1", "glory", "seg-1")]
def _suggest(service, **overrides):
kwargs = dict(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
kwargs.update(overrides)
return service.suggest(**kwargs)
def test_cache_hit_skips_model_call() -> None:
service = AutoCorrectService()
cached_result = AutoCorrectResult(
suggestions=[
Suggestion(
id="cached-1",
op="replace",
word_ids=["w1"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="r",
category="mishearing",
confidence=0.9,
)
],
model="claude-fable-5",
elapsed_seconds=0.0,
settings_applied=AutoCorrectSettings(),
cached=True,
)
with patch.object(service, "_cache_get", return_value=cached_result), \
patch.object(service, "_call_model") as call, \
patch.object(service, "_cache_put") as put:
result = _suggest(service)
call.assert_not_called()
put.assert_not_called()
assert result.cached is True
assert result.suggestions[0].id == "cached-1"
def test_cache_miss_calls_model_and_writes_cache() -> None:
service = AutoCorrectService()
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_call_model", return_value=(RAW, None)) as call, \
patch.object(service, "_cache_put") as put:
result = _suggest(service)
call.assert_called_once()
put.assert_called_once()
assert result.cached is False
assert put.call_args.args[1] is result
def test_cache_key_stable_for_identical_input() -> None:
s = AutoCorrectSettings()
k1 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
k2 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
assert k1 == k2
assert k1.startswith("jobs/j/lyrics/auto_correct_cache/")
def test_cache_key_changes_with_input() -> None:
s = AutoCorrectSettings()
base = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
edited_words = [("w0", "straight", "seg-1"), ("w1", "chlorine", "seg-1")]
assert AutoCorrectService._cache_path("j", ["m"], s, edited_words, REFS, "A", "T") != base
assert AutoCorrectService._cache_path("j", ["m", "m2"], s, FLAT, REFS, "A", "T") != base
other_settings = AutoCorrectSettings(min_confidence=0.8)
assert AutoCorrectService._cache_path("j", ["m"], other_settings, FLAT, REFS, "A", "T") != base
other_refs = {"genius": {"segments": [{"text": "different text"}]}}
assert AutoCorrectService._cache_path("j", ["m"], s, FLAT, other_refs, "A", "T") != base
def test_cache_get_round_trips_via_storage_payload() -> None:
"""_cache_put's payload must be readable by _cache_get."""
service = AutoCorrectService()
stored = {}
class FakeBlob:
def exists(self):
return bool(stored)
class FakeStorage:
class bucket: # noqa: N801 - mimic attribute access
@staticmethod
def blob(path):
return FakeBlob()
@staticmethod
def upload_json(path, data):
stored[path] = data
@staticmethod
def download_json(path):
return stored[path]
with patch.object(service, "_get_storage", return_value=FakeStorage()):
original = AutoCorrectResult(
suggestions=[
Suggestion(
id="s1",
op="replace",
word_ids=["w1"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="r",
category="mishearing",
confidence=0.9,
models=["m1", "m2"],
consensus=2,
total_models=2,
conflict_group=None,
)
],
model="m1, m2",
elapsed_seconds=5.0,
settings_applied=AutoCorrectSettings(compare_models=True),
warnings=["w"],
)
service._cache_put("p", original)
restored = service._cache_get("p")
assert restored is not None
assert restored.cached is True
assert restored.model == "m1, m2"
assert restored.warnings == ["w"]
assert restored.settings_applied == AutoCorrectSettings(compare_models=True)
s = restored.suggestions[0]
assert s.consensus == 2 and s.models == ["m1", "m2"]
def test_corrupt_cache_entry_is_a_miss() -> None:
service = AutoCorrectService()
class FakeBlob:
def exists(self):
return True
class FakeStorage:
class bucket: # noqa: N801
@staticmethod
def blob(path):
return FakeBlob()
@staticmethod
def download_json(path):
return {"suggestions": [{"bogus": True}], "model": "m"}
with patch.object(service, "_get_storage", return_value=FakeStorage()):
assert service._cache_get("p") is None
def test_storage_failure_never_breaks_request() -> None:
service = AutoCorrectService()
with patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
patch.object(service, "_call_model", return_value=(RAW, None)):
result = _suggest(service)
assert result.cached is False
assert len(result.suggestions) == 1
@@ -0,0 +1,172 @@
"""Tests for multi-model compare: parallel calls, dedup, consensus, conflicts."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
SEGMENTS = [
{
"id": "seg-1",
"words": [
{"id": "w0", "text": "Sippin'"},
{"id": "w1", "text": "on"},
{"id": "w2", "text": "straight"},
{"id": "w3", "text": "glory"},
{"id": "w4", "text": "today"},
],
},
]
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
COMPARE = AutoCorrectSettings(compare_models=True)
def _sugg(start, end, text, op="replace", confidence=0.9):
return {
"op": op,
"start_idx": start,
"end_idx": end,
"new_text": text,
"reason": "r",
"category": "mishearing",
"confidence": confidence,
}
def _run_compare(responses_by_model, compare_models_env="model-a;model-b",
settings=COMPARE, single_model="gemini-3.1-pro-preview"):
"""responses_by_model: model name -> raw dict response or Exception."""
service = AutoCorrectService()
def fake_call(model, system_prompt, user_prompt, *, job_id):
resp = responses_by_model[model]
if isinstance(resp, Exception):
raise resp
# _call_model now returns (parsed_json, token_usage).
return resp, None
with patch.object(
service.settings, "auto_correct_compare_models", compare_models_env
), patch.object(
service.settings, "auto_correct_model", single_model
), patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", side_effect=fake_call):
return service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=settings,
)
def test_identical_suggestions_deduped_with_consensus() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.9)]},
"model-b": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.95)]},
})
assert len(result.suggestions) == 1
s = result.suggestions[0]
assert sorted(s.models) == ["model-a", "model-b"]
assert s.consensus == 2
assert s.total_models == 2
assert s.confidence == 0.95 # max across models
assert s.conflict_group is None
assert result.model == "model-a, model-b"
def test_conflicting_suggestions_share_group() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"suggestions": [_sugg(2, 3, "straight chlorine gas")]},
})
assert len(result.suggestions) == 2
groups = {s.conflict_group for s in result.suggestions}
assert len(groups) == 1 and None not in groups
assert all(s.consensus == 1 and s.total_models == 2 for s in result.suggestions)
def test_non_overlapping_suggestions_have_no_group() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"suggestions": [_sugg(0, 0, "Sipping")]},
})
assert all(s.conflict_group is None for s in result.suggestions)
# sorted by document position
assert [s.word_ids[0] for s in result.suggestions] == ["w0", "w3"]
def test_insert_after_does_not_conflict_with_replace_on_anchor() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"suggestions": [_sugg(3, 3, "up", op="insert_after")]},
})
assert all(s.conflict_group is None for s in result.suggestions)
def test_one_model_failing_produces_warning_not_error() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": AutoCorrectServiceError("AI model call failed", status_code=502),
})
assert len(result.suggestions) == 1
assert result.suggestions[0].total_models == 1 # only one model answered
assert any("model-b failed" in w for w in result.warnings)
assert result.model == "model-a"
def test_malformed_model_output_warns_instead_of_aborting_compare() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"not_suggestions": []}, # malformed -> _validate raises
})
assert len(result.suggestions) == 1
assert any("model-b failed" in w for w in result.warnings)
assert result.model == "model-a"
def test_all_models_failing_raises_502() -> None:
with pytest.raises(AutoCorrectServiceError) as exc_info:
_run_compare({
"model-a": AutoCorrectServiceError("boom", status_code=502),
"model-b": AutoCorrectServiceError("boom", status_code=502),
})
assert exc_info.value.status_code == 502
def test_compare_falls_back_to_single_when_unconfigured() -> None:
result = _run_compare(
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
compare_models_env="",
)
s = result.suggestions[0]
assert s.total_models == 1
assert s.consensus == 1
def test_single_model_mode_unchanged() -> None:
result = _run_compare(
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
settings=AutoCorrectSettings(), # compare off
)
assert len(result.suggestions) == 1
assert result.suggestions[0].models == ["gemini-3.1-pro-preview"]
def test_three_way_conflict_chain_unifies_groups() -> None:
# a: w2-w3, b: w3-w4, c: w4 — chained overlaps must land in ONE group
result = _run_compare({
"model-a": {"suggestions": [_sugg(2, 3, "x y")]},
"model-b": {"suggestions": [_sugg(3, 4, "y z"), _sugg(4, 4, "z")]},
})
groups = {s.conflict_group for s in result.suggestions}
assert len(groups) == 1 and None not in groups
@@ -0,0 +1,173 @@
"""Tests for auto-correct token pricing and usage extraction/logging."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
from backend.services.auto_correct.pricing import (
MODEL_PRICING,
estimate_cost_usd,
get_rate,
)
from backend.services.auto_correct.service import AutoCorrectService
from backend.services.auto_correct.settings import AutoCorrectSettings
# ---- pricing ----
def test_estimate_cost_fable_known_rates() -> None:
# 5000 in @ $10/M + 4000 out @ $50/M = 0.05 + 0.20 = 0.25
usage = {
"input_tokens": 5000,
"output_tokens": 4000,
"cache_read_tokens": 0,
"thinking_tokens": None,
}
cost = estimate_cost_usd("claude-fable-5", usage)
assert cost == round(0.05 + 0.20, 10)
def test_estimate_cost_includes_cache_read() -> None:
usage = {
"input_tokens": 1_000_000,
"output_tokens": 0,
"cache_read_tokens": 1_000_000,
"thinking_tokens": None,
}
# 1M input @ $10 + 1M cache_read @ $1 = 11.0
assert estimate_cost_usd("claude-fable-5", usage) == 11.0
def test_estimate_cost_none_usage_returns_none() -> None:
assert estimate_cost_usd("claude-fable-5", None) is None
def test_estimate_cost_unknown_model_returns_none() -> None:
usage = {
"input_tokens": 1000,
"output_tokens": 1000,
"cache_read_tokens": 0,
"thinking_tokens": None,
}
assert estimate_cost_usd("some-unknown-model-9", usage) is None
def test_get_rate_prefix_match_for_dated_snapshot() -> None:
# A dated snapshot id still resolves to its family rate card.
assert get_rate("claude-fable-5-20260601") == MODEL_PRICING["claude-fable-5"]
# ---- usage extraction ----
def test_anthropic_usage_extraction() -> None:
response = SimpleNamespace(
usage=SimpleNamespace(
input_tokens=4321,
output_tokens=3210,
cache_read_input_tokens=100,
)
)
usage = AutoCorrectService._anthropic_usage(response)
assert usage == {
"input_tokens": 4321,
"output_tokens": 3210, # already includes thinking
"cache_read_tokens": 100,
"thinking_tokens": None,
}
def test_gemini_usage_folds_thoughts_into_output() -> None:
response = SimpleNamespace(
usage_metadata=SimpleNamespace(
prompt_token_count=4000,
candidates_token_count=500,
thoughts_token_count=2500,
cached_content_token_count=0,
)
)
usage = AutoCorrectService._gemini_usage(response)
assert usage == {
"input_tokens": 4000,
"output_tokens": 3000, # 500 visible + 2500 thinking
"cache_read_tokens": 0,
"thinking_tokens": 2500,
}
def test_usage_extraction_never_raises_on_bad_shape() -> None:
# Missing usage attribute entirely -> None, not an exception.
assert AutoCorrectService._anthropic_usage(SimpleNamespace()) is None
assert AutoCorrectService._gemini_usage(SimpleNamespace()) is None
# ---- logging ----
SEGMENTS = [
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
]
REFS = {"genius": {"segments": [{"text": "chlorine"}]}}
def _raw():
return {
"suggestions": [
{
"op": "replace",
"start_idx": 0,
"end_idx": 0,
"new_text": "chlorine",
"reason": "r",
"category": "mishearing",
"confidence": 0.9,
}
]
}
def test_suggest_logs_per_model_and_total_cost(caplog) -> None:
service = AutoCorrectService()
usage = {
"input_tokens": 5000,
"output_tokens": 4000,
"cache_read_tokens": 0,
"thinking_tokens": None,
}
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", return_value=(_raw(), usage)), \
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
with caplog.at_level("INFO"):
service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
text = caplog.text
assert "auto-correct usage job=job-1 model=claude-fable-5" in text
assert "input_tokens=5000" in text
assert "output_tokens=4000" in text
assert "est_cost_usd=0.2500" in text
assert "auto-correct cost job=job-1" in text
assert "total_est_cost_usd=0.2500" in text
def test_suggest_logs_unavailable_usage_without_crashing(caplog) -> None:
service = AutoCorrectService()
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", return_value=(_raw(), None)), \
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
with caplog.at_level("INFO"):
service.suggest(
job_id="job-2",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
assert "auto-correct usage job=job-2 model=claude-fable-5 tokens=unavailable" in caplog.text
assert "total_est_cost_usd=unknown" in caplog.text
@@ -0,0 +1,56 @@
"""Tests for auto-correct prompt construction."""
from __future__ import annotations
from backend.services.auto_correct.prompts import (
build_system_prompt,
build_user_prompt,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
def test_system_prompt_default_allows_adlib_suggestions() -> None:
p = build_system_prompt(AutoCorrectSettings())
assert "adlib_removal" in p
assert "NEVER suggest deleting backing vocals" not in p
assert "insert_after" in p
def test_system_prompt_adlib_disabled() -> None:
p = build_system_prompt(AutoCorrectSettings(suggest_adlib_removal=False))
assert "NEVER suggest deleting backing vocals" in p
def test_system_prompt_insertions_disabled() -> None:
p = build_system_prompt(AutoCorrectSettings(allow_insertions=False))
assert 'NEVER use the "insert_after" operation' in p
def test_user_prompt_word_indices_are_global_and_sequential() -> None:
segments = [
{"id": "s1", "words": [{"id": "a", "text": "Hello"}, {"id": "b", "text": "there"}]},
{"id": "s2", "words": [{"id": "c", "text": "world"}]},
]
refs = {
"genius": {"segments": [{"text": "Hello there"}, {"text": "world"}]},
"lrclib": {"segments": [{"text": "Hello their world"}]},
}
p = build_user_prompt(
segments=segments, reference_lyrics=refs, artist="Artist", title="Title"
)
assert "ARTIST: Artist" in p
assert "[L000] 0:Hello 1:there" in p
assert "[L001] 2:world" in p
assert "REFERENCE LYRICS (genius):" in p
assert "REFERENCE LYRICS (lrclib):" in p
assert "Hello their world" in p
def test_user_prompt_handles_missing_metadata() -> None:
p = build_user_prompt(
segments=[{"id": "s1", "words": []}],
reference_lyrics={},
artist=None,
title=None,
)
assert "ARTIST: unknown" in p
assert "TITLE: unknown" in p
@@ -0,0 +1,281 @@
"""Tests for AutoCorrectService validation and suggestion mapping."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
SEGMENTS = [
{
"id": "seg-1",
"words": [
{"id": "w0", "text": "Sippin'"},
{"id": "w1", "text": "on"},
{"id": "w2", "text": "straight"},
{"id": "w3", "text": "glory"},
],
},
{
"id": "seg-2",
"words": [
{"id": "w4", "text": "yeah"},
{"id": "w5", "text": "yeah"},
],
},
]
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
def _suggest(raw_response, settings=None):
service = AutoCorrectService()
with patch.object(service, "_call_model", return_value=(raw_response, None)), \
patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"):
return service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=settings or AutoCorrectSettings(),
)
def _raw(op="replace", start=3, end=3, text="chlorine", category="mishearing",
confidence=0.95):
return {
"suggestions": [
{
"op": op,
"start_idx": start,
"end_idx": end,
"new_text": text,
"reason": "matches reference",
"category": category,
"confidence": confidence,
}
]
}
def test_replace_maps_indices_to_word_ids() -> None:
result = _suggest(_raw())
assert len(result.suggestions) == 1
s = result.suggestions[0]
assert s.op == "replace"
assert s.word_ids == ["w3"]
assert s.segment_ids == ["seg-1"]
assert s.original_text == "glory"
assert s.new_text == "chlorine"
assert result.warnings == []
def test_multi_word_span_crossing_segments() -> None:
result = _suggest(_raw(start=3, end=4, text="chlorine yeah"))
s = result.suggestions[0]
assert s.word_ids == ["w3", "w4"]
assert sorted(s.segment_ids) == ["seg-1", "seg-2"]
assert s.original_text == "glory yeah"
def test_delete_suggestion() -> None:
result = _suggest(_raw(op="delete", start=4, end=5, text=""))
s = result.suggestions[0]
assert s.op == "delete"
assert s.new_text == ""
assert s.word_ids == ["w4", "w5"]
def test_insert_after_uses_anchor_word() -> None:
result = _suggest(_raw(op="insert_after", start=2, end=2, text="up"))
s = result.suggestions[0]
assert s.op == "insert_after"
assert s.word_ids == ["w2"]
def test_out_of_range_indices_dropped_with_warning() -> None:
result = _suggest(_raw(start=99, end=99))
assert result.suggestions == []
assert len(result.warnings) == 1
assert "out of range" in result.warnings[0]
def test_replace_with_empty_text_dropped() -> None:
result = _suggest(_raw(text=" "))
assert result.suggestions == []
assert "empty new_text" in result.warnings[0]
def test_below_min_confidence_dropped() -> None:
result = _suggest(
_raw(confidence=0.4), settings=AutoCorrectSettings(min_confidence=0.6)
)
assert result.suggestions == []
assert "below threshold" in result.warnings[0]
def test_adlib_removal_dropped_when_disabled() -> None:
result = _suggest(
_raw(op="delete", start=4, end=5, text="", category="adlib_removal"),
settings=AutoCorrectSettings(suggest_adlib_removal=False),
)
assert result.suggestions == []
assert "adlib removal disabled" in result.warnings[0]
def test_insertions_dropped_when_disabled() -> None:
result = _suggest(
_raw(op="insert_after", start=2, end=2, text="up"),
settings=AutoCorrectSettings(allow_insertions=False),
)
assert result.suggestions == []
assert "insertions disabled" in result.warnings[0]
def test_unknown_category_coerced_to_other() -> None:
result = _suggest(_raw(category="weird"))
assert result.suggestions[0].category == "other"
def test_confidence_clamped() -> None:
result = _suggest(_raw(confidence=1.7))
assert result.suggestions[0].confidence == 1.0
def test_no_reference_lyrics_raises_422() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError) as exc_info:
service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics={},
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
assert exc_info.value.status_code == 422
def test_empty_segments_raises_400() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError) as exc_info:
service.suggest(
job_id="job-1",
segments=[],
reference_lyrics=REFS,
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
assert exc_info.value.status_code == 400
def test_missing_segment_ids_raises() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError, match="segments must have ids"):
service.suggest(
job_id="job-1",
segments=[{"words": [{"id": "w0", "text": "hi"}]}],
reference_lyrics=REFS,
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
def test_missing_word_ids_raises() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError, match="ids"):
service.suggest(
job_id="job-1",
segments=[{"id": "s", "words": [{"text": "no-id"}]}],
reference_lyrics=REFS,
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
def test_malformed_model_response_raises_502() -> None:
with pytest.raises(AutoCorrectServiceError) as exc_info:
_suggest({"not_suggestions": []})
assert exc_info.value.status_code == 502
def test_non_dict_suggestion_entries_dropped() -> None:
result = _suggest({"suggestions": ["bogus", 42]})
assert result.suggestions == []
assert len(result.warnings) == 2
def test_call_model_dispatches_claude_to_anthropic() -> None:
service = AutoCorrectService()
with patch.object(service, "_call_anthropic", return_value=({"suggestions": []}, None)) as anth, \
patch.object(service, "_call_gemini", return_value=({"suggestions": []}, None)) as gem:
service._call_model("claude-fable-5", "s", "u", job_id="j")
anth.assert_called_once()
gem.assert_not_called()
service._call_model("gemini-3.1-pro-preview", "s", "u", job_id="j")
gem.assert_called_once()
def test_anthropic_schema_strips_genai_pollution(monkeypatch) -> None:
"""google-genai mutates schema dicts in place (adds property_ordering);
the anthropic path must send a clean strict schema regardless."""
from unittest.mock import MagicMock
import backend.services.auto_correct.service as svc_mod
import copy
monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
# Deep copy so this test never mutates the real module-level schema.
polluted = copy.deepcopy(svc_mod.RESPONSE_SCHEMA)
polluted["property_ordering"] = ["suggestions"]
polluted["properties"]["suggestions"]["items"]["property_ordering"] = ["op"]
monkeypatch.setattr(svc_mod, "RESPONSE_SCHEMA", polluted)
captured = {}
class FakeClient:
def __init__(self, **kwargs):
self.messages = MagicMock()
def create(**ckwargs):
captured.update(ckwargs)
block = MagicMock()
block.type = "text"
block.text = '{"suggestions": []}'
resp = MagicMock()
resp.content = [block]
return resp
self.messages.create = create
import anthropic as anthropic_sdk
monkeypatch.setattr(anthropic_sdk, "Anthropic", FakeClient)
service = AutoCorrectService()
raw, _usage = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
assert raw == {"suggestions": []}
schema = captured["output_config"]["format"]["schema"]
assert "property_ordering" not in schema
assert "property_ordering" not in schema["properties"]["suggestions"]["items"]
assert schema["additionalProperties"] is False
# and the polluted module constant was not further mutated
assert "property_ordering" in polluted
def test_anthropic_without_api_key_raises_502(monkeypatch) -> None:
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError) as exc_info:
service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
assert exc_info.value.status_code == 502
assert "not configured" in str(exc_info.value)
@@ -0,0 +1,61 @@
"""Tests for AutoCorrectSettings parsing/validation."""
from __future__ import annotations
import pytest
from backend.services.auto_correct.settings import (
AutoCorrectSettings,
settings_from_dict,
)
def test_default_settings() -> None:
s = AutoCorrectSettings()
assert s.suggest_adlib_removal is True
assert s.allow_insertions is True
assert s.min_confidence == 0.0
def test_settings_from_dict_defaults_when_empty() -> None:
assert settings_from_dict({}) == AutoCorrectSettings()
def test_settings_from_dict_partial() -> None:
s = settings_from_dict({"suggest_adlib_removal": False})
assert s.suggest_adlib_removal is False
assert s.allow_insertions is True
def test_settings_from_dict_full() -> None:
s = settings_from_dict(
{
"suggest_adlib_removal": False,
"allow_insertions": False,
"min_confidence": 0.75,
}
)
assert s == AutoCorrectSettings(
suggest_adlib_removal=False, allow_insertions=False, min_confidence=0.75
)
def test_settings_from_dict_unknown_key_raises() -> None:
with pytest.raises(ValueError, match="unknown settings"):
settings_from_dict({"bogus": 1})
@pytest.mark.parametrize("value", [-0.1, 1.5, "high", None, True, False])
def test_settings_from_dict_invalid_confidence_raises(value) -> None:
with pytest.raises(ValueError, match="min_confidence"):
settings_from_dict({"min_confidence": value})
@pytest.mark.parametrize("key", ["suggest_adlib_removal", "allow_insertions"])
def test_settings_from_dict_non_bool_flag_raises(key) -> None:
with pytest.raises(ValueError, match=key):
settings_from_dict({key: "yes"})
def test_to_dict_round_trip() -> None:
s = AutoCorrectSettings(suggest_adlib_removal=False, min_confidence=0.5)
assert settings_from_dict(s.to_dict()) == s
@@ -0,0 +1,102 @@
"""Tests for backend.services.timing_sanitizer."""
import pytest
from backend.services.timing_sanitizer import sanitize_corrections
def _sample_corrections():
return {
"corrected_segments": [
{
"id": "s1",
"text": "A whiskey and a beer,",
"start_time": 15.18,
"end_time": 18.04,
"words": [
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
],
}
]
}
def test_clamps_out_of_bounds_words():
cleaned, count = sanitize_corrections(_sample_corrections())
words = cleaned["corrected_segments"][0]["words"]
for w in words:
assert w["start_time"] >= 15.18
assert w["end_time"] >= w["start_time"]
assert w["end_time"] <= 18.04 + 1e-9
assert count >= 4
def test_valid_corrections_unchanged():
payload = {
"corrected_segments": [
{
"id": "s", "text": "Filling up", "start_time": 21.4, "end_time": 22.1,
"words": [
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
],
}
]
}
cleaned, count = sanitize_corrections(payload)
assert count == 0
assert cleaned == payload
def test_missing_segments_key_is_noop():
cleaned, count = sanitize_corrections({"foo": "bar"})
assert count == 0
assert cleaned == {"foo": "bar"}
def test_non_finite_segment_bounds_left_untouched():
payload = {"corrected_segments": [
{"id": "s", "start_time": None, "end_time": None, "text": "x",
"words": [{"id": "w", "text": "x", "start_time": 3, "end_time": 5}]}
]}
cleaned, count = sanitize_corrections(payload)
assert count == 0
assert cleaned["corrected_segments"][0]["words"][0]["start_time"] == 3
def test_start_past_segment_end_uses_prev_end():
"""A word whose start_time is far outside [seg_start, seg_end] must be repaired
to prev_end (clamped into the segment window), not silently collapsed to seg_end."""
payload = {"corrected_segments": [{
"id": "s", "start_time": 10.0, "end_time": 12.0, "text": "hello world",
"words": [
{"id": "w0", "text": "hello", "start_time": 10.0, "end_time": 11.0},
{"id": "w1", "text": "world", "start_time": 99.0, "end_time": 100.0},
],
}]}
cleaned, count = sanitize_corrections(payload)
assert count >= 2 # both start and end of w1 were repaired
w = cleaned["corrected_segments"][0]["words"][1]
# start must fall inside the segment window
assert 10.0 <= w["start_time"] <= 12.0
# end must be >= start and within the segment
assert w["end_time"] >= w["start_time"]
assert w["end_time"] <= 12.0
# start should be prev_end (11.0), not collapsed to seg_end (12.0)
assert w["start_time"] == 11.0
@pytest.mark.parametrize("bad_value", [True, False, float("inf"), float("-inf"), float("nan"), None])
def test_non_finite_word_timing_is_clamped(bad_value):
payload = {"corrected_segments": [{
"id": "s", "start_time": 10.0, "end_time": 12.0, "text": "x",
"words": [{"id": "w", "text": "x", "start_time": bad_value, "end_time": bad_value}]
}]}
cleaned, count = sanitize_corrections(payload)
assert count >= 1
w = cleaned["corrected_segments"][0]["words"][0]
assert 10.0 <= w["start_time"] <= 12.0
assert w["end_time"] >= w["start_time"]
+18
View File
@@ -314,6 +314,24 @@ class TestApplyAudioEdit:
assert resp.status_code == 400
assert "Invalid operation" in resp.json()["detail"]
@pytest.mark.parametrize("operation", ["fade_in", "fade_out"])
def test_apply_fade_operations_accepted(self, operation, test_client, mock_job_manager, mock_services, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-1/audio_edit/edit_fade.flac",
)
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": operation,
"params": {"start_seconds": 0.0, "end_seconds": 3.0},
})
assert resp.status_code == 200
called_op = mock_services["edit"].apply_edit.call_args.kwargs["operation"]
assert called_op == operation
def test_apply_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="wrong-status", status=JobStatus.COMPLETE,
input_media_gcs_path="jobs/x/input/song.flac", state_data={})
+133
View File
@@ -152,6 +152,84 @@ class TestFFmpegOperations:
assert "volume=enable='between(t,10.0,15.0)':volume=0" in af_str
assert result.duration_seconds == 245.0 # Duration preserved
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_fade_in(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
result = service.fade_region("/tmp/input.flac", 0.0, 3.0, "in", "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-af" in cmd
af_str = cmd[cmd.index("-af") + 1]
assert "afade=t=in:st=0.0:d=3.0" in af_str
assert result.duration_seconds == 245.0 # Duration preserved
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_fade_out(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
result = service.fade_region("/tmp/input.flac", 240.0, 245.0, "out", "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-af" in cmd
af_str = cmd[cmd.index("-af") + 1]
assert "afade=t=out:st=240.0:d=5.0" in af_str
assert result.duration_seconds == 245.0 # Duration preserved
def test_fade_region_rejects_invalid_direction(self):
service = AudioEditService(storage_service=Mock())
with pytest.raises(ValueError, match="Invalid fade direction"):
service.fade_region("/tmp/input.flac", 0.0, 3.0, "sideways", "/tmp/output.flac")
def test_fade_region_rejects_inverted_region(self):
service = AudioEditService(storage_service=Mock())
with pytest.raises(ValueError, match="Invalid fade region"):
service.fade_region("/tmp/input.flac", 3.0, 3.0, "in", "/tmp/output.flac")
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
def test_fade_in_rejects_unanchored_start(self, mock_meta):
# Backend must reject a fade-in that isn't anchored to the clip start,
# even if a caller bypasses the UI gating (afade would silence the lead-in).
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(ValueError, match="anchored to the clip start"):
service.fade_region("/tmp/input.flac", 50.0, 53.0, "in", "/tmp/output.flac")
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
def test_fade_out_rejects_unanchored_end(self, mock_meta):
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(ValueError, match="anchored to the clip end"):
service.fade_region("/tmp/input.flac", 50.0, 55.0, "out", "/tmp/output.flac")
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
def test_fade_region_rejects_end_beyond_duration(self, mock_meta):
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(ValueError, match="exceeds clip duration"):
service.fade_region("/tmp/input.flac", 0.0, 300.0, "in", "/tmp/output.flac")
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_join_audio_end(self, mock_run, mock_meta):
@@ -229,6 +307,61 @@ class TestApplyEdit:
assert result_path == "jobs/123/audio_edit/edit_abc.flac"
assert metadata.duration_seconds == 200.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_fade_in(self, mock_tmpdir, mock_run, mock_meta):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
metadata, result_path = service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="fade_in",
params={"start_seconds": 0.0, "end_seconds": 3.0},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
cmd = mock_run.call_args[0][0]
af_str = cmd[cmd.index("-af") + 1]
assert "afade=t=in:st=0.0:d=3.0" in af_str
assert metadata.duration_seconds == 200.0 # Duration preserved
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_fade_out(self, mock_tmpdir, mock_run, mock_meta):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="fade_out",
params={"start_seconds": 197.0, "end_seconds": 200.0},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
cmd = mock_run.call_args[0][0]
af_str = cmd[cmd.index("-af") + 1]
assert "afade=t=out:st=197.0:d=3.0" in af_str
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
+67
View File
@@ -0,0 +1,67 @@
"""
Regression tests for AudioShake leading-padding handling.
Some user-provided audio (e.g. the Vocal Star bulk-batch MP3s) begins with a block of
null bytes before the first ID3/MPEG frame. ffmpeg tolerates it, but AudioShake rejects
the asset with "Error fetching or processing asset" (400 on /tasks). The AudioUploadOptimizer
must detect this and losslessly remux before upload — while leaving clean files and
container formats (.mp4/.mov, which legitimately start with null box-size bytes) untouched.
"""
import os
import tempfile
from unittest.mock import MagicMock, patch
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioUploadOptimizer
def _write(tmp_path, name, head: bytes):
p = os.path.join(tmp_path, name)
with open(p, "wb") as f:
f.write(head + b"\x00" * 2048)
return p
def test_has_leading_padding_detects_null_start(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
assert opt._has_leading_padding(padded) is True
def test_has_leading_padding_false_for_id3(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
assert opt._has_leading_padding(clean) is False
def test_has_leading_padding_false_for_frame_sync(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "sync.mp3", b"\xff\xfb\xc0\x04")
assert opt._has_leading_padding(clean) is False
def test_padded_mp3_is_remuxed(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
padded = _write(str(tmp_path), "padded.mp3", b"\x00\x00\x00\x00")
with patch.object(opt, "_remux_clean", return_value=("/tmp/clean.mp3", "/tmp/clean.mp3")) as remux:
result = opt.prepare_for_upload(padded)
remux.assert_called_once()
assert result == ("/tmp/clean.mp3", "/tmp/clean.mp3")
def test_clean_mp3_uploaded_directly(tmp_path):
opt = AudioUploadOptimizer(MagicMock())
clean = _write(str(tmp_path), "clean.mp3", b"ID3\x04")
with patch.object(opt, "_remux_clean") as remux:
result = opt.prepare_for_upload(clean)
remux.assert_not_called()
assert result == (clean, None)
def test_container_format_not_remuxed_despite_null_start(tmp_path):
""".mp4/.mov begin with a null box-size prefix — must NOT be treated as padding."""
opt = AudioUploadOptimizer(MagicMock())
mp4 = _write(str(tmp_path), "video.mp4", b"\x00\x00\x00\x20ftyp")
with patch.object(opt, "_remux_clean") as remux:
result = opt.prepare_for_upload(mp4)
remux.assert_not_called()
assert result == (mp4, None)
+5 -55
View File
@@ -241,31 +241,14 @@ class TestUserEmailExtraction:
class TestUrlJobWorkerSequencing:
"""
Issue 2: YouTube URL download race condition.
URL job worker triggering.
Root cause: Both audio and lyrics workers were triggered in parallel.
For URL jobs, lyrics worker would timeout waiting for audio to download.
These tests verify that URL jobs trigger workers sequentially.
URL jobs are now downloaded by the flacfetch service in create_from_url
BEFORE any worker runs, so `input_media_gcs_path` is already set and both
workers can start in parallel (no sequential audio→lyrics handoff, no local
yt-dlp fallback in the worker).
"""
@pytest.mark.asyncio
async def test_url_job_triggers_only_audio_worker_initially(self):
"""
create-from-url must only trigger audio worker, not lyrics worker.
The audio worker will trigger lyrics after download completes.
"""
from backend.api.routes.file_upload import _trigger_audio_worker_only
with patch('backend.api.routes.file_upload.worker_service') as mock_ws:
mock_ws.trigger_audio_worker = AsyncMock()
mock_ws.trigger_lyrics_worker = AsyncMock()
await _trigger_audio_worker_only("test-job-id")
mock_ws.trigger_audio_worker.assert_called_once_with("test-job-id")
mock_ws.trigger_lyrics_worker.assert_not_called()
@pytest.mark.asyncio
async def test_parallel_worker_triggers_both_workers(self):
"""
@@ -284,39 +267,6 @@ class TestUrlJobWorkerSequencing:
mock_ws.trigger_audio_worker.assert_called_once_with("test-job-id")
mock_ws.trigger_lyrics_worker.assert_called_once_with("test-job-id")
@pytest.mark.asyncio
async def test_audio_worker_triggers_lyrics_after_url_download(self):
"""
Audio worker must trigger lyrics worker after successful URL download.
"""
from backend.workers.audio_worker import _trigger_lyrics_worker_after_url_download
# Mock at the source module where it's imported from
with patch('backend.services.worker_service.get_worker_service') as mock_get_ws:
mock_ws = Mock()
mock_ws.trigger_lyrics_worker = AsyncMock()
mock_get_ws.return_value = mock_ws
await _trigger_lyrics_worker_after_url_download("test-job-id")
mock_ws.trigger_lyrics_worker.assert_called_once_with("test-job-id")
@pytest.mark.asyncio
async def test_audio_worker_lyrics_trigger_handles_errors_gracefully(self):
"""
If lyrics worker trigger fails, audio processing should continue.
"""
from backend.workers.audio_worker import _trigger_lyrics_worker_after_url_download
# Mock at the source module where it's imported from
with patch('backend.services.worker_service.get_worker_service') as mock_get_ws:
mock_ws = Mock()
mock_ws.trigger_lyrics_worker = AsyncMock(side_effect=Exception("Network error"))
mock_get_ws.return_value = mock_ws
# Should not raise exception
await _trigger_lyrics_worker_after_url_download("test-job-id")
class TestAudioSearchCacheIndependence:
"""
@@ -0,0 +1,124 @@
"""Tests for proactive auto-correct: the service-side worker + the lyrics-worker trigger.
The work runs on the API service (process_proactive_auto_correct); the lyrics
worker only fires an HTTP trigger. Both must be best-effort: gated by a flag,
never raise, never block, and use the multi-model default settings that line up
with the review UI's request.
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.workers.auto_correct_worker import process_proactive_auto_correct
from backend.workers.lyrics_worker import _trigger_proactive_auto_correct
CORRECTIONS = {
"corrected_segments": [
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
],
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
}
def _settings(enabled: bool):
return SimpleNamespace(auto_correct_proactive_enabled=enabled)
def _patch(enabled=True, corrections=CORRECTIONS, exists=True, service=None, job=None):
"""Patch the dependencies process_proactive_auto_correct imports lazily."""
storage = MagicMock()
storage.file_exists.return_value = exists
storage.download_json.return_value = corrections
jm = MagicMock()
jm.return_value.get_job.return_value = job or SimpleNamespace(artist="A", title="T")
return (
patch("backend.config.get_settings", return_value=_settings(enabled)),
patch("backend.services.storage_service.StorageService", return_value=storage),
patch("backend.services.job_manager.JobManager", jm),
patch("backend.services.auto_correct.get_auto_correct_service",
return_value=service or MagicMock()),
storage,
)
# ---- service-side worker ----
@pytest.mark.asyncio
async def test_disabled_flag_short_circuits() -> None:
p_set, p_st, p_jm, p_svc, storage = _patch(enabled=False)
with p_set, p_st, p_jm, p_svc:
result = await process_proactive_auto_correct("job-1")
assert result == {"status": "disabled"}
storage.file_exists.assert_not_called()
@pytest.mark.asyncio
async def test_skips_when_no_references() -> None:
corr = {"corrected_segments": [{"id": "s", "words": []}], "reference_lyrics": {}}
p_set, p_st, p_jm, p_svc, storage = _patch(corrections=corr)
svc = MagicMock()
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-1")
assert result["status"] == "skipped"
svc.suggest.assert_not_called()
@pytest.mark.asyncio
async def test_skips_when_no_corrections_file() -> None:
p_set, p_st, p_jm, p_svc, storage = _patch(exists=False)
with p_set, p_st, p_jm, p_svc:
result = await process_proactive_auto_correct("job-1")
assert result["status"] == "skipped"
@pytest.mark.asyncio
async def test_happy_path_runs_multi_model_and_caches() -> None:
svc = MagicMock()
svc.suggest.return_value = SimpleNamespace(
suggestions=[1, 2], model="claude-fable-5, gemini-3.1-pro-preview",
elapsed_seconds=12.3,
)
p_set, p_st, p_jm, _p_svc, storage = _patch(service=svc)
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-1")
assert result == {"status": "generated", "suggestions": 2}
kwargs = svc.suggest.call_args.kwargs
assert kwargs["job_id"] == "job-1"
assert kwargs["settings"].compare_models is True
assert kwargs["artist"] == "A"
assert kwargs["segments"] == CORRECTIONS["corrected_segments"]
@pytest.mark.asyncio
async def test_swallows_service_errors() -> None:
svc = MagicMock()
svc.suggest.side_effect = RuntimeError("anthropic down / out of credits")
p_set, p_st, p_jm, _p_svc, storage = _patch(service=svc)
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-1") # must not raise
assert result["status"] == "error"
# ---- lyrics-worker trigger ----
@pytest.mark.asyncio
async def test_lyrics_worker_fires_trigger() -> None:
ws = MagicMock()
ws.trigger_auto_correct = AsyncMock(return_value=True)
with patch("backend.services.worker_service.WorkerService", return_value=ws):
await _trigger_proactive_auto_correct("job-1", MagicMock())
ws.trigger_auto_correct.assert_awaited_once_with("job-1")
@pytest.mark.asyncio
async def test_lyrics_worker_trigger_swallows_errors() -> None:
ws = MagicMock()
ws.trigger_auto_correct = AsyncMock(side_effect=RuntimeError("network down"))
job_log = MagicMock()
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()
+51
View File
@@ -545,6 +545,57 @@ class TestCreateJobFromSearch:
assert job_create.artist == "Abba (Display)"
assert job_create.title == "Waterloo (Karaoke)"
def test_corrected_artist_title_wins_over_session_query(self, create_from_search_client, auth_headers):
"""Regression: when the user clicks "Use official formatting", the corrected
artist/title sent in the request body must win over the original (raw) search
query stored in the session. Previously the job was named with the raw query,
so the official formatting selection was silently ignored."""
# Session was created from the raw lowercase query the user typed...
raw_session = _make_search_session(user_email="test@example.com")
raw_session["artist"] = "hard-fi"
raw_session["title"] = "hard to beat"
create_from_search_client._mock_firestore.get_search_session.return_value = raw_session
create_from_search_client._mock_firestore.consume_search_session.return_value = raw_session
# ...then the user picked the official formatting, so the frontend sends the
# corrected artist/title (no separate display override).
create_from_search_client.post(
"/api/jobs/create-from-search",
json={
"search_session_id": "sess-abc-123",
"selection_index": 0,
"artist": "Hard-Fi",
"title": "Hard to Beat",
},
headers=auth_headers,
)
call_args = create_from_search_client._mock_jm.create_job.call_args
job_create = call_args[0][0]
assert job_create.artist == "Hard-Fi"
assert job_create.title == "Hard to Beat"
# The original query is still preserved for audio-search matching metadata.
assert job_create.audio_search_artist == "hard-fi"
assert job_create.audio_search_title == "hard to beat"
def test_blank_body_artist_title_falls_back_to_session_query(self, create_from_search_client, auth_headers):
"""Whitespace-only artist/title in the body must not become the job name —
fall back to the stored search query instead."""
create_from_search_client.post(
"/api/jobs/create-from-search",
json={
"search_session_id": "sess-abc-123",
"selection_index": 0,
"artist": " ",
"title": "\t",
},
headers=auth_headers,
)
call_args = create_from_search_client._mock_jm.create_job.call_args
job_create = call_args[0][0]
# Session stores "ABBA" / "Waterloo" (see _make_search_session).
assert job_create.artist == "ABBA"
assert job_create.title == "Waterloo"
def test_session_consumed_atomically(self, create_from_search_client, auth_headers):
"""Session is consumed (atomically read+deleted) via consume_search_session."""
create_from_search_client.post(
+91 -8
View File
@@ -56,6 +56,43 @@ def _make_job_mock(**kwargs):
return job
class TestSelectMixedAudioFiles:
"""Regression tests for _select_mixed_audio_files() in file_upload.py.
The existing-instrumental file shares the uploads/{job}/audio/ directory with the
mixed audio, so the 'audio/' prefix matches both. Before the fix, files[0] resolved to
'existing_instrumental.mp3' (it sorts first) and transcription ran on the instrumental.
"""
def _fn(self):
from backend.api.routes.file_upload import _select_mixed_audio_files
return _select_mixed_audio_files
def test_excludes_existing_instrumental(self):
fn = self._fn()
# Listing is sorted alphabetically by GCS, so the instrumental comes first.
files = [
"uploads/job123/audio/existing_instrumental.mp3",
"uploads/job123/audio/mixed.mp3",
]
result = fn(files)
assert result == ["uploads/job123/audio/mixed.mp3"]
assert result[0] == "uploads/job123/audio/mixed.mp3"
def test_plain_audio_only_unchanged(self):
fn = self._fn()
files = ["uploads/job123/audio/My Song.flac"]
assert fn(files) == files
def test_real_filenames_with_instrumental(self):
fn = self._fn()
files = [
"uploads/job123/audio/existing_instrumental.mp3",
"uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3",
]
assert fn(files) == ["uploads/job123/audio/Eddy Grant - I Don't Wanna Dance Guide.mp3"]
class TestApplyTenantOverrides:
"""Tests for _apply_tenant_overrides() in file_upload.py."""
@@ -125,24 +162,70 @@ class TestApplyTenantOverrides:
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
assert yt_upload is False
def test_request_values_take_precedence(self):
"""Explicit request-level values are not overridden by tenant defaults."""
def test_tenant_config_overrides_global_defaults(self):
"""Tenant config is authoritative: it overrides any global/consumer default
distribution settings already seeded into `dist`.
Regression guard: prod sets DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID /
DEFAULT_BRAND_PREFIX globally, which get_effective_distribution_settings seeds
into `dist`. If tenant overrides only filled in *unset* fields, every tenant job
would leak into the shared consumer Dropbox folder and global Google Drive.
"""
apply_fn = self._get_apply_fn()
tenant_config = _make_tenant_config()
# `dist` arrives pre-seeded with the GLOBAL consumer defaults.
dist = EffectiveDistributionSettings(
dropbox_path="/Custom/Path",
gdrive_folder_id="custom-folder",
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized", # global default
gdrive_folder_id="global-consumer-folder", # global default
discord_webhook_url=None,
brand_prefix="CUSTOM",
brand_prefix="NOMAD", # global default
enable_youtube_upload=True,
youtube_description=None,
)
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.brand_prefix == "CUSTOM"
assert new_dist.dropbox_path == "/Custom/Path"
assert new_dist.gdrive_folder_id == "custom-folder"
# Tenant config wins on every distribution field.
assert new_dist.brand_prefix == "VSTAR"
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
def test_gdrive_disabled_clears_global_default(self):
"""When the tenant disables gdrive_upload, the global default GDrive folder is
cleared so the tenant job never publishes to Google Drive (the B2B requirement)."""
apply_fn = self._get_apply_fn()
# Tenant has a gdrive folder configured but the feature is OFF — the disabled
# flag must win, clearing both the configured folder and any global default.
tenant_config = _make_tenant_config()
tenant_config.features.gdrive_upload = False
dist = EffectiveDistributionSettings(
dropbox_path=None,
gdrive_folder_id="global-consumer-folder", # would otherwise leak
discord_webhook_url=None,
brand_prefix=None,
enable_youtube_upload=True,
youtube_description=None,
)
new_dist, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.gdrive_folder_id is None
assert yt_upload is False
def test_dropbox_disabled_clears_path(self):
"""When the tenant disables dropbox_upload, the Dropbox path is cleared."""
apply_fn = self._get_apply_fn()
tenant_config = _make_tenant_config()
tenant_config.features.dropbox_upload = False
dist = EffectiveDistributionSettings(
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized",
gdrive_folder_id=None, discord_webhook_url=None,
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
)
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.dropbox_path is None
def test_no_tenant_config_passthrough(self):
"""When no tenant config, all values pass through unchanged."""
+43 -98
View File
@@ -780,61 +780,16 @@ class TestAudioWorkerModelConfiguration:
assert call_kwargs['other_stems_models'] == []
class TestDownloadFromUrl:
"""Tests for download_from_url function - URL-based audio download."""
def test_download_from_url_function_exists(self):
"""Test that download_from_url function exists in audio_worker."""
from backend.workers.audio_worker import download_from_url
assert callable(download_from_url)
def test_download_from_url_signature(self):
"""Test that download_from_url has the expected signature."""
import inspect
from backend.workers.audio_worker import download_from_url
sig = inspect.signature(download_from_url)
params = list(sig.parameters.keys())
# Should have these parameters
assert 'url' in params
assert 'temp_dir' in params
assert 'artist' in params
assert 'title' in params
assert 'job_manager' in params
assert 'job_id' in params
def test_download_from_url_is_async(self):
"""Test that download_from_url is an async function."""
import inspect
from backend.workers.audio_worker import download_from_url
assert inspect.iscoroutinefunction(download_from_url)
@pytest.mark.asyncio
async def test_download_from_url_returns_none_for_invalid_url(self):
"""Test that download_from_url handles errors gracefully."""
from backend.workers.audio_worker import download_from_url
with tempfile.TemporaryDirectory() as temp_dir:
# This should fail gracefully (no yt-dlp in test env or invalid URL)
result = await download_from_url(
url='not-a-valid-url',
temp_dir=temp_dir,
artist='Test',
title='Test'
)
# Should return None on error (graceful failure)
assert result is None
class TestDownloadAudioWithUrl:
"""Tests for download_audio function with URL-based jobs."""
"""Tests for download_audio: it only ever consumes a pre-downloaded GCS file.
URLs are downloaded by the flacfetch service in create_job_from_url before
any worker runs — the audio worker never runs yt-dlp on Cloud Run.
"""
@pytest.fixture
def mock_job_with_url(self):
"""Create a mock job with a URL."""
"""A URL job that (incorrectly) reached the worker without a GCS path."""
return Job(
job_id="test123",
status=JobStatus.PROCESSING,
@@ -844,7 +799,7 @@ class TestDownloadAudioWithUrl:
title="Test Song",
url="https://www.youtube.com/watch?v=test123"
)
@pytest.fixture
def mock_job_manager(self, mock_job_with_url):
"""Create a mock JobManager."""
@@ -852,40 +807,34 @@ class TestDownloadAudioWithUrl:
manager.get_job.return_value = mock_job_with_url
manager.update_job.return_value = None
return manager
@pytest.fixture
def mock_storage(self):
"""Create a mock StorageService."""
storage = MagicMock()
return storage
@pytest.mark.asyncio
async def test_download_audio_from_url(self, mock_job_with_url, mock_job_manager, mock_storage):
"""Test download_audio routes to URL download when job has URL."""
with patch('backend.workers.audio_worker.download_from_url', return_value='/tmp/test.wav') as mock_download:
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Should have called download_from_url
mock_download.assert_called_once()
# Check positional args
args = mock_download.call_args[0]
assert args[0] == "https://www.youtube.com/watch?v=test123" # url
assert args[1] == temp_dir # temp_dir
assert args[2] == "Test Artist" # artist
assert args[3] == "Test Song" # title
async def test_download_audio_url_without_gcs_path_refuses(self, mock_job_with_url, mock_job_manager, mock_storage):
"""A URL job with no GCS file must fail (no local yt-dlp fallback)."""
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Refuses to download locally → returns None, never touches storage
assert result is None
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_download_audio_from_gcs_when_no_url(self, mock_job_manager, mock_storage):
"""Test download_audio downloads from GCS when job has no URL."""
async def test_download_audio_from_gcs(self, mock_job_manager, mock_storage):
"""Test download_audio downloads from GCS when input_media_gcs_path is set."""
mock_job_no_url = Job(
job_id="test123",
status=JobStatus.PROCESSING,
@@ -895,24 +844,20 @@ class TestDownloadAudioWithUrl:
title="Test Song",
input_media_gcs_path="uploads/test123/song.flac"
)
with patch('backend.workers.audio_worker.download_from_url') as mock_url_download:
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_no_url,
job_manager_instance=mock_job_manager
)
# Should NOT have called download_from_url
mock_url_download.assert_not_called()
# Should have called storage.download_file
mock_storage.download_file.assert_called()
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_no_url,
job_manager_instance=mock_job_manager
)
# Should have downloaded the pre-existing GCS file
mock_storage.download_file.assert_called()
class TestBackingVocalsAnalysis:
+24 -26
View File
@@ -4,7 +4,6 @@ Unit tests for YouTubeDownloadService.
Tests the consolidated YouTube download service that handles all YouTube
downloads in the cloud backend.
"""
import os
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -179,43 +178,42 @@ class TestYouTubeDownloadService:
assert "Remote download failed" in str(exc.value)
# =========================================================================
# Local Fallback Tests
# Generic (non-YouTube) URL Tests
# =========================================================================
@pytest.mark.asyncio
async def test_download_falls_back_to_local_when_remote_disabled(self):
"""When remote not configured, should use local yt_dlp."""
mock_storage = MagicMock()
mock_storage.upload_fileobj = MagicMock()
mock_file_handler = MagicMock()
mock_file_handler.download_video = MagicMock(return_value="/tmp/test.webm")
mock_file_handler.convert_to_wav = MagicMock(return_value="/tmp/test.wav")
async def test_download_generic_url_uses_url_source(self):
"""Non-YouTube URLs route through flacfetch's generic 'URL' source."""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job123/audio/Artist - Title.m4a",
})
fb_url = "https://www.facebook.com/share/v/1EnC8Bi5Uq/"
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
), patch(
'backend.services.youtube_download_service.StorageService',
return_value=mock_storage
), patch(
'backend.services.youtube_download_service.YouTubeDownloadService._download_local',
new_callable=AsyncMock,
return_value="uploads/job123/audio/test.wav"
) as mock_local:
return_value=mock_client
):
service = YouTubeDownloadService()
result = await service.download(
url="https://youtu.be/dQw4w9WgXcQ",
url=fb_url,
job_id="job123",
artist="Artist",
title="Title",
)
assert result == "uploads/job123/audio/test.wav"
mock_local.assert_called_once()
assert result == "uploads/job123/audio/Artist - Title.m4a"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == fb_url
assert call_kwargs["source_id"] == fb_url
@pytest.mark.asyncio
async def test_download_invalid_url_raises_error(self):
"""Should raise error for URLs that can't extract video ID."""
async def test_download_raises_when_remote_not_configured(self):
"""No silent local fallback: hard-fail when flacfetch isn't configured."""
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None
@@ -224,11 +222,11 @@ class TestYouTubeDownloadService:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="https://vimeo.com/123456",
url="https://youtu.be/dQw4w9WgXcQ",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
# =========================================================================
# Singleton Tests
+21 -197
View File
@@ -21,9 +21,7 @@ import shutil
import tempfile
import time
from typing import Optional, Dict, Any
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.job_health_service import validate_worker_can_run
@@ -40,29 +38,6 @@ from karaoke_gen.audio_processor import AudioProcessor
logger = logging.getLogger(__name__)
async def _trigger_lyrics_worker_after_url_download(job_id: str) -> None:
"""
Trigger lyrics worker after URL audio download completes.
For URL jobs, we use sequential triggering:
1. Audio worker downloads and uploads audio to GCS
2. Audio worker triggers lyrics worker (this function)
3. Both workers then proceed in parallel (audio separation + lyrics transcription)
This prevents the race condition where lyrics worker times out waiting for audio.
"""
from backend.services.worker_service import get_worker_service
try:
worker_service = get_worker_service()
await worker_service.trigger_lyrics_worker(job_id)
logger.info(f"Job {job_id}: Triggered lyrics worker after URL download")
except Exception as e:
# Log but don't fail - audio processing can still continue
# The job will eventually timeout if lyrics worker doesn't run
logger.error(f"Job {job_id}: Failed to trigger lyrics worker: {e}")
# Default ensemble presets — resolved by audio-separator package into models + algorithm.
# To change models, update ensemble_presets.json in audio-separator and release a new version.
DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean" # Fv7z + Resurrection, SDR ~17.5
@@ -80,126 +55,6 @@ AUDIO_WORKER_LOGGERS = [
]
async def download_from_url(url: str, temp_dir: str, artist: str, title: str, job_manager: JobManager = None, job_id: str = None) -> Optional[str]:
"""
Download audio from a URL using local yt_dlp.
IMPORTANT: This is a LEGACY FALLBACK for non-YouTube URLs only!
For YouTube URLs, use YouTubeDownloadService instead, which:
- Uses remote flacfetch when configured (avoids Cloud Run bot detection)
- Has proper error handling and GCS upload
This function uses local yt_dlp and will likely FAIL for YouTube URLs
on Cloud Run due to bot detection (YouTube blocks Cloud Run IP ranges).
Uses the FileHandler from karaoke_gen which includes:
- Anti-detection options (user agent, headers, delays)
- Cookie support for authenticated downloads
- Retry logic
If artist and/or title are not provided, attempts to extract them from
the URL metadata.
Args:
url: URL to download from (NOT recommended for YouTube - use YouTubeDownloadService)
temp_dir: Temporary directory to save to
artist: Artist name for filename (can be None for auto-detection)
title: Song title for filename (can be None for auto-detection)
job_manager: Optional JobManager to update job with detected metadata
job_id: Optional job ID to update
Returns:
Path to downloaded audio file, or None if failed
"""
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler instance
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
)
# Try to extract metadata if artist or title not provided
if not artist or not title:
logger.info(f"Extracting metadata from URL: {url}")
metadata = file_handler.extract_metadata_from_url(url)
if metadata:
if not artist:
artist = metadata.get('artist', 'Unknown')
logger.info(f"Auto-detected artist: {artist}")
if not title:
title = metadata.get('title', 'Unknown')
logger.info(f"Auto-detected title: {title}")
# Update job with detected metadata if job_manager provided
if job_manager and job_id:
update_data = {}
if artist:
update_data['artist'] = artist
if title:
update_data['title'] = title
if update_data:
job_manager.update_job(job_id, update_data)
logger.info(f"Updated job {job_id} with detected metadata")
else:
logger.warning("Could not extract metadata from URL, using defaults")
artist = artist or "Unknown"
title = title or "Unknown"
# Create output filename (without extension)
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(temp_dir, f"{safe_artist} - {safe_title}")
# Get YouTube cookies from environment variable if available
# This helps bypass "Sign in to confirm you're not a bot" errors
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for download authentication")
else:
logger.info("No YOUTUBE_COOKIES env var set - attempting download without cookies")
# Download using FileHandler (includes anti-detection features)
logger.info(f"Downloading from URL: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if downloaded_file and os.path.exists(downloaded_file):
logger.info(f"Downloaded video: {downloaded_file}")
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if wav_file and os.path.exists(wav_file):
logger.info(f"Converted to WAV: {wav_file}")
return wav_file
else:
logger.error("WAV conversion failed")
return None
else:
logger.error("Download failed - no file returned")
return None
except ImportError as e:
logger.error(f"Import error: {e}. Check karaoke_gen installation.")
return None
except Exception as e:
logger.error(f"Failed to download from URL {url}: {e}", exc_info=True)
return None
def create_audio_processor(
temp_dir: str,
model_file_dir: Optional[str] = None,
@@ -543,12 +398,16 @@ async def download_audio(
job_manager_instance: JobManager = None
) -> Optional[str]:
"""
Download or fetch audio file to local temp directory.
Handles two cases:
1. Uploaded file: Download from GCS using input_media_gcs_path
2. URL (YouTube, etc.): Download using yt-dlp or other tools
Fetch the job's audio file from GCS to a local temp directory.
All inputs are expected to already be in GCS by the time this worker runs:
- Uploaded files: at input_media_gcs_path
- URL jobs: downloaded by the flacfetch service in create_job_from_url
before any worker is triggered
This worker never downloads from a URL itself (no yt-dlp on Cloud Run); a
URL job arriving without a GCS file is treated as an upstream bug.
Args:
job_id: Job ID
temp_dir: Temporary directory to save to
@@ -594,55 +453,20 @@ async def download_audio(
logger.info(f"Job {job_id}: Downloaded audio from GCS: {input_url}")
return local_path
# Case 3: Fresh URL that needs downloading (legacy fallback)
# NOTE: YouTube URLs should be downloaded by YouTubeDownloadService in file_upload.py
# BEFORE triggering this worker. If we reach here with a YouTube URL, it means
# the download was not done upfront, which will likely fail due to bot detection.
# A URL job that reached this worker WITHOUT a pre-downloaded GCS file is
# an upstream bug: all URLs are downloaded by the flacfetch service in
# create_job_from_url before any worker runs. We never run yt-dlp on
# Cloud Run, so there is no local fallback — fail clearly instead.
if job.url:
# Check if this is a YouTube URL that should have been handled earlier
is_youtube = any(domain in job.url.lower() for domain in ['youtube.com', 'youtu.be'])
if is_youtube:
logger.warning(
f"Job {job_id}: YouTube URL reached download_audio() fallback. "
"This may fail due to bot detection. YouTube URLs should be "
"downloaded via YouTubeDownloadService before triggering workers."
)
logger.info(f"Job {job_id}: Downloading from URL: {job.url}")
# Use provided job_manager or create new one
jm = job_manager_instance or JobManager()
local_path = await download_from_url(
job.url,
temp_dir,
job.artist,
job.title,
job_manager=jm,
job_id=job_id
logger.error(
f"Job {job_id}: URL job reached the audio worker without a "
f"downloaded input_media_gcs_path (url={job.url}). URLs must be "
"fetched via the flacfetch service before processing; refusing to "
"download locally."
)
return None
if local_path and os.path.exists(local_path):
# Upload to GCS and update job
gcs_path = f"jobs/{job_id}/input/{os.path.basename(local_path)}"
url = storage.upload_file(local_path, gcs_path)
# Update job with GCS path for lyrics worker
jm.update_job(job_id, {'input_media_gcs_path': gcs_path})
jm.update_file_url(job_id, 'input', 'audio', url)
logger.info(f"Job {job_id}: Downloaded and uploaded audio to GCS: {gcs_path}")
# For URL jobs, trigger lyrics worker now that audio is available
# This is the sequential trigger pattern - audio first, then lyrics
await _trigger_lyrics_worker_after_url_download(job_id)
return local_path
else:
logger.error(f"Job {job_id}: Failed to download from URL: {job.url}")
return None
logger.error(f"Job {job_id}: No input source found (no GCS path, file_urls, or URL)")
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
return None
except Exception as e:
+83
View File
@@ -0,0 +1,83 @@
"""Proactive auto-correct generation, run on the API service.
The lyrics worker (a Cloud Run Job) triggers this via the internal endpoint
once transcription + references are ready. It runs HERE — on the API service —
rather than in the lyrics job, because the service already has a working
ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS configuration (the lyrics job's
secrets use Cloud Run secret aliases that `gcloud run jobs update
--update-secrets` can't extend; see docs/archive/2026-06-11-proactive-autocorrect-plan.md).
Pre-generates + caches the multi-model suggestion run so the review UI's
on-load request is an instant cache hit. Best-effort: it must never raise — a
failure just means the UI does the call on demand instead.
"""
from __future__ import annotations
import asyncio
import logging
logger = logging.getLogger(__name__)
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
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()
corrections_path = f"jobs/{job_id}/lyrics/corrections.json"
if not storage.file_exists(corrections_path):
logger.info("[job:%s] proactive auto-correct skipped: no corrections.json", job_id)
return {"status": "skipped", "reason": "no_corrections"}
data = storage.download_json(corrections_path)
segments = data.get("corrected_segments") or data.get("segments") or []
reference_lyrics = data.get("reference_lyrics") or {}
if not segments or not reference_lyrics:
# No references → nothing to compare against. The reviewer can paste
# references in the UI and trigger auto-correct manually later.
logger.info(
"[job:%s] proactive auto-correct skipped: %d segments, %d ref sources",
job_id, len(segments), len(reference_lyrics),
)
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),
),
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)}
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)}
+29 -1
View File
@@ -170,6 +170,26 @@ def create_lyrics_processor(
)
async def _trigger_proactive_auto_correct(job_id, job_log) -> None:
"""Trigger proactive auto-correct generation on the API service.
The actual multi-model LLM call + caching runs on the API service (which
has the working Anthropic key / compare-models config) — see
backend/workers/auto_correct_worker.py. Here we just fire the HTTP trigger
and await it. Best-effort and fully isolated: it must NEVER raise, fail the
job, or block the pipeline — downstream stages are already triggered before
this runs, and the service gates the work behind AUTO_CORRECT_PROACTIVE_ENABLED.
"""
try:
from backend.services.worker_service import WorkerService
ok = await WorkerService().trigger_auto_correct(job_id)
job_log.info("Proactive auto-correct trigger %s", "ok" if ok else "skipped/failed")
except Exception as e: # noqa: BLE001 — never let auto-correct affect the job
job_log.warning(f"Proactive auto-correct trigger failed (non-fatal): {e}")
logger.warning(f"[job:{job_id}] Proactive auto-correct trigger failed (non-fatal): {e}")
async def process_lyrics_transcription(job_id: str) -> bool:
"""
Process lyrics transcription and correction for a job using karaoke_gen.LyricsProcessor.
@@ -516,7 +536,15 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# This will check if audio is also complete and transition to next stage if so
job_log.info("Lyrics worker complete, checking if audio is also done...")
job_manager.mark_lyrics_complete(job_id)
# Proactively pre-generate + cache AI auto-correct suggestions so
# they're ready when the reviewer opens the lyrics UI. The work
# runs on the API service (it has the Anthropic key); we just fire
# the trigger here. Done AFTER mark_lyrics_complete (downstream is
# already triggered, so this never blocks it) and fully isolated —
# it can never fail or delay the job beyond its own timeout.
await _trigger_proactive_auto_correct(job_id, job_log)
duration = time.time() - start_time
# Store worker-level timing
job_manager.update_processing_metadata(job_id, "timing.lyrics_worker_seconds", round(duration, 1))
+89
View File
@@ -545,6 +545,95 @@ Adds user-pasted lyrics as a new reference source, re-runs the correction pipeli
Returns `{ "status": "success", "data": <CorrectionData> }`.
#### AI Auto-Correct Suggestions
```http
POST /api/review/{job_id}/auto-correct
Content-Type: application/json
{
"segments": [ "...client's current corrected_segments..." ],
"reference_lyrics": { "genius": { "segments": [...] } },
"artist": "Twenty One Pilots",
"title": "Chlorine",
"settings": {
"suggest_adlib_removal": true,
"allow_insertions": true,
"min_confidence": 0.0,
"compare_models": true
}
}
```
AI correction suggestions for the lyrics review UI. Stateless: one whole-song
LLM call per model (Claude models use the Anthropic API via the
`anthropic-api-key` secret, Gemini models use Vertex AI) compares the
client's current transcription against the reference sources and returns
word-id-keyed suggestions. Nothing is applied server-side — the reviewer
accepts/rejects each suggestion in the UI and persistence flows through the
existing corrections/complete paths.
The review UI always requests the multi-model path (`compare_models: true`)
and auto-runs once on load, so suggestions appear without a click. To make
that load instant, suggestions are **proactively pre-generated and cached**
once transcription + references are ready: the lyrics worker fires an internal
trigger (`POST /api/internal/workers/auto-correct`) that runs the same
multi-model generation on the API service (gated by
`AUTO_CORRECT_PROACTIVE_ENABLED`; best-effort — it never blocks or fails the
karaoke job). Because the proactive run uses the same default settings the UI
sends, the on-load request is normally a cache hit with no extra cost.
With `"compare_models": true`, every model in `AUTO_CORRECT_COMPARE_MODELS`
(semicolon-separated) is queried in parallel; identical suggestions are
deduplicated with a per-suggestion `consensus` count, and suggestions that
target overlapping words with different outcomes share a `conflict_group`
(the UI accepts at most one per group). A model failure in compare mode is
reported in `warnings` while remaining model results are returned; only if
all models fail does the endpoint return 502.
Returns:
```json
{
"suggestions": [
{
"id": "uuid",
"op": "replace",
"word_ids": ["w3"],
"segment_ids": ["seg-1"],
"original_text": "glory",
"new_text": "chlorine",
"reason": "All references read 'chlorine' here",
"category": "mishearing",
"confidence": 0.95,
"models": ["claude-opus-4-8", "gemini-3.1-pro-preview"],
"consensus": 2,
"total_models": 2,
"conflict_group": null
}
],
"model": "claude-opus-4-8, gemini-3.1-pro-preview",
"elapsed_seconds": 27.4,
"settings_applied": { "suggest_adlib_removal": true, "allow_insertions": true, "min_confidence": 0.0 },
"warnings": [],
"cached": false
}
```
Results are cached per job in GCS
(`jobs/{job_id}/lyrics/auto_correct_cache/{hash}.json`), keyed on the exact
input: word ids + texts, reference lyrics texts, settings, and the resolved
model list. Re-running on unmodified lyrics returns the previous result with
`"cached": true` and incurs no LLM cost; any edit to the lyrics, references,
or settings produces a new key and a fresh run. Cache reads/writes are
best-effort — storage failures degrade to a normal uncached run.
`op` is `replace` | `delete` | `insert_after` (for `insert_after`, `word_ids`
holds the anchor word). Errors: `422` when no reference lyrics are available,
`400` for invalid settings, `502` when the model call fails or returns
malformed output. Design/eval background:
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`.
#### Search Reference Lyrics
```http
+6
View File
@@ -8,6 +8,12 @@ Key insights for future AI agents working on this codebase.
## AI Generation Patterns
### Auto-Correction Take 3: Suggestion Layer, Not Silent Application (Jun 2026)
Lyrics auto-correction failed twice (rule handlers, per-gap agentic LLM) and was fully disabled in PR #321 because it "created more work than it saved". The failures were architectural, not fundamental: per-gap calls with tiny context (10-30s × up to 74 gaps, blocking the pipeline) and silent application (every wrong fix = invisible reviewer work). The 2026 redesign inverts all three properties: **one whole-song call** (a full song + 3 reference sources ≈ 3K tokens), **on-demand from the review UI** (zero pipeline impact, failure = "no suggestions" never a stuck job), and **a pending-suggestion layer** the reviewer accepts/rejects per change (wrong suggestion = one click, and the EditLog `ai_suggestion_*` entries measure real accept rates for free). Eval before building: 30 real jobs with corrections.json (pre-review) + corrections_updated.json (human ground truth) made a 5-model benchmark trivial — and showed GPT-5.2 would have *worsened* lyrics (accept-all gap-closed −0.80) while Fable 5/Gemini 3.1 Pro close ~half the human-edit gap. Without that eval we might have shipped on the wrong model. Harness: `lyrics-alignment-eval-dataset/auto-correct-eval/`.
### Eval Metric Gotcha: Relative Metrics Explode on Near-Perfect Inputs (Jun 2026)
"Gap closed" (how much of the pre→ground-truth distance accept-all closes) goes violently negative on near-perfect transcriptions: one human edit in 198 words means 1−sim_before ≈ 0.003, so two harmless style suggestions read as −300%. Inspect the *suggestions themselves* before concluding a model is unsafe — in our case they were reference-supported tweaks (`all right`→`alright`) a human just didn't bother making. Report medians alongside means, and treat strict-precision as a floor, not the expected accept rate.
### Validate-and-Repair Loop with Plateau Detection (May 2026)
When chaining LLM calls into a repair loop (e.g. syllable-aware custom lyrics), score plateau detection on the **full score tuple** (`(violation_count, total_min_delta)`), not just count. A loop that compares `new_violation_count >= prev_violation_count` will trip on iteration 0 because there's no prior count to compare against — and even past the first iteration, you can lose deltas (fewer overshoot, but still N violations) without count moving. Using the tuple lets the loop detect "still improving" cases that pure count misses. Spec'd plan pseudocode often gets this wrong; verify against tests like `test_max_iters_reached`.
+3
View File
@@ -18,6 +18,7 @@
| Audio upload & separation | Working |
| Lyrics transcription | Working |
| Auto-correction (agentic + heuristic) | Disabled (raw transcription goes to human review) |
| **AI auto-correct suggestions (opt-in)** | Working ("AI Suggest" button in lyrics review — whole-song LLM call, per-suggestion accept/reject) |
| Combined review (lyrics + instrumental) | Working |
| Preview video generation | Working |
| Multi-format encoding | Working |
@@ -50,6 +51,8 @@
## Recent Changes
- **AI Auto-Correct Suggestions** (2026-06-11): Opt-in AI correction suggestions in the lyrics review UI — the third attempt at lyrics auto-correction, redesigned around the failures that led to disabling it in PR #321 (Jan 2026). One whole-song LLM call (default Gemini 3.1 Pro via Vertex, `AUTO_CORRECT_MODEL` env) compares the working transcription against reference lyrics and returns word-id-keyed suggestions; nothing is applied until the reviewer accepts each one (or accept-all) in a dedicated panel with per-row undo. New `POST /api/review/{job_id}/auto-correct` endpoint + `backend/services/auto_correct/`; frontend `useAutoCorrect` hook, `AutoCorrectModal` (knobs: adlib removal, insertions, confidence filter), `AutoCorrectPanel`. Accept/reject decisions land in the EditLog (`ai_suggestion_*` ops) to measure real accept rates. 5-model offline eval over 30 real jobs with human ground truth picked the default (Fable 5 ≈ Gemini 3.1 Pro ≫ GPT-5.2, which made lyrics worse). See [archive/2026-06-10-lyrics-auto-correction-reeval-plan.md](archive/2026-06-10-lyrics-auto-correction-reeval-plan.md).
- **Syllable-Aware Custom Lyrics** (2026-05-02): Enhanced the Custom Lyrics LLM mode with syllable-count validation and a per-line repair loop. Backend computes per-line target/candidate syllable counts via the existing `SyllablesMatchHandler` engine and re-prompts Gemini up to 3 times until lines fit budget (Δ ≤ 2 default, configurable via Verbatim/Loose/Balanced/Tight/Strict strictness). New `GenerationSettings` (`allow_reword`, `allow_omit`, `fixed_line_count`, `strictness`) exposed in the modal as a collapsible settings panel. New `CustomLyricsPreview` component shows per-line syllable annotations (target / actual / Δ) with severity badges and stop-reason banners. Variable-line-count mode (when `fixed_line_count=false`) re-times segments proportionally. Eval harness with disk-backed Gemini cache, per-line + per-fixture + corpus scorers, and 4 fixtures (1 from production, 3 handcrafted public-domain). v1-ships criteria validation (Year 5 ≥75% pass@2, macro corpus ≥70% pass@2) deferred to post-merge. See [archive/2026-05-02-custom-lyrics-syllable-aware-design.md](archive/2026-05-02-custom-lyrics-syllable-aware-design.md) and [archive/2026-05-02-custom-lyrics-syllable-aware-plan.md](archive/2026-05-02-custom-lyrics-syllable-aware-plan.md).
- **Custom Lyrics LLM Mode** (2026-04-28): New AI-powered lyrics-replacement mode in the lyrics review modal. Users (or admins editing client jobs) can paste custom lyrics or instructions — or upload a document — and an LLM returns lyrics that match the original line count exactly, ready to drop into the existing replace-segments flow. Includes backend `CustomLyricsService` with file extraction, prompt construction, and line-count validation; new `POST /api/review/{job_id}/custom-lyrics/generate` endpoint; preview UI with regenerate/save controls; manual-sync toast guidance after save. See [archive/2026-04-28-llm-custom-lyrics-design.md](archive/2026-04-28-llm-custom-lyrics-design.md) and [archive/2026-04-28-llm-custom-lyrics-plan.md](archive/2026-04-28-llm-custom-lyrics-plan.md).
@@ -0,0 +1,93 @@
# Lyrics Review — Graceful Audio Loading + Silence Benign AbortError Noise
**Date:** 2026-06-07
**Branch:** `feat/sess-20260607-1834-lyrics-audio-loading`
**Origin:** Prod error alert — `AbortError: The fetching process for the media resource was aborted by the user agent at the user's request.` (Firefox 151, `/en/app/jobs/`, build `e8066164`). User reproduced it: clicked the play icon beside a lyric line, nothing happened (audio still loading), clicked around, reloaded, then it worked.
## Two problems, one root cause
The lyrics-review audio element (`new Audio(audioUrl)` in `AudioPlayer.tsx`) begins fetching a large file from the backend on mount. Until it has buffered enough, calling `.play()` does nothing visible — and the resulting rejected `play()` promise is reported to the error monitor as noise.
1. **Noise:** three bare `play()` calls in `AudioPlayer.tsx` (lines 82, 105, 115) have no `.catch()`. Every other audio player in the app already uses `audio.play().catch(() => {})`. The rejection becomes an `unhandledrejection` → reported via `lib/crash-reporter.ts`.
2. **UX:** there is no loading state. Playback controls are live before the media can play, so early clicks/spacebar silently do nothing.
## Architecture (current)
- `AudioPlayer.tsx` (mounted in `Header.tsx:341`) owns the single `<audio>` element and exposes imperative globals: `window.seekAndPlayAudio(time)`, `window.toggleAudioPlayback()`, `window.getAudioDuration()`, `window.isAudioPlaying`.
- **Every** playback trigger funnels through two globals:
- `window.seekAndPlayAudio` ← `LyricsAnalyzer.handlePlaySegment` (`LyricsAnalyzer.tsx:982`), which backs the segment play buttons and `EditModal`'s `onPlaySegment`.
- `window.toggleAudioPlayback` ← spacebar (`lib/lyrics-review/utils/keyboardHandlers.ts:113-117`), the player button, `EditModal`, `LyricsSynchronizer`.
- `EditModal` already polls `window.isAudioPlaying` every 100ms — there's precedent for a window-state bridge.
**Consequence:** gating the two globals at their source makes *all* playback non-janky automatically. A reactive readiness signal handles the *visual* requirements (spinner, disabled buttons).
## Design
### Part A — Silence the noise
1. `AudioPlayer.tsx`: add `.catch(() => {})` to the three `play()` calls (matches existing convention everywhere else).
2. `lib/crash-reporter.ts`: in `reportClientError`, early-return for benign `AbortError` (`args.error instanceof DOMException && args.error.name === 'AbortError'`) before dedup/POST. Defense-in-depth so any future un-caught media abort never pages.
### Part B — Readiness as single source of truth (`AudioPlayer.tsx`)
Track media-element readiness and expose it both imperatively (for guards) and via event (for reactive UI):
- New state/refs: `isReady`, `loadProgress` (0–1, or `null` = indeterminate), `hasError`. Keep an `isReadyRef` mirror so the global closures aren't stale.
- Listeners on the `audio` element:
- `loadstart` → `isReady=false`, `progress=0`, `hasError=false`
- `loadedmetadata`/`durationchange` → record duration (enables determinate progress)
- `progress` → `progress = buffered.length ? buffered.end(buffered.length-1) / duration : 0`
- **`canplaythrough` → `isReady=true`** (chosen readiness threshold — see Decision). Fallback: also treat fully-buffered (`buffered.end(last) >= duration - 0.25`) as ready, since `canplaythrough` is unreliable in some browsers.
- `error` → `hasError=true`, `isReady=false`
- reset all on `audioUrl` change
- On any readiness change: set `window.isAudioReady = isReady` (+ `window.audioLoadProgress`) and dispatch `new CustomEvent('karaoke:audio-ready', { detail: { ready, progress } })`.
- **Guard the globals:** `seekAndPlay()` and `togglePlayback()` early-return when `!isReadyRef.current`. This neutralises the spacebar, segment buttons, and modal triggers at the source.
- **Player UI:** while `!isReady && !hasError`, replace the play button with a disabled spinner and the slider/time with a progress bar (determinate once duration known, else indeterminate) + a "Loading audio…" label. On `hasError`, show an inline error.
### Part C — Reactive bridge for consumers
New hook `lib/lyrics-review/hooks/useAudioReady.ts`:
```ts
export function useAudioReady() {
const [s, setS] = useState({ ready: false, progress: 0 })
useEffect(() => {
const sync = () => setS({ ready: !!window.isAudioReady, progress: window.audioLoadProgress ?? 0 })
sync()
const onChange = (e: Event) => setS((e as CustomEvent).detail)
window.addEventListener('karaoke:audio-ready', onChange)
return () => window.removeEventListener('karaoke:audio-ready', onChange)
}, [])
return s
}
```
Wire it into the play-button surfaces so they visually disable + show a "still loading" tooltip while `!ready`:
- `LyricsAnalyzer.handlePlaySegment` — early-return if `!window.isAudioReady` (redundant with the global guard, but lets us also disable the buttons reactively).
- Segment play buttons: `TranscriptionView.tsx`, `TimelineEditor.tsx`, `EditTimelineSection.tsx` — `disabled` + tooltip via the hook.
- `EditModal.tsx` — disable its play/sync-play buttons while `!ready`.
- Spacebar: no change needed — `window.toggleAudioPlayback` is guarded at source.
### Part D — i18n
Add new strings to `frontend/messages/en.json` (e.g. `loadingAudio`, `audioStillLoading`, `audioLoadError`) under the lyrics-review namespace, then `python frontend/scripts/translate.py --messages-dir frontend/messages --target all` (33 locales — CI enforces completeness).
## Decision (confirmed by user)
- **Readiness threshold = `canplaythrough`**: playback is only allowed once the full file is ready, so seeking anywhere is smooth and no mid-playback buffering UI is needed. The progress bar shows buffer progress until `canplaythrough` fires. Because `canplaythrough` can be unreliable across browsers, also flip to ready when the buffered range covers the full duration (fallback). Trade-off accepted: on long files / slow connections the controls stay disabled (with spinner + progress) longer.
## Files to modify / add
- `frontend/components/lyrics-review/AudioPlayer.tsx` — readiness, spinner/progress UI, guard globals, `.catch()`.
- `frontend/lib/crash-reporter.ts` — filter benign `AbortError`.
- `frontend/lib/lyrics-review/hooks/useAudioReady.ts` — **new** bridge hook.
- `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — guard `handlePlaySegment`, thread readiness.
- `frontend/components/lyrics-review/TranscriptionView.tsx`, `TimelineEditor.tsx`, `EditTimelineSection.tsx` — disable segment play buttons while loading.
- `frontend/components/lyrics-review/modals/EditModal.tsx` — disable play buttons while loading.
- `frontend/messages/en.json` (+ 32 translated locales).
## Testing strategy
- **Unit (Jest + RTL):**
- `crash-reporter` — `reportClientError` no-ops on a `DOMException('…','AbortError')`; still reports a normal `Error`.
- `AudioPlayer` — simulate `canplay`/`error` events (mock `HTMLMediaElement`), assert spinner→controls transition, `window.isAudioReady`, and that `seekAndPlay`/`togglePlayback` no-op before `canplay` and work after.
- `useAudioReady` — updates on `karaoke:audio-ready` dispatch.
- `handlePlaySegment` — does not call `window.seekAndPlayAudio` when `window.isAudioReady` is false.
- **Component:** segment buttons + EditModal play buttons render `disabled` while `!ready`.
- **E2E (Playwright, prod):** load a job review page, assert the loading spinner appears then controls enable; optionally throttle network to make the loading state observable.
- `make test` must pass before PR.
## Out of scope
- Changing how the audio URL is served / streamed (no backend changes).
- The instrumental-review and audio-editor players (already `.catch()` their `play()` calls).
@@ -0,0 +1,78 @@
# Prompt: Audit karaoke-gen for legacy "fallback" logic
**Purpose:** A lot of this codebase was written by an earlier LLM that, when
unsure what should happen in some situation, tended to invent a silent
*fallback* path rather than (a) asking the human what the desired behaviour was,
or (b) failing loudly with a clear error. These fallbacks hide bugs: the system
appears to "work" while doing the wrong thing, and the real failure only surfaces
much later (or never).
**Motivating example (2026-06-08):** A job submitted from a Facebook share URL
failed with a generic `Failed to download audio file`. The non-YouTube URL path
silently fell back to running yt-dlp *locally inside the Cloud Run container*,
which then died in a buggy `convert_to_wav` (ffmpeg given both `-y` and `-n`).
The download had actually succeeded — the fallback path was both unintended
(flacfetch was supposed to be the sole downloader) and broken. See
`docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md` (workspace root) and
the memory note `project_flacfetch_sole_downloader`. The fix deleted the
fallback rather than patching it.
## Your task
Systematically find every "fallback" in karaoke-gen, and for each one bring it to
the user (Andrew) with a crisp question about intended behaviour. Do **not**
change any behaviour without his answer — fallbacks sometimes ARE the right call
(e.g. graceful degradation of an optional feature). The goal is to make each one
an explicit, intentional decision.
### 1. Discover candidates (cast a wide net)
Search code, comments, docstrings, and docs. Suggested sweeps (run several):
- Literal: `rg -in "fallback|fall back|fall-back" backend/ karaoke_gen/ frontend/`
- Intent words near logic: `rg -in "best effort|best-effort|silently|swallow|ignore (the )?error|just in case|legacy|deprecated path|for now|TODO|HACK|workaround"`
- Defensive swallowing: `except Exception` / bare `except:` that `pass`, `return None`, `return`, or log-and-continue without re-raising.
- Silent defaults: `\.get\(.*,\s*['\"]?(unknown|default|none)` style, `or "Unknown"`, `or {}`, env-var defaults that mask misconfiguration.
- "If not configured, do X instead" branches (the most dangerous class — like the yt-dlp one).
- Try-import / optional-dependency fallbacks that change behaviour rather than failing.
Record each candidate with `file:line`, a one-line description, and which class
it falls into.
### 2. Triage each candidate
For each, classify and note evidence:
- **A — Legitimate graceful degradation** (optional feature, clearly intended, fails safe and visible). Likely keep; confirm it's logged/observable.
- **B — Silent fallback masking a bug / misconfiguration** (like the yt-dlp case). Candidate for: delete, or convert to fail-fast with a clear error.
- **C — Ambiguous** — needs the user's intent.
Don't trust comments that *say* a path is a safe fallback — verify what actually
happens when it triggers (what does the user see? does the job silently produce
wrong output?).
### 3. Interview the user
Present findings grouped by class, B and C first. For each B/C item ask a
focused question, e.g.:
> `audio_worker.py:NN` falls back to <X> when <Y>. Today that means <observable
> consequence>. Should this (a) fail loudly with a clear error, (b) keep the
> fallback but log/alert, or (c) something else?
Batch related items. Capture his answers as direct quotes in a plan doc
(`docs/archive/YYYY-MM-DD-fallback-audit-plan.md`) — he values verbatim
decisions.
### 4. Execute
Implement the agreed changes in small, reviewable PRs (one logical area each),
with tests. Prefer fail-fast + clear error messages over silent fallbacks.
Update `docs/LESSONS-LEARNED.md` with the principle and notable examples.
## Guardrails
- This is an audit, not a rewrite — minimise behaviour change until the user
decides per item.
- Some "fallbacks" are load-bearing; deleting blindly will cause incidents.
- Pay special attention to anything touching: audio/lyrics download, payment,
job state transitions, and worker triggering — silent wrong behaviour there is
most costly.
@@ -0,0 +1,264 @@
# Lyrics Auto-Correction Re-Evaluation & Design Plan
**Date:** 2026-06-10
**Branch:** `feat/sess-20260610-2332-lyrics-auto-correction`
**Status:** Research complete, design proposed, awaiting Andrew's decisions on open questions
## 1. Why we're revisiting this
Auto-correction has been attempted and abandoned multiple times over 2 years. As of
PR #321 (Jan 20, 2026), **all auto-correction is disabled** (`SKIP_CORRECTION=true`):
raw AudioShake transcription goes straight to human review, with anchor/gap analysis
still computed for reviewer guidance (anchors preserved by commits 60baca42/414606e5).
New frontier models (e.g. Claude Fable 5, released 2026-06-09) are dramatically more
capable at exactly this task shape: long-context, multilingual, audio-capable,
structured-output reasoning over messy text. The proposal: reintroduce correction as a
**fully optional, user-triggered, transparent suggestion layer in the review UI** —
never silently applied, every change individually accept/undo-able.
## 2. Why past attempts failed (evidence from git/docs history)
Three compounding killers, all documented in `docs/archive/` and LESSONS-LEARNED.md:
1. **Pipeline blocking + latency.** Agentic correction ran *inside* the job pipeline,
one LLM call per gap (10–30s × 20–74 gaps = 5–37 min). Even after optimization
(~55s/20 gaps, PR around 2026-01-08) it added minutes and required timeout
band-aids (PR #149) that silently skipped correction anyway.
2. **Net-negative accuracy.** From PR #321: *"auto-correction was creating more work
for reviewers by introducing errors that needed manual correction."* Both rule
handlers and Gemini-Flash-per-gap corrections applied changes silently, so every
wrong correction was invisible work added.
3. **Operational fragility.** Gemini 2→3 breaking changes (location=global, multimodal
response format, 2025-12-30 doc), silent hangs, Langfuse/OTEL leakage.
Key insight: **the failures were architectural, not fundamental.** Per-gap calls with
tiny context windows, applied silently, in the critical path. None of those three
properties is necessary in 2026.
## 3. Evidence from 30 real production jobs
Dataset: `/Users/andrew/Projects/nomadkaraoke/lyrics-alignment-eval-dataset/` (built
2026-05-18 from GCS for the forced-alignment eval; 30 jobs, each with
`corrections.json` = state served to review UI, `corrections_updated.json` = human
ground truth, plus `vocals.flac` stem and reference-source metadata).
Analysis script: `analyze_human_edits.py` (added this session, same dir).
### Aggregate (word-level diff, pre- vs post-human-review)
- **9,877 words total; 10.0% text-edited** — 825 replaced, 153 deleted, 13 inserted
- Median job ~7% edits; range 0.4% (Juanes) to 45% (Saetia screamo)
- **Timing-only edits are rare**: ~1% of unchanged words, excluding one full-resync
job (568d4317, 100% = global re-sync) and one partial (9229d13c, 5%)
- Reference quality predicts edit volume: jobs with best-source Jaccard ≥0.9 cluster
at low edit rates; the heavy-rewrite jobs (Saetia 0.894-but-screamo, Bathory 0.693,
Playa Fly 0.448) are where transcription hallucinated against noisy/extreme vocals
### Edit taxonomy (from sampled diffs)
| Category | Examples | Auto-correctable? |
|---|---|---|
| Sound-alike mishearings (dominant) | `glory`→`chlorine`, `ladder`→`matter`, `sell`→`sail`, `reincarnation`→`red carnation`, `Recht`→`Reich` | ✅ trivial with reference in context |
| Repeated chorus errors (same fix ×12) | `Hold it up`→`Holding out` ×12 (Parcels) | ✅ one decision, propagate |
| Contractions / inflections | `Won`→`Won't`, `burn,`→`burned,`, `I'll`→`I'd` | ✅ |
| Adlib/backing-vocal deletions | `(oh- oh- oh- oh)` deleted, `(Welcome to the camp)` deleted | ✅ with policy guidance |
| Censoring style | `Nigga,`→`N****,` | ✅ but needs explicit user-preference setting |
| Hallucinated lines (extreme vocals) | whole-line rewrites in Saetia/Bathory | ⚠️ possible with reference + audio, lower confidence |
| Non-English | German (Söhne Mannheims), French (Naika), Spanish (Juanes) | ✅ modern models are strongly multilingual |
| Full re-sync | Playa Fly timing offset | ❌ out of scope — keep tap-to-sync |
**Context size check:** a 78-segment song + 3 reference sources ≈ 10KB compact text
≈ 3K tokens. Whole-song single-call correction is trivially cheap (cents) and fast
(one ~10–30s call) vs the old 74-sequential-calls design.
## 4. Proposed approach: opt-in "AI Suggest" in the review UI
### Product shape
- A button in the lyrics review screen (e.g. in Header or above TranscriptionView):
**"Suggest corrections (AI)"**. Nothing runs unless clicked. Zero change to the
default journey.
- On click: backend endpoint makes **one whole-song LLM call** with: compact
transcription (segments + words, ids preserved), all reference lyrics, anchor/gap
annotations, artist/title, and explicit conservative instructions (only suggest
when audio-plausible AND reference-supported; never invent).
- Response: list of proposed changes in `WordCorrection` shape (word_id-keyed,
with `reason`, `confidence`, `source`).
- **Suggestions are a pending layer** — `corrected_segments` is NOT mutated until
the user accepts. UI shows each suggestion inline (reuse the existing
`CorrectedWordWithActions` accept/revert/edit/detail affordance + correction
tooltips + `CorrectionDetailCard`), plus a summary bar: "23 suggestions —
Accept all / Reject all / step through".
- Every accept/reject lands in the existing **history stack** (undo works) and
**EditLog** (`operation: 'ai_suggestion_accept' | 'ai_suggestion_reject'`),
which doubles as labeled training/eval data accruing from day one.
### Why this fixes each historical killer
| Past killer | This design |
|---|---|
| Pipeline blocking/latency | On-demand in review UI; user watches a progress state for one call; job pipeline untouched |
| Silently introduced errors | Nothing applied without explicit accept; wrong suggestions cost one click, not invisible rework |
| Per-gap myopia | Whole-song context: chorus repetition, reference alignment, song-level consistency in one shot |
| Provider fragility | Single thin endpoint, structured output, easy to swap models; failure = "no suggestions", never a stuck job |
| No trust measurement | Accept-rate per suggestion category measured from EditLog; promotion to default someday is a data decision |
### Architecture sketch
1. **Backend** — `POST /api/review/{job_id}/auto-correct` (follows the
custom-lyrics endpoint pattern, `backend/api/routes/review.py`). Loads current
correction data (or accepts the client's current working state in the request
body so it reflects in-session edits), builds compact prompt, calls model,
validates word_ids, returns `{suggestions: WordCorrection[], model, warnings}`.
2. **Frontend** — new state in `LyricsAnalyzer`: `pendingSuggestions`. Word
rendering already supports correction highlighting; generalize the
`handler === 'AgenticCorrector'` gate in `HighlightedText.tsx` (lines ~200, ~301)
to a pending-suggestion check. Add summary/navigation bar (pattern:
`GapNavigator`).
3. **Model layer** — reuse `correction/agentic/providers/` LangChain bridge
(already supports Vertex Gemini, Anthropic, OpenAI, Ollama) or a simpler direct
client; structured output schema = list of word-id-keyed operations
(replace/delete/insert-after, new text, reason, confidence).
4. **Eval harness (build FIRST)** — script over the 30-job dataset: feed
`corrections.json`, generate suggestions, score against the human diff from
`corrections_updated.json`. Metrics: **precision** (would the human have made
this change?) and **recall** (% of human edits reproduced). Precision is the
north star — a low-recall/high-precision assistant is still a big win; the
reverse destroys trust (that's what happened before).
### Phasing
- **Phase 0:** Eval harness + prompt iteration offline against the 30-job dataset.
Compare models (Fable 5 / Opus 4.8 / Gemini) and prompt variants. Gate: precision
target agreed with Andrew (suggest ≥90% before shipping even as opt-in).
- **Phase 1:** Backend endpoint + minimal UI (button → suggestions → accept/reject
individually + accept-all). Ship to prod behind the button (it IS the flag).
- **Phase 2:** UX polish: category grouping (mishearings / deletions / formatting),
propagate-identical-fix grouping, per-suggestion audio play button (segment
playback already exists).
- **Phase 3 (experiment):** attach vocals stem audio for low-confidence gaps —
models now accept audio input; dataset already has `vocals.flac` per job to eval
this offline.
- **Someday:** auto-apply-by-default, only when prod accept-rate data earns it.
## 4b. Phase 0 results (2026-06-11): 5-model eval over all 30 jobs
Harness: `lyrics-alignment-eval-dataset/auto-correct-eval/harness.py`; results in
`auto-correct-eval/results/*.json`. One whole-song call per job; suggestions
scored against the human ground-truth diff. *Strict* = same span + same
normalized text as the human edit; *region* = touches a span the human also
edited; *gap_closed* = how much of the pre→truth distance accept-all closes.
| model | prec strict | prec region | recall strict | recall region | mean gap closed | median gap | harmful jobs | median latency |
|---|---|---|---|---|---|---|---|---|
| claude-fable-5 | **0.615** | 0.862 | **0.511** | 0.696 | **+0.505** | +0.77 | 2 | 27s |
| claude-opus-4-8 | **0.627** | **0.897** | 0.336 | 0.466 | +0.475 | +0.58 | 2 | 29s |
| gemini-3.1-pro-preview | 0.556 | 0.860 | 0.464 | 0.717 | +0.499 | +0.67 | 3 | 35s |
| gpt-5.5 | 0.442 | 0.832 | 0.357 | **0.726** | +0.502 | **+0.80** | 2 | 63s |
| claude-sonnet-4-6 | 0.209 | 0.710 | 0.174 | 0.632 | +0.091 | +0.34 | 4 | 14s |
| gpt-5.2 | 0.153 | 0.603 | 0.138 | 0.587 | **−0.796** | +0.24 | 11 | 11s |
Notes:
- GPT-5.5 (added after the first pass — it wasn't visible to the original
API key's project) lands in the top tier on outcome quality (best median
gap-closed, best region recall) but with the lowest strict precision of
the tier and ~2× the latency (median 63s). GPT-5.2 actively damages
lyrics in accept-all simulation — it would have repeated the 2025 failure.
Sonnet 4.6 is also below the bar. **Fable 5, Opus 4.8, Gemini 3.1 Pro and
GPT-5.5 are the viable tier**; the default-model decision below is
unchanged by the GPT-5.5 result (slower, less precise, new billing
surface). gpt-5.5-pro requires the OpenAI Responses API and wasn't
evaluated.
- "Harmful jobs" are almost all near-perfect transcriptions (e.g. Townes Van
Zandt: 1 human edit in 198 words) where the model proposes
reference-supported style tweaks (`all right`→`alright`, adding a leading
"And") that the human didn't bother making — mostly acceptable-or-one-click
suggestions, not hallucinations. Strict precision therefore *underestimates*
real-world accept rate; prod accept-rate from the EditLog is the metric that
matters.
- Confidence is well calibrated (style tweaks 0.55–0.6, real fixes 0.8+), so
the min-confidence knob meaningfully trades recall for precision.
- Cost ≈ $0.05–0.18/job depending on model. Latency 27–35s for the top tier.
**Decision: v1 default `AUTO_CORRECT_MODEL=gemini-3.1-pro-preview`** — within
noise of Fable 5 on gap-closed (0.499 vs 0.505), best region recall, already
served via Vertex AI in this GCP project (same path as custom-lyrics), no new
secret/billing surface. Fable 5 is the quality ceiling (best strict
recall/balance); switching is a one-env-var change and worth revisiting once
prod accept-rate data exists or if an Anthropic key is added to Secret Manager.
## 4c. Decisions captured from Andrew (2026-06-11)
1. **Models**: test Fable 5 + a cheaper Claude + latest GPT + latest Gemini Pro
— done (table above).
2. **Scope**: text-only v1 agreed. Later: simple *heuristics* (not LLM) for
timing pathologies — e.g. AudioShake leaving an unrealistically long last
word on a segment, or transcribing a 10+ second instrumental as one long
"And"/"But". Future work.
3. **Knobs**: user-facing with sensible defaults → implemented
(adlib-removal toggle, insertions toggle, confidence filter).
4. **No-reference songs**: button disabled with explanation (backend also 422s).
Future experiment (separate plan doc someday): enrich context via audio
analysis (genre/theme/key/energy), music-matching APIs and web research to
review transcriptions without references.
5. **Precision gate**: "depends how you measure" — strict precision is the
conservative floor (0.56–0.63 for the top tier), region precision 0.86–0.90.
Shipped as fully opt-in suggestions; prod accept-rate from EditLog
(`ai_suggestion_accept`/`reject` entries) becomes the real gate for any
future default-on behaviour.
## 4d. Follow-up shipped (2026-06-11, v0.178.0): Fable default + multi-model compare
Per Andrew's decisions after v0.177.0 shipped:
- **Default model switched to Claude Fable 5** (`AUTO_CORRECT_MODEL=claude-fable-5`
in the Cloud Run deploy). Anthropic provider path added to the service
(Anthropic API, structured outputs, adaptive thinking — same configuration
the eval used). Key lives in the `anthropic-api-key` secret (container
Pulumi-managed in `infrastructure/modules/secrets.py`, value added manually).
- **Multi-model compare mode** (Andrew's idea): `compare_models` setting
queries all of `AUTO_CORRECT_COMPARE_MODELS` (prod: Fable 5 + Gemini 3.1
Pro) in parallel, dedupes identical suggestions with a consensus count
(e.g. "2/2 models"), and groups conflicting overlapping suggestions —
accepting one variant rejects its siblings; accept-all picks the
highest-consensus variant per group. Partial model failures degrade to
warnings; all-fail → 502.
- **Gotcha for posterity**: the google-genai SDK mutates `response_schema`
dicts in place (injects `property_ordering`), which the Anthropic API
rejects — schemas must be deep-copied per provider call. Caught by the
real-call smoke test, now covered by a regression test.
## 5. Open questions for Andrew
1. **Model:** start with Claude Fable 5 (best reasoning, audio-capable) via the
existing Anthropic provider, or stay all-Google (Vertex Gemini 3) for billing
consolidation? Eval harness can score both — recommend deciding on data.
2. **Suggestion scope v1:** text-only (replace/delete/insert)? Timing edits are
~1% of human work and risky — recommend excluding from v1.
3. **Policy knobs:** adlib deletion and censoring are taste decisions — bake into
prompt defaults, or expose as settings like `CustomLyricsSettings` does
(allow_reword/strictness pattern)?
4. **No-reference behavior:** when no internet source matched (custom/niche songs),
suggestions are audio-only guesses — disable the button, or allow with a
warning?
5. **Precision gate:** what offline precision threshold before Phase 1 ships?
## 6. Key file references
- Correction types & pipeline: `karaoke_gen/lyrics_transcriber/types.py`
(`Word`, `LyricsSegment`, `WordCorrection`, `AnchorSequence`, `GapSequence`,
`CorrectionResult`), `correction/corrector.py`, `correction/anchor_sequence.py`
- Old agentic system (reusable provider layer): `correction/agentic/`
- Review API: `backend/api/routes/review.py` (`correction-data`, `complete`,
`custom-lyrics/generate` — the pattern to follow)
- Review UI: `frontend/components/lyrics-review/LyricsAnalyzer.tsx` (history/undo,
EditLog), `shared/HighlightedText.tsx`, `CorrectedWordWithActions.tsx`,
`CorrectionDetailCard.tsx`, `GapNavigator.tsx`,
`modals/CustomLyricsMode.tsx` (closest end-to-end LLM feature pattern)
- Frontend types: `frontend/lib/lyrics-review/types.ts`
- Eval dataset: `/Users/andrew/Projects/nomadkaraoke/lyrics-alignment-eval-dataset/`
(30 jobs; `analyze_human_edits.py` for the human-edit ground-truth diff)
- History: `docs/archive/2025-12-30-gemini3-agentic-correction-fix.md`,
`docs/archive/2025-12-31-agentic-timeout-implementation.md`,
`docs/archive/2026-01-08-performance-investigation.md`, PR #321 (disable), PR #149
(timeouts), PR #738 (custom lyrics LLM mode)
@@ -0,0 +1,160 @@
# Review-Phase Word-Timing Validation & Sanitization — Design
**Date:** 2026-06-10
**Status:** Approved (brainstorming) → ready for implementation plan
**Worktree:** `karaoke-gen-review-timing-validation` (`feat/sess-20260610-2307-review-timing-validation`)
## Background
Job `17f7c313` ("Atmosphere - Scalp") rendered two screens of lyrics overlapping. Root
cause: the segment `"A whiskey and a beer, let's forget where we are"` (segment bounds a
correct `15.18–18.04`) had its 4 leading words ("A whiskey and a") carrying invalid
timestamps `start=0.0, end=-0.005`. When the resizer split that line, the new line
inherited `start_time=0.0`, which mis-sorted the lyric screen ahead of the INTRO section
and stacked two screens.
We shipped a **render-time** safety net (`SegmentResizer._sanitize_segment_timings`,
v0.176.2, PR #804) that clamps invalid word timings into segment bounds while building the
ASS. That stops the visual overlap but does **not** fix the source: the bad data is created
and persisted during the lyrics review phase.
### Verified origin (not AudioShake)
- Base `corrections.json` (lyrics phase output) had **valid** timings for these words; 0
corrections touched them.
- The `-0.005` value is the unique fingerprint of `frontend/hooks/useManualSync.ts`
(`previousWord.end_time = currentStartTime - 0.005`, plus `currentWord.start_time =
currentTimeRef.current`).
- So the **manual-sync ("tap-to-time") tool** assigned `start=0` (words synced while the
audio playhead sat at 0) and cascaded `end = 0 - 0.005`. Manual-sync timing edits are not
recorded in the edit log (which only logs text ops), which is why the segment looked
untouched.
- Symptom the operator hit: opening that segment in the editor modal was buggy with the
0/`-0.005` values; they had to type timestamps in by hand before they could drag-adjust.
## Goal
Prevent invalid word timings from being **created** or **persisted** during review, while
keeping the editing experience flexible — specifically, the operator must still be able to
make a segment start earlier / end later easily. Render-time sanitization remains as the
last-resort net.
## Core invariant (one definition, four enforcement points)
A segment's word timings are **valid** iff, for every word:
```
segment.start_time ≤ word.start_time ≤ word.end_time ≤ segment.end_time
and words are non-decreasing in start_time across the segment
and all times are finite and ≥ 0
```
This is the same invariant the shipped render-time clamp enforces. We mirror it earlier.
### The key reconciliation: clamping is operation-specific, not global
The invariant holds **at rest** (after every save). The operator is never "trapped" by it
because the way you extend a segment is to edit a word, and **word edits expand the segment
to fit** rather than clamping the word back:
| Operation | Behavior |
|---|---|
| Drag / type a word's start earlier (or end later) in the modal | **Segment bounds auto-expand** to contain the new word time. This *is* the "make the segment start earlier / end later" control. No clamp. |
| Manual-sync tap (`useManualSync`) | Tap time is **clamped** to the segment's current audio window `[start, end]` (a tap outside is a sync glitch, the root cause). Warn if clamped. |
| Modal opens a segment containing pre-existing out-of-bounds / broken values | **Repair on open**: clamp offending words into the loaded segment bounds / fix `end<start`/negative, show a non-blocking banner. Restores a sane editing surface. |
| Backend save (`POST /corrections`) | **Sanitize** the submitted corrections to the invariant before persisting to GCS; `logger.warning` a summary. Belt-and-suspenders for any frontend gap. |
Because user edits expand the segment *before* save, legitimate extensions are within
bounds at submit time and are never clamped — only true glitches (a word at 0 in a 15 s
segment) get repaired.
UX philosophy (operator-confirmed): **clamp/repair + non-blocking warn**, never silently and
never blocking the save.
## Components
### Shared sanitizer (one canonical implementation per language)
- **Frontend:** `frontend/lib/lyrics-review/sanitizeWordTimings.ts`
- `sanitizeSegmentTimings(segment): { segment, changes: TimingChange[] }`
- Pure function. Returns the corrected segment plus a list of what changed (word id, field,
from, to) so callers can render warnings. Valid input returns `changes: []` and an
unchanged segment (referential no-op where possible).
- Also exports `expandSegmentToWords(segment)` (grow `start_time`/`end_time` to the
min/max of word times) used by the modal's edit handlers.
- **Backend:** reuse / co-locate with the existing
`SegmentResizer._sanitize_segment_timings` logic so render and submit share one definition.
Expose a thin `sanitize_corrections(corrections: dict) -> (dict, summary)` helper for the
route to call.
### Layer 1 — Manual-sync guard (`frontend/hooks/useManualSync.ts`)
- Clamp the synced `start_time` (and the derived previous-word `end_time`) into the
segment's current `[start_time, end_time]` window in both the `handleKeyDown` tap path
(~L120-155) and the `handleTap` path (~L285-316).
- Keep `end ≥ start` and non-decreasing ordering.
- If a clamp changed a value, surface a non-blocking toast (e.g. *"'A whiskey' timing was
outside the segment — snapped to 15.18s"*).
### Layer 2 — Edit-segment modal (`frontend/components/lyrics-review/modals/EditModal.tsx` + word list / `TimeInput`)
- **Sanitize-on-open:** when `editedSegment` initializes from the incoming segment, run
`sanitizeSegmentTimings`; if it changed anything, show a dismissible warning banner listing
affected words. The segment now opens with sane values so the timeline/drag editor works.
- **Segment-follows-words on edit:** word edit handlers (`handleWordChange`, drag handles,
`handleAddWord`, `splitWordWithTiming`) call `expandSegmentToWords` so editing a word's
start earlier / end later grows the segment rather than being clamped. Replace the fragile
`?? 0` fallbacks.
- **Robust inputs:** `TimeInput` and the timeline drag math tolerate `null`/`0`/inverted
values without NaN, off-canvas blocks, or unclickable handles.
### Layer 3 — Backend safety net (`backend/api/routes/jobs.py::submit_corrections`, POST `/{job_id}/corrections`)
- Before `storage.upload_json(corrections_updated.json, ...)`, run `sanitize_corrections`
over `submission.corrections['corrected_segments']`.
- Clamp words outside their segment bounds, fix `end<start`/negative, persist the cleaned
payload. `logger.warning` with job id + count + a sample. Non-blocking (the save succeeds).
- `complete-review` renders from this saved file, so this guarantees clean stored data.
## Data flow
```
Manual sync tap ─clamp→ word times (within segment) ─┐
Modal word edit ─expand segment→ word times ─────────┤→ EditModal state
Modal open (bad data) ─repair+banner→ ───────────────┘
│ POST /corrections (submission.corrections)
▼
submit_corrections ─sanitize+log→ corrections_updated.json (GCS)
│ complete-review → render worker
▼
OutputGenerator → SegmentResizer._sanitize_segment_timings (last-resort net, already shipped)
```
## Testing
- **Frontend (Jest):**
- `sanitizeWordTimings`: the exact `17f7c313` fixture ("A whiskey and a" at `0/-0.005`,
segment `15.18–18.04`) → words clamped into bounds, `end≥start`, non-decreasing; valid
input untouched (`changes: []`); `expandSegmentToWords` grows bounds for a deliberate
out-of-bounds edit.
- `useManualSync`: a tap at playhead 0 clamps to segment start and reports a change.
- `EditModal`: opening a segment with the bad fixture shows the banner and renders
sane values; dragging a word's start before `segment.start` expands the segment.
- **Backend (pytest):**
- `submit_corrections` clamps out-of-bounds words before upload and logs; a valid payload
passes through byte-for-byte; segment-expanded (legitimately extended) payloads are not
clamped.
- **Regression anchor:** the `17f7c313` shape is the shared fixture across all layers.
## Scope guardrails (YAGNI)
- No backfill of existing jobs — the render-time net already protects them.
- No change to the `complete-review` flow.
- No new "timing health" UI beyond the inline toast/banner.
- i18n: new warning strings go in `frontend/messages/en.json` and run through
`translate.py --target all` (CI enforces locale completeness).
## Out of scope / follow-ups
- Investigating *why* the manual-sync playhead can be at 0 when a tap arrives (a deeper
interaction fix) — the clamp makes it harmless regardless; revisit only if it recurs.
@@ -0,0 +1,645 @@
# Review-Phase Word-Timing Validation Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Prevent invalid word timings (the `start=0`/`end=-0.005` class that caused job `17f7c313`'s overlapping lyrics) from being created or persisted during lyrics review, while keeping segment editing flexible.
**Architecture:** One invariant — every word within its segment's `[start_time, end_time]`, `end ≥ start ≥ 0`, non-decreasing — enforced at four points: manual-sync (clamp taps, source prevention), modal-open (repair + warn), backend submit (sanitize + log), and the already-shipped render-time net. The modal already derives segment bounds from word `min/max` (`updateSegment`), so dragging a word earlier/later expands the segment naturally; that's why "word outside saved bounds" reliably means corruption, not a legit edit.
**Tech Stack:** Frontend TypeScript/React + Jest (`frontend/`); backend Python/FastAPI + pytest (`backend/`); i18n via next-intl + `translate.py`.
**Design doc:** `docs/archive/2026-06-10-review-timing-validation-design.md`
---
## File Structure
- Create `frontend/lib/lyrics-review/sanitizeWordTimings.ts` — pure sanitizer + change report (frontend canonical).
- Create `frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts` — unit tests.
- Modify `frontend/hooks/useManualSync.ts` — clamp synced times to segment bounds (Layer 1).
- Create `frontend/hooks/__tests__/useManualSync.test.ts` — sync clamp test.
- Modify `frontend/components/lyrics-review/modals/EditModal.tsx` — sanitize-on-open + warning banner (Layer 2).
- Modify `frontend/components/lyrics-review/__tests__/EditModal.test.tsx` (create if absent) — open-repair test.
- Create `backend/services/timing_sanitizer.py` — dict-level sanitizer (backend canonical).
- Create `tests/unit/services/test_timing_sanitizer.py` — unit tests.
- Modify `backend/api/routes/jobs.py` (`submit_corrections`, ~L1076-1117) — call sanitizer before GCS upload (Layer 3).
- Modify `tests/unit/api/routes/test_jobs_corrections.py` (create if absent) — submit sanitize test.
- Modify `frontend/messages/en.json` — warning strings; then `translate.py --target all`.
---
## Task 1: Frontend sanitizer (`sanitizeWordTimings.ts`)
**Files:**
- Create: `frontend/lib/lyrics-review/sanitizeWordTimings.ts`
- Test: `frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts
import { sanitizeSegmentTimings } from '../sanitizeWordTimings'
import { LyricsSegment } from '../types'
// The exact shape that broke job 17f7c313.
function scalpSegment(): LyricsSegment {
return {
id: 's1',
text: 'A whiskey and a beer, ...',
start_time: 15.18,
end_time: 18.04,
words: [
{ id: 'a', text: 'A', start_time: 0, end_time: -0.005 },
{ id: 'b', text: 'whiskey', start_time: 0, end_time: -0.005 },
{ id: 'c', text: 'and', start_time: 0, end_time: 0 },
{ id: 'd', text: 'a', start_time: 0, end_time: 0 },
{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 },
],
}
}
describe('sanitizeSegmentTimings', () => {
it('clamps out-of-bounds leading words into the segment window', () => {
const { segment, changes } = sanitizeSegmentTimings(scalpSegment())
for (const w of segment.words) {
expect(w.start_time!).toBeGreaterThanOrEqual(15.18)
expect(w.end_time!).toBeGreaterThanOrEqual(w.start_time!)
expect(w.end_time!).toBeLessThanOrEqual(18.04 + 1e-9)
}
expect(changes.length).toBeGreaterThan(0)
expect(changes.some((c) => c.wordId === 'a')).toBe(true)
})
it('leaves already-valid segments untouched and reports no changes', () => {
const seg: LyricsSegment = {
id: 's', text: 'Filling up that cup', start_time: 21.4, end_time: 22.78,
words: [
{ id: 'w0', text: 'Filling', start_time: 21.4, end_time: 21.82 },
{ id: 'w1', text: 'up', start_time: 21.86, end_time: 22.1 },
{ id: 'w2', text: 'that', start_time: 22.14, end_time: 22.42 },
{ id: 'w3', text: 'cup', start_time: 22.46, end_time: 22.78 },
],
}
const { changes } = sanitizeSegmentTimings(seg)
expect(changes).toEqual([])
})
it('handles null word timings by clamping to the segment start', () => {
const seg: LyricsSegment = {
id: 's', text: 'x y', start_time: 5, end_time: 6,
words: [
{ id: 'w0', text: 'x', start_time: null, end_time: null },
{ id: 'w1', text: 'y', start_time: 5.5, end_time: 6 },
],
}
const { segment } = sanitizeSegmentTimings(seg)
expect(segment.words[0].start_time!).toBeGreaterThanOrEqual(5)
expect(segment.words[0].end_time!).toBeGreaterThanOrEqual(segment.words[0].start_time!)
})
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd frontend && npx jest lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts`
Expected: FAIL — `Cannot find module '../sanitizeWordTimings'`.
- [ ] **Step 3: Write minimal implementation**
```typescript
// frontend/lib/lyrics-review/sanitizeWordTimings.ts
import { LyricsSegment, Word } from './types'
export interface TimingChange {
wordId: string
wordText: string
field: 'start_time' | 'end_time'
from: number | null
to: number
}
/**
* Enforce the timing invariant for one segment:
* segment.start <= word.start <= word.end <= segment.end, non-decreasing, finite, >= 0.
*
* The segment's own start/end are treated as the authoritative window. Because the
* editor derives segment bounds from word min/max on every edit (updateSegment), a word
* outside the segment window only happens via corruption (e.g. a manual-sync glitch),
* never via a legitimate extension. Returns a NEW segment plus the list of clamps applied
* so callers can warn. A clean segment returns the same word objects and changes: [].
*/
export function sanitizeSegmentTimings(segment: LyricsSegment): {
segment: LyricsSegment
changes: TimingChange[]
} {
const changes: TimingChange[] = []
const segStart = isFiniteNumber(segment.start_time) ? (segment.start_time as number) : 0
const segEndRaw = isFiniteNumber(segment.end_time) ? (segment.end_time as number) : segStart
const segEnd = Math.max(segEndRaw, segStart)
let prevEnd = segStart
const words: Word[] = segment.words.map((w) => {
const clamp = (v: number) => Math.min(Math.max(v, segStart), segEnd)
let start = isFiniteNumber(w.start_time) ? (w.start_time as number) : null
let end = isFiniteNumber(w.end_time) ? (w.end_time as number) : null
// start: must be finite, within [prevEnd-clamped-to-window, segEnd]
const wantStart = start === null ? prevEnd : start
const newStart = clamp(Math.max(wantStart, segStart))
// end: must be finite and >= start, within window
const wantEnd = end === null ? newStart : end
const newEnd = clamp(Math.max(wantEnd, newStart))
let next = w
if (newStart !== start) {
changes.push({ wordId: w.id, wordText: w.text, field: 'start_time', from: w.start_time, to: newStart })
next = { ...next, start_time: newStart }
}
if (newEnd !== end) {
changes.push({ wordId: w.id, wordText: w.text, field: 'end_time', from: w.end_time, to: newEnd })
next = { ...next, end_time: newEnd }
}
prevEnd = newEnd
return next
})
if (changes.length === 0) return { segment, changes }
return { segment: { ...segment, words }, changes }
}
function isFiniteNumber(v: number | null | undefined): boolean {
return typeof v === 'number' && Number.isFinite(v)
}
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd frontend && npx jest lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts`
Expected: PASS (3 tests).
- [ ] **Step 5: Commit**
```bash
git add frontend/lib/lyrics-review/sanitizeWordTimings.ts frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts
git commit -m "feat(lyrics-review): add word-timing sanitizer with change report"
```
---
## Task 2: Manual-sync clamp (Layer 1, source prevention)
**Files:**
- Modify: `frontend/hooks/useManualSync.ts` (the `handleKeyDown` tap path ~L120-155 and `handleTap` path ~L283-316)
- Test: `frontend/hooks/__tests__/useManualSync.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// frontend/hooks/__tests__/useManualSync.test.ts
import { clampSyncTime } from '../useManualSync'
describe('clampSyncTime', () => {
it('clamps a playhead-at-0 tap up to the segment start', () => {
expect(clampSyncTime(0, 15.18, 18.04)).toBe(15.18)
})
it('clamps a tap past the segment end down to the end', () => {
expect(clampSyncTime(99, 15.18, 18.04)).toBe(18.04)
})
it('leaves an in-window tap unchanged', () => {
expect(clampSyncTime(16.0, 15.18, 18.04)).toBe(16.0)
})
it('falls back gracefully when segment bounds are null', () => {
expect(clampSyncTime(5, null, null)).toBe(5)
})
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd frontend && npx jest hooks/__tests__/useManualSync.test.ts`
Expected: FAIL — `clampSyncTime` is not exported.
- [ ] **Step 3: Add the helper and apply it in both sync paths**
Add this exported helper near the top of `frontend/hooks/useManualSync.ts` (after the constants block, ~L16):
```typescript
/**
* Clamp a manual-sync tap time into the segment's audio window. A tap should always land
* within the segment being synced; a value outside (e.g. the playhead sitting at 0) is a
* sync glitch — the source of the start=0/end=-0.005 corruption. Null bounds => no clamp.
*/
export function clampSyncTime(
time: number,
segStart: number | null,
segEnd: number | null
): number {
let t = time
if (typeof segStart === 'number' && Number.isFinite(segStart)) t = Math.max(t, segStart)
if (typeof segEnd === 'number' && Number.isFinite(segEnd)) t = Math.min(t, segEnd)
return t
}
```
In the `handleKeyDown` path, replace (~L123):
```typescript
const currentStartTime = currentTimeRef.current
```
with:
```typescript
const rawStartTime = currentTimeRef.current
const currentStartTime = clampSyncTime(
rawStartTime,
editedSegment?.start_time ?? null,
editedSegment?.end_time ?? null
)
if (currentStartTime !== rawStartTime) {
onTimingClamped?.(newWords[syncWordIndex]?.text ?? '', currentStartTime)
}
```
Apply the identical change in the `handleTap` path (~L286), reusing `clampSyncTime` and `onTimingClamped`.
Add `onTimingClamped?: (wordText: string, snappedTo: number) => void` to `UseManualSyncProps` (after `updateSegment`, ~L10) and destructure it in the hook signature (~L22). The previous-word `end_time = currentStartTime - 0.005` lines (~L144/L305) now operate on the clamped `currentStartTime`, so they can no longer produce negative values.
- [ ] **Step 4: Run test to verify it passes**
Run: `cd frontend && npx jest hooks/__tests__/useManualSync.test.ts`
Expected: PASS (4 tests).
- [ ] **Step 5: Commit**
```bash
git add frontend/hooks/useManualSync.ts frontend/hooks/__tests__/useManualSync.test.ts
git commit -m "fix(lyrics-review): clamp manual-sync taps to segment bounds (root cause of start=0)"
```
---
## Task 3: Modal sanitize-on-open + warning banner (Layer 2)
**Files:**
- Modify: `frontend/components/lyrics-review/modals/EditModal.tsx` (~L58, L67-69, render)
- Test: `frontend/components/lyrics-review/__tests__/EditModal.test.tsx` (create if absent)
- [ ] **Step 1: Write the failing test**
```tsx
// frontend/components/lyrics-review/__tests__/EditModal.test.tsx
import { render, screen } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import EditModal from '../modals/EditModal'
import en from '@/messages/en.json'
import { LyricsSegment } from '@/lib/lyrics-review/types'
const badSegment: LyricsSegment = {
id: 's1', text: 'A whiskey and a beer,', start_time: 15.18, end_time: 18.04,
words: [
{ id: 'a', text: 'A', start_time: 0, end_time: -0.005 },
{ id: 'b', text: 'whiskey', start_time: 0, end_time: -0.005 },
{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 },
],
}
function renderModal(segment: LyricsSegment) {
return render(
<NextIntlClientProvider locale="en" messages={en}>
<EditModal open segment={segment} segmentIndex={0} originalSegment={null}
onClose={() => {}} onSave={() => {}} />
</NextIntlClientProvider>
)
}
it('shows the timing-repaired banner when a segment opens with out-of-bounds words', () => {
renderModal(badSegment)
expect(screen.getByTestId('timing-sanitized-banner')).toBeInTheDocument()
})
it('shows no banner for a clean segment', () => {
renderModal({ ...badSegment, words: [{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 }] })
expect(screen.queryByTestId('timing-sanitized-banner')).not.toBeInTheDocument()
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd frontend && npx jest components/lyrics-review/__tests__/EditModal.test.tsx`
Expected: FAIL — no `timing-sanitized-banner` test id.
- [ ] **Step 3: Sanitize on open and render the banner**
In `EditModal.tsx`, add the import (after L15):
```typescript
import { sanitizeSegmentTimings } from '@/lib/lyrics-review/sanitizeWordTimings'
```
Add banner state (after L59 `const [isPlaying, ...]`):
```typescript
const [timingFixCount, setTimingFixCount] = useState(0)
```
Replace the segment-init effect (L67-69):
```typescript
useEffect(() => {
if (!segment) {
setEditedSegment(null)
setTimingFixCount(0)
return
}
const { segment: cleaned, changes } = sanitizeSegmentTimings(segment)
setEditedSegment(cleaned)
setTimingFixCount(changes.length)
}, [segment])
```
Render the banner at the top of the modal body (inside `<DialogContent>`, before the word list). Use the namespace already loaded at L54 (`t = useTranslations('lyricsReview.modals.editAll')`):
```tsx
{timingFixCount > 0 && (
<div
data-testid="timing-sanitized-banner"
className="mb-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800"
>
{t('timingSanitized', { count: timingFixCount })}
</div>
)}
```
Pass the clamp callback to the manual-sync hook (at the `useManualSync({...})` call, ~L110-115) so sync clamps also surface a toast — add `onTimingClamped` there:
```typescript
onTimingClamped: (wordText: string, snappedTo: number) => {
toast.warning(t('timingClamped', { word: wordText, time: snappedTo.toFixed(2) }))
},
```
Add the sonner import at top (after L7): `import { toast } from 'sonner'`.
- [ ] **Step 4: Add i18n strings**
In `frontend/messages/en.json`, under `lyricsReview.modals.editAll`, add:
```json
"timingSanitized": "Fixed {count} word timing(s) that fell outside this segment.",
"timingClamped": "\"{word}\" timing was outside the segment — snapped to {time}s."
```
- [ ] **Step 5: Run test to verify it passes**
Run: `cd frontend && npx jest components/lyrics-review/__tests__/EditModal.test.tsx`
Expected: PASS (2 tests).
- [ ] **Step 6: Commit**
```bash
git add frontend/components/lyrics-review/modals/EditModal.tsx frontend/components/lyrics-review/__tests__/EditModal.test.tsx frontend/messages/en.json
git commit -m "feat(lyrics-review): repair invalid word timings on segment-edit open with a warning banner"
```
---
## Task 4: Backend sanitizer + submit integration (Layer 3)
**Files:**
- Create: `backend/services/timing_sanitizer.py`
- Test: `tests/unit/services/test_timing_sanitizer.py`
- Modify: `backend/api/routes/jobs.py` (`submit_corrections`, ~L1110-1117)
- [ ] **Step 1: Write the failing test**
```python
# tests/unit/services/test_timing_sanitizer.py
from backend.services.timing_sanitizer import sanitize_corrections
def _scalp_corrections():
return {
"corrected_segments": [
{
"id": "s1",
"text": "A whiskey and a beer,",
"start_time": 15.18,
"end_time": 18.04,
"words": [
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
],
}
]
}
def test_clamps_out_of_bounds_words():
cleaned, count = sanitize_corrections(_scalp_corrections())
words = cleaned["corrected_segments"][0]["words"]
for w in words:
assert w["start_time"] >= 15.18
assert w["end_time"] >= w["start_time"]
assert w["end_time"] <= 18.04 + 1e-9
assert count >= 4
def test_valid_corrections_unchanged():
payload = {
"corrected_segments": [
{
"id": "s", "text": "Filling up", "start_time": 21.4, "end_time": 22.1,
"words": [
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
],
}
]
}
cleaned, count = sanitize_corrections(payload)
assert count == 0
assert cleaned == payload
def test_missing_segments_key_is_noop():
cleaned, count = sanitize_corrections({"foo": "bar"})
assert count == 0
assert cleaned == {"foo": "bar"}
```
- [ ] **Step 2: Run test to verify it fails**
Run (from the repo root): `python -m pytest tests/unit/services/test_timing_sanitizer.py -q`
Expected: FAIL — `ModuleNotFoundError: backend.services.timing_sanitizer`.
- [ ] **Step 3: Write the sanitizer (dict-level, mirrors the frontend invariant and SegmentResizer._sanitize_segment_timings)**
```python
# backend/services/timing_sanitizer.py
"""Sanitize submitted review corrections so word timings stay within their segment.
Mirrors the frontend sanitizeWordTimings.ts and the render-time
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
segment window or is inverted/negative. Returns (cleaned_dict, num_clamps)."""
from __future__ import annotations
import math
from typing import Any, Dict, Tuple
def _finite(v: Any) -> bool:
return isinstance(v, (int, float)) and math.isfinite(v)
def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
segments = corrections.get("corrected_segments")
if not isinstance(segments, list):
return corrections, 0
changes = 0
for seg in segments:
if not isinstance(seg, dict):
continue
seg_start = seg.get("start_time")
seg_end = seg.get("end_time")
seg_start = seg_start if _finite(seg_start) else 0.0
seg_end = seg_end if _finite(seg_end) else seg_start
seg_end = max(seg_end, seg_start)
prev_end = seg_start
for w in seg.get("words", []):
if not isinstance(w, dict):
continue
start = w.get("start_time")
end = w.get("end_time")
want_start = start if _finite(start) else prev_end
new_start = min(max(want_start, seg_start), seg_end)
want_end = end if _finite(end) else new_start
new_end = min(max(want_end, new_start), seg_end)
if new_start != start:
w["start_time"] = new_start
changes += 1
if new_end != end:
w["end_time"] = new_end
changes += 1
prev_end = new_end
return corrections, changes
```
- [ ] **Step 4: Run test to verify it passes**
Run: `python -m pytest tests/unit/services/test_timing_sanitizer.py -q`
Expected: PASS (3 tests).
- [ ] **Step 5: Call the sanitizer in `submit_corrections`**
In `backend/api/routes/jobs.py`, inside `submit_corrections`, immediately before the GCS upload (the `corrections_gcs_path = ...` / `storage.upload_json(...)` block ~L1115), insert:
```python
# Safety net: never persist word timings that fall outside their segment.
# Frontend should already prevent this; this guarantees clean stored data
# (the render worker reads corrections_updated.json verbatim).
from backend.services.timing_sanitizer import sanitize_corrections
sanitized, clamp_count = sanitize_corrections(submission.corrections)
if clamp_count:
logger.warning(
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
f"in submitted corrections before persisting"
)
submission.corrections = sanitized
```
(`submission.corrections` is then uploaded by the existing `storage.upload_json(corrections_gcs_path, submission.corrections)` line.)
- [ ] **Step 6: Write the route-level failing test**
```python
# tests/unit/api/routes/test_jobs_corrections.py
from unittest.mock import patch, MagicMock
from backend.services.timing_sanitizer import sanitize_corrections
def test_submit_sanitizes_before_upload(monkeypatch):
"""The corrections written to GCS must have in-bounds word timings."""
captured = {}
def fake_upload_json(path, data):
captured["data"] = data
# Sanitizer is the unit under contract here; assert the integration call clamps.
bad = {
"corrected_segments": [
{"id": "s", "start_time": 15.18, "end_time": 18.04, "text": "A",
"words": [{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005}]}
]
}
cleaned, count = sanitize_corrections(bad)
assert count >= 1
assert cleaned["corrected_segments"][0]["words"][0]["start_time"] >= 15.18
```
(If the repo has FastAPI route integration harnesses under `tests/integration/`, add a fuller request-level test there following the existing pattern; the unit contract above is the minimum.)
- [ ] **Step 7: Run tests**
Run: `python -m pytest tests/unit/services/test_timing_sanitizer.py tests/unit/api/routes/test_jobs_corrections.py -q`
Expected: PASS.
- [ ] **Step 8: Commit**
```bash
git add backend/services/timing_sanitizer.py tests/unit/services/test_timing_sanitizer.py tests/unit/api/routes/test_jobs_corrections.py backend/api/routes/jobs.py
git commit -m "feat(api): sanitize out-of-bounds word timings on corrections submit"
```
---
## Task 5: Translate new strings + full suites
**Files:**
- Modify: `frontend/messages/*.json` (generated)
- [ ] **Step 1: Translate the two new keys to all locales**
Run: `cd frontend && python scripts/translate.py --messages-dir messages --target all`
Expected: `timingSanitized` / `timingClamped` added to all 33 locales (cache hits for repeats).
- [ ] **Step 2: Run the frontend suite**
Run: `cd frontend && npx jest lib/lyrics-review hooks components/lyrics-review`
Expected: PASS (all new + existing lyrics-review tests).
- [ ] **Step 3: Run the backend unit suite for touched areas**
Run: `python -m pytest tests/unit/services/test_timing_sanitizer.py tests/unit/api -q`
Expected: PASS.
- [ ] **Step 4: Version bump**
Bump `version` in `pyproject.toml` (patch, e.g. `0.176.2 -> 0.176.3`).
- [ ] **Step 5: Commit**
```bash
git add frontend/messages pyproject.toml
git commit -m "chore: translate timing-validation strings; bump version"
```
---
## Self-review notes (covered)
- **Spec coverage:** Layer 1 → Task 2; Layer 2 → Task 3; Layer 3 → Task 4; shared invariant → Tasks 1 & 4; "segment follows words" → relies on existing `EditModal.updateSegment` min/max derivation (no new code, noted in Architecture); i18n → Tasks 3 & 5; render-time net → already shipped (v0.176.2), unchanged.
- **Naming consistency:** `sanitizeSegmentTimings` (FE), `sanitize_corrections` (BE), `clampSyncTime` (sync) used identically across tasks.
- **No clamp-traps-extension:** clamping references the segment's saved bounds; legit extensions move those bounds via `updateSegment`, so they are never clamped. Only corruption (words diverged from bounds) is repaired.
@@ -0,0 +1,53 @@
# Audio Editor: Fade In / Fade Out Buttons
**Date:** 2026-06-11
**Branch:** `feat/sess-20260611-1250-audio-fade`
## Goal
Add **Fade In** and **Fade Out** action buttons to the audio editor toolbar so users
can ramp the volume of a selected region gracefully instead of a hard cut.
**Primary use case (user quote):** "when cutting off a long intro from a song, we'll
likely want it to fade in gracefully over a few seconds rather than come in really loud
at the point it was trimmed to."
## Design Decisions
- **Edge-gated display**, mirroring the existing `Trim Start` / `Trim End` buttons:
- **Fade In** appears when the selection starts near the beginning (`startSeconds < 1`).
- **Fade Out** appears when the selection ends near the end (`endSeconds > duration - 1`).
- This matches the real use case (fade the new start after trimming an intro; fade the
new end after trimming an outro) and avoids `afade`'s surprising behaviour of
silencing audio outside the fade window for mid-track selections.
- **Duration-preserving** (like `mute`) — fades only adjust volume, they don't change length.
- Implemented with FFmpeg's `afade` filter: `afade=t=in|out:st={start}:d={end-start}`.
- No new keyboard shortcut (a single key can't disambiguate in vs out cleanly).
## Changes
### Backend
1. `backend/services/audio_edit_service.py`
- Add `fade_region(input_path, start, end, direction, output_path)` — validates
`direction in {"in","out"}`, runs `afade`, returns metadata (duration preserved).
- Dispatch `fade_in` / `fade_out` in `apply_edit`.
2. `backend/api/routes/review.py`
- Add `"fade_in"`, `"fade_out"` to `valid_operations`.
### Frontend
3. `frontend/components/audio-editor/AudioEditor.tsx`
- `handleFadeIn()` / `handleFadeOut()` → `handleApply("fade_in"|"fade_out", {start_seconds, end_seconds})`.
- Edge-gated toolbar buttons with `TrendingUp` / `TrendingDown` icons.
4. i18n: add `fadeIn`, `fadeOut`, `fadeInSelection`, `fadeOutSelection` to
`frontend/messages/en.json`, then `translate.py --target all` (33 locales).
## Tests
- **Backend unit** (`test_audio_edit_service.py`): `fade_region` in/out ffmpeg args,
duration preserved, invalid direction rejected, `apply_edit` dispatch for fade_in/out.
- **Backend route** (`test_audio_edit_routes.py`): fade_in/fade_out accepted (not "Invalid operation").
- **Frontend** (`AudioEditor.test.tsx`): Fade In button renders for a start-anchored
selection and calls `applyAudioEdit` with `fade_in`.
## Out of Scope (possible future work)
- Mid-track fades (would need a `volume` envelope filter, not `afade`).
- Configurable fade curve / duration input box.
@@ -0,0 +1,82 @@
# Proactive AI Auto-Correction + UI De-AI-ification
**Date:** 2026-06-11
**Branch:** `feat/sess-20260611-1514-autocorrect-cost-logging`
**Context:** Measured cost ~$0.13/track (multi-model). Cheap enough to run on every job.
## Goal (user's words)
Run multi-model auto-correction automatically on every karaoke job so suggestions
are ready to review/approve/reject by the time anyone reaches the lyrics review UI.
Must fail gracefully — never block the karaoke job if AI APIs are flaky / out of
credits. Remove all "AI"/"model" mentions from the review UI; button becomes just
"Auto-correct"; drop the user-configurable model selection and always use multi-model.
Keep the button for the case where references arrive later (user pastes reference
lyrics during review, then clicks it).
## Architecture decisions (validated against the codebase)
1. **Where proactive runs: the `lyrics-transcription-job` Cloud Run Job**, after
`mark_lyrics_complete()` (so downstream screens/render are already triggered and
are NOT blocked), awaited (a fire-and-forget task would die when the job
entrypoint returns). The job is long-lived, so an extra ~15-30s is fine and the
process stays alive to finish the cache write.
2. **Cache alignment = the whole point.** `AutoCorrectService` already writes a
per-job GCS cache keyed on (models, settings, word-id+text list, ref texts,
artist, title). If the proactive run uses the SAME inputs + settings + models the
UI will send, the UI's on-load call is a **cache hit** (instant, no second spend).
- Proactive settings = `AutoCorrectSettings(compare_models=True)` (all other
fields default). Backend defaults == frontend `DEFAULT_AUTO_CORRECT_SETTINGS`
once we flip `compare_models` to `true`. Both paths build settings server-side
and hash the same dict.
- `models` is derived server-side identically in both paths via `_models_for()`.
- Proactive reads `corrections.json` (corrected_segments + reference_lyrics) — the
exact data the review-data endpoint serves on first load (before any edits).
3. **Env/secret wiring (REQUIRED for it to actually work).** The lyrics job currently
has neither `ANTHROPIC_API_KEY` nor `AUTO_CORRECT_*`. It uses the SAME SA as the
API service (`karaoke-backend@…`), which already reads `anthropic-api-key`
(project-level secret access) — so adding the secret to the job is low-risk.
Add via `--update-env-vars`/`--update-secrets` in the ci.yml job-update step
(merges, doesn't wipe the existing 12 vars).
4. **Feature flag:** `auto_correct_proactive_enabled` (config), default **false** in
code, set `AUTO_CORRECT_PROACTIVE_ENABLED=true` on the lyrics job via ci.yml.
5. **UI auto-run on load:** on review load, if references exist, auto-invoke
auto-correct (cache hit → instant). Keep the button for manual re-run after the
user pastes references. Always send `compare_models: true`.
## Changes
### Backend
- `backend/config.py`: add `auto_correct_proactive_enabled`.
- `backend/workers/lyrics_worker.py`: after `mark_lyrics_complete`, await a guarded
helper `_run_proactive_auto_correct(job_id, ...)` — loads corrections.json, calls
`suggest(..., settings=AutoCorrectSettings(compare_models=True))`, `asyncio.wait_for`
timeout, swallow ALL exceptions (log only). Never affects job status.
- Tests: worker test that it's gated by the flag, swallows errors, and skips when no
references.
### Infra
- `.github/workflows/ci.yml`: lyrics-transcription-job update step gains
`--update-env-vars "AUTO_CORRECT_MODEL=claude-fable-5,AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true"`
and `--update-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest"`.
### Frontend (`frontend/`, next-intl, 33 locales)
- Always multi-model: `DEFAULT_AUTO_CORRECT_SETTINGS.compare_models = true`; remove
the compare/model toggle from `AutoCorrectModal.tsx`.
- Strip model attribution: remove model-name badge + consensus "X/Y models" badge in
`AutoCorrectPanel.tsx`; reword the conflict badge to not mention models (keep the
conflict-resolution behavior).
- Rename button to "Auto-correct"; remove "AI"/"model" from all related strings.
- Auto-run on review load when references exist (cache hit → instant); keep button.
- i18n: edit `messages/en.json`, then `python frontend/scripts/translate.py
--messages-dir frontend/messages --target all` for all 33 locales.
- Update `e2e/production/auto-correct-suggestions.spec.ts` button selector.
## Failure modes (all non-blocking by design)
- Anthropic down / no credits → claude call raises, caught; Gemini result still cached
(multi-model degrades to whatever answered). UI on-load call same behaviour.
- Both providers fail → proactive logs warning, job proceeds normally; UI on-load call
returns 502 and the panel shows nothing (or the manual button can retry later).
- Proactive task times out → `wait_for` cancels it, job proceeds.
- No references at lyrics-complete time → proactive skipped; user pastes refs in UI →
clicks button → on-demand call.
@@ -0,0 +1,96 @@
/**
* @jest-environment jsdom
*
* Tests that the API client attaches the X-Tenant-ID header on white-label tenant
* portals (sourced from window.__TENANT_CONFIG__) and omits it on the consumer build.
*
* Regression guard for the root-cause bug: the frontend never sent X-Tenant-ID, so the
* shared api.nomadkaraoke.com backend could not detect the tenant and every tenant-portal
* job/sign-in silently fell back to consumer behavior (0 tenant jobs ever ran in prod).
*/
import { api, getTenantId } from '@/lib/api'
function setEdgeTenant(id: string | null) {
if (id) {
;(window as any).__TENANT_CONFIG__ = {
tenant: { id, name: id, subdomain: `${id}.nomadkaraoke.com` },
is_default: false,
}
} else {
delete (window as any).__TENANT_CONFIG__
}
}
describe('getTenantId', () => {
afterEach(() => setEdgeTenant(null))
it('returns null when no tenant config is present (consumer build)', () => {
setEdgeTenant(null)
expect(getTenantId()).toBeNull()
})
it('returns the tenant id from window.__TENANT_CONFIG__', () => {
setEdgeTenant('vocalstar')
expect(getTenantId()).toBe('vocalstar')
})
it('returns null when the injected config has no tenant (default/consumer domain)', () => {
;(window as any).__TENANT_CONFIG__ = { tenant: null, is_default: true }
expect(getTenantId()).toBeNull()
})
})
describe('X-Tenant-ID header attachment', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(global as any).fetch = fetchMock
fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) })
})
afterEach(() => setEdgeTenant(null))
it('attaches X-Tenant-ID to authenticated requests (createJobWithUploadUrls) on a tenant portal', async () => {
setEdgeTenant('vocalstar')
window.localStorage.setItem('karaoke_access_token', 'tok-123')
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ job_id: 'j1', upload_urls: [] }),
})
await api.createJobWithUploadUrls('Adele', 'Hello', [], {
is_private: true,
existing_instrumental: true,
})
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['X-Tenant-ID']).toBe('vocalstar')
expect(init.headers['Authorization']).toBe('Bearer tok-123')
window.localStorage.removeItem('karaoke_access_token')
})
it('attaches X-Tenant-ID to the magic-link request on a tenant portal', async () => {
setEdgeTenant('singa')
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
await api.sendMagicLink('user@singa.com')
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/api\/users\/auth\/magic-link$/)
expect(init.headers['X-Tenant-ID']).toBe('singa')
})
it('does NOT attach X-Tenant-ID on the consumer build', async () => {
setEdgeTenant(null)
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
await api.sendMagicLink('user@example.com')
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['X-Tenant-ID']).toBeUndefined()
})
})
+32
View File
@@ -62,6 +62,38 @@ describe('crash-reporter.reportClientError', () => {
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('ignores benign media AbortError (DOMException)', async () => {
await reportClientError({
error: new DOMException(
'The fetching process for the media resource was aborted by the user agent at the user\'s request.',
'AbortError'
),
source: 'unhandledrejection',
context: { href: 'https://gen.nomadkaraoke.com/en/app/jobs/', userAgent: 'ua' },
})
expect(fetchMock).not.toHaveBeenCalled()
})
it('ignores benign AbortError surfaced as a plain Error', async () => {
const err = new Error('aborted')
err.name = 'AbortError'
await reportClientError({
error: err,
source: 'window.onerror',
context: { href: '', userAgent: '' },
})
expect(fetchMock).not.toHaveBeenCalled()
})
it('still reports a non-abort DOMException', async () => {
await reportClientError({
error: new DOMException('nope', 'NotAllowedError'),
source: 'test',
context: { href: '', userAgent: '' },
})
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('does not throw on fetch failure', async () => {
fetchMock.mockRejectedValueOnce(new Error('offline'))
await expect(
@@ -387,6 +387,11 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
style={{ height: 40 }}
/>
<h1 className="text-lg font-bold">Lyrics Transcription Review</h1>
{(job.artist || job.title) && (
<span className="text-xs md:text-sm text-muted-foreground truncate">
{[job.artist, job.title].filter(Boolean).join(" - ")}
</span>
)}
</div>
<ThemeToggle />
</div>
@@ -20,6 +20,8 @@ import {
SkipForward,
Volume2,
VolumeX,
TrendingUp,
TrendingDown,
Upload,
Check,
ChevronDown,
@@ -382,6 +384,12 @@ export function AudioEditor({ job }: AudioEditorProps) {
? (audioInfo?.original_duration_seconds ?? 0)
: (audioInfo?.current_duration_seconds ?? 0)
// Trim/Fade are edge actions — only valid when the selection touches the
// very start or very end of the track (1s tolerance, matching the
// server-side anchoring in audio_edit_service.fade_region).
const atStartEdge = !!selection && selection.startSeconds < 1
const atEndEdge = !!selection && selection.endSeconds > currentDuration - 1
// ─── Auto-save ─────────────────────────────────────────────────
const { saveSession } = useAudioEditAutoSave({
@@ -614,6 +622,22 @@ export function AudioEditor({ job }: AudioEditorProps) {
})
}
function handleFadeIn() {
if (!selection) return
handleApply("fade_in", {
start_seconds: selection.startSeconds,
end_seconds: selection.endSeconds,
})
}
function handleFadeOut() {
if (!selection) return
handleApply("fade_out", {
start_seconds: selection.startSeconds,
end_seconds: selection.endSeconds,
})
}
// ─── Join (upload) ─────────────────────────────────────────────
const [showJoinDialog, setShowJoinDialog] = useState(false)
@@ -866,28 +890,52 @@ export function AudioEditor({ job }: AudioEditorProps) {
{formatTimePrecise(selection.startSeconds)} - {formatTimePrecise(selection.endSeconds)}
({formatTimePrecise(selection.endSeconds - selection.startSeconds)})
</span>
{selection.startSeconds < 1 && (
<Button
variant="outline"
size="sm"
disabled={isOperating}
onClick={handleTrimStart}
className="text-xs h-7"
>
{t('trimStart')}
</Button>
)}
{selection.endSeconds > currentDuration - 1 && (
<Button
variant="outline"
size="sm"
disabled={isOperating}
onClick={handleTrimEnd}
className="text-xs h-7"
>
{t('trimEnd')}
</Button>
)}
{/* Trim/Fade are edge actions: enabled only when the selection
touches the very start (start) or very end (end) of the track.
Always rendered (disabled off-edge) so the actions stay
discoverable, with a tooltip explaining how to enable them. */}
<Button
variant="outline"
size="sm"
disabled={isOperating || !atStartEdge}
onClick={handleTrimStart}
className="text-xs h-7"
title={atStartEdge ? t('trimStartSelection') : t('trimStartDisabledHint')}
>
{t('trimStart')}
</Button>
<Button
variant="outline"
size="sm"
disabled={isOperating || !atStartEdge}
onClick={handleFadeIn}
className="text-xs h-7"
title={atStartEdge ? t('fadeInSelection') : t('fadeInDisabledHint')}
>
<TrendingUp className="w-3 h-3 mr-1" />
{t('fadeIn')}
</Button>
<Button
variant="outline"
size="sm"
disabled={isOperating || !atEndEdge}
onClick={handleTrimEnd}
className="text-xs h-7"
title={atEndEdge ? t('trimEndSelection') : t('trimEndDisabledHint')}
>
{t('trimEnd')}
</Button>
<Button
variant="outline"
size="sm"
disabled={isOperating || !atEndEdge}
onClick={handleFadeOut}
className="text-xs h-7"
title={atEndEdge ? t('fadeOutSelection') : t('fadeOutDisabledHint')}
>
<TrendingDown className="w-3 h-3 mr-1" />
{t('fadeOut')}
</Button>
<Button
variant="outline"
size="sm"
@@ -327,6 +327,100 @@ describe("AudioEditor", () => {
})
})
it("shows Fade In button and applies fade_in for a start-anchored selection", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
mockApi.applyAudioEdit.mockResolvedValue({ ...mockEditResponse, operation: "fade_in" })
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
const canvas = document.querySelector("canvas") as HTMLCanvasElement
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
toJSON: () => ({}),
} as DOMRect)
// Drag from the very start to ~6s (duration 200, width 1000 → 6s ≈ 30px)
fireEvent.mouseDown(canvas, { clientX: 0 })
fireEvent.mouseMove(canvas, { clientX: 30 })
fireEvent.mouseUp(canvas, { clientX: 30 })
const fadeInButton = await screen.findByText("Fade In")
fireEvent.click(fadeInButton)
await waitFor(() => {
expect(mockApi.applyAudioEdit).toHaveBeenCalledWith(
"test-job-123",
"fade_in",
expect.objectContaining({ start_seconds: 0 }),
)
})
})
it("shows Fade Out button and applies fade_out for an end-anchored selection", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
mockApi.applyAudioEdit.mockResolvedValue({ ...mockEditResponse, operation: "fade_out" })
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
const canvas = document.querySelector("canvas") as HTMLCanvasElement
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
toJSON: () => ({}),
} as DOMRect)
// Drag from ~194s to the end (duration 200, width 1000 → 194s ≈ 970px, end ≈ 1000px)
fireEvent.mouseDown(canvas, { clientX: 970 })
fireEvent.mouseMove(canvas, { clientX: 1000 })
fireEvent.mouseUp(canvas, { clientX: 1000 })
const fadeOutButton = await screen.findByText("Fade Out")
fireEvent.click(fadeOutButton)
await waitFor(() => {
expect(mockApi.applyAudioEdit).toHaveBeenCalledWith(
"test-job-123",
"fade_out",
expect.objectContaining({ end_seconds: 200 }),
)
})
})
it("renders Trim/Fade buttons disabled for a mid-track selection", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
await waitFor(() => {
expect(screen.getByText("Audio Editor")).toBeInTheDocument()
})
const canvas = document.querySelector("canvas") as HTMLCanvasElement
jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({
left: 0, top: 0, right: 1000, bottom: 140, width: 1000, height: 140, x: 0, y: 0,
toJSON: () => ({}),
} as DOMRect)
// Drag a mid-track region (duration 200, width 1000 → 100px≈20s, 300px≈60s)
fireEvent.mouseDown(canvas, { clientX: 100 })
fireEvent.mouseMove(canvas, { clientX: 300 })
fireEvent.mouseUp(canvas, { clientX: 300 })
// Buttons stay visible (discoverable) but disabled off-edge
const fadeIn = (await screen.findByText("Fade In")).closest("button")
const fadeOut = screen.getByText("Fade Out").closest("button")
const trimStart = screen.getByText("Trim Start").closest("button")
const trimEnd = screen.getByText("Trim End").closest("button")
expect(fadeIn).toBeDisabled()
expect(fadeOut).toBeDisabled()
expect(trimStart).toBeDisabled()
expect(trimEnd).toBeDisabled()
})
it("shows playback controls", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
@@ -1,5 +1,6 @@
"use client"
import { useTranslations } from "next-intl"
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api"
import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner"
@@ -1410,6 +1411,7 @@ function FallbackSection({
onUrlSubmit: (e: React.FormEvent) => void
onUploadSubmit: (e: React.FormEvent) => void
}) {
const t = useTranslations('jobFlow')
const isTier3WithResults = tier === 3 && hasResults
const largeButtons = !hasResults
const buttonHeight = largeButtons ? 'h-12' : 'h-9'
@@ -1435,7 +1437,7 @@ function FallbackSection({
style={{ borderColor: fallbackMode === "url" ? 'var(--brand-pink)' : 'var(--card-border)', color: 'var(--text)' }}
>
<Youtube className={`${iconSize} mr-1.5`} />
YouTube URL
{t('pasteUrlButton')}
</Button>
<Button
variant="outline"
@@ -1464,13 +1466,25 @@ function FallbackSection({
autoFocus
/>
</div>
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
{t('urlSupportedSitesHint')}{' '}
<a
href="https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md"
target="_blank"
rel="noopener noreferrer"
className="underline"
style={{ color: 'var(--brand-pink)' }}
>
{t('urlSupportedSitesLink')}
</a>
</p>
<Button
type="submit"
size="sm"
disabled={!youtubeUrl.trim() || noCredits}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
Use This URL
{t('useThisUrl')}
</Button>
</form>
)}
+100 -31
View File
@@ -1,9 +1,11 @@
'use client'
import { useEffect, useRef, useState, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Slider } from '@/components/ui/slider'
import { Play, Pause } from 'lucide-react'
import { Progress } from '@/components/ui/progress'
import { Play, Pause, Loader2, AlertCircle } from 'lucide-react'
// Extend Window interface for global audio functions
declare global {
@@ -12,26 +14,62 @@ declare global {
toggleAudioPlayback?: () => void
getAudioDuration?: () => number
isAudioPlaying?: boolean
/** True once the media is ready to play through (see AUDIO_READY_EVENT). */
isAudioReady?: boolean
/** Buffered fraction of the audio file, 0..1. */
audioLoadProgress?: number
}
}
/**
* Dispatched on `window` whenever audio readiness or load progress changes.
* detail: { ready: boolean, progress: number }. Subscribe via useAudioReady().
*/
export const AUDIO_READY_EVENT = 'karaoke:audio-ready'
interface AudioPlayerProps {
audioUrl: string | null
onTimeUpdate?: (time: number) => void
}
export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps) {
const t = useTranslations('lyricsReview.header')
const [isPlaying, setIsPlaying] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [duration, setDuration] = useState(0)
const [isReady, setIsReady] = useState(false)
const [loadProgress, setLoadProgress] = useState(0) // 0..1 buffered fraction
const [hasError, setHasError] = useState(false)
const audioRef = useRef<HTMLAudioElement | null>(null)
// Ref mirror so the imperative globals always read current readiness.
const isReadyRef = useRef(false)
// Broadcast readiness to imperative consumers (window globals) and to
// reactive subscribers (useAudioReady hook) via a CustomEvent.
const publishReady = useCallback((ready: boolean, progress: number) => {
isReadyRef.current = ready
if (typeof window === 'undefined') return
window.isAudioReady = ready
window.audioLoadProgress = progress
window.dispatchEvent(new CustomEvent(AUDIO_READY_EVENT, { detail: { ready, progress } }))
}, [])
useEffect(() => {
if (!audioUrl) return
if (!audioUrl) {
publishReady(false, 0)
return
}
const audio = new Audio(audioUrl)
audio.preload = 'auto'
audioRef.current = audio
// Reset readiness for the new source.
setIsReady(false)
setHasError(false)
setLoadProgress(0)
publishReady(false, 0)
let animationFrameId: number
const updateTime = () => {
@@ -41,51 +79,60 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
animationFrameId = requestAnimationFrame(updateTime)
}
audio.addEventListener('play', () => {
setIsPlaying(true)
window.isAudioPlaying = true
updateTime()
})
const markReady = () => {
if (isReadyRef.current) return
setIsReady(true)
setLoadProgress(1)
publishReady(true, 1)
}
audio.addEventListener('pause', () => {
setIsPlaying(false)
window.isAudioPlaying = false
cancelAnimationFrame(animationFrameId)
})
const updateProgress = () => {
const d = audio.duration
if (!d || !isFinite(d) || audio.buffered.length === 0) return
const bufferedEnd = audio.buffered.end(audio.buffered.length - 1)
const frac = Math.min(1, bufferedEnd / d)
setLoadProgress(frac)
if (!isReadyRef.current) publishReady(false, frac)
// canplaythrough is unreliable across browsers — treat fully-buffered as ready too.
if (bufferedEnd >= d - 0.25) markReady()
}
audio.addEventListener('ended', () => {
cancelAnimationFrame(animationFrameId)
setIsPlaying(false)
window.isAudioPlaying = false
setCurrentTime(0)
})
audio.addEventListener('loadedmetadata', () => {
setDuration(audio.duration)
})
const handlers: Array<[string, EventListener]> = [
['play', () => { setIsPlaying(true); window.isAudioPlaying = true; updateTime() }],
['pause', () => { setIsPlaying(false); window.isAudioPlaying = false; cancelAnimationFrame(animationFrameId) }],
['ended', () => { cancelAnimationFrame(animationFrameId); setIsPlaying(false); window.isAudioPlaying = false; setCurrentTime(0) }],
['loadedmetadata', () => setDuration(audio.duration)],
['durationchange', () => setDuration(audio.duration)],
['progress', updateProgress],
['canplaythrough', markReady],
['error', () => { setHasError(true); setIsReady(false); publishReady(false, 0) }],
]
handlers.forEach(([ev, fn]) => audio.addEventListener(ev, fn))
return () => {
cancelAnimationFrame(animationFrameId)
handlers.forEach(([ev, fn]) => audio.removeEventListener(ev, fn))
audio.pause()
audio.src = ''
audioRef.current = null
window.isAudioPlaying = false
publishReady(false, 0)
}
}, [audioUrl, onTimeUpdate])
}, [audioUrl, onTimeUpdate, publishReady])
const handlePlayPause = () => {
if (!audioRef.current) return
if (!audioRef.current || !isReadyRef.current) return
if (isPlaying) {
audioRef.current.pause()
} else {
audioRef.current.play()
audioRef.current.play().catch(() => {})
}
setIsPlaying(!isPlaying)
}
const handleSeek = (value: number[]) => {
if (!audioRef.current) return
if (!audioRef.current || !isReadyRef.current) return
const time = value[0]
audioRef.current.currentTime = time
setCurrentTime(time)
@@ -98,21 +145,21 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
}
const seekAndPlay = useCallback((time: number) => {
if (!audioRef.current) return
if (!audioRef.current || !isReadyRef.current) return
audioRef.current.currentTime = time
setCurrentTime(time)
audioRef.current.play()
audioRef.current.play().catch(() => {})
setIsPlaying(true)
}, [])
const togglePlayback = useCallback(() => {
if (!audioRef.current) return
if (!audioRef.current || !isReadyRef.current) return
if (isPlaying) {
audioRef.current.pause()
} else {
audioRef.current.play()
audioRef.current.play().catch(() => {})
}
setIsPlaying(!isPlaying)
}, [isPlaying])
@@ -134,9 +181,31 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
if (!audioUrl) return null
// Failed to load — surface a clear, non-blocking error in place of controls.
if (hasError) {
return (
<div className="flex items-center gap-2 bg-card rounded h-8 text-xs text-destructive">
<AlertCircle className="h-4 w-4" />
<span>{t('audioLoadError')}</span>
</div>
)
}
// Still loading — show a spinner + buffer progress and keep controls disabled.
if (!isReady) {
return (
<div className="flex items-center gap-2 bg-card rounded h-8" aria-busy="true">
<span className="text-xs text-muted-foreground mr-1">{t('playback')}</span>
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
<span className="text-xs text-muted-foreground">{t('loadingAudio')}</span>
<Progress value={Math.round(loadProgress * 100)} className="w-[100px] mx-1 h-1.5" />
</div>
)
}
return (
<div className="flex items-center gap-2 bg-card rounded h-8">
<span className="text-xs text-muted-foreground mr-1">Playback:</span>
<span className="text-xs text-muted-foreground mr-1">{t('playback')}</span>
<Button variant="ghost" size="icon" className="h-7 w-7 p-0.5" onClick={handlePlayPause}>
{isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
@@ -0,0 +1,182 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Sparkles, Loader2, AlertTriangle } from 'lucide-react'
import {
AutoCorrectSettings,
DEFAULT_AUTO_CORRECT_SETTINGS,
} from '@/lib/api/autoCorrect'
import type { AutoCorrectStatus } from '@/hooks/useAutoCorrect'
interface AutoCorrectModalProps {
open: boolean
onClose: () => void
onRun: (settings: AutoCorrectSettings) => void
onCancelRun: () => void
status: AutoCorrectStatus
error: string | null
hasReferences: boolean
}
const CONFIDENCE_PRESETS = ['all', 'balanced', 'high'] as const
type ConfidencePreset = (typeof CONFIDENCE_PRESETS)[number]
const PRESET_THRESHOLDS: Record<ConfidencePreset, number> = {
all: 0,
balanced: 0.5,
high: 0.8,
}
export default function AutoCorrectModal({
open,
onClose,
onRun,
onCancelRun,
status,
error,
hasReferences,
}: AutoCorrectModalProps) {
const t = useTranslations('lyricsReview.autoCorrect')
const [adlibRemoval, setAdlibRemoval] = useState(
DEFAULT_AUTO_CORRECT_SETTINGS.suggest_adlib_removal,
)
const [allowInsertions, setAllowInsertions] = useState(
DEFAULT_AUTO_CORRECT_SETTINGS.allow_insertions,
)
const [confidencePreset, setConfidencePreset] = useState<ConfidencePreset>('all')
const isRunning = status === 'running'
const handleRun = () => {
onRun({
suggest_adlib_removal: adlibRemoval,
allow_insertions: allowInsertions,
min_confidence: PRESET_THRESHOLDS[confidencePreset],
// Always multi-model — kept aligned with the backend proactive run so
// the cached result is reused.
compare_models: DEFAULT_AUTO_CORRECT_SETTINGS.compare_models,
})
}
const handleClose = () => {
if (isRunning) onCancelRun()
onClose()
}
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleClose()}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-purple-500" />
{t('title')}
</DialogTitle>
<DialogDescription>{t('description')}</DialogDescription>
</DialogHeader>
{!hasReferences ? (
<div className="flex items-start gap-2 rounded-md border border-amber-500/50 bg-amber-500/10 p-3 text-sm">
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0 text-amber-500" />
<span>{t('noReferences')}</span>
</div>
) : isRunning ? (
<div className="flex flex-col items-center gap-3 py-6">
<Loader2 className="h-8 w-8 animate-spin text-purple-500" />
<p className="text-sm text-muted-foreground">{t('running')}</p>
</div>
) : (
<div className="space-y-4">
<div className="flex items-center justify-between gap-4">
<div>
<Label htmlFor="ac-adlib">{t('adlibRemovalLabel')}</Label>
<p className="text-xs text-muted-foreground">
{t('adlibRemovalHint')}
</p>
</div>
<Switch
id="ac-adlib"
checked={adlibRemoval}
onCheckedChange={setAdlibRemoval}
/>
</div>
<div className="flex items-center justify-between gap-4">
<div>
<Label htmlFor="ac-insertions">{t('insertionsLabel')}</Label>
<p className="text-xs text-muted-foreground">
{t('insertionsHint')}
</p>
</div>
<Switch
id="ac-insertions"
checked={allowInsertions}
onCheckedChange={setAllowInsertions}
/>
</div>
<div className="flex items-center justify-between gap-4">
<div>
<Label>{t('confidenceLabel')}</Label>
<p className="text-xs text-muted-foreground">
{t('confidenceHint')}
</p>
</div>
<Select
value={confidencePreset}
onValueChange={(v) => setConfidencePreset(v as ConfidencePreset)}
>
<SelectTrigger className="w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CONFIDENCE_PRESETS.map((p) => (
<SelectItem key={p} value={p}>
{t(`confidence_${p}`)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{error && (
<div className="flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm">
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0 text-destructive" />
<span>{error}</span>
</div>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
{isRunning ? t('cancel') : t('close')}
</Button>
{!isRunning && hasReferences && (
<Button onClick={handleRun}>
<Sparkles className="h-4 w-4 mr-2" />
{t('runButton')}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,265 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import {
Sparkles,
Check,
X,
Undo2,
ChevronDown,
ChevronUp,
AlertTriangle,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import type { AiSuggestion } from '@/lib/api/autoCorrect'
import type { AutoCorrectController } from '@/hooks/useAutoCorrect'
interface AutoCorrectPanelProps {
controller: AutoCorrectController
isReadOnly: boolean
}
function scrollToWord(wordId: string | undefined) {
if (!wordId) return
const el = document.getElementById(`word-${wordId}`)
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
el.classList.add('animate-lyrics-flash')
setTimeout(() => el.classList.remove('animate-lyrics-flash'), 1300)
}
}
const CATEGORY_BADGE: Record<AiSuggestion['category'], string> = {
mishearing: 'bg-purple-500/15 text-purple-600 dark:text-purple-400',
grammar: 'bg-blue-500/15 text-blue-600 dark:text-blue-400',
adlib_removal: 'bg-orange-500/15 text-orange-600 dark:text-orange-400',
repeated_chorus_fix: 'bg-teal-500/15 text-teal-600 dark:text-teal-400',
formatting: 'bg-slate-500/15 text-slate-600 dark:text-slate-400',
other: 'bg-slate-500/15 text-slate-600 dark:text-slate-400',
}
export default function AutoCorrectPanel({
controller,
isReadOnly,
}: AutoCorrectPanelProps) {
const t = useTranslations('lyricsReview.autoCorrect')
const [collapsed, setCollapsed] = useState(false)
const {
suggestions,
decisions,
pendingCount,
acceptedCount,
accept,
reject,
undoAccept,
acceptAll,
rejectAll,
dismiss,
isPendingAndStale,
} = controller
if (controller.status !== 'reviewing') return null
return (
<Card className="mb-3 border-purple-500/40">
<div className="flex items-center justify-between gap-2 px-3 py-2">
<div className="flex items-center gap-2 min-w-0">
<Sparkles className="h-4 w-4 shrink-0 text-purple-500" />
<span className="text-sm font-medium truncate">
{suggestions.length === 0
? t('noSuggestions')
: t('summary', {
total: suggestions.length,
pending: pendingCount,
accepted: acceptedCount,
})}
</span>
</div>
<div className="flex items-center gap-1 shrink-0">
{!isReadOnly && pendingCount > 0 && (
<>
<Button size="sm" variant="outline" onClick={acceptAll}>
<Check className="h-3.5 w-3.5 mr-1" />
{t('acceptAll')}
</Button>
<Button size="sm" variant="outline" onClick={rejectAll}>
<X className="h-3.5 w-3.5 mr-1" />
{t('rejectAll')}
</Button>
</>
)}
<Button
size="sm"
variant="ghost"
onClick={() => setCollapsed((c) => !c)}
aria-label={collapsed ? t('expand') : t('collapse')}
>
{collapsed ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronUp className="h-4 w-4" />
)}
</Button>
<Button size="sm" variant="ghost" onClick={dismiss} aria-label={t('dismiss')}>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{!collapsed && suggestions.length > 0 && (
// Plain overflow div, NOT the ScrollArea component: its Radix root
// has no overflow-hidden, so a max-height there doesn't clip and
// long suggestion lists spill over the panel border.
<div className="max-h-64 overflow-y-auto border-t">
<ul className="divide-y">
{suggestions.map((s) => {
const decision = decisions[s.id]
const stale = decision === 'stale' || isPendingAndStale(s)
return (
<li
key={s.id}
role="button"
tabIndex={0}
className={cn(
'flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none',
decision === 'rejected' && 'opacity-50',
)}
onClick={() => scrollToWord(s.word_ids[0])}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
scrollToWord(s.word_ids[0])
}
}}
>
<Badge
className={cn('shrink-0 text-[10px]', CATEGORY_BADGE[s.category])}
>
{t(`category_${s.category}`)}
</Badge>
{s.conflict_group && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant="outline"
className="shrink-0 text-[10px] border-purple-500/50 text-purple-600 dark:text-purple-400"
>
{t('conflictBadge')}
</Badge>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
{t('conflictTooltip')}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
<span className="min-w-0 flex-1 truncate">
{s.op === 'insert_after' ? (
<>
<span className="text-muted-foreground">{t('insertMarker')} </span>
<span className="text-green-600 dark:text-green-400">
{s.new_text}
</span>
</>
) : s.op === 'delete' ? (
<span className="line-through text-red-600 dark:text-red-400">
{s.original_text}
</span>
) : (
<>
<span className="line-through text-red-600 dark:text-red-400">
{s.original_text}
</span>{' '}
<span className="text-green-600 dark:text-green-400">
{s.new_text}
</span>
</>
)}
</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="shrink-0 text-xs text-muted-foreground tabular-nums">
{Math.round(s.confidence * 100)}%
</span>
</TooltipTrigger>
<TooltipContent className="max-w-xs">{s.reason}</TooltipContent>
</Tooltip>
</TooltipProvider>
<div
className="flex items-center gap-1 shrink-0"
onClick={(e) => e.stopPropagation()}
>
{stale ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<AlertTriangle className="h-4 w-4 text-amber-500" />
</TooltipTrigger>
<TooltipContent>{t('staleHint')}</TooltipContent>
</Tooltip>
</TooltipProvider>
) : decision === 'pending' && !isReadOnly ? (
<>
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-green-600 hover:text-green-700"
onClick={() => accept(s.id)}
aria-label={t('accept')}
>
<Check className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-red-600 hover:text-red-700"
onClick={() => reject(s.id)}
aria-label={t('reject')}
>
<X className="h-4 w-4" />
</Button>
</>
) : decision === 'accepted' ? (
<>
<Badge variant="outline" className="text-[10px] text-green-600">
{t('accepted')}
</Badge>
{!isReadOnly && (
<Button
size="sm"
variant="ghost"
className="h-7 px-2"
onClick={() => undoAccept(s.id)}
aria-label={t('undo')}
>
<Undo2 className="h-4 w-4" />
</Button>
)}
</>
) : decision === 'rejected' ? (
<Badge variant="outline" className="text-[10px]">
{t('rejected')}
</Badge>
) : null}
</div>
</li>
)
})}
</ul>
</div>
)}
</Card>
)
}
@@ -21,6 +21,7 @@ import {
Eye,
CheckCircle2,
XCircle,
Sparkles,
} from 'lucide-react'
import { CorrectionData, InteractionMode } from '@/lib/lyrics-review/types'
import ModeSelector from './ModeSelector'
@@ -67,6 +68,7 @@ interface HeaderProps {
onRevertAllCorrections?: () => void
isDuet?: boolean
onToggleDuet?: () => void
onAutoCorrect?: () => void
}
export default function Header({
@@ -100,6 +102,7 @@ export default function Header({
onRevertAllCorrections,
isDuet = false,
onToggleDuet,
onAutoCorrect,
}: HeaderProps) {
const t = useTranslations('lyricsReview.header')
const tDuet = useTranslations('lyricsReview.duet')
@@ -290,6 +293,23 @@ export default function Header({
</Tooltip>
)}
{!isReadOnly && onAutoCorrect && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onClick={onAutoCorrect}
className="h-8 text-xs text-purple-500 border-purple-500/50 hover:border-purple-500 hover:bg-purple-500/10"
>
<Sparkles className="h-3.5 w-3.5 mr-1" />
{t('autoCorrect')}
</Button>
</TooltipTrigger>
<TooltipContent className="max-w-xs">{t('autoCorrectDesc')}</TooltipContent>
</Tooltip>
)}
{!isReadOnly && onTimingOffset && (
<Tooltip>
<TooltipTrigger asChild>
@@ -55,6 +55,9 @@ import { hasMultipleSingers } from '@/lib/lyrics-review/duet'
import SessionRestoreDialog from './SessionRestoreDialog'
import Header from './Header'
import GapNavigator from './GapNavigator'
import AutoCorrectModal from './AutoCorrectModal'
import AutoCorrectPanel from './AutoCorrectPanel'
import { useAutoCorrect } from '@/hooks/useAutoCorrect'
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
import { applyOffsetToCorrectionData, applyOffsetToSegment } from '@/lib/lyrics-review/utils/timingUtils'
@@ -154,6 +157,9 @@ export default function LyricsAnalyzer({
const [countdown, setCountdown] = useState(2)
const [showInstrumentalReview, setShowInstrumentalReview] = useState(false)
// AI auto-correct state
const [isAutoCorrectModalOpen, setIsAutoCorrectModalOpen] = useState(false)
// Edit log state
const [editLog] = useState<EditLog>(() => createEditLog(jobId ?? 'unknown', audioHash))
const [lastEditEntry, setLastEditEntry] = useState<EditLogEntry | null>(null)
@@ -214,6 +220,27 @@ export default function LyricsAnalyzer({
[history, historyIndex]
)
// AI auto-correct suggestions (opt-in; nothing runs unless triggered)
const autoCorrect = useAutoCorrect({
jobId,
data,
updateDataWithHistory,
editLog,
getAuthToken: () => getAccessToken() ?? undefined,
// Auto-run once on load so suggestions are ready without a click. The
// backend pre-generates + caches them during lyrics processing, so this
// is normally an instant cache hit. Skipped in read-only / local mode,
// and only when a jobId exists (the request needs one).
autoRunOnLoad: !isReadOnly && !isLocalMode && Boolean(jobId),
})
// Close the run modal once suggestions arrive (panel takes over)
useEffect(() => {
if (autoCorrect.status === 'reviewing') {
setIsAutoCorrectModalOpen(false)
}
}, [autoCorrect.status])
// Compute which word IDs have been edited by the user (compared to initial state)
const editedWordIds = useMemo(() => {
const initial = history[0]
@@ -981,6 +1008,9 @@ export default function LyricsAnalyzer({
// Play segment handler
const handlePlaySegment = useCallback(
(startTime: number) => {
// Ignore playback requests until the audio can play through. AudioPlayer's
// globals already no-op when not ready; this avoids even seeking early.
if (typeof window !== 'undefined' && !window.isAudioReady) return
if (typeof window !== 'undefined' && window.seekAndPlayAudio) {
const adjustedStartTime =
timingOffsetMs !== 0 ? startTime + timingOffsetMs / 1000 : startTime
@@ -1296,8 +1326,11 @@ export default function LyricsAnalyzer({
onRevertAllCorrections={handleRevertAllCorrections}
isDuet={isDuet}
onToggleDuet={() => setIsDuet(d => !d)}
onAutoCorrect={!isLocalMode && jobId ? () => setIsAutoCorrectModalOpen(true) : undefined}
/>
<AutoCorrectPanel controller={autoCorrect} isReadOnly={isReadOnly} />
<div className={cn('grid gap-2', isMobile ? 'grid-cols-1' : 'grid-cols-2')}>
<TranscriptionView
data={displayData}
@@ -1506,6 +1539,16 @@ export default function LyricsAnalyzer({
authToken={getAccessToken() ?? undefined}
/>
<AutoCorrectModal
open={isAutoCorrectModalOpen}
onClose={() => setIsAutoCorrectModalOpen(false)}
onRun={(settings) => void autoCorrect.run(settings)}
onCancelRun={autoCorrect.cancel}
status={autoCorrect.status}
error={autoCorrect.error}
hasReferences={autoCorrect.hasReferences}
/>
<EditFeedbackBar
entry={lastEditEntry}
visible={showFeedbackBar}
@@ -14,6 +14,7 @@ import SegmentDetailsModal from './modals/SegmentDetailsModal'
import DurationTimelineView from './DurationTimelineView'
import SingerChip from './SingerChip'
import { resolveSegmentSinger, hasWordOverrides } from '@/lib/lyrics-review/duet'
import { useAudioReady } from '@/lib/lyrics-review/hooks/useAudioReady'
import type { SingerId } from '@/lib/lyrics-review/types'
import { cn } from '@/lib/utils'
@@ -43,6 +44,8 @@ export default function TranscriptionView({
onSegmentFocus,
}: TranscriptionViewProps) {
const t = useTranslations('lyricsReview.transcription')
const tHeader = useTranslations('lyricsReview.header')
const { ready: audioReady } = useAudioReady()
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
const [viewMode, setViewMode] = useState<'text' | 'duration'>('text')
@@ -191,7 +194,8 @@ export default function TranscriptionView({
size="icon"
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px]"
onClick={() => onPlaySegment?.(segment.start_time!)}
title={t('playSegment')}
disabled={!audioReady}
title={audioReady ? t('playSegment') : tHeader('audioStillLoading')}
>
<Play className="h-3.5 w-3.5" />
</Button>
@@ -0,0 +1,97 @@
/**
* @jest-environment jsdom
*/
import { render, screen, act } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import enMessages from '@/messages/en.json'
import AudioPlayer, { AUDIO_READY_EVENT } from '../AudioPlayer'
// Capture every Audio element AudioPlayer constructs so tests can drive media events.
let created: HTMLAudioElement[]
beforeEach(() => {
created = []
;(global as unknown as { Audio: unknown }).Audio = jest.fn().mockImplementation((src?: string) => {
const a = document.createElement('audio')
if (src) a.src = src
// jsdom doesn't implement play(); make it a resolved promise so .catch() is safe.
a.play = jest.fn().mockResolvedValue(undefined)
a.pause = jest.fn()
created.push(a)
return a
})
})
afterEach(() => {
delete (window as Window).isAudioReady
delete (window as Window).seekAndPlayAudio
delete (window as Window).toggleAudioPlayback
jest.restoreAllMocks()
})
function renderPlayer(audioUrl: string | null = 'https://example.test/audio.mp3') {
return render(
<NextIntlClientProvider locale="en" messages={enMessages}>
<AudioPlayer audioUrl={audioUrl} />
</NextIntlClientProvider>
)
}
function fireOnAudio(type: string) {
act(() => {
created[0].dispatchEvent(new Event(type))
})
}
describe('AudioPlayer readiness gating', () => {
it('renders nothing without an audioUrl', () => {
const { container } = renderPlayer(null)
expect(container).toBeEmptyDOMElement()
})
it('shows the loading state and is not ready before canplaythrough', () => {
renderPlayer()
expect(screen.getByText('Loading audio...')).toBeInTheDocument()
// No play button while loading.
expect(screen.queryByRole('button')).not.toBeInTheDocument()
expect(window.isAudioReady).toBe(false)
})
it('imperative globals no-op until ready, then play', () => {
renderPlayer()
// Before ready: seekAndPlay must not touch the media element.
act(() => {
window.seekAndPlayAudio?.(12)
})
expect(created[0].play).not.toHaveBeenCalled()
fireOnAudio('canplaythrough')
expect(window.isAudioReady).toBe(true)
act(() => {
window.seekAndPlayAudio?.(12)
})
expect(created[0].play).toHaveBeenCalledTimes(1)
expect(created[0].currentTime).toBe(12)
})
it('reveals playback controls and publishes ready once canplaythrough fires', () => {
const onReady = jest.fn()
window.addEventListener(AUDIO_READY_EVENT, onReady)
renderPlayer()
fireOnAudio('canplaythrough')
expect(screen.queryByText('Loading audio...')).not.toBeInTheDocument()
expect(screen.getByRole('button')).toBeInTheDocument()
expect(onReady).toHaveBeenCalled()
window.removeEventListener(AUDIO_READY_EVENT, onReady)
})
it('shows an error state and stays not-ready on media error', () => {
renderPlayer()
fireOnAudio('error')
expect(screen.getByText("Couldn't load audio")).toBeInTheDocument()
expect(window.isAudioReady).toBe(false)
})
})
@@ -0,0 +1,75 @@
import { render, screen } from '@testing-library/react'
import EditModal from '../modals/EditModal'
import { LyricsSegment } from '@/lib/lyrics-review/types'
// Mock complex sub-components that have their own heavy dependencies
jest.mock('../EditWordList', () => ({
__esModule: true,
default: () => <div data-testid="edit-word-list">EditWordList</div>,
}))
jest.mock('../EditTimelineSection', () => ({
__esModule: true,
default: () => <div data-testid="edit-timeline-section">EditTimelineSection</div>,
}))
// Mock sonner toast to avoid jsdom issues
jest.mock('sonner', () => ({
toast: {
warning: jest.fn(),
error: jest.fn(),
success: jest.fn(),
},
}))
// Mock useAudioReady to avoid window event listeners
jest.mock('@/lib/lyrics-review/hooks/useAudioReady', () => ({
useAudioReady: () => ({ ready: true, progress: 1 }),
}))
// Mock setModalHandler to avoid global keyboard state side-effects
jest.mock('@/lib/lyrics-review/utils/keyboardHandlers', () => ({
setModalHandler: jest.fn(),
}))
const cleanWord = { id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 }
const badSegment: LyricsSegment = {
id: 's1',
text: 'A whiskey and a beer,',
start_time: 15.18,
end_time: 18.04,
words: [
{ id: 'a', text: 'A', start_time: 0, end_time: -0.005 },
{ id: 'b', text: 'whiskey', start_time: 0, end_time: -0.005 },
{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 },
],
}
const cleanSegment: LyricsSegment = {
...badSegment,
words: [cleanWord],
}
function renderModal(segment: LyricsSegment) {
return render(
<EditModal
open
segment={segment}
segmentIndex={0}
originalSegment={segment}
onClose={() => {}}
onSave={() => {}}
/>
)
}
it('shows the timing-repaired banner when a segment opens with out-of-bounds words', () => {
renderModal(badSegment)
expect(screen.getByTestId('timing-sanitized-banner')).toBeInTheDocument()
})
it('shows no banner for a clean segment', () => {
renderModal(cleanSegment)
expect(screen.queryByTestId('timing-sanitized-banner')).not.toBeInTheDocument()
})
@@ -2,6 +2,7 @@
import { useTranslations } from 'next-intl'
import { useState, useEffect, useCallback, useRef } from 'react'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Loader2, Play, Square, RotateCcw, Trash2, History } from 'lucide-react'
@@ -11,7 +12,9 @@ import EditWordList from '../EditWordList'
import EditTimelineSection from '../EditTimelineSection'
import useManualSync from '@/hooks/useManualSync'
import { setModalHandler } from '@/lib/lyrics-review/utils/keyboardHandlers'
import { useAudioReady } from '@/lib/lyrics-review/hooks/useAudioReady'
import { splitWordWithTiming, createWordsWithDistributedTiming } from '@/lib/lyrics-review/utils/wordUtils'
import { sanitizeSegmentTimings } from '@/lib/lyrics-review/sanitizeWordTimings'
interface EditModalProps {
open: boolean
@@ -52,7 +55,10 @@ export default function EditModal({
}: EditModalProps) {
const t = useTranslations('lyricsReview.modals.editAll')
const tActions = useTranslations('lyricsReview.editActionBar')
const tHeader = useTranslations('lyricsReview.header')
const { ready: audioReady } = useAudioReady()
const [editedSegment, setEditedSegment] = useState<LyricsSegment | null>(segment)
const [timingFixCount, setTimingFixCount] = useState(0)
const [isPlaying, setIsPlaying] = useState(false)
const currentTimeRef = useRef(currentTime)
@@ -62,7 +68,14 @@ export default function EditModal({
}, [currentTime])
useEffect(() => {
setEditedSegment(segment)
if (!segment) {
setEditedSegment(null)
setTimingFixCount(0)
return
}
const { segment: cleaned, changes } = sanitizeSegmentTimings(segment)
setEditedSegment(cleaned)
setTimingFixCount(changes.length)
}, [segment])
// Track playing state from global window
@@ -94,6 +107,13 @@ export default function EditModal({
})
}, [editedSegment])
const handleTimingClamped = useCallback(
(wordText: string, snappedTo: number) => {
toast.warning(t('timingClamped', { word: wordText, time: snappedTo.toFixed(2) }))
},
[t] // toast is a module-level singleton; t is stable in next-intl
)
// Manual sync hook
const {
isManualSyncing,
@@ -109,6 +129,7 @@ export default function EditModal({
currentTime,
onPlaySegment,
updateSegment,
onTimingClamped: handleTimingClamped,
})
// Wire up spacebar handler - use setModalHandler directly for proper modal state
@@ -264,12 +285,16 @@ export default function EditModal({
const handleReset = useCallback(() => {
if (!originalSegment) return
setEditedSegment(JSON.parse(JSON.stringify(originalSegment)))
const { segment: cleaned, changes } = sanitizeSegmentTimings(JSON.parse(JSON.stringify(originalSegment)))
setEditedSegment(cleaned)
setTimingFixCount(changes.length)
}, [originalSegment])
const handleRevertToOriginal = useCallback(() => {
if (!originalTranscribedSegment) return
setEditedSegment(JSON.parse(JSON.stringify(originalTranscribedSegment)))
const { segment: cleaned, changes } = sanitizeSegmentTimings(JSON.parse(JSON.stringify(originalTranscribedSegment)))
setEditedSegment(cleaned)
setTimingFixCount(changes.length)
}, [originalTranscribedSegment])
const handleClose = useCallback(() => {
@@ -368,6 +393,8 @@ export default function EditModal({
size="icon"
className="h-8 w-8"
onClick={handlePlayToggle}
disabled={!audioReady}
title={audioReady ? undefined : tHeader('audioStillLoading')}
>
{isPlaying ? <Square className="h-4 w-4" /> : <Play className="h-4 w-4" />}
</Button>
@@ -384,6 +411,17 @@ export default function EditModal({
</div>
) : editedSegment ? (
<div className="flex-1 overflow-auto space-y-4">
{timingFixCount > 0 && (
<div
role="status"
aria-live="polite"
data-testid="timing-sanitized-banner"
className="mb-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800"
>
{t('timingSanitized', { count: timingFixCount })}
</div>
)}
{/* Timeline editor with Tap To Sync */}
{editedSegment.words.some((w) => w.start_time !== null) && (
<EditTimelineSection
@@ -0,0 +1,113 @@
import { test, expect, Page } from '@playwright/test'
/**
* AI Auto-Correct Suggestions (production)
*
* Verifies the opt-in AI suggestions flow end-to-end against live production:
* 1. Lists jobs filtered by status=in_review (admin can see all jobs).
* 2. Navigates to the lyrics review page for the first matching job.
* 3. Opens the "Auto-correct" modal and runs suggestion generation.
* 4. Waits for the suggestions panel (up to 120s for the LLM call).
* 5. Asserts the panel renders with accept/reject affordances (or the
* explicit "no suggestions" state), then dismisses it WITHOUT
* accepting — production review state is never mutated.
*
* Skipped if KARAOKE_ADMIN_TOKEN is unset or no in_review jobs exist.
*
* Run with:
* KARAOKE_ADMIN_TOKEN=xxx npx playwright test \
* e2e/production/auto-correct-suggestions.spec.ts \
* --config=playwright.production.config.ts --reporter=list
*/
const PROD_URL = 'https://gen.nomadkaraoke.com'
const API_URL = 'https://api.nomadkaraoke.com'
const ADMIN_TOKEN = process.env.KARAOKE_ADMIN_TOKEN
async function openReviewPage(page: Page): Promise<string> {
const listResponse = await page.request.get(
`${API_URL}/api/jobs?status=in_review&limit=1&fields=summary`,
{ headers: { Authorization: `Bearer ${ADMIN_TOKEN}` } },
)
expect(listResponse.ok()).toBe(true)
const listBody = (await listResponse.json()) as
| { jobs?: Array<{ id?: string; job_id?: string }> }
| Array<{ id?: string; job_id?: string }>
const jobs = Array.isArray(listBody) ? listBody : listBody.jobs ?? []
test.skip(!jobs.length, 'No in_review jobs available for E2E')
const jobId = jobs[0].id ?? jobs[0].job_id
expect(jobId, 'List response did not include a job id').toBeTruthy()
await page.addInitScript((token: string) => {
window.localStorage.setItem('karaoke_access_token', token)
}, ADMIN_TOKEN!)
await page.goto(`${PROD_URL}/app/jobs/#/${jobId}/review`)
return jobId as string
}
test.describe('AI auto-correct suggestions (production)', () => {
test.skip(!ADMIN_TOKEN, 'KARAOKE_ADMIN_TOKEN not set')
// No retries: each retry would be another paid LLM call.
test.describe.configure({ retries: 0 })
test('run suggestions, review panel, dismiss without applying', async ({
page,
}: {
page: Page
}) => {
test.setTimeout(180_000) // includes one LLM call (~15-60s)
await openReviewPage(page)
// Generous timeout: right after a deploy the first review-page load can
// exceed 30s (cold Cloud Run instance + uncached correction payload).
// A "Saved Review Sessions" dialog may open on load (it aria-hides the
// rest of the app); close it without restoring before proceeding.
const suggestBtn = page.getByRole('button', { name: /Auto-correct/i })
const sessionDialog = page.getByRole('dialog', { name: /Saved Review Sessions/i })
await expect(suggestBtn.or(sessionDialog).first()).toBeVisible({ timeout: 90_000 })
if (await sessionDialog.isVisible().catch(() => false)) {
await sessionDialog.getByRole('button', { name: /^Close$/i }).click()
await expect(sessionDialog).not.toBeVisible()
}
await expect(suggestBtn).toBeVisible({ timeout: 30_000 })
await suggestBtn.click()
// Settings modal appears with the run button (or the no-references
// warning, in which case the flow correctly ends here).
const runBtn = page.getByRole('button', { name: /Get suggestions/i })
const noRefs = page.getByText(/No reference lyrics are available/i)
await expect(runBtn.or(noRefs).first()).toBeVisible({ timeout: 10_000 })
if (await noRefs.isVisible().catch(() => false)) {
test.info().annotations.push({
type: 'note',
description: 'Job had no reference lyrics; verified disabled state.',
})
return
}
await runBtn.click()
// Panel appears after the LLM call: either a suggestions summary with
// Accept all / Reject all, or the explicit no-suggestions state.
const summary = page.getByText(/suggestions? · .* pending/i)
const none = page.getByText(/no issues found/i)
await expect(summary.or(none).first()).toBeVisible({ timeout: 120_000 })
if (await summary.isVisible().catch(() => false)) {
await expect(
page.getByRole('button', { name: /Accept all/i }),
).toBeVisible()
await expect(
page.getByRole('button', { name: /Reject all/i }),
).toBeVisible()
}
// Dismiss without accepting anything — leaves review state untouched.
await page.getByRole('button', { name: /Dismiss suggestions/i }).click()
await expect(summary.or(none).first()).not.toBeVisible()
})
})
@@ -0,0 +1,16 @@
import { clampSyncTime } from '../useManualSync'
describe('clampSyncTime', () => {
it('clamps a playhead-at-0 tap up to the segment start', () => {
expect(clampSyncTime(0, 15.18, 18.04)).toBe(15.18)
})
it('clamps a tap past the segment end down to the end', () => {
expect(clampSyncTime(99, 15.18, 18.04)).toBe(18.04)
})
it('leaves an in-window tap unchanged', () => {
expect(clampSyncTime(16.0, 15.18, 18.04)).toBe(16.0)
})
it('falls back gracefully when segment bounds are null', () => {
expect(clampSyncTime(5, null, null)).toBe(5)
})
})
+311
View File
@@ -0,0 +1,311 @@
'use client'
/**
* State machine for the opt-in AI auto-correct suggestions feature.
*
* Nothing runs unless the reviewer explicitly triggers it; suggestions are a
* pending layer that never mutates the working data until individually (or
* bulk) accepted. Every accept/reject/undo lands in the edit log so we can
* measure real-world accept rates per category over time.
*/
import { useCallback, useEffect, useRef, useState } from 'react'
import {
AiSuggestion,
AutoCorrectApiError,
AutoCorrectSettings,
DEFAULT_AUTO_CORRECT_SETTINGS,
fetchAutoCorrectSuggestions,
} from '@/lib/api/autoCorrect'
import {
applySuggestion,
revertSuggestion,
isSuggestionStale,
SuggestionUndoInfo,
} from '@/lib/lyrics-review/utils/autoCorrectApply'
import {
getConflictSiblings,
pickAcceptAllWinners,
} from '@/lib/lyrics-review/utils/autoCorrectConflicts'
import { addEditEntry } from '@/lib/lyrics-review/utils/editLog'
import type { CorrectionData, EditLog } from '@/lib/lyrics-review/types'
export type SuggestionDecision = 'pending' | 'accepted' | 'rejected' | 'stale'
export type AutoCorrectStatus = 'idle' | 'running' | 'reviewing' | 'error'
interface UseAutoCorrectArgs {
jobId?: string
data: CorrectionData
updateDataWithHistory: (newData: CorrectionData, desc?: string) => void
editLog: EditLog
getAuthToken: () => string | undefined
/** Auto-trigger one run on load (when references exist) so suggestions are
* ready without a click. Normally a cache hit (backend pre-generates). */
autoRunOnLoad?: boolean
}
export function useAutoCorrect({
jobId,
data,
updateDataWithHistory,
editLog,
getAuthToken,
autoRunOnLoad = false,
}: UseAutoCorrectArgs) {
const [status, setStatus] = useState<AutoCorrectStatus>('idle')
const [suggestions, setSuggestions] = useState<AiSuggestion[]>([])
const [decisions, setDecisions] = useState<Record<string, SuggestionDecision>>({})
const [model, setModel] = useState<string>('')
const [cached, setCached] = useState(false)
const [error, setError] = useState<string | null>(null)
const undoInfos = useRef<Record<string, SuggestionUndoInfo>>({})
const abortRef = useRef<AbortController | null>(null)
const hasReferences = Object.keys(data.reference_lyrics ?? {}).length > 0
// Abort any in-flight request on unmount so no state updates land after.
useEffect(() => {
return () => {
abortRef.current?.abort()
}
}, [])
const run = useCallback(
async (settings: AutoCorrectSettings = DEFAULT_AUTO_CORRECT_SETTINGS) => {
if (!jobId) return
setStatus('running')
setError(null)
abortRef.current?.abort()
const ac = new AbortController()
abortRef.current = ac
try {
const response = await fetchAutoCorrectSuggestions(
jobId,
{
segments: data.corrected_segments,
referenceLyrics: data.reference_lyrics ?? {},
artist: data.metadata?.artist,
title: data.metadata?.title,
settings,
},
ac.signal,
getAuthToken(),
)
setSuggestions(response.suggestions)
setDecisions(
Object.fromEntries(response.suggestions.map((s) => [s.id, 'pending'])),
)
undoInfos.current = {}
setModel(response.model)
setCached(response.cached)
setStatus('reviewing')
addEditEntry(editLog, 'ai_suggestion_run', {
details: {
model: response.model,
cached: response.cached,
suggestion_count: response.suggestions.length,
elapsed_seconds: response.elapsed_seconds,
settings: response.settings_applied as unknown as Record<string, unknown>,
},
})
} catch (err) {
if ((err as Error).name === 'AbortError') {
setStatus('idle')
return
}
const message =
err instanceof AutoCorrectApiError
? err.message
: 'Unexpected error generating suggestions'
setError(message)
setStatus('error')
}
},
[jobId, data, editLog, getAuthToken],
)
const cancel = useCallback(() => {
abortRef.current?.abort()
}, [])
// Fire exactly one run on load once references + segments are available.
// The ref guard ensures it never re-fires as `data` changes during review.
const autoRanRef = useRef(false)
useEffect(() => {
if (!autoRunOnLoad || autoRanRef.current) return
if (!jobId || status !== 'idle') return
if (!hasReferences || !(data.corrected_segments?.length > 0)) return
autoRanRef.current = true
void run()
}, [autoRunOnLoad, jobId, status, hasReferences, data.corrected_segments, run])
const logDecision = useCallback(
(s: AiSuggestion, op: 'ai_suggestion_accept' | 'ai_suggestion_reject' | 'ai_suggestion_undo') => {
addEditEntry(editLog, op, {
segment_id: s.segment_ids[0] ?? null,
word_ids_before: s.word_ids,
text_before: s.original_text,
text_after: s.new_text,
details: {
suggestion_id: s.id,
op: s.op,
category: s.category,
confidence: s.confidence,
reason: s.reason,
model,
models: s.models,
consensus: s.consensus,
total_models: s.total_models,
conflict_group: s.conflict_group,
},
})
},
[editLog, model],
)
const accept = useCallback(
(id: string) => {
const s = suggestions.find((x) => x.id === id)
if (!s || decisions[id] !== 'pending') return
const result = applySuggestion(data.corrected_segments, s)
if (!result) {
setDecisions((d) => ({ ...d, [id]: 'stale' }))
return
}
undoInfos.current[id] = result.undo
updateDataWithHistory(
{ ...data, corrected_segments: result.segments },
'accept AI suggestion',
)
// Accepting one variant of a conflict group rejects the others —
// they target the same words with a different outcome.
const siblingUpdates: Record<string, SuggestionDecision> = {}
for (const sibling of getConflictSiblings(suggestions, id)) {
if (decisions[sibling.id] === 'pending') {
siblingUpdates[sibling.id] = 'rejected'
logDecision(sibling, 'ai_suggestion_reject')
}
}
setDecisions((d) => ({ ...d, ...siblingUpdates, [id]: 'accepted' }))
logDecision(s, 'ai_suggestion_accept')
},
[suggestions, decisions, data, updateDataWithHistory, logDecision],
)
const reject = useCallback(
(id: string) => {
const s = suggestions.find((x) => x.id === id)
if (!s || decisions[id] !== 'pending') return
setDecisions((d) => ({ ...d, [id]: 'rejected' }))
logDecision(s, 'ai_suggestion_reject')
},
[suggestions, decisions, logDecision],
)
const undoAccept = useCallback(
(id: string): boolean => {
const s = suggestions.find((x) => x.id === id)
const undo = undoInfos.current[id]
if (!s || decisions[id] !== 'accepted' || !undo) return false
const reverted = revertSuggestion(data.corrected_segments, undo)
if (!reverted) return false
delete undoInfos.current[id]
updateDataWithHistory(
{ ...data, corrected_segments: reverted },
'undo AI suggestion',
)
setDecisions((d) => ({ ...d, [id]: 'pending' }))
logDecision(s, 'ai_suggestion_undo')
return true
},
[suggestions, decisions, data, updateDataWithHistory, logDecision],
)
const acceptAll = useCallback(() => {
let segments = data.corrected_segments
const newDecisions: Record<string, SuggestionDecision> = { ...decisions }
// In conflict groups only the winner (highest consensus, then
// confidence) is applied; the losing variants are rejected.
const winners = new Set(
pickAcceptAllWinners(suggestions.filter((s) => newDecisions[s.id] === 'pending')),
)
let applied = 0
for (const s of suggestions) {
if (newDecisions[s.id] !== 'pending') continue
if (!winners.has(s.id)) {
newDecisions[s.id] = 'rejected'
logDecision(s, 'ai_suggestion_reject')
continue
}
const result = applySuggestion(segments, s)
if (!result) {
newDecisions[s.id] = 'stale'
continue
}
segments = result.segments
undoInfos.current[s.id] = result.undo
newDecisions[s.id] = 'accepted'
logDecision(s, 'ai_suggestion_accept')
applied += 1
}
if (applied > 0) {
updateDataWithHistory(
{ ...data, corrected_segments: segments },
'accept all AI suggestions',
)
}
setDecisions(newDecisions)
}, [suggestions, decisions, data, updateDataWithHistory, logDecision])
const rejectAll = useCallback(() => {
const newDecisions: Record<string, SuggestionDecision> = { ...decisions }
for (const s of suggestions) {
if (newDecisions[s.id] !== 'pending') continue
newDecisions[s.id] = 'rejected'
logDecision(s, 'ai_suggestion_reject')
}
setDecisions(newDecisions)
}, [suggestions, decisions, logDecision])
const dismiss = useCallback(() => {
abortRef.current?.abort()
setStatus('idle')
setSuggestions([])
setDecisions({})
undoInfos.current = {}
setError(null)
}, [])
/** Recompute staleness for pending suggestions against the latest data. */
const isPendingAndStale = useCallback(
(s: AiSuggestion) =>
decisions[s.id] === 'pending' &&
isSuggestionStale(data.corrected_segments, s),
[decisions, data.corrected_segments],
)
const pendingCount = suggestions.filter((s) => decisions[s.id] === 'pending').length
const acceptedCount = suggestions.filter((s) => decisions[s.id] === 'accepted').length
return {
status,
suggestions,
decisions,
model,
cached,
error,
hasReferences,
pendingCount,
acceptedCount,
run,
cancel,
accept,
reject,
undoAccept,
acceptAll,
rejectAll,
dismiss,
isPendingAndStale,
}
}
export type AutoCorrectController = ReturnType<typeof useAutoCorrect>
+48 -10
View File
@@ -8,6 +8,23 @@ interface UseManualSyncProps {
currentTime: number
onPlaySegment?: (startTime: number) => void
updateSegment: (words: Word[]) => void
onTimingClamped?: (wordText: string, snappedTo: number) => void
}
/**
* Clamp a manual-sync tap time into the segment's audio window. A tap should always land
* within the segment being synced; a value outside (e.g. the playhead sitting at 0) is a
* sync glitch — the source of the start=0/end=-0.005 corruption. Null bounds => no clamp.
*/
export function clampSyncTime(
time: number,
segStart: number | null,
segEnd: number | null
): number {
let t = time
if (typeof segStart === 'number' && Number.isFinite(segStart)) t = Math.max(t, segStart)
if (typeof segEnd === 'number' && Number.isFinite(segEnd)) t = Math.min(t, segEnd)
return t
}
// Constants for tap detection
@@ -20,6 +37,7 @@ export default function useManualSync({
currentTime,
onPlaySegment,
updateSegment,
onTimingClamped,
}: UseManualSyncProps) {
const [isManualSyncing, setIsManualSyncing] = useState(false)
const [isPaused, setIsPaused] = useState(false)
@@ -120,7 +138,16 @@ export default function useManualSync({
if (syncWordIndex < editedSegment.words.length) {
const newWords = [...wordsRef.current]
const currentWord = newWords[syncWordIndex]
const currentStartTime = currentTimeRef.current
const rawStartTime = currentTimeRef.current
// Keep this clamp+callback block in sync with the other sync path
const currentStartTime = clampSyncTime(
rawStartTime,
editedSegment?.start_time ?? null,
editedSegment?.end_time ?? null
)
if (currentStartTime !== rawStartTime) {
onTimingClamped?.(newWords[syncWordIndex]?.text ?? '', currentStartTime)
}
// Set the start time for the current word
currentWord.start_time = currentStartTime
@@ -141,7 +168,7 @@ export default function useManualSync({
previousWord.end_time = previousWord.start_time + 0.5
} else {
// Normal flow - set previous word's end time to current word's start time minus 5ms
previousWord.end_time = currentStartTime - 0.005
previousWord.end_time = Math.max(currentStartTime - 0.005, previousWord.start_time ?? (currentStartTime - 0.005))
}
}
}
@@ -172,7 +199,7 @@ export default function useManualSync({
}
}
},
[isManualSyncing, editedSegment, syncWordIndex, onPlaySegment, isSpacebarPressed, isPaused]
[isManualSyncing, editedSegment, syncWordIndex, onPlaySegment, isSpacebarPressed, isPaused, onTimingClamped]
)
const handleKeyUp = useCallback(
@@ -199,10 +226,11 @@ export default function useManualSync({
// For a tap, set a default duration
const defaultEndTime =
(wordStartTimeRef.current || currentTimeRef.current) + DEFAULT_WORD_DURATION
currentWord.end_time = defaultEndTime
currentWord.end_time = Math.max(defaultEndTime, currentWord.start_time ?? defaultEndTime)
} else {
// For a hold, use the current time as the end time
currentWord.end_time = currentTimeRef.current
const rawEndTime = currentTimeRef.current
currentWord.end_time = Math.max(rawEndTime, currentWord.start_time ?? rawEndTime)
}
// Update our ref
@@ -283,7 +311,16 @@ export default function useManualSync({
if (syncWordIndex < editedSegment.words.length) {
const newWords = [...wordsRef.current]
const currentWord = newWords[syncWordIndex]
const currentStartTime = currentTimeRef.current
const rawStartTime = currentTimeRef.current
// Keep this clamp+callback block in sync with the other sync path
const currentStartTime = clampSyncTime(
rawStartTime,
editedSegment?.start_time ?? null,
editedSegment?.end_time ?? null
)
if (currentStartTime !== rawStartTime) {
onTimingClamped?.(newWords[syncWordIndex]?.text ?? '', currentStartTime)
}
// Set the start time for the current word
currentWord.start_time = currentStartTime
@@ -302,7 +339,7 @@ export default function useManualSync({
if (timeSincePreviousStart > 1.0) {
previousWord.end_time = previousWord.start_time + 0.5
} else {
previousWord.end_time = currentStartTime - 0.005
previousWord.end_time = Math.max(currentStartTime - 0.005, previousWord.start_time ?? (currentStartTime - 0.005))
}
}
}
@@ -314,7 +351,7 @@ export default function useManualSync({
// Mark that we need to update the segment
needsSegmentUpdateRef.current = true
}
}, [isManualSyncing, editedSegment, syncWordIndex, isSpacebarPressed, isPaused])
}, [isManualSyncing, editedSegment, syncWordIndex, isSpacebarPressed, isPaused, onTimingClamped])
const handleTapEnd = useCallback(() => {
if (!isManualSyncing || !editedSegment || !isSpacebarPressed || isPaused) return
@@ -334,9 +371,10 @@ export default function useManualSync({
if (isTap) {
const defaultEndTime =
(wordStartTimeRef.current || currentTimeRef.current) + DEFAULT_WORD_DURATION
currentWord.end_time = defaultEndTime
currentWord.end_time = Math.max(defaultEndTime, currentWord.start_time ?? defaultEndTime)
} else {
currentWord.end_time = currentTimeRef.current
const rawEndTime = currentTimeRef.current
currentWord.end_time = Math.max(rawEndTime, currentWord.start_time ?? rawEndTime)
}
// Update our ref
+3
View File
@@ -76,6 +76,9 @@ function resetStore() {
error: null,
isInitialized: false,
})
// The store now mirrors resolved config onto window.__TENANT_CONFIG__ (so lib/api.ts
// can read it synchronously). Clear it between tests to keep them isolated.
delete (window as { __TENANT_CONFIG__?: unknown }).__TENANT_CONFIG__
}
describe("useTenant store", () => {
+42 -2
View File
@@ -55,10 +55,45 @@ function getLocaleFromPath(): string {
return 'en';
}
function getAuthHeaders(): HeadersInit {
const headers: HeadersInit = {
/**
* Resolve the current white-label tenant id, if any.
*
* On tenant portals the Cloudflare Pages edge function (frontend/functions/[[path]].ts)
* injects `window.__TENANT_CONFIG__` into the HTML before any app JS runs, and the
* tenant store (lib/tenant.ts) mirrors the same shape there in dev/preview. Reading it
* directly here keeps api.ts free of an import cycle with tenant.ts (which imports
* API_BASE_URL from this module).
*
* Returns null on the consumer build / consumer domain, so no tenant header is sent and
* existing consumer behavior is unchanged.
*/
export function getTenantId(): string | null {
if (typeof window === 'undefined') return null;
const injected = (window as { __TENANT_CONFIG__?: { tenant?: { id?: string } | null } }).__TENANT_CONFIG__;
const id = injected?.tenant?.id;
return typeof id === 'string' && id ? id : null;
}
/**
* Base headers attached to every API request: locale, and the X-Tenant-ID header when
* on a white-label tenant portal. The shared backend (api.nomadkaraoke.com) cannot infer
* the tenant from the Host (it's not the tenant subdomain) or from the prod-disabled
* `?tenant=` query param, so this header is the primary tenant-detection signal that lets
* the backend apply tenant config (locked theme, Dropbox path, no YouTube/GDrive).
*/
function getBaseHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Accept-Language': getLocaleFromPath(),
};
const tenantId = getTenantId();
if (tenantId) {
headers['X-Tenant-ID'] = tenantId;
}
return headers;
}
function getAuthHeaders(): HeadersInit {
const headers: Record<string, string> = getBaseHeaders();
const token = getAccessToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
@@ -1285,6 +1320,11 @@ export const api = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Carry tenant context so the backend validates the email domain against the
// tenant, embeds tenant_id in the magic-link token, and uses the tenant's
// sender email + portal URL. Without this, tenant sign-in silently falls back
// to the consumer (nomad) flow.
...getBaseHeaders(),
},
body: JSON.stringify(body),
});
+148
View File
@@ -0,0 +1,148 @@
/**
* Client for the AI auto-correct suggestions endpoint.
*
* POST /api/review/{job_id}/auto-correct
*
* Stateless: posts the client's current working segments + reference lyrics
* and returns word-id-keyed suggestions. Nothing is applied server-side —
* the reviewer accepts/rejects each suggestion in the UI and persistence
* flows through the existing corrections/complete paths.
*/
import type { LyricsSegment, ReferenceSource } from '@/lib/lyrics-review/types'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
export type AiSuggestionOp = 'replace' | 'delete' | 'insert_after'
export type AiSuggestionCategory =
| 'mishearing'
| 'grammar'
| 'adlib_removal'
| 'repeated_chorus_fix'
| 'formatting'
| 'other'
export interface AutoCorrectSettings {
suggest_adlib_removal: boolean
allow_insertions: boolean
min_confidence: number
/** Query all configured models in parallel and report consensus. */
compare_models: boolean
}
export const DEFAULT_AUTO_CORRECT_SETTINGS: AutoCorrectSettings = {
suggest_adlib_removal: true,
allow_insertions: true,
min_confidence: 0,
// Always multi-model. Kept in sync with the backend proactive run
// (AutoCorrectSettings(compare_models=True)) so the on-load request is a
// cache hit. Not user-configurable.
compare_models: true,
}
export interface AiSuggestion {
id: string
op: AiSuggestionOp
word_ids: string[]
segment_ids: string[]
original_text: string
new_text: string
reason: string
category: AiSuggestionCategory
confidence: number
/** Models that proposed this exact suggestion. */
models: string[]
/** How many of total_models agreed on this exact suggestion. */
consensus: number
total_models: number
/** Suggestions sharing a conflict_group target overlapping words with
* different outcomes — accept at most one per group. */
conflict_group: string | null
}
export interface AutoCorrectResponse {
suggestions: AiSuggestion[]
model: string
elapsed_seconds: number
settings_applied: AutoCorrectSettings
warnings: string[]
/** Served from the per-job cache — no AI cost was incurred. */
cached: boolean
}
export class AutoCorrectApiError extends Error {
readonly status: number
constructor(status: number, message: string) {
super(message)
this.name = 'AutoCorrectApiError'
this.status = status
}
}
export interface AutoCorrectParams {
segments: LyricsSegment[]
referenceLyrics: Record<string, ReferenceSource>
artist?: string
title?: string
settings: AutoCorrectSettings
}
export async function fetchAutoCorrectSuggestions(
jobId: string,
params: AutoCorrectParams,
signal?: AbortSignal,
token?: string,
): Promise<AutoCorrectResponse> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
}
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/auto-correct`,
{
method: 'POST',
headers,
signal,
body: JSON.stringify({
segments: params.segments,
reference_lyrics: params.referenceLyrics,
artist: params.artist,
title: params.title,
settings: params.settings,
}),
},
)
if (!response.ok) {
let detail = `Request failed (${response.status})`
try {
const body = await response.json()
if (body && typeof body.detail === 'string') detail = body.detail
} catch {
/* swallow JSON parse errors and use generic message */
}
throw new AutoCorrectApiError(response.status, detail)
}
const data = await response.json()
const rawSuggestions: AiSuggestion[] = Array.isArray(data.suggestions)
? data.suggestions
: []
return {
suggestions: rawSuggestions.map((s: AiSuggestion) => ({
...s,
models: s.models ?? [],
consensus: s.consensus ?? 1,
total_models: s.total_models ?? 1,
conflict_group: s.conflict_group ?? null,
})),
model: data.model,
elapsed_seconds: data.elapsed_seconds,
settings_applied: data.settings_applied,
warnings: data.warnings ?? [],
cached: data.cached ?? false,
}
}
+17
View File
@@ -90,8 +90,25 @@ function signatureFor(message: string, stack: string | null, source: string): st
return `${source}|${stack?.slice(0, 500) ?? message.slice(0, 500)}`
}
/**
* Benign errors that are routinely produced by the browser during normal use
* and carry no diagnostic value. The most common is a rejected
* `HTMLMediaElement.play()` promise (DOMException "AbortError") that fires when
* playback is interrupted by a pause / src change / unmount — e.g. clicking play
* on the lyrics-review audio while it is still loading. These must never reach
* the error monitor.
*/
function isBenignError(e: unknown): boolean {
if (e instanceof DOMException && e.name === 'AbortError') return true
// Some browsers surface the same media abort as a plain Error.
if (e instanceof Error && e.name === 'AbortError') return true
return false
}
export async function reportClientError(args: ReportArgs): Promise<void> {
try {
if (isBenignError(args.error)) return
const { message, stack } = normalizeError(args.error)
const sig = signatureFor(message, stack, args.source)
const now = Date.now()
@@ -0,0 +1,89 @@
import { sanitizeSegmentTimings } from '../sanitizeWordTimings'
import { LyricsSegment } from '../types'
// The exact shape that broke job 17f7c313.
function scalpSegment(): LyricsSegment {
return {
id: 's1',
text: 'A whiskey and a beer, ...',
start_time: 15.18,
end_time: 18.04,
words: [
{ id: 'a', text: 'A', start_time: 0, end_time: -0.005 },
{ id: 'b', text: 'whiskey', start_time: 0, end_time: -0.005 },
{ id: 'c', text: 'and', start_time: 0, end_time: 0 },
{ id: 'd', text: 'a', start_time: 0, end_time: 0 },
{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 },
],
}
}
describe('sanitizeSegmentTimings', () => {
it('clamps out-of-bounds leading words into the segment window', () => {
const { segment, changes } = sanitizeSegmentTimings(scalpSegment())
for (const w of segment.words) {
expect(w.start_time!).toBeGreaterThanOrEqual(15.18)
expect(w.end_time!).toBeGreaterThanOrEqual(w.start_time!)
expect(w.end_time!).toBeLessThanOrEqual(18.04 + 1e-9)
}
expect(changes.length).toBeGreaterThan(0)
expect(changes.some((c) => c.wordId === 'a')).toBe(true)
})
it('leaves already-valid segments untouched and reports no changes', () => {
const seg: LyricsSegment = {
id: 's', text: 'Filling up that cup', start_time: 21.4, end_time: 22.78,
words: [
{ id: 'w0', text: 'Filling', start_time: 21.4, end_time: 21.82 },
{ id: 'w1', text: 'up', start_time: 21.86, end_time: 22.1 },
{ id: 'w2', text: 'that', start_time: 22.14, end_time: 22.42 },
{ id: 'w3', text: 'cup', start_time: 22.46, end_time: 22.78 },
],
}
const { changes } = sanitizeSegmentTimings(seg)
expect(changes).toEqual([])
})
it('handles null word timings by clamping to the segment start', () => {
const seg: LyricsSegment = {
id: 's', text: 'x y', start_time: 5, end_time: 6,
words: [
{ id: 'w0', text: 'x', start_time: null, end_time: null },
{ id: 'w1', text: 'y', start_time: 5.5, end_time: 6 },
],
}
const { segment } = sanitizeSegmentTimings(seg)
expect(segment.words[0].start_time!).toBeGreaterThanOrEqual(5)
expect(segment.words[0].end_time!).toBeGreaterThanOrEqual(segment.words[0].start_time!)
})
it('places a word whose start is past the segment end at the previous word end, not collapsed', () => {
const seg: LyricsSegment = {
id: 's', text: 'x y', start_time: 10, end_time: 12,
words: [
{ id: 'w0', text: 'x', start_time: 10, end_time: 11 },
{ id: 'w1', text: 'y', start_time: 99, end_time: 100 },
],
}
const { segment } = sanitizeSegmentTimings(seg)
expect(segment.words[1].start_time!).toBe(11)
expect(segment.words[1].end_time!).toBeGreaterThanOrEqual(11)
expect(segment.words[1].end_time!).toBeLessThanOrEqual(12)
})
it('returns segment untouched when segment bounds are null (non-finite)', () => {
const seg: LyricsSegment = {
id: 's', text: 'hello world', start_time: null, end_time: null,
words: [
{ id: 'w0', text: 'hello', start_time: 3, end_time: 4 },
{ id: 'w1', text: 'world', start_time: 4, end_time: 5 },
],
}
const { segment: out, changes } = sanitizeSegmentTimings(seg)
expect(changes).toEqual([])
expect(out.words[0].start_time).toBe(3)
expect(out.words[0].end_time).toBe(4)
expect(out.words[1].start_time).toBe(4)
expect(out.words[1].end_time).toBe(5)
})
})
@@ -0,0 +1,56 @@
/**
* @jest-environment jsdom
*/
import { renderHook, act } from '@testing-library/react'
import { useAudioReady } from '@/lib/lyrics-review/hooks/useAudioReady'
import { AUDIO_READY_EVENT } from '@/components/lyrics-review/AudioPlayer'
describe('useAudioReady', () => {
afterEach(() => {
delete (window as Window).isAudioReady
delete (window as Window).audioLoadProgress
})
it('initialises from window state set before subscribing', () => {
window.isAudioReady = true
window.audioLoadProgress = 1
const { result } = renderHook(() => useAudioReady())
expect(result.current).toEqual({ ready: true, progress: 1 })
})
it('defaults to not-ready when nothing has been published', () => {
const { result } = renderHook(() => useAudioReady())
expect(result.current.ready).toBe(false)
expect(result.current.progress).toBe(0)
})
it('updates when AUDIO_READY_EVENT is dispatched', () => {
const { result } = renderHook(() => useAudioReady())
act(() => {
window.dispatchEvent(
new CustomEvent(AUDIO_READY_EVENT, { detail: { ready: false, progress: 0.42 } })
)
})
expect(result.current).toEqual({ ready: false, progress: 0.42 })
act(() => {
window.dispatchEvent(
new CustomEvent(AUDIO_READY_EVENT, { detail: { ready: true, progress: 1 } })
)
})
expect(result.current).toEqual({ ready: true, progress: 1 })
})
it('stops updating after unmount', () => {
const { result, unmount } = renderHook(() => useAudioReady())
unmount()
act(() => {
window.dispatchEvent(
new CustomEvent(AUDIO_READY_EVENT, { detail: { ready: true, progress: 1 } })
)
})
// Last observed value should remain the initial not-ready state.
expect(result.current.ready).toBe(false)
})
})
@@ -0,0 +1,44 @@
'use client'
import { useEffect, useState } from 'react'
import { AUDIO_READY_EVENT } from '@/components/lyrics-review/AudioPlayer'
export interface AudioReadyState {
/** True once the lyrics-review audio can play through without rebuffering. */
ready: boolean
/** Buffered fraction of the audio file, 0..1. */
progress: number
}
/**
* Reactive subscription to the lyrics-review audio readiness.
*
* AudioPlayer is the single source of truth: it owns the <audio> element, sets
* `window.isAudioReady` / `window.audioLoadProgress`, and dispatches
* AUDIO_READY_EVENT on every change. Components that trigger playback (segment
* play buttons, the edit modal) use this hook to disable their controls while
* the media is still loading.
*/
export function useAudioReady(): AudioReadyState {
const [state, setState] = useState<AudioReadyState>({ ready: false, progress: 0 })
useEffect(() => {
if (typeof window === 'undefined') return
// Sync immediately in case readiness was published before we subscribed.
setState({
ready: !!window.isAudioReady,
progress: window.audioLoadProgress ?? 0,
})
const onChange = (e: Event) => {
const detail = (e as CustomEvent<AudioReadyState>).detail
if (detail) setState({ ready: !!detail.ready, progress: detail.progress ?? 0 })
}
window.addEventListener(AUDIO_READY_EVENT, onChange)
return () => window.removeEventListener(AUDIO_READY_EVENT, onChange)
}, [])
return state
}
@@ -0,0 +1,86 @@
import { LyricsSegment, Word } from './types'
export interface TimingChange {
wordId: string
wordText: string
field: 'start_time' | 'end_time'
from: number | null
to: number
}
/**
* Clamp word timings for one segment into the segment's authoritative window.
*
* Behaviour:
* - If `segment.start_time` or `segment.end_time` is null/NaN/Infinity the segment
* bounds are unknown, so the segment is returned **untouched** with `changes: []`.
* (The editor derives segment bounds from word min/max on every edit; corrupted
* segment bounds are a separate concern.)
* - Each word's `start_time` and `end_time` are clamped into
* `[segment.start_time, segment.end_time]`.
* - Words whose `start_time` is missing or non-finite are placed at the previous
* word's (repaired) end time, keeping repaired words in order within the window.
* - `word.end_time` is forced `>= word.start_time` (after clamping).
* - Already-valid in-bounds word timings are left as-is; only out-of-window or
* missing values are corrected.
*
* These semantics intentionally mirror the shipped backend
* `SegmentResizer._sanitize_segment_timings`. Returns a NEW segment object plus the
* list of clamps applied so callers can warn. A clean segment returns the same word
* objects and `changes: []`.
*/
export function sanitizeSegmentTimings(segment: LyricsSegment): {
segment: LyricsSegment
changes: TimingChange[]
} {
// Guard: if segment bounds are non-finite we cannot clamp words — leave untouched.
if (!isFiniteNumber(segment.start_time) || !isFiniteNumber(segment.end_time)) {
return { segment, changes: [] }
}
const changes: TimingChange[] = []
const segStart = segment.start_time as number
const segEnd = Math.max(segment.end_time as number, segStart)
// Hoist clamp once — segStart/segEnd are constant for the whole segment.
const clamp = (v: number) => Math.min(Math.max(v, segStart), segEnd)
let prevEnd = segStart
const words: Word[] = segment.words.map((w) => {
const start = isFiniteNumber(w.start_time) ? (w.start_time as number) : null
const end = isFiniteNumber(w.end_time) ? (w.end_time as number) : null
// Invalid start = non-finite OR outside the segment window -> place at previous word's end.
const newStart = start !== null && start >= segStart && start <= segEnd
? start
: clamp(Math.max(prevEnd, segStart))
// Invalid end = non-finite, before start, or past segment end.
let newEnd: number
if (end !== null && end >= newStart && end <= segEnd) {
newEnd = end
} else {
newEnd = clamp(Math.max(newStart, end ?? newStart))
if (newEnd < newStart) newEnd = newStart
}
let next = w
if (newStart !== start) {
changes.push({ wordId: w.id, wordText: w.text, field: 'start_time', from: w.start_time, to: newStart })
next = { ...next, start_time: newStart }
}
if (newEnd !== end) {
changes.push({ wordId: w.id, wordText: w.text, field: 'end_time', from: w.end_time, to: newEnd })
next = { ...next, end_time: newEnd }
}
prevEnd = newEnd
return next
})
if (changes.length === 0) return { segment, changes }
return { segment: { ...segment, words }, changes }
}
function isFiniteNumber(v: number | null | undefined): boolean {
return typeof v === 'number' && Number.isFinite(v)
}
+1
View File
@@ -180,6 +180,7 @@ export type EditOperationType =
| 'segment_delete' | 'segment_add' | 'segment_split' | 'segment_merge'
| 'find_replace' | 'replace_all_lyrics' | 'change_case' | 'custom_lyrics_replace'
| 'timing_change' | 'revert_correction' | 'revert_all'
| 'ai_suggestion_run' | 'ai_suggestion_accept' | 'ai_suggestion_reject' | 'ai_suggestion_undo'
export type EditFeedbackReason =
| 'misheard_word' | 'wrong_lyrics' | 'spelling_punctuation'
@@ -0,0 +1,244 @@
import {
applySuggestion,
revertSuggestion,
isSuggestionStale,
} from '../autoCorrectApply'
import type { LyricsSegment } from '../../types'
import type { AiSuggestion } from '@/lib/api/autoCorrect'
function makeSegments(): LyricsSegment[] {
return [
{
id: 'seg-1',
text: "Sippin' on straight glory",
start_time: 10,
end_time: 12,
words: [
{ id: 'w0', text: "Sippin'", start_time: 10, end_time: 10.5 },
{ id: 'w1', text: 'on', start_time: 10.5, end_time: 11 },
{ id: 'w2', text: 'straight', start_time: 11, end_time: 11.5 },
{ id: 'w3', text: 'glory', start_time: 11.5, end_time: 12 },
],
},
{
id: 'seg-2',
text: 'oh oh oh',
start_time: 13,
end_time: 14.5,
words: [
{ id: 'w4', text: 'oh', start_time: 13, end_time: 13.5 },
{ id: 'w5', text: 'oh', start_time: 13.5, end_time: 14 },
{ id: 'w6', text: 'oh', start_time: 14, end_time: 14.5 },
],
},
]
}
function suggestion(partial: Partial<AiSuggestion>): AiSuggestion {
return {
id: 'sug-1',
op: 'replace',
word_ids: ['w3'],
segment_ids: ['seg-1'],
original_text: 'glory',
new_text: 'chlorine',
reason: 'reference match',
category: 'mishearing',
confidence: 0.95,
models: ['test-model'],
consensus: 1,
total_models: 1,
conflict_group: null,
...partial,
}
}
describe('applySuggestion', () => {
it('replaces a single word and rebuilds segment text', () => {
const result = applySuggestion(makeSegments(), suggestion({}))
expect(result).not.toBeNull()
const seg = result!.segments[0]
expect(seg.text).toBe("Sippin' on straight chlorine")
expect(seg.words).toHaveLength(4)
const newWord = seg.words[3]
expect(newWord.text).toBe('chlorine')
expect(newWord.id).not.toBe('w3')
expect(newWord.start_time).toBe(11.5)
expect(newWord.end_time).toBe(12)
expect(newWord.created_during_correction).toBe(true)
expect(result!.undo.newWordIds).toEqual([newWord.id])
expect(result!.undo.removedWords.map((w) => w.id)).toEqual(['w3'])
})
it('replaces a multi-word span with a different word count', () => {
const result = applySuggestion(
makeSegments(),
suggestion({
word_ids: ['w2', 'w3'],
original_text: 'straight glory',
new_text: 'straight-up chlorine gas',
}),
)
const seg = result!.segments[0]
expect(seg.words.map((w) => w.text)).toEqual([
"Sippin'",
'on',
'straight-up',
'chlorine',
'gas',
])
// timings distributed across the original 11→12 span
expect(seg.words[2].start_time).toBeCloseTo(11)
expect(seg.words[4].end_time).toBeCloseTo(12)
})
it('does not mutate the input segments', () => {
const input = makeSegments()
applySuggestion(input, suggestion({}))
expect(input[0].words[3].text).toBe('glory')
expect(input[0].text).toBe("Sippin' on straight glory")
})
it('deletes words and rebuilds text', () => {
const result = applySuggestion(
makeSegments(),
suggestion({
op: 'delete',
word_ids: ['w4', 'w5'],
segment_ids: ['seg-2'],
original_text: 'oh oh',
new_text: '',
}),
)
const seg = result!.segments[1]
expect(seg.words.map((w) => w.text)).toEqual(['oh'])
expect(seg.text).toBe('oh')
})
it('removes the segment entirely when a delete empties it', () => {
const result = applySuggestion(
makeSegments(),
suggestion({
op: 'delete',
word_ids: ['w4', 'w5', 'w6'],
segment_ids: ['seg-2'],
original_text: 'oh oh oh',
new_text: '',
}),
)
expect(result!.segments).toHaveLength(1)
expect(result!.undo.removedSegment).not.toBeNull()
expect(result!.undo.removedSegment!.index).toBe(1)
})
it('inserts words after the anchor', () => {
const result = applySuggestion(
makeSegments(),
suggestion({
op: 'insert_after',
word_ids: ['w1'],
original_text: '',
new_text: 'the',
}),
)
const seg = result!.segments[0]
expect(seg.words.map((w) => w.text)).toEqual([
"Sippin'",
'on',
'the',
'straight',
'glory',
])
// inserted word sits between anchor end (11) and next word start (11)
expect(seg.words[2].start_time).toBeGreaterThanOrEqual(11 - 1e-9)
})
it('returns null for stale suggestions (missing word ids)', () => {
expect(
applySuggestion(makeSegments(), suggestion({ word_ids: ['gone'] })),
).toBeNull()
})
it('returns null for non-contiguous word ids', () => {
expect(
applySuggestion(makeSegments(), suggestion({ word_ids: ['w1', 'w3'] })),
).toBeNull()
})
})
describe('revertSuggestion', () => {
it('round-trips a replace', () => {
const original = makeSegments()
const applied = applySuggestion(original, suggestion({}))!
const reverted = revertSuggestion(applied.segments, applied.undo)!
expect(reverted[0].words.map((w) => w.id)).toEqual(['w0', 'w1', 'w2', 'w3'])
expect(reverted[0].text).toBe("Sippin' on straight glory")
})
it('round-trips a delete', () => {
const applied = applySuggestion(
makeSegments(),
suggestion({
op: 'delete',
word_ids: ['w5'],
segment_ids: ['seg-2'],
original_text: 'oh',
new_text: '',
}),
)!
const reverted = revertSuggestion(applied.segments, applied.undo)!
expect(reverted[1].words.map((w) => w.id)).toEqual(['w4', 'w5', 'w6'])
})
it('round-trips a whole-segment delete', () => {
const applied = applySuggestion(
makeSegments(),
suggestion({
op: 'delete',
word_ids: ['w4', 'w5', 'w6'],
segment_ids: ['seg-2'],
original_text: 'oh oh oh',
new_text: '',
}),
)!
const reverted = revertSuggestion(applied.segments, applied.undo)!
expect(reverted).toHaveLength(2)
expect(reverted[1].id).toBe('seg-2')
expect(reverted[1].words).toHaveLength(3)
})
it('round-trips an insert_after', () => {
const applied = applySuggestion(
makeSegments(),
suggestion({
op: 'insert_after',
word_ids: ['w1'],
original_text: '',
new_text: 'the real',
}),
)!
const reverted = revertSuggestion(applied.segments, applied.undo)!
expect(reverted[0].words.map((w) => w.id)).toEqual(['w0', 'w1', 'w2', 'w3'])
})
it('returns null when the applied words were since removed', () => {
const applied = applySuggestion(makeSegments(), suggestion({}))!
const tampered = applied.segments.map((s) => ({
...s,
words: s.words.filter((w) => !applied.undo.newWordIds.includes(w.id)),
}))
expect(revertSuggestion(tampered, applied.undo)).toBeNull()
})
})
describe('isSuggestionStale', () => {
it('is false for intact targets', () => {
expect(isSuggestionStale(makeSegments(), suggestion({}))).toBe(false)
})
it('is true after the target word was edited away', () => {
const segments = makeSegments()
segments[0].words = segments[0].words.filter((w) => w.id !== 'w3')
expect(isSuggestionStale(segments, suggestion({}))).toBe(true)
})
})
@@ -0,0 +1,76 @@
import {
getConflictSiblings,
pickAcceptAllWinners,
} from '../autoCorrectConflicts'
import type { AiSuggestion } from '@/lib/api/autoCorrect'
function sugg(partial: Partial<AiSuggestion>): AiSuggestion {
return {
id: 'x',
op: 'replace',
word_ids: ['w1'],
segment_ids: ['s1'],
original_text: 'a',
new_text: 'b',
reason: '',
category: 'mishearing',
confidence: 0.9,
models: ['m1'],
consensus: 1,
total_models: 2,
conflict_group: null,
...partial,
}
}
describe('getConflictSiblings', () => {
const list = [
sugg({ id: 'a', conflict_group: 'g1' }),
sugg({ id: 'b', conflict_group: 'g1' }),
sugg({ id: 'c', conflict_group: 'g2' }),
sugg({ id: 'd', conflict_group: null }),
]
it('returns other members of the same group', () => {
expect(getConflictSiblings(list, 'a').map((s) => s.id)).toEqual(['b'])
})
it('returns empty for ungrouped or unknown ids', () => {
expect(getConflictSiblings(list, 'd')).toEqual([])
expect(getConflictSiblings(list, 'zzz')).toEqual([])
})
})
describe('pickAcceptAllWinners', () => {
it('keeps all non-conflicting suggestions', () => {
const list = [sugg({ id: 'a' }), sugg({ id: 'b' })]
expect(pickAcceptAllWinners(list)).toEqual(['a', 'b'])
})
it('picks highest consensus within a group', () => {
const list = [
sugg({ id: 'a', conflict_group: 'g', consensus: 1, confidence: 0.99 }),
sugg({ id: 'b', conflict_group: 'g', consensus: 2, confidence: 0.6 }),
sugg({ id: 'c' }),
]
expect(pickAcceptAllWinners(list)).toEqual(['b', 'c'])
})
it('breaks consensus ties by confidence', () => {
const list = [
sugg({ id: 'a', conflict_group: 'g', consensus: 1, confidence: 0.7 }),
sugg({ id: 'b', conflict_group: 'g', consensus: 1, confidence: 0.9 }),
]
expect(pickAcceptAllWinners(list)).toEqual(['b'])
})
it('handles multiple independent groups', () => {
const list = [
sugg({ id: 'a', conflict_group: 'g1', consensus: 2 }),
sugg({ id: 'b', conflict_group: 'g1', consensus: 1 }),
sugg({ id: 'c', conflict_group: 'g2', consensus: 1, confidence: 0.5 }),
sugg({ id: 'd', conflict_group: 'g2', consensus: 1, confidence: 0.8 }),
]
expect(pickAcceptAllWinners(list)).toEqual(['a', 'd'])
})
})
@@ -0,0 +1,244 @@
/**
* Pure apply/revert logic for AI auto-correct suggestions.
*
* Suggestions reference words by id, so they stay valid as long as the
* targeted words still exist — if the reviewer has edited those words since
* the suggestions were generated, the suggestion is "stale" and cannot be
* applied. Every apply returns enough information to undo that single
* suggestion later, independent of the global history stack.
*/
import { nanoid } from 'nanoid'
import type { LyricsSegment, Word } from '../types'
import type { AiSuggestion } from '@/lib/api/autoCorrect'
export interface SuggestionUndoInfo {
suggestionId: string
op: AiSuggestion['op']
/** Word ids created by the apply (replace / insert_after). */
newWordIds: string[]
/** Original words removed by the apply (replace / delete). */
removedWords: Word[]
/** Segment the change happened in. */
segmentId: string
/** Id of the word preceding the affected span (null = segment start). */
prevWordId: string | null
/** Set when a delete emptied the segment and removed it entirely. */
removedSegment: { segment: LyricsSegment; index: number } | null
}
function rebuildText(words: Word[]): string {
return words.map((w) => w.text).join(' ')
}
function findSegmentWithWords(
segments: LyricsSegment[],
wordIds: string[],
): { segment: LyricsSegment; index: number; wordIndices: number[] } | null {
for (let i = 0; i < segments.length; i++) {
const seg = segments[i]
const indices = wordIds.map((id) => seg.words.findIndex((w) => w.id === id))
if (indices.every((x) => x >= 0)) {
return { segment: seg, index: i, wordIndices: indices }
}
}
return null
}
/** A suggestion is stale when its target words no longer exist in one segment, contiguously. */
export function isSuggestionStale(
segments: LyricsSegment[],
suggestion: AiSuggestion,
): boolean {
const found = findSegmentWithWords(segments, suggestion.word_ids)
if (!found) return true
const sorted = [...found.wordIndices].sort((a, b) => a - b)
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] !== sorted[i - 1] + 1) return true
}
return false
}
/** Evenly distribute [start, end] across n new words; null timings pass through. */
function distributeTimings(
n: number,
start: number | null,
end: number | null,
): Array<{ start_time: number | null; end_time: number | null }> {
if (n <= 0) return []
if (start === null || end === null || end <= start) {
return Array.from({ length: n }, () => ({
start_time: start,
end_time: end,
}))
}
const step = (end - start) / n
return Array.from({ length: n }, (_, i) => ({
start_time: start + i * step,
end_time: start + (i + 1) * step,
}))
}
export function applySuggestion(
segments: LyricsSegment[],
suggestion: AiSuggestion,
): { segments: LyricsSegment[]; undo: SuggestionUndoInfo } | null {
if (isSuggestionStale(segments, suggestion)) return null
const found = findSegmentWithWords(segments, suggestion.word_ids)
if (!found) return null
const { segment, index: segIndex, wordIndices } = found
const spanStart = Math.min(...wordIndices)
const spanEnd = Math.max(...wordIndices)
const prevWordId = spanStart > 0 ? segment.words[spanStart - 1].id : null
const result = segments.map((s) => ({ ...s, words: [...s.words] }))
const seg = result[segIndex]
if (suggestion.op === 'insert_after') {
const anchor = seg.words[spanEnd]
const next = seg.words[spanEnd + 1] as Word | undefined
const newTexts = suggestion.new_text.split(/\s+/).filter(Boolean)
const windowStart = anchor.end_time
const windowEnd =
next?.start_time != null && windowStart != null && next.start_time > windowStart
? next.start_time
: windowStart != null
? windowStart + 0.5 * newTexts.length
: null
const timings = distributeTimings(newTexts.length, windowStart, windowEnd)
const newWords: Word[] = newTexts.map((text, i) => ({
id: nanoid(),
text,
start_time: timings[i].start_time,
end_time: timings[i].end_time,
confidence: 1,
created_during_correction: true,
}))
seg.words.splice(spanEnd + 1, 0, ...newWords)
seg.text = rebuildText(seg.words)
return {
segments: result,
undo: {
suggestionId: suggestion.id,
op: suggestion.op,
newWordIds: newWords.map((w) => w.id),
removedWords: [],
segmentId: seg.id,
prevWordId: anchor.id,
removedSegment: null,
},
}
}
const removedWords = seg.words.slice(spanStart, spanEnd + 1)
if (suggestion.op === 'delete') {
seg.words.splice(spanStart, removedWords.length)
let removedSegment: SuggestionUndoInfo['removedSegment'] = null
if (seg.words.length === 0) {
removedSegment = { segment: segments[segIndex], index: segIndex }
result.splice(segIndex, 1)
} else {
seg.text = rebuildText(seg.words)
seg.start_time = seg.words[0].start_time
seg.end_time = seg.words[seg.words.length - 1].end_time
}
return {
segments: result,
undo: {
suggestionId: suggestion.id,
op: suggestion.op,
newWordIds: [],
removedWords,
segmentId: seg.id,
prevWordId,
removedSegment,
},
}
}
// replace
const newTexts = suggestion.new_text.split(/\s+/).filter(Boolean)
const timings = distributeTimings(
newTexts.length,
removedWords[0]?.start_time ?? null,
removedWords[removedWords.length - 1]?.end_time ?? null,
)
const newWords: Word[] = newTexts.map((text, i) => ({
id: nanoid(),
text,
start_time: timings[i].start_time,
end_time: timings[i].end_time,
confidence: 1,
created_during_correction: true,
}))
seg.words.splice(spanStart, removedWords.length, ...newWords)
seg.text = rebuildText(seg.words)
return {
segments: result,
undo: {
suggestionId: suggestion.id,
op: suggestion.op,
newWordIds: newWords.map((w) => w.id),
removedWords,
segmentId: seg.id,
prevWordId,
removedSegment: null,
},
}
}
/**
* Undo a previously applied suggestion. Returns null when the affected
* words/segment have since been edited in a way that makes a safe revert
* impossible (caller should tell the user to use global Undo instead).
*/
export function revertSuggestion(
segments: LyricsSegment[],
undo: SuggestionUndoInfo,
): LyricsSegment[] | null {
// Deleted-whole-segment case: reinsert the snapshot.
if (undo.removedSegment) {
const result = segments.map((s) => ({ ...s, words: [...s.words] }))
const at = Math.min(undo.removedSegment.index, result.length)
result.splice(at, 0, JSON.parse(JSON.stringify(undo.removedSegment.segment)))
return result
}
const segIndex = segments.findIndex((s) => s.id === undo.segmentId)
if (segIndex < 0) return null
const result = segments.map((s) => ({ ...s, words: [...s.words] }))
const seg = result[segIndex]
if (undo.newWordIds.length > 0) {
// replace / insert_after: the created words must still be present, contiguous.
const indices = undo.newWordIds.map((id) =>
seg.words.findIndex((w) => w.id === id),
)
if (indices.some((x) => x < 0)) return null
const sorted = [...indices].sort((a, b) => a - b)
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] !== sorted[i - 1] + 1) return null
}
seg.words.splice(
sorted[0],
sorted.length,
...JSON.parse(JSON.stringify(undo.removedWords)),
)
} else {
// delete: reinsert removed words after prevWordId (or at segment start).
let at = 0
if (undo.prevWordId) {
const prevIndex = seg.words.findIndex((w) => w.id === undo.prevWordId)
if (prevIndex < 0) return null
at = prevIndex + 1
}
seg.words.splice(at, 0, ...JSON.parse(JSON.stringify(undo.removedWords)))
}
seg.text = rebuildText(seg.words)
if (seg.words.length > 0) {
seg.start_time = seg.words[0].start_time
seg.end_time = seg.words[seg.words.length - 1].end_time
}
return result
}
@@ -0,0 +1,42 @@
/**
* Conflict-group helpers for multi-model auto-correct suggestions.
*
* Suggestions sharing a conflict_group target overlapping words with
* different outcomes; the reviewer accepts at most one per group.
*/
import type { AiSuggestion } from '@/lib/api/autoCorrect'
/** Other suggestions in the same conflict group as `id`. */
export function getConflictSiblings(
suggestions: AiSuggestion[],
id: string,
): AiSuggestion[] {
const target = suggestions.find((s) => s.id === id)
if (!target?.conflict_group) return []
return suggestions.filter(
(s) => s.id !== id && s.conflict_group === target.conflict_group,
)
}
/**
* For accept-all: pick the winner of each conflict group (highest model
* consensus, then highest confidence); non-conflicting suggestions all win.
* Returns ids in the original suggestion order.
*/
export function pickAcceptAllWinners(suggestions: AiSuggestion[]): string[] {
const bestOfGroup = new Map<string, AiSuggestion>()
for (const s of suggestions) {
if (!s.conflict_group) continue
const current = bestOfGroup.get(s.conflict_group)
if (
!current ||
s.consensus > current.consensus ||
(s.consensus === current.consensus && s.confidence > current.confidence)
) {
bestOfGroup.set(s.conflict_group, s)
}
}
return suggestions
.filter((s) => !s.conflict_group || bestOfGroup.get(s.conflict_group)?.id === s.id)
.map((s) => s.id)
}
+19
View File
@@ -238,6 +238,11 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
isInitialized: true,
})
// Mirror to the edge-config global so synchronous, import-cycle-free consumers
// (e.g. getTenantId() in lib/api.ts) can read the tenant in dev/preview where the
// Cloudflare edge function does not inject __TENANT_CONFIG__.
mirrorTenantConfigToWindow(data)
// Apply tenant branding to CSS variables
if (data.tenant) {
applyTenantBranding(data.tenant.branding)
@@ -256,6 +261,7 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
setTenant: (tenant, isDefault) => {
set({ tenant, isDefault, isInitialized: true })
mirrorTenantConfigToWindow({ tenant, is_default: isDefault })
if (tenant) {
applyTenantBranding(tenant.branding)
}
@@ -348,6 +354,19 @@ function applyTenantBranding(branding: TenantBranding) {
}
}
/**
* Mirror the resolved tenant config onto `window.__TENANT_CONFIG__`.
*
* The Cloudflare edge function injects this global on tenant subdomains in production,
* but not in local dev or admin preview (where the tenant is resolved by fetch or
* setTenant). Mirroring it here gives lib/api.ts a single synchronous, import-cycle-free
* source of truth for attaching the X-Tenant-ID header in every environment.
*/
function mirrorTenantConfigToWindow(data: TenantConfigResponse) {
if (typeof window === "undefined") return
;(window as { __TENANT_CONFIG__?: TenantConfigResponse }).__TENANT_CONFIG__ = data
}
/**
* Hook to get tenant-aware API headers.
* Use this when making API calls that need tenant context.
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "بريد إلكتروني عند الجاهزية",
"afterApproval": "بعد الموافقة، يتم عرض فيديو الكاريوكي الخاص بك وتسليمه. ~10 دقائق",
"trackProgressTenant": "تتبع التقدم في قائمة المهام الأخيرة.",
"submitAnother": "إرسال مسار آخر"
"submitAnother": "إرسال مسار آخر",
"pasteUrlButton": "لصق رابط",
"urlSupportedSitesHint": "يعمل مع YouTube و Facebook و SoundCloud و TikTok و Vimeo ومئات المواقع الأخرى.",
"urlSupportedSitesLink": "عرض جميع المواقع المدعومة",
"useThisUrl": "استخدام هذا الرابط"
},
"jobStatus": {
"settingUp": "جاري الإعداد",
@@ -772,7 +776,17 @@
"undoFailed": "فشل التراجع",
"redoFailed": "فشلت الإعادة",
"restoreFailed": "فشلت الاستعادة — قد لا يتم تطبيق بعض التعديلات",
"submitFailed": "فشل الإرسال"
"submitFailed": "فشل الإرسال",
"fadeIn": "ظهور تدريجي",
"fadeInSelection": "ظهور تدريجي في المنطقة المحددة",
"fadeOut": "تلاشي تدريجي",
"fadeOutSelection": "تلاشي تدريجي في المنطقة المحددة",
"fadeInDisabledHint": "لإضافة تأثير الظهور التدريجي، حدد منطقة تبدأ من بداية المسار تماماً",
"fadeOutDisabledHint": "لإضافة تأثير التلاشي التدريجي، حدد منطقة تنتهي عند نهاية المسار تماماً",
"trimEndDisabledHint": "لقص النهاية، حدد منطقة تنتهي عند نهاية المسار تماماً",
"trimEndSelection": "إزالة كل شيء بعد التحديد",
"trimStartDisabledHint": "لقص البداية، حدد منطقة تبدأ من بداية المسار تماماً",
"trimStartSelection": "إزالة كل شيء قبل التحديد"
},
"audioEditRestore": {
"title": "جلسات تعديل الصوت المحفوظة",
@@ -799,7 +813,7 @@
"acceptAll": "قبول الكل",
"revertAll": "تراجع عن الكل",
"undoAll": "تراجع عن الكل",
"resetAllChanges": "إعادة تعيين جميع التغييرات إلى الكلمات الأصلية المصححة بالذكاء الاصطناعي",
"resetAllChanges": "إعادة تعيين جميع التغييرات والعودة إلى الكلمات المصححة الأصلية",
"undo": "تراجع",
"redo": "إعادة",
"findReplace": "بحث/استبدال",
@@ -809,7 +823,12 @@
"timingOffset": "إزاحة التوقيت",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "إزاحة جميع توقيتات الكلمات للأمام أو للخلف. استخدمه إذا ظهرت الكلمات مبكراً أو متأخراً قليلاً في المعاينة.",
"playback": "التشغيل"
"playback": "التشغيل",
"audioLoadError": "تعذر تحميل الصوت",
"audioStillLoading": "لا يزال الصوت قيد التحميل...",
"loadingAudio": "جاري تحميل الصوت...",
"autoCorrect": "التصحيح التلقائي",
"autoCorrectDesc": "إنشاء اقتراحات تصحيح من خلال مقارنة التفريغ الصوتي مع الكلمات المرجعية. لن يتم تغيير أي شيء حتى توافق على كل اقتراح."
},
"guidance": {
"showTips": "إظهار النصائح",
@@ -983,7 +1002,9 @@
"loadingAll": "جاري تحميل جميع الكلمات...",
"loadingSegment": "جاري تحميل المقطع...",
"noData": "لا تتوفر بيانات للمقطع",
"unCorrect": "إلغاء التصحيح"
"unCorrect": "إلغاء التصحيح",
"timingClamped": "توقيت \"{word}\" كان خارج المقطع — تم ضبطه إلى {time} ثانية.",
"timingSanitized": "تم إصلاح توقيت {count} كلمة وقعت خارج هذا المقطع."
},
"findReplace": {
"title": "بحث واستبدال",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "تم تطبيق الكلمات المخصصة. يرجى مزامنة كل مقطع معدل يدوياً لضمان توافق توقيت الكلمات بشكل مثالي."
},
"autoCorrect": {
"accept": "قبول الاقتراح",
"acceptAll": "قبول الكل",
"accepted": "تم القبول",
"adlibRemovalHint": "السماح بالاقتراحات التي تحذف الغناء الخلفي غير الموجود في المراجع",
"adlibRemovalLabel": "اقتراح إزالة الارتجالات",
"category_adlib_removal": "ارتجال",
"category_formatting": "تنسيق",
"category_grammar": "قواعد",
"category_mishearing": "خطأ سمعي",
"category_other": "أخرى",
"category_repeated_chorus_fix": "كورس",
"collapse": "طي الاقتراحات",
"confidenceHint": "مستوى الثقة المطلوب للاقتراح قبل ظهوره",
"confidenceLabel": "تصفية الاقتراحات",
"confidence_all": "عرض الكل",
"confidence_high": "ثقة عالية",
"description": "يقارن التصحيح التلقائي التفريغ الصوتي بالمصادر المرجعية ويقترح تعديلات على مستوى الكلمة. يمكنك مراجعة كل اقتراح — ولن يتم تطبيق أي شيء حتى توافق عليه.",
"dismiss": "تجاهل الاقتراحات",
"expand": "توسيع الاقتراحات",
"insertMarker": "إدراج:",
"insertionsHint": "السماح بالاقتراحات التي تدرج الكلمات المفقودة في النسخ",
"insertionsLabel": "اقتراح الكلمات المفقودة",
"noReferences": "لا تتوفر كلمات مرجعية لهذه الأغنية، لذا لا يمكن إنشاء اقتراحات. أضف الكلمات من اللوحة المرجعية أولاً.",
"noSuggestions": "لم يتم العثور على أي مشاكل — لا توجد تغييرات مقترحة.",
"reject": "رفض الاقتراح",
"rejectAll": "رفض الكل",
"rejected": "مرفوض",
"runButton": "الحصول على اقتراحات",
"running": "جاري تحليل الكلمات... يستغرق هذا عادةً بين 15 و 60 ثانية.",
"staleHint": "تم تعديل هذه الكلمات بعد إنشاء الاقتراحات، لذا لم يعد هذا الاقتراح صالحاً.",
"summary": "{total} اقتراحات · {pending} قيد الانتظار · {accepted} مقبولة",
"title": "اقتراحات التصحيح التلقائي",
"undo": "التراجع عن هذا الاقتراح",
"cancel": "إلغاء",
"close": "إغلاق",
"confidence_balanced": "متوازن",
"compareHint": "أبطأ وأعلى تكلفة، لكنه يوضح الاقتراحات التي تتفق عليها عدة نماذج",
"compareLabel": "مقارنة عدة نماذج للذكاء الاصطناعي",
"conflictBadge": "بديل",
"conflictTooltip": "توجد اقتراحات مختلفة لهذه الكلمات — قبول أحد الخيارات يؤدي إلى رفض الخيارات الأخرى.",
"consensusBadge": "{consensus}/{total} من النماذج",
"consensusTooltip": "مقترح من: {models}",
"cachedBadge": "مخزن مؤقتاً",
"cachedTooltip": "تمت الاستعادة من معالجة سابقة لنفس الكلمات — لم يتم احتساب أي تكلفة للذكاء الاصطناعي."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Correu electrònic quan estigui llest",
"afterApproval": "Després de l'aprovació, el teu vídeo de karaoke es renderitza i s'entrega. ~10 minuts",
"trackProgressTenant": "Fes un seguiment del progrés a la llista de Treballs recents.",
"submitAnother": "Envia una altra pista"
"submitAnother": "Envia una altra pista",
"pasteUrlButton": "Enganxa un enllaç",
"urlSupportedSitesHint": "Funciona amb YouTube, Facebook, SoundCloud, TikTok, Vimeo i centenars de llocs més.",
"urlSupportedSitesLink": "Consulta tots els llocs compatibles",
"useThisUrl": "Utilitza aquest URL"
},
"jobStatus": {
"settingUp": "Configurant",
@@ -772,7 +776,17 @@
"undoFailed": "No s'ha pogut desfer",
"redoFailed": "No s'ha pogut refer",
"restoreFailed": "La restauració ha fallat — és possible que algunes edicions no s'hagin aplicat",
"submitFailed": "L'enviament ha fallat"
"submitFailed": "L'enviament ha fallat",
"fadeIn": "Fosa d'entrada",
"fadeInSelection": "Aplica una fosa d'entrada a la regió seleccionada",
"fadeOut": "Fosa de sortida",
"fadeOutSelection": "Aplica una fosa de sortida a la regió seleccionada",
"fadeInDisabledHint": "Per fer una fosa d'entrada, selecciona una regió que comenci just al principi de la pista",
"fadeOutDisabledHint": "Per fer una fosa de sortida, selecciona una regió que acabi just al final de la pista",
"trimEndDisabledHint": "Per retallar el final, selecciona una regió que acabi just al final de la pista",
"trimEndSelection": "Elimina tot el que hi ha després de la selecció",
"trimStartDisabledHint": "Per retallar el principi, selecciona una regió que comenci just al principi de la pista",
"trimStartSelection": "Elimina tot el que hi ha abans de la selecció"
},
"audioEditRestore": {
"title": "Sessions d'edició d'àudio desades",
@@ -799,7 +813,7 @@
"acceptAll": "Accepta-ho tot",
"revertAll": "Reverteix-ho tot",
"undoAll": "Desfés-ho tot",
"resetAllChanges": "Restableix tots els canvis a les lletres originals corregides per IA",
"resetAllChanges": "Restableix tots els canvis a la lletra corregida original",
"undo": "Desfés",
"redo": "Refés",
"findReplace": "Cerca/Reemplaça",
@@ -809,7 +823,12 @@
"timingOffset": "Desplaçament de temps",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Desplaça tots els temps de les paraules cap endavant o cap enrere. Utilitza-ho si les lletres apareixen lleugerament aviat o tard a la previsualització.",
"playback": "Reproducció"
"playback": "Reproducció",
"audioLoadError": "No s'ha pogut carregar l'àudio",
"audioStillLoading": "L'àudio encara s'està carregant...",
"loadingAudio": "Carregant l'àudio...",
"autoCorrect": "Autocorrecció",
"autoCorrectDesc": "Genera suggeriments de correcció comparant la transcripció amb la lletra de referència. No es canvia res fins que acceptes cada suggeriment."
},
"guidance": {
"showTips": "Mostra els consells",
@@ -983,7 +1002,9 @@
"loadingAll": "Carregant totes les paraules...",
"loadingSegment": "Carregant el segment...",
"noData": "No hi ha dades del segment disponibles",
"unCorrect": "Desfés la correcció"
"unCorrect": "Desfés la correcció",
"timingClamped": "La sincronització de \"{word}\" estava fora del segment — s'ha ajustat a {time}s.",
"timingSanitized": "S'han corregit {count} sincronitzacions de paraules que quedaven fora d'aquest segment."
},
"findReplace": {
"title": "Cerca i reemplaça",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Lletra personalitzada aplicada. Sincronitza manualment cada segment editat per assegurar-te que els temps de les paraules són correctes per a la lletra personalitzada."
},
"autoCorrect": {
"accept": "Accepta el suggeriment",
"acceptAll": "Accepta-ho tot",
"accepted": "Acceptat",
"adlibRemovalHint": "Permet suggeriments que eliminin les veus de fons que les referències no tenen",
"adlibRemovalLabel": "Suggereix eliminar els adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "gramàtica",
"category_mishearing": "error d'audició",
"category_other": "altres",
"category_repeated_chorus_fix": "tornada",
"collapse": "Contreu els suggeriments",
"confidenceHint": "Quin nivell de confiança ha de tenir un suggeriment abans de mostrar-se",
"confidenceLabel": "Filtre de suggeriments",
"confidence_all": "Mostra-ho tot",
"confidence_high": "Certesa alta",
"description": "L'autocorrecció compara la lletra transcrita amb les fonts de referència i suggereix correccions a nivell de paraula. Tu revises cada suggeriment — no s'aplica res fins que ho acceptes.",
"dismiss": "Descarta els suggeriments",
"expand": "Desplega els suggeriments",
"insertMarker": "insereix:",
"insertionsHint": "Permet suggeriments que insereixin paraules que la transcripció ha omès",
"insertionsLabel": "Suggereix paraules que falten",
"noReferences": "No hi ha cap lletra de referència disponible per a aquesta cançó, així que no es poden generar suggeriments. Afegeix primer la lletra des del panell de referència.",
"noSuggestions": "No s'han trobat problemes — no hi ha cap canvi suggerit.",
"reject": "Rebutja el suggeriment",
"rejectAll": "Rebutja-ho tot",
"rejected": "Rebutjat",
"runButton": "Obtén suggeriments",
"running": "S'està analitzant la lletra... això sol trigar entre 15 i 60 segons.",
"staleHint": "Aquestes paraules s'han editat des que es van generar els suggeriments, per la qual cosa aquest suggeriment ja no és vàlid.",
"summary": "{total} suggeriments · {pending} pendents · {accepted} acceptats",
"title": "Suggeriments d'autocorrecció",
"undo": "Desfés aquest suggeriment",
"cancel": "Cancel·la",
"close": "Tanca",
"confidence_balanced": "Equilibrat",
"compareHint": "Més lent i més car, però mostra en quins suggeriments coincideixen diversos models",
"compareLabel": "Compara diversos models d'IA",
"conflictBadge": "variant",
"conflictTooltip": "Hi ha diferents suggeriments per a aquestes paraules — si acceptes una variant, es rebutgen les altres.",
"consensusBadge": "{consensus}/{total} models",
"consensusTooltip": "Proposat per: {models}",
"cachedBadge": "en memòria cau",
"cachedTooltip": "Restaurat a partir d'una execució anterior amb la mateixa lletra — no s'ha generat cap cost d'IA."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, až bude hotovo",
"afterApproval": "Po schválení se tvé karaoke video vyrenderuje a doručí. ~10 minut",
"trackProgressTenant": "Sleduj postup v seznamu Nedávné úlohy.",
"submitAnother": "Odeslat další stopu"
"submitAnother": "Odeslat další stopu",
"pasteUrlButton": "Vložit odkaz",
"urlSupportedSitesHint": "Funguje se službami YouTube, Facebook, SoundCloud, TikTok, Vimeo a stovkami dalších webů.",
"urlSupportedSitesLink": "Zobrazit všechny podporované weby",
"useThisUrl": "Použít tuto URL"
},
"jobStatus": {
"settingUp": "Nastavování",
@@ -772,7 +776,17 @@
"undoFailed": "Krok zpět selhal",
"redoFailed": "Krok znovu selhal",
"restoreFailed": "Obnovení selhalo — některé úpravy možná nebyly aplikovány",
"submitFailed": "Odeslání selhalo"
"submitFailed": "Odeslání selhalo",
"fadeIn": "Postupné zesílení",
"fadeInSelection": "Postupné zesílení vybraného úseku",
"fadeOut": "Postupné zeslabení",
"fadeOutSelection": "Postupné zeslabení vybraného úseku",
"fadeInDisabledHint": "Pro postupné zesílení vyber úsek, který začíná na úplném začátku stopy",
"fadeOutDisabledHint": "Pro postupné zeslabení vyber úsek, který končí na úplném konci stopy",
"trimEndDisabledHint": "Pro oříznutí konce vyber úsek, který končí na úplném konci stopy",
"trimEndSelection": "Odstranit vše za výběrem",
"trimStartDisabledHint": "Pro oříznutí začátku vyber úsek, který začíná na úplném začátku stopy",
"trimStartSelection": "Odstranit vše před výběrem"
},
"audioEditRestore": {
"title": "Uložené relace úprav zvuku",
@@ -799,7 +813,7 @@
"acceptAll": "Přijmout vše",
"revertAll": "Vrátit vše",
"undoAll": "Vrátit vše zpět",
"resetAllChanges": "Resetovat všechny změny zpět na původní text opravený AI",
"resetAllChanges": "Vrátit všechny změny zpět na původní opravený text",
"undo": "Zpět",
"redo": "Znovu",
"findReplace": "Najít/Nahradit",
@@ -809,7 +823,12 @@
"timingOffset": "Posun časování",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Posuň časování všech slov dopředu nebo dozadu. Použij, pokud se text v náhledu objevuje mírně brzy nebo pozdě.",
"playback": "Přehrávání"
"playback": "Přehrávání",
"audioLoadError": "Nepodařilo se načíst audio",
"audioStillLoading": "Audio se stále načítá...",
"loadingAudio": "Načítání audia...",
"autoCorrect": "Automatická oprava",
"autoCorrectDesc": "Vygenerovat návrhy oprav porovnáním přepisu s referenčním textem. Nic se nezmění, dokud každý návrh nepřijmeš."
},
"guidance": {
"showTips": "Zobrazit tipy",
@@ -983,7 +1002,9 @@
"loadingAll": "Načítání všech slov...",
"loadingSegment": "Načítání segmentu...",
"noData": "Nejsou k dispozici žádná data segmentu",
"unCorrect": "Zrušit opravu"
"unCorrect": "Zrušit opravu",
"timingClamped": "Časování \"{word}\" bylo mimo segment — zarovnáno na {time} s.",
"timingSanitized": "Opraveno {count} časování slov, která byla mimo tento segment."
},
"findReplace": {
"title": "Najít a nahradit",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Vlastní text byl aplikován. Ručně synchronizuj každý upravený segment, aby bylo zajištěno správné načasování slov pro upravený text."
},
"autoCorrect": {
"accept": "Přijmout návrh",
"acceptAll": "Přijmout vše",
"accepted": "Přijato",
"adlibRemovalHint": "Povolit návrhy, které odstraní doprovodné vokály, které v referenčním textu chybí",
"adlibRemovalLabel": "Navrhnout odstranění adlibů",
"category_adlib_removal": "adlib",
"category_formatting": "formát",
"category_grammar": "gramatika",
"category_mishearing": "přeslechnutí",
"category_other": "ostatní",
"category_repeated_chorus_fix": "refrén",
"collapse": "Sbalit návrhy",
"confidenceHint": "Jak vysoká musí být jistota návrhu, než se zobrazí",
"confidenceLabel": "Filtr návrhů",
"confidence_all": "Zobrazit vše",
"confidence_high": "Vysoká jistota",
"description": "Automatická oprava porovnává přepsaný text s referenčními zdroji a navrhuje opravy na úrovni slov. Každý návrh si zkontroluješ — nic se neaplikuje, dokud ho nepřijmeš.",
"dismiss": "Skrýt návrhy",
"expand": "Rozbalit návrhy",
"insertMarker": "vložit:",
"insertionsHint": "Povolit návrhy, které vkládají slova, která v přepisu chybí",
"insertionsLabel": "Navrhnout chybějící slova",
"noReferences": "Pro tuto píseň nejsou k dispozici žádné referenční texty, takže nelze vygenerovat návrhy. Nejprve přidej text z referenčního panelu.",
"noSuggestions": "Nebyly nalezeny žádné problémy — nejsou navrženy žádné změny.",
"reject": "Odmítnout návrh",
"rejectAll": "Odmítnout vše",
"rejected": "Odmítnuto",
"runButton": "Získat návrhy",
"running": "Analyzuji text… obvykle to trvá 15–60 sekund.",
"staleHint": "Tato slova byla upravena od chvíle, kdy byly návrhy vygenerovány, takže tento návrh již neplatí.",
"summary": "{total} návrhů · {pending} čeká · {accepted} přijato",
"title": "Návrhy automatické opravy",
"undo": "Vzít tento návrh zpět",
"cancel": "Zrušit",
"close": "Zavřít",
"confidence_balanced": "Vyvážená",
"compareHint": "Pomalejší a dražší, ale ukáže, na kterých návrzích se shodne více modelů",
"compareLabel": "Porovnat více AI modelů",
"conflictBadge": "varianta",
"conflictTooltip": "Pro tato slova existují různé návrhy — přijetím jedné varianty odmítneš ostatní.",
"consensusBadge": "{consensus}/{total} modelů",
"consensusTooltip": "Navrženo: {models}",
"cachedBadge": "z mezipaměti",
"cachedTooltip": "Obnoveno z předchozího zpracování stejného textu — nevznikly žádné náklady na AI."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, når den er klar",
"afterApproval": "Efter godkendelse renderes og leveres din karaokevideo. ~10 minutter",
"trackProgressTenant": "Følg fremskridt i listen over seneste job.",
"submitAnother": "Indsend et andet nummer"
"submitAnother": "Indsend et andet nummer",
"pasteUrlButton": "Indsæt et link",
"urlSupportedSitesHint": "Fungerer med YouTube, Facebook, SoundCloud, TikTok, Vimeo og hundredvis af andre sider.",
"urlSupportedSitesLink": "Se alle understøttede sider",
"useThisUrl": "Brug denne URL"
},
"jobStatus": {
"settingUp": "Sætter op",
@@ -772,7 +776,17 @@
"undoFailed": "Fortryd mislykkedes",
"redoFailed": "Gendan mislykkedes",
"restoreFailed": "Gendannelse mislykkedes — nogle redigeringer er muligvis ikke blevet anvendt",
"submitFailed": "Indsendelse mislykkedes"
"submitFailed": "Indsendelse mislykkedes",
"fadeIn": "Fade ind",
"fadeInSelection": "Fade ind over det valgte område",
"fadeOut": "Fade ud",
"fadeOutSelection": "Fade ud over det valgte område",
"fadeInDisabledHint": "For at fade ind skal du vælge et område, der begynder helt i starten af sporet",
"fadeOutDisabledHint": "For at fade ud skal du vælge et område, der slutter helt for enden af sporet",
"trimEndDisabledHint": "For at beskære slutningen skal du vælge et område, der slutter helt for enden af sporet",
"trimEndSelection": "Fjern alt efter markeringen",
"trimStartDisabledHint": "For at beskære starten skal du vælge et område, der begynder helt i starten af sporet",
"trimStartSelection": "Fjern alt før markeringen"
},
"audioEditRestore": {
"title": "Gemte lydredigeringssessioner",
@@ -799,7 +813,7 @@
"acceptAll": "Accepter alle",
"revertAll": "Gendan alle",
"undoAll": "Fortryd alle",
"resetAllChanges": "Nulstil alle ændringer tilbage til de originale AI-rettede sangtekster",
"resetAllChanges": "Nulstil alle ændringer tilbage til den oprindelige rettede sangtekst",
"undo": "Fortryd",
"redo": "Gendan",
"findReplace": "Find/Erstat",
@@ -809,7 +823,12 @@
"timingOffset": "Timingforskydning",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Forskyd alle ordtiminger frem eller tilbage. Brug, hvis sangtekster vises lidt tidligt eller sent i forhåndsvisningen.",
"playback": "Afspilning"
"playback": "Afspilning",
"audioLoadError": "Kunne ikke indlæse lyd",
"audioStillLoading": "Lyden indlæses stadig...",
"loadingAudio": "Indlæser lyd...",
"autoCorrect": "Autokorrektur",
"autoCorrectDesc": "Generer forslag til rettelser ved at sammenligne transskriptionen med referenceteksten. Intet ændres, før du accepterer hvert forslag."
},
"guidance": {
"showTips": "Vis tips",
@@ -983,7 +1002,9 @@
"loadingAll": "Indlæser alle ord...",
"loadingSegment": "Indlæser segment...",
"noData": "Ingen segmentdata tilgængelige",
"unCorrect": "Fjern rettelse"
"unCorrect": "Fjern rettelse",
"timingClamped": "\"{word}\" timing var uden for segmentet — justeret til {time}s.",
"timingSanitized": "Rettede {count} ord-timing(er), der faldt uden for dette segment."
},
"findReplace": {
"title": "Find og erstat",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Tilpasset sangtekst anvendt. Synkroniser manuelt hvert redigeret segment for at sikre, at ordtimingen passer til den tilpassede sangtekst."
},
"autoCorrect": {
"accept": "Accepter forslag",
"acceptAll": "Accepter alle",
"accepted": "Accepteret",
"adlibRemovalHint": "Tillad forslag, der sletter korvokal, som ikke findes i referencerne",
"adlibRemovalLabel": "Foreslå at fjerne adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "grammatik",
"category_mishearing": "fejlhørt",
"category_other": "andet",
"category_repeated_chorus_fix": "omkvæd",
"collapse": "Skjul forslag",
"confidenceHint": "Hvor sikkert et forslag skal være, før det vises",
"confidenceLabel": "Forslagsfilter",
"confidence_all": "Vis alle",
"confidence_high": "Høj sikkerhed",
"description": "Autokorrektur sammenligner den transskriberede sangtekst med referencekilderne og foreslår rettelser på ordniveau. Du gennemgår hvert forslag — intet anvendes, før du accepterer det.",
"dismiss": "Fjern forslag",
"expand": "Udvid forslag",
"insertMarker": "indsæt:",
"insertionsHint": "Tillad forslag, der indsætter ord, som transskriptionen overså",
"insertionsLabel": "Foreslå manglende ord",
"noReferences": "Der er ingen referencetekster tilgængelige for denne sang, så der kan ikke genereres forslag. Tilføj en sangtekst fra referencepanelet først.",
"noSuggestions": "Ingen problemer fundet — der er ingen foreslåede ændringer.",
"reject": "Afvis forslag",
"rejectAll": "Afvis alle",
"rejected": "Afvist",
"runButton": "Hent forslag",
"running": "Analyserer tekst… dette tager normalt 15–60 sekunder.",
"staleHint": "Disse ord er blevet redigeret, siden forslagene blev genereret, så dette forslag gælder ikke længere.",
"summary": "{total} forslag · {pending} afventer · {accepted} accepteret",
"title": "Forslag til autokorrektur",
"undo": "Fortryd dette forslag",
"cancel": "Annuller",
"close": "Luk",
"confidence_balanced": "Balanceret",
"compareHint": "Langsommere og koster mere, men viser, hvilke forslag flere modeller er enige om",
"compareLabel": "Sammenlign flere AI-modeller",
"conflictBadge": "variant",
"conflictTooltip": "Der er forskellige forslag til disse ord — hvis du accepterer én variant, afvises de andre.",
"consensusBadge": "{consensus}/{total} modeller",
"consensusTooltip": "Foreslået af: {models}",
"cachedBadge": "cachet",
"cachedTooltip": "Gendannet fra en tidligere kørsel med de samme sangtekster — der påløb ingen AI-omkostninger."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-Mail, wenn fertig",
"afterApproval": "Nach der Genehmigung wird dein Karaoke-Video gerendert und geliefert. ~10 Minuten",
"trackProgressTenant": "Verfolge den Fortschritt in der Liste Aktuelle Aufträge.",
"submitAnother": "Weiteren Track einreichen"
"submitAnother": "Weiteren Track einreichen",
"pasteUrlButton": "Link einfügen",
"urlSupportedSitesHint": "Funktioniert mit YouTube, Facebook, SoundCloud, TikTok, Vimeo und Hunderten anderen Seiten.",
"urlSupportedSitesLink": "Alle unterstützten Seiten ansehen",
"useThisUrl": "Diese URL verwenden"
},
"jobStatus": {
"settingUp": "Richte ein",
@@ -772,7 +776,17 @@
"undoFailed": "Rückgängig machen fehlgeschlagen",
"redoFailed": "Wiederholen fehlgeschlagen",
"restoreFailed": "Wiederherstellung fehlgeschlagen — einige Bearbeitungen wurden möglicherweise nicht angewendet",
"submitFailed": "Einreichen fehlgeschlagen"
"submitFailed": "Einreichen fehlgeschlagen",
"fadeIn": "Einblenden",
"fadeInSelection": "Über den ausgewählten Bereich einblenden",
"fadeOut": "Ausblenden",
"fadeOutSelection": "Über den ausgewählten Bereich ausblenden",
"fadeInDisabledHint": "Um einzublenden, wähle einen Bereich, der ganz am Anfang des Tracks beginnt",
"fadeOutDisabledHint": "Um auszublenden, wähle einen Bereich, der ganz am Ende des Tracks endet",
"trimEndDisabledHint": "Um das Ende abzuschneiden, wähle einen Bereich, der ganz am Ende des Tracks endet",
"trimEndSelection": "Alles nach der Auswahl entfernen",
"trimStartDisabledHint": "Um den Anfang abzuschneiden, wähle einen Bereich, der ganz am Anfang des Tracks beginnt",
"trimStartSelection": "Alles vor der Auswahl entfernen"
},
"audioEditRestore": {
"title": "Gespeicherte Audiobearbeitungs-Sitzungen",
@@ -799,7 +813,7 @@
"acceptAll": "Alle akzeptieren",
"revertAll": "Alle verwerfen",
"undoAll": "Alle rückgängig machen",
"resetAllChanges": "Alle Änderungen auf den ursprünglichen KI-korrigierten Text zurücksetzen",
"resetAllChanges": "Alle Änderungen auf den ursprünglich korrigierten Text zurücksetzen",
"undo": "Rückgängig",
"redo": "Wiederholen",
"findReplace": "Suchen/Ersetzen",
@@ -809,7 +823,12 @@
"timingOffset": "Zeitversatz",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Verschiebe alle Wort-Timings nach vorne oder hinten. Verwende dies, wenn der Text in der Vorschau etwas zu früh oder zu spät erscheint.",
"playback": "Wiedergabe"
"playback": "Wiedergabe",
"audioLoadError": "Audio konnte nicht geladen werden",
"audioStillLoading": "Audio wird noch geladen...",
"loadingAudio": "Audio wird geladen...",
"autoCorrect": "Autokorrektur",
"autoCorrectDesc": "Generiere Korrekturvorschläge, indem du die Transkription mit dem Referenztext vergleichst. Nichts wird geändert, bis du jeden Vorschlag akzeptierst."
},
"guidance": {
"showTips": "Tipps anzeigen",
@@ -983,7 +1002,9 @@
"loadingAll": "Lade alle Wörter...",
"loadingSegment": "Lade Segment...",
"noData": "Keine Segmentdaten verfügbar",
"unCorrect": "Ent-Korrigieren"
"unCorrect": "Ent-Korrigieren",
"timingClamped": "Das Timing von \"{word}\" lag außerhalb des Segments — auf {time}s gesetzt.",
"timingSanitized": "{count} Wort-Timing(s) korrigiert, die außerhalb dieses Segments lagen."
},
"findReplace": {
"title": "Suchen und Ersetzen",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Benutzerdefinierter Text angewendet. Synchronisiere jedes bearbeitete Segment manuell, um sicherzustellen, dass das Wort-Timing für den neuen Text stimmt."
},
"autoCorrect": {
"accept": "Vorschlag akzeptieren",
"acceptAll": "Alle akzeptieren",
"accepted": "Akzeptiert",
"adlibRemovalHint": "Erlaube Vorschläge, die Hintergrundgesang entfernen, der im Referenztext nicht vorkommt",
"adlibRemovalLabel": "Entfernen von Adlibs vorschlagen",
"category_adlib_removal": "Adlib",
"category_formatting": "Format",
"category_grammar": "Grammatik",
"category_mishearing": "Falsch erkannt",
"category_other": "Sonstiges",
"category_repeated_chorus_fix": "Refrain",
"collapse": "Vorschläge einklappen",
"confidenceHint": "Wie sicher ein Vorschlag sein muss, bevor er angezeigt wird",
"confidenceLabel": "Vorschlagsfilter",
"confidence_all": "Alle anzeigen",
"confidence_high": "Hohe Sicherheit",
"description": "Die Autokorrektur vergleicht den transkribierten Text mit den Referenzquellen und schlägt Korrekturen auf Wortebene vor. Du überprüfst jeden Vorschlag — nichts wird angewendet, bis du ihn akzeptierst.",
"dismiss": "Vorschläge verwerfen",
"expand": "Vorschläge ausklappen",
"insertMarker": "einfügen:",
"insertionsHint": "Erlaube Vorschläge, die Wörter einfügen, die bei der Transkription übersehen wurden",
"insertionsLabel": "Fehlende Wörter vorschlagen",
"noReferences": "Für diesen Song ist kein Referenztext verfügbar, daher können keine Vorschläge generiert werden. Füge zuerst einen Text über das Referenz-Panel hinzu.",
"noSuggestions": "Keine Probleme gefunden — es gibt keine Änderungsvorschläge.",
"reject": "Vorschlag ablehnen",
"rejectAll": "Alle ablehnen",
"rejected": "Abgelehnt",
"runButton": "Vorschläge abrufen",
"running": "Text wird analysiert… dies dauert normalerweise 15–60 Sekunden.",
"staleHint": "Diese Wörter wurden bearbeitet, seit die Vorschläge generiert wurden, daher gilt dieser Vorschlag nicht mehr.",
"summary": "{total} Vorschläge · {pending} ausstehend · {accepted} akzeptiert",
"title": "Autokorrektur-Vorschläge",
"undo": "Diesen Vorschlag rückgängig machen",
"cancel": "Abbrechen",
"close": "Schließen",
"confidence_balanced": "Ausgewogen",
"compareHint": "Langsamer und teurer, zeigt aber, bei welchen Vorschlägen mehrere Modelle übereinstimmen",
"compareLabel": "Mehrere KI-Modelle vergleichen",
"conflictBadge": "Variante",
"conflictTooltip": "Es gibt verschiedene Vorschläge für diese Wörter — wenn du eine Variante akzeptierst, werden die anderen abgelehnt.",
"consensusBadge": "{consensus}/{total} Modelle",
"consensusTooltip": "Vorgeschlagen von: {models}",
"cachedBadge": "zwischengespeichert",
"cachedTooltip": "Wiederhergestellt aus einem vorherigen Durchlauf mit demselben Text — es sind keine KI-Kosten angefallen."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email όταν είναι έτοιμο",
"afterApproval": "Μετά την έγκριση, το karaoke video σου γίνεται render και παραδίδεται. ~10 λεπτά",
"trackProgressTenant": "Παρακολούθησε την πρόοδο στη λίστα Πρόσφατες Εργασίες.",
"submitAnother": "Υποβολή Άλλου Κομματιού"
"submitAnother": "Υποβολή Άλλου Κομματιού",
"pasteUrlButton": "Επικόλλησε έναν σύνδεσμο",
"urlSupportedSitesHint": "Λειτουργεί με YouTube, Facebook, SoundCloud, TikTok, Vimeo και εκατοντάδες άλλους ιστότοπους.",
"urlSupportedSitesLink": "Δες όλους τους υποστηριζόμενους ιστότοπους",
"useThisUrl": "Χρησιμοποίησε αυτό το URL"
},
"jobStatus": {
"settingUp": "Ρύθμιση",
@@ -772,7 +776,17 @@
"undoFailed": "Η αναίρεση απέτυχε",
"redoFailed": "Η επανάληψη απέτυχε",
"restoreFailed": "Η επαναφορά απέτυχε — κάποιες επεξεργασίες μπορεί να μην έχουν εφαρμοστεί",
"submitFailed": "Η υποβολή απέτυχε"
"submitFailed": "Η υποβολή απέτυχε",
"fadeIn": "Fade In",
"fadeInSelection": "Εφάρμοσε fade in στην επιλεγμένη περιοχή",
"fadeOut": "Fade Out",
"fadeOutSelection": "Εφάρμοσε fade out στην επιλεγμένη περιοχή",
"fadeInDisabledHint": "Για fade in, επίλεξε μια περιοχή που ξεκινά ακριβώς στην αρχή του κομματιού",
"fadeOutDisabledHint": "Για fade out, επίλεξε μια περιοχή που τελειώνει ακριβώς στο τέλος του κομματιού",
"trimEndDisabledHint": "Για να περικόψεις το τέλος, επίλεξε μια περιοχή που τελειώνει ακριβώς στο τέλος του κομματιού",
"trimEndSelection": "Αφαίρεσε τα πάντα μετά την επιλογή",
"trimStartDisabledHint": "Για να περικόψεις την αρχή, επίλεξε μια περιοχή που ξεκινά ακριβώς στην αρχή του κομματιού",
"trimStartSelection": "Αφαίρεσε τα πάντα πριν από την επιλογή"
},
"audioEditRestore": {
"title": "Αποθηκευμένες Συνεδρίες Επεξεργασίας Ήχου",
@@ -799,7 +813,7 @@
"acceptAll": "Αποδοχή Όλων",
"revertAll": "Επαναφορά Όλων",
"undoAll": "Αναίρεση Όλων",
"resetAllChanges": "Επαναφορά όλων των αλλαγών πίσω στους αρχικούς στίχους που διορθώθηκαν από το AI",
"resetAllChanges": "Επαναφορά όλων των αλλαγών στους αρχικούς διορθωμένους στίχους",
"undo": "Αναίρεση",
"redo": "Επανάληψη",
"findReplace": "Εύρεση/Αντικατάσταση",
@@ -809,7 +823,12 @@
"timingOffset": "Μετατόπιση Χρονισμού",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Μετατόπισε όλους τους χρονισμούς λέξεων προς τα εμπρός ή προς τα πίσω. Χρησιμοποίησέ το αν οι στίχοι εμφανίζονται ελαφρώς νωρίς ή αργά στην προεπισκόπηση.",
"playback": "Αναπαραγωγή"
"playback": "Αναπαραγωγή",
"audioLoadError": "Δεν ήταν δυνατή η φόρτωση του ήχου",
"audioStillLoading": "Ο ήχος φορτώνει ακόμα...",
"loadingAudio": "Φόρτωση ήχου...",
"autoCorrect": "Αυτόματη διόρθωση",
"autoCorrectDesc": "Δημιούργησε προτάσεις διόρθωσης συγκρίνοντας τη μεταγραφή με τους στίχους αναφοράς. Τίποτα δεν αλλάζει μέχρι να αποδεχτείς κάθε πρόταση."
},
"guidance": {
"showTips": "Εμφάνιση συμβουλών",
@@ -983,7 +1002,9 @@
"loadingAll": "Φόρτωση όλων των λέξεων...",
"loadingSegment": "Φόρτωση τμήματος...",
"noData": "Δεν υπάρχουν διαθέσιμα δεδομένα τμήματος",
"unCorrect": "Αναίρεση Διόρθωσης"
"unCorrect": "Αναίρεση Διόρθωσης",
"timingClamped": "Ο χρονισμός του \"{word}\" ήταν εκτός του τμήματος — προσαρμόστηκε στα {time}s.",
"timingSanitized": "Διορθώθηκαν {count} χρονισμοί λέξεων που έπεφταν εκτός αυτού του τμήματος."
},
"findReplace": {
"title": "Εύρεση και Αντικατάσταση",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Οι προσαρμοσμένοι στίχοι εφαρμόστηκαν. Συγχρόνισε χειροκίνητα κάθε επεξεργασμένο τμήμα για να βεβαιωθείς ότι ο χρονισμός των λέξεων είναι σωστός για τους προσαρμοσμένους στίχους."
},
"autoCorrect": {
"accept": "Αποδοχή πρότασης",
"acceptAll": "Αποδοχή όλων",
"accepted": "Έγινε αποδοχή",
"adlibRemovalHint": "Επίτρεψε προτάσεις που διαγράφουν δεύτερα φωνητικά τα οποία δεν υπάρχουν στις πηγές αναφοράς",
"adlibRemovalLabel": "Πρόταση αφαίρεσης adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "μορφοποίηση",
"category_grammar": "γραμματική",
"category_mishearing": "παρανόηση",
"category_other": "άλλο",
"category_repeated_chorus_fix": "ρεφρέν",
"collapse": "Σύμπτυξη προτάσεων",
"confidenceHint": "Πόσο βέβαιη πρέπει να είναι μια πρόταση πριν εμφανιστεί",
"confidenceLabel": "Φίλτρο προτάσεων",
"confidence_all": "Εμφάνιση όλων",
"confidence_high": "Υψηλή βεβαιότητα",
"description": "Η αυτόματη διόρθωση συγκρίνει τους μεταγραμμένους στίχους με τις πηγές αναφοράς και προτείνει διορθώσεις σε επίπεδο λέξης. Ελέγχεις κάθε πρόταση — τίποτα δεν εφαρμόζεται μέχρι να την αποδεχτείς.",
"dismiss": "Αγνόηση προτάσεων",
"expand": "Ανάπτυξη προτάσεων",
"insertMarker": "εισαγωγή:",
"insertionsHint": "Επίτρεψε προτάσεις που εισάγουν λέξεις που παραλείφθηκαν κατά τη μεταγραφή",
"insertionsLabel": "Πρόταση λέξεων που λείπουν",
"noReferences": "Δεν υπάρχουν διαθέσιμοι στίχοι αναφοράς για αυτό το τραγούδι, επομένως δεν μπορούν να δημιουργηθούν προτάσεις. Πρόσθεσε πρώτα στίχους από τον πίνακα αναφοράς.",
"noSuggestions": "Δεν βρέθηκαν προβλήματα — δεν υπάρχουν προτεινόμενες αλλαγές.",
"reject": "Απόρριψη πρότασης",
"rejectAll": "Απόρριψη όλων",
"rejected": "Απορρίφθηκε",
"runButton": "Λήψη προτάσεων",
"running": "Ανάλυση στίχων… αυτό συνήθως διαρκεί 15–60 δευτερόλεπτα.",
"staleHint": "Αυτές οι λέξεις επεξεργάστηκαν μετά τη δημιουργία των προτάσεων, επομένως αυτή η πρόταση δεν ισχύει πλέον.",
"summary": "{total} προτάσεις · {pending} σε εκκρεμότητα · {accepted} αποδεκτές",
"title": "Προτάσεις αυτόματης διόρθωσης",
"undo": "Αναίρεση αυτής της πρότασης",
"cancel": "Ακύρωση",
"close": "Κλείσιμο",
"confidence_balanced": "Ισορροπημένη",
"compareHint": "Πιο αργό και κοστίζει περισσότερο, αλλά δείχνει σε ποιες προτάσεις συμφωνούν πολλαπλά μοντέλα",
"compareLabel": "Σύγκρινε πολλαπλά μοντέλα AI",
"conflictBadge": "παραλλαγή",
"conflictTooltip": "Υπάρχουν διαφορετικές προτάσεις για αυτές τις λέξεις — η αποδοχή μιας παραλλαγής απορρίπτει τις υπόλοιπες.",
"consensusBadge": "{consensus}/{total} μοντέλα",
"consensusTooltip": "Προτάθηκε από: {models}",
"cachedBadge": "προσωρινά αποθηκευμένο",
"cachedTooltip": "Ανακτήθηκε από προηγούμενη επεξεργασία των ίδιων στίχων — δεν υπήρξε χρέωση AI."
}
},
"instrumentalReview": {
+70 -3
View File
@@ -473,6 +473,10 @@
"weFindBestAudio": "We find the best audio",
"uploadAFile": "upload a file",
"youtubeUrl": "YouTube URL",
"pasteUrlButton": "Paste a link",
"useThisUrl": "Use This URL",
"urlSupportedSitesHint": "Works with YouTube, Facebook, SoundCloud, TikTok, Vimeo and hundreds of other sites.",
"urlSupportedSitesLink": "See all supported sites",
"onNextPage": "(on next page)",
"artist": "Artist",
"artistPlaceholder": "e.g. Queen",
@@ -749,6 +753,16 @@
"trimEnd": "Trim End",
"cutSelection": "Cut selection (Delete)",
"muteSelection": "Mute selection (M)",
"fadeIn": "Fade In",
"fadeOut": "Fade Out",
"fadeInSelection": "Fade in over the selected region",
"fadeOutSelection": "Fade out over the selected region",
"trimStartSelection": "Remove everything before the selection",
"trimEndSelection": "Remove everything after the selection",
"trimStartDisabledHint": "To trim the start, select a region that begins at the very start of the track",
"trimEndDisabledHint": "To trim the end, select a region that ends at the very end of the track",
"fadeInDisabledHint": "To fade in, select a region that begins at the very start of the track",
"fadeOutDisabledHint": "To fade out, select a region that ends at the very end of the track",
"undo": "Undo (Ctrl+Z)",
"redo": "Redo (Ctrl+Shift+Z)",
"playPause": "Play/Pause (Space)",
@@ -799,7 +813,7 @@
"acceptAll": "Accept All",
"revertAll": "Revert All",
"undoAll": "Undo All",
"resetAllChanges": "Reset all changes back to the original AI-corrected lyrics",
"resetAllChanges": "Reset all changes back to the original corrected lyrics",
"undo": "Undo",
"redo": "Redo",
"findReplace": "Find/Replace",
@@ -809,7 +823,12 @@
"timingOffset": "Timing Offset",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Shift all word timings forward or backward. Use if lyrics appear slightly early or late in the preview.",
"playback": "Playback"
"playback": "Playback",
"loadingAudio": "Loading audio...",
"audioStillLoading": "Audio is still loading...",
"audioLoadError": "Couldn't load audio",
"autoCorrect": "Auto-correct",
"autoCorrectDesc": "Generate correction suggestions by comparing the transcription against the reference lyrics. Nothing is changed until you accept each suggestion."
},
"guidance": {
"showTips": "Show tips",
@@ -986,7 +1005,9 @@
"loadingAll": "Loading all words...",
"loadingSegment": "Loading segment...",
"noData": "No segment data available",
"unCorrect": "Un-Correct"
"unCorrect": "Un-Correct",
"timingSanitized": "Fixed {count} word timing(s) that fell outside this segment.",
"timingClamped": "\"{word}\" timing was outside the segment — snapped to {time}s."
},
"findReplace": {
"title": "Find and Replace",
@@ -1265,6 +1286,52 @@
"legendSinger": "Singer:",
"keyboardHintSegment": "With a segment focused, press 1 / 2 / B",
"resetOverridesTooltip": "Reset word overrides in this segment"
},
"autoCorrect": {
"title": "Auto-correct suggestions",
"description": "Auto-correct compares the transcribed lyrics against the reference sources and suggests word-level fixes. You review every suggestion — nothing is applied until you accept it.",
"noReferences": "No reference lyrics are available for this song, so suggestions can’t be generated. Add lyrics from the reference panel first.",
"running": "Analyzing lyrics… this usually takes 15–60 seconds.",
"adlibRemovalLabel": "Suggest removing adlibs",
"adlibRemovalHint": "Allow suggestions that delete backing vocals the references don’t have",
"insertionsLabel": "Suggest missing words",
"insertionsHint": "Allow suggestions that insert words the transcription missed",
"confidenceLabel": "Suggestion filter",
"confidenceHint": "How confident a suggestion must be before it’s shown",
"confidence_all": "Show all",
"confidence_balanced": "Balanced",
"confidence_high": "High confidence",
"cancel": "Cancel",
"close": "Close",
"runButton": "Get suggestions",
"noSuggestions": "No issues found — there are no suggested changes.",
"summary": "{total} suggestions · {pending} pending · {accepted} accepted",
"acceptAll": "Accept all",
"rejectAll": "Reject all",
"expand": "Expand suggestions",
"collapse": "Collapse suggestions",
"dismiss": "Dismiss suggestions",
"insertMarker": "insert:",
"staleHint": "These words were edited since suggestions were generated, so this suggestion no longer applies.",
"accept": "Accept suggestion",
"reject": "Reject suggestion",
"accepted": "Accepted",
"rejected": "Rejected",
"undo": "Undo this suggestion",
"category_mishearing": "misheard",
"category_grammar": "grammar",
"category_adlib_removal": "adlib",
"category_repeated_chorus_fix": "chorus",
"category_formatting": "format",
"category_other": "other",
"compareLabel": "Compare multiple AI models",
"compareHint": "Slower and costs more, but shows which suggestions multiple models agree on",
"consensusBadge": "{consensus}/{total} models",
"consensusTooltip": "Proposed by: {models}",
"conflictBadge": "variant",
"conflictTooltip": "There are different suggestions for these words — accepting one variant rejects the others.",
"cachedBadge": "cached",
"cachedTooltip": "Restored from a previous run on the same lyrics — no AI cost was incurred."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Correo cuando esté listo",
"afterApproval": "Después de la aprobación, tu video de karaoke se renderiza y se entrega. ~10 minutos",
"trackProgressTenant": "Sigue el progreso en la lista de Trabajos recientes.",
"submitAnother": "Enviar otra pista"
"submitAnother": "Enviar otra pista",
"pasteUrlButton": "Pega un enlace",
"urlSupportedSitesHint": "Funciona con YouTube, Facebook, SoundCloud, TikTok, Vimeo y cientos de sitios más.",
"urlSupportedSitesLink": "Ver todos los sitios compatibles",
"useThisUrl": "Usar esta URL"
},
"jobStatus": {
"settingUp": "Configurando",
@@ -772,7 +776,17 @@
"undoFailed": "Error al deshacer",
"redoFailed": "Error al rehacer",
"restoreFailed": "Error al restaurar — algunas ediciones pueden no haberse aplicado",
"submitFailed": "Error al enviar"
"submitFailed": "Error al enviar",
"fadeIn": "Fundido de entrada",
"fadeInSelection": "Aplicar fundido de entrada en la región seleccionada",
"fadeOut": "Fundido de salida",
"fadeOutSelection": "Aplicar fundido de salida en la región seleccionada",
"fadeInDisabledHint": "Para hacer un fundido de entrada, selecciona una región que comience justo al principio de la pista",
"fadeOutDisabledHint": "Para hacer un fundido de salida, selecciona una región que termine justo al final de la pista",
"trimEndDisabledHint": "Para recortar el final, selecciona una región que termine justo al final de la pista",
"trimEndSelection": "Eliminar todo después de la selección",
"trimStartDisabledHint": "Para recortar el principio, selecciona una región que comience justo al principio de la pista",
"trimStartSelection": "Eliminar todo antes de la selección"
},
"audioEditRestore": {
"title": "Sesiones de edición de audio guardadas",
@@ -799,7 +813,7 @@
"acceptAll": "Aceptar todo",
"revertAll": "Revertir todo",
"undoAll": "Deshacer todo",
"resetAllChanges": "Restablecer todos los cambios a las letras originales corregidas por IA",
"resetAllChanges": "Restablecer todos los cambios a las letras corregidas originales",
"undo": "Deshacer",
"redo": "Rehacer",
"findReplace": "Buscar/Reemplazar",
@@ -809,7 +823,12 @@
"timingOffset": "Desplazamiento de tiempo",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Desplaza todos los tiempos de las palabras hacia adelante o hacia atrás. Úsalo si las letras aparecen un poco antes o después en la vista previa.",
"playback": "Reproducción"
"playback": "Reproducción",
"audioLoadError": "No se pudo cargar el audio",
"audioStillLoading": "El audio aún se está cargando...",
"loadingAudio": "Cargando audio...",
"autoCorrect": "Autocorrección",
"autoCorrectDesc": "Genera sugerencias de corrección comparando la transcripción con las letras de referencia. No se cambia nada hasta que aceptas cada sugerencia."
},
"guidance": {
"showTips": "Mostrar consejos",
@@ -983,7 +1002,9 @@
"loadingAll": "Cargando todas las palabras...",
"loadingSegment": "Cargando segmento...",
"noData": "No hay datos de segmento disponibles",
"unCorrect": "Des-corregir"
"unCorrect": "Des-corregir",
"timingClamped": "El tiempo de \"{word}\" estaba fuera del segmento — ajustado a {time}s.",
"timingSanitized": "Se corrigió el tiempo de {count} palabra(s) que quedaban fuera de este segmento."
},
"findReplace": {
"title": "Buscar y reemplazar",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Letras personalizadas aplicadas. Sincroniza manualmente cada segmento editado para asegurar que los tiempos de las palabras sean correctos para las letras personalizadas."
},
"autoCorrect": {
"accept": "Aceptar sugerencia",
"acceptAll": "Aceptar todas",
"accepted": "Aceptada",
"adlibRemovalHint": "Permitir sugerencias que eliminen coros que las referencias no tienen",
"adlibRemovalLabel": "Sugerir eliminar improvisaciones",
"category_adlib_removal": "improvisación",
"category_formatting": "formato",
"category_grammar": "gramática",
"category_mishearing": "mal escuchada",
"category_other": "otro",
"category_repeated_chorus_fix": "estribillo",
"collapse": "Contraer sugerencias",
"confidenceHint": "Qué nivel de confianza debe tener una sugerencia para mostrarse",
"confidenceLabel": "Filtro de sugerencias",
"confidence_all": "Mostrar todas",
"confidence_high": "Alta confianza",
"description": "La autocorrección compara las letras transcritas con las fuentes de referencia y sugiere correcciones a nivel de palabra. Revisas cada sugerencia — no se aplica nada hasta que la aceptas.",
"dismiss": "Descartar sugerencias",
"expand": "Expandir sugerencias",
"insertMarker": "insertar:",
"insertionsHint": "Permitir sugerencias que inserten palabras que la transcripción omitió",
"insertionsLabel": "Sugerir palabras faltantes",
"noReferences": "No hay letras de referencia disponibles para esta canción, por lo que no se pueden generar sugerencias. Primero añade letras desde el panel de referencia.",
"noSuggestions": "No se encontraron problemas — no hay cambios sugeridos.",
"reject": "Rechazar sugerencia",
"rejectAll": "Rechazar todas",
"rejected": "Rechazada",
"runButton": "Obtener sugerencias",
"running": "Analizando letras… esto suele tardar entre 15 y 60 segundos.",
"staleHint": "Estas palabras fueron editadas desde que se generaron las sugerencias, por lo que esta sugerencia ya no es válida.",
"summary": "{total} sugerencias · {pending} pendientes · {accepted} aceptadas",
"title": "Sugerencias de autocorrección",
"undo": "Deshacer esta sugerencia",
"cancel": "Cancelar",
"close": "Cerrar",
"confidence_balanced": "Equilibrada",
"compareHint": "Es más lento y cuesta más, pero muestra en qué sugerencias coinciden varios modelos",
"compareLabel": "Comparar varios modelos de IA",
"conflictBadge": "variante",
"conflictTooltip": "Hay diferentes sugerencias para estas palabras — al aceptar una variante se rechazan las demás.",
"consensusBadge": "{consensus}/{total} modelos",
"consensusTooltip": "Propuesto por: {models}",
"cachedBadge": "en caché",
"cachedTooltip": "Restaurado de una ejecución anterior con las mismas letras — no generó costos de IA."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Sähköposti kun valmis",
"afterApproval": "Hyväksymisen jälkeen karaokevideosi renderöidään ja toimitetaan. ~10 minuuttia",
"trackProgressTenant": "Seuraa edistymistä Viimeisimmät työt -luettelossa.",
"submitAnother": "Lähetä toinen raita"
"submitAnother": "Lähetä toinen raita",
"pasteUrlButton": "Liitä linkki",
"urlSupportedSitesHint": "Toimii YouTuben, Facebookin, SoundCloudin, TikTokin, Vimeon ja satojen muiden sivustojen kanssa.",
"urlSupportedSitesLink": "Katso kaikki tuetut sivustot",
"useThisUrl": "Käytä tätä osoitetta"
},
"jobStatus": {
"settingUp": "Asetetaan",
@@ -772,7 +776,17 @@
"undoFailed": "Kumoaminen epäonnistui",
"redoFailed": "Uudelleentekeminen epäonnistui",
"restoreFailed": "Palauttaminen epäonnistui — joitain muokkauksia ei ehkä ole sovellettu",
"submitFailed": "Lähetys epäonnistui"
"submitFailed": "Lähetys epäonnistui",
"fadeIn": "Häivytä sisään",
"fadeInSelection": "Häivytä sisään valitulla alueella",
"fadeOut": "Häivytä ulos",
"fadeOutSelection": "Häivytä ulos valitulla alueella",
"fadeInDisabledHint": "Jos haluat lisätä sisäänhäivytyksen, valitse alue, joka alkaa aivan raidan alusta",
"fadeOutDisabledHint": "Jos haluat lisätä uloshäivytyksen, valitse alue, joka päättyy aivan raidan loppuun",
"trimEndDisabledHint": "Jos haluat leikata lopun, valitse alue, joka päättyy aivan raidan loppuun",
"trimEndSelection": "Poista kaikki valinnan jälkeen",
"trimStartDisabledHint": "Jos haluat leikata alun, valitse alue, joka alkaa aivan raidan alusta",
"trimStartSelection": "Poista kaikki ennen valintaa"
},
"audioEditRestore": {
"title": "Tallennetut äänimuokkausistunnot",
@@ -799,7 +813,7 @@
"acceptAll": "Hyväksy kaikki",
"revertAll": "Palauta kaikki",
"undoAll": "Kumoa kaikki",
"resetAllChanges": "Palauta kaikki muutokset takaisin alkuperäisiin tekoälyn korjaamiin sanoituksiin",
"resetAllChanges": "Peru kaikki muutokset ja palauta alkuperäiset korjatut sanoitukset",
"undo": "Kumoa",
"redo": "Tee uudelleen",
"findReplace": "Etsi/Korvaa",
@@ -809,7 +823,12 @@
"timingOffset": "Ajoituksen siirtymä",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Siirrä kaikkien sanojen ajoitusta eteen- tai taaksepäin. Käytä, jos sanoitukset näkyvät hieman liian aikaisin tai myöhään esikatselussa.",
"playback": "Toisto"
"playback": "Toisto",
"audioLoadError": "Ääntä ei voitu ladata",
"audioStillLoading": "Ääni latautuu yhä...",
"loadingAudio": "Ladataan ääntä...",
"autoCorrect": "Automaattinen korjaus",
"autoCorrectDesc": "Luo korjausehdotuksia vertaamalla litterointia vertailusanoituksiin. Mitään ei muuteta ennen kuin hyväksyt jokaisen ehdotuksen."
},
"guidance": {
"showTips": "Näytä vinkit",
@@ -983,7 +1002,9 @@
"loadingAll": "Ladataan kaikkia sanoja...",
"loadingSegment": "Ladataan segmenttiä...",
"noData": "Segmentin dataa ei saatavilla",
"unCorrect": "Peru korjaus"
"unCorrect": "Peru korjaus",
"timingClamped": "\"{word}\" ajoitus oli segmentin ulkopuolella — kohdistettiin aikaan {time} s.",
"timingSanitized": "Korjattu {count} sanan ajoitus(ta), jotka jäivät tämän segmentin ulkopuolelle."
},
"findReplace": {
"title": "Etsi ja korvaa",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Mukautetut sanoitukset otettu käyttöön. Synkronoi jokainen muokattu segmentti manuaalisesti varmistaaksesi, että sanojen ajoitukset sopivat mukautettuihin sanoituksiin."
},
"autoCorrect": {
"accept": "Hyväksy ehdotus",
"acceptAll": "Hyväksy kaikki",
"accepted": "Hyväksytty",
"adlibRemovalHint": "Salli ehdotukset, jotka poistavat taustalauluja, joita ei ole viitesanoituksissa",
"adlibRemovalLabel": "Ehdotukset adlibien poistamisesta",
"category_adlib_removal": "adlib",
"category_formatting": "muotoilu",
"category_grammar": "kielioppi",
"category_mishearing": "väärin kuultu",
"category_other": "muu",
"category_repeated_chorus_fix": "kertosäe",
"collapse": "Pienennä ehdotukset",
"confidenceHint": "Kuinka varma ehdotuksen pitää olla, jotta se näytetään",
"confidenceLabel": "Ehdotusten suodatin",
"confidence_all": "Näytä kaikki",
"confidence_high": "Korkea varmuus",
"description": "Automaattinen korjaus vertaa litteroituja sanoituksia vertailulähteisiin ja ehdottaa sanakohtaisia korjauksia. Käyt läpi jokaisen ehdotuksen — mitään ei oteta käyttöön ennen kuin hyväksyt sen.",
"dismiss": "Ohita ehdotukset",
"expand": "Laajenna ehdotukset",
"insertMarker": "lisää:",
"insertionsHint": "Salli ehdotukset, jotka lisäävät transkriptiosta puuttuvia sanoja",
"insertionsLabel": "Ehdotukset puuttuvien sanojen lisäämisestä",
"noReferences": "Tälle kappaleelle ei ole saatavilla vertailusanoituksia, joten ehdotuksia ei voida luoda. Lisää sanoitukset ensin vertailupaneelista.",
"noSuggestions": "Ongelmia ei löytynyt — ei ehdotettuja muutoksia.",
"reject": "Hylkää ehdotus",
"rejectAll": "Hylkää kaikki",
"rejected": "Hylätty",
"runButton": "Hae ehdotuksia",
"running": "Analysoidaan sanoituksia… tässä kestää yleensä 15–60 sekuntia.",
"staleHint": "Näitä sanoja on muokattu sen jälkeen, kun ehdotukset luotiin, joten tämä ehdotus ei enää päde.",
"summary": "{total} ehdotusta · {pending} odottaa · {accepted} hyväksytty",
"title": "Automaattisen korjauksen ehdotukset",
"undo": "Kumoa tämä ehdotus",
"cancel": "Peruuta",
"close": "Sulje",
"confidence_balanced": "Tasapainoinen",
"compareHint": "Hitaampi ja kalliimpi, mutta näyttää, mistä ehdotuksista useampi malli on samaa mieltä",
"compareLabel": "Vertaile useita tekoälymalleja",
"conflictBadge": "vaihtoehto",
"conflictTooltip": "Näille sanoille on eri ehdotuksia — yhden vaihtoehdon hyväksyminen hylkää muut.",
"consensusBadge": "{consensus}/{total} mallia",
"consensusTooltip": "Ehdottanut: {models}",
"cachedBadge": "välimuistissa",
"cachedTooltip": "Palautettu aiemmasta ajosta samoilla sanoituksilla — tekoälykustannuksia ei syntynyt."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail quand c'est prêt",
"afterApproval": "Après approbation, ta vidéo karaoké est rendue et livrée. ~10 minutes",
"trackProgressTenant": "Suis la progression dans la liste des Projets récents.",
"submitAnother": "Soumettre une autre piste"
"submitAnother": "Soumettre une autre piste",
"pasteUrlButton": "Coller un lien",
"urlSupportedSitesHint": "Fonctionne avec YouTube, Facebook, SoundCloud, TikTok, Vimeo et des centaines d'autres sites.",
"urlSupportedSitesLink": "Voir tous les sites compatibles",
"useThisUrl": "Utiliser cette URL"
},
"jobStatus": {
"settingUp": "Configuration",
@@ -772,7 +776,17 @@
"undoFailed": "Échec de l'annulation",
"redoFailed": "Échec du rétablissement",
"restoreFailed": "Échec de la restauration — certaines modifications peuvent ne pas avoir été appliquées",
"submitFailed": "Échec de la soumission"
"submitFailed": "Échec de la soumission",
"fadeIn": "Fondu entrant",
"fadeInSelection": "Fondu entrant sur la zone sélectionnée",
"fadeOut": "Fondu sortant",
"fadeOutSelection": "Fondu sortant sur la zone sélectionnée",
"fadeInDisabledHint": "Pour faire un fondu en ouverture, sélectionne une région qui commence tout au début de la piste",
"fadeOutDisabledHint": "Pour faire un fondu en fermeture, sélectionne une région qui se termine tout à la fin de la piste",
"trimEndDisabledHint": "Pour couper la fin, sélectionne une région qui se termine tout à la fin de la piste",
"trimEndSelection": "Tout supprimer après la sélection",
"trimStartDisabledHint": "Pour couper le début, sélectionne une région qui commence tout au début de la piste",
"trimStartSelection": "Tout supprimer avant la sélection"
},
"audioEditRestore": {
"title": "Sessions d'édition audio sauvegardées",
@@ -799,7 +813,7 @@
"acceptAll": "Tout accepter",
"revertAll": "Tout annuler",
"undoAll": "Tout défaire",
"resetAllChanges": "Réinitialiser toutes les modifications aux paroles originales corrigées par l'IA",
"resetAllChanges": "Réinitialiser toutes les modifications pour revenir aux paroles corrigées d'origine",
"undo": "Annuler",
"redo": "Rétablir",
"findReplace": "Chercher/Remplacer",
@@ -809,7 +823,12 @@
"timingOffset": "Décalage temporel",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Décale tous les timings des mots vers l'avant ou l'arrière. Utilise ceci si les paroles apparaissent légèrement en avance ou en retard dans l'aperçu.",
"playback": "Lecture"
"playback": "Lecture",
"audioLoadError": "Impossible de charger l'audio",
"audioStillLoading": "L'audio est toujours en cours de chargement...",
"loadingAudio": "Chargement de l'audio...",
"autoCorrect": "Correction automatique",
"autoCorrectDesc": "Génère des suggestions de correction en comparant la transcription aux paroles de référence. Rien n'est modifié tant que tu n'as pas accepté chaque suggestion."
},
"guidance": {
"showTips": "Afficher les conseils",
@@ -983,7 +1002,9 @@
"loadingAll": "Chargement de tous les mots...",
"loadingSegment": "Chargement du segment...",
"noData": "Aucune donnée de segment disponible",
"unCorrect": "Dé-corriger"
"unCorrect": "Dé-corriger",
"timingClamped": "Le timing de \"{word}\" était en dehors du segment — ajusté à {time}s.",
"timingSanitized": "Correction de {count} timing(s) de mot(s) en dehors de ce segment."
},
"findReplace": {
"title": "Chercher et Remplacer",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Paroles personnalisées appliquées. Synchronise manuellement chaque segment modifié pour t'assurer que le timing des mots est correct."
},
"autoCorrect": {
"accept": "Accepter la suggestion",
"acceptAll": "Tout accepter",
"accepted": "Accepté",
"adlibRemovalHint": "Autoriser les suggestions qui suppriment les voix de fond absentes des références",
"adlibRemovalLabel": "Suggérer la suppression des adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "grammaire",
"category_mishearing": "mal compris",
"category_other": "autre",
"category_repeated_chorus_fix": "refrain",
"collapse": "Réduire les suggestions",
"confidenceHint": "Le niveau de certitude requis pour qu'une suggestion soit affichée",
"confidenceLabel": "Filtre de suggestions",
"confidence_all": "Tout afficher",
"confidence_high": "Certitude élevée",
"description": "La correction automatique compare les paroles transcrites aux sources de référence et suggère des corrections mot par mot. Tu examines chaque suggestion — rien n'est appliqué tant que tu ne l'as pas acceptée.",
"dismiss": "Ignorer les suggestions",
"expand": "Développer les suggestions",
"insertMarker": "insérer :",
"insertionsHint": "Autoriser les suggestions qui insèrent les mots manquants dans la transcription",
"insertionsLabel": "Suggérer les mots manquants",
"noReferences": "Il n'y a pas de paroles de référence disponibles pour cette chanson, les suggestions ne peuvent donc pas être générées. Ajoute d'abord des paroles depuis le panneau de référence.",
"noSuggestions": "Aucun problème trouvé — il n'y a aucune modification suggérée.",
"reject": "Rejeter la suggestion",
"rejectAll": "Tout rejeter",
"rejected": "Rejeté",
"runButton": "Obtenir des suggestions",
"running": "Analyse des paroles… cela prend généralement 15 à 60 secondes.",
"staleHint": "Ces mots ont été modifiés depuis la génération des suggestions, celle-ci ne s'applique donc plus.",
"summary": "{total} suggestions · {pending} en attente · {accepted} acceptées",
"title": "Suggestions de correction automatique",
"undo": "Annuler cette suggestion",
"cancel": "Annuler",
"close": "Fermer",
"confidence_balanced": "Équilibrée",
"compareHint": "Plus lent et plus cher, mais montre les suggestions sur lesquelles plusieurs modèles s'accordent",
"compareLabel": "Comparer plusieurs modèles d'IA",
"conflictBadge": "variante",
"conflictTooltip": "Plusieurs suggestions sont proposées pour ces mots — en accepter une rejette les autres.",
"consensusBadge": "{consensus}/{total} modèles",
"consensusTooltip": "Proposé par : {models}",
"cachedBadge": "en cache",
"cachedTooltip": "Restauré depuis un traitement précédent sur les mêmes paroles — aucun coût d'IA n'a été engagé."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "אימייל כשמוכן",
"afterApproval": "לאחר האישור, וידאו הקריוקי שלך מרונדר ומסופק. ~10 דקות",
"trackProgressTenant": "עקוב אחר ההתקדמות ברשימת העבודות האחרונות.",
"submitAnother": "שלח רצועה נוספת"
"submitAnother": "שלח רצועה נוספת",
"pasteUrlButton": "הדבקת קישור",
"urlSupportedSitesHint": "עובד עם YouTube, Facebook, SoundCloud, TikTok, Vimeo ומאות אתרים נוספים.",
"urlSupportedSitesLink": "לצפייה בכל האתרים הנתמכים",
"useThisUrl": "שימוש בכתובת זו"
},
"jobStatus": {
"settingUp": "מגדיר",
@@ -772,7 +776,17 @@
"undoFailed": "ביטול נכשל",
"redoFailed": "ביצוע שוב נכשל",
"restoreFailed": "שחזור נכשל — ייתכן שחלק מהעריכות לא הוחלו",
"submitFailed": "שליחה נכשלה"
"submitFailed": "שליחה נכשלה",
"fadeIn": "פייד אין",
"fadeInSelection": "החלת פייד אין על האזור הנבחר",
"fadeOut": "פייד אאוט",
"fadeOutSelection": "החלת פייד אאוט על האזור הנבחר",
"fadeInDisabledHint": "כדי לבצע הגברה הדרגתית, בחרו אזור שמתחיל בדיוק בתחילת הרצועה",
"fadeOutDisabledHint": "כדי לבצע הנמכה הדרגתית, בחרו אזור שמסתיים בדיוק בסוף הרצועה",
"trimEndDisabledHint": "כדי לחתוך את הסוף, בחרו אזור שמסתיים בדיוק בסוף הרצועה",
"trimEndSelection": "הסירו הכל אחרי האזור הנבחר",
"trimStartDisabledHint": "כדי לחתוך את ההתחלה, בחרו אזור שמתחיל בדיוק בתחילת הרצועה",
"trimStartSelection": "הסירו הכל לפני האזור הנבחר"
},
"audioEditRestore": {
"title": "הפעלות עריכת אודיו שמורות",
@@ -799,7 +813,7 @@
"acceptAll": "אשר הכל",
"revertAll": "החזר הכל",
"undoAll": "בטל הכל",
"resetAllChanges": "אפס את כל השינויים חזרה למילים המקוריות שתוקנו על ידי AI",
"resetAllChanges": "איפוס כל השינויים בחזרה למילים המתוקנות המקוריות",
"undo": "בטל",
"redo": "בצע שוב",
"findReplace": "חפש/החלף",
@@ -809,7 +823,12 @@
"timingOffset": "היסט תזמון",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "הזז את כל תזמוני המילים קדימה או אחורה. השתמש אם המילים מופיעות מעט מוקדם או מאוחר בתצוגה המקדימה.",
"playback": "השמעה"
"playback": "השמעה",
"audioLoadError": "לא הצלחנו לטעון את האודיו",
"audioStillLoading": "האודיו עדיין נטען...",
"loadingAudio": "טוען אודיו...",
"autoCorrect": "תיקון אוטומטי",
"autoCorrectDesc": "הפקת הצעות לתיקון על ידי השוואת התמלול למילות הייחוס. שום שינוי לא יחול עד לאישור כל הצעה."
},
"guidance": {
"showTips": "הצג טיפים",
@@ -983,7 +1002,9 @@
"loadingAll": "טוען את כל המילים...",
"loadingSegment": "טוען מקטע...",
"noData": "אין נתוני מקטע זמינים",
"unCorrect": "בטל תיקון"
"unCorrect": "בטל תיקון",
"timingClamped": "התזמון של \"{word}\" היה מחוץ למקטע — הוצמד ל-{time} שניות.",
"timingSanitized": "תוקנו {count} תזמוני מילים שחרגו מהמקטע הזה."
},
"findReplace": {
"title": "חפש והחלף",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "המילים המותאמות אישית הוחלו. יש לסנכרן ידנית כל מקטע שנערך כדי להבטיח שתזמוני המילים מדויקים."
},
"autoCorrect": {
"accept": "קבל הצעה",
"acceptAll": "קבל הכל",
"accepted": "התקבל",
"adlibRemovalHint": "אפשר הצעות שמוחקות קולות רקע שאינם מופיעים במקורות",
"adlibRemovalLabel": "הצע הסרת אלתורים",
"category_adlib_removal": "אלתור",
"category_formatting": "עיצוב",
"category_grammar": "דקדוק",
"category_mishearing": "שמיעה שגויה",
"category_other": "אחר",
"category_repeated_chorus_fix": "פזמון",
"collapse": "צמצם הצעות",
"confidenceHint": "רמת הוודאות הנדרשת לפני שהצעה תוצג",
"confidenceLabel": "מסנן הצעות",
"confidence_all": "הצג הכל",
"confidence_high": "ביטחון גבוה",
"description": "התיקון האוטומטי משווה את המילים שתומללו למקורות הייחוס ומציע תיקונים ברמת המילה. באפשרותך לעבור על כל הצעה — שום שינוי לא יחול עד לאישורו.",
"dismiss": "הסתר הצעות",
"expand": "הרחב הצעות",
"insertMarker": "הוסף:",
"insertionsHint": "אפשר הצעות שמוסיפות מילים שהתפספסו בתמלול",
"insertionsLabel": "הצע מילים חסרות",
"noReferences": "אין מילות ייחוס זמינות לשיר זה, ולכן לא ניתן להפיק הצעות. יש להוסיף תחילה מילים מחלונית הייחוס.",
"noSuggestions": "לא נמצאו בעיות — אין שינויים מוצעים.",
"reject": "דחה הצעה",
"rejectAll": "דחה הכל",
"rejected": "נדחה",
"runButton": "קבל הצעות",
"running": "מנתח מילים… פעולה זו אורכת בדרך כלל 15–60 שניות.",
"staleHint": "מילים אלו נערכו מאז שההצעות נוצרו, ולכן הצעה זו כבר אינה רלוונטית.",
"summary": "{total} הצעות · {pending} ממתינות · {accepted} התקבלו",
"title": "הצעות לתיקון אוטומטי",
"undo": "בטל הצעה זו",
"cancel": "ביטול",
"close": "סגירה",
"confidence_balanced": "מאוזנת",
"compareHint": "איטי ויקר יותר, אבל מראה על אילו הצעות מספר מודלים מסכימים",
"compareLabel": "השוואה בין מספר מודלי AI",
"conflictBadge": "גרסה",
"conflictTooltip": "ישנן הצעות שונות למילים אלו — אישור גרסה אחת ידחה את האחרות.",
"consensusBadge": "{consensus}/{total} מודלים",
"consensusTooltip": "הוצע על ידי: {models}",
"cachedBadge": "שמור במטמון",
"cachedTooltip": "שוחזר מהרצה קודמת על אותן מילים — ללא חיוב עלות AI."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "तैयार होने पर ईमेल",
"afterApproval": "अप्रूवल के बाद, तुम्हारा कराओके वीडियो रेंडर और डिलीवर किया जाता है। ~10 मिनट",
"trackProgressTenant": "हाल के जॉब्स लिस्ट में प्रोग्रेस ट्रैक करो।",
"submitAnother": "एक और ट्रैक सबमिट करो"
"submitAnother": "एक और ट्रैक सबमिट करो",
"pasteUrlButton": "एक लिंक पेस्ट करो",
"urlSupportedSitesHint": "यह YouTube, Facebook, SoundCloud, TikTok, Vimeo और सैकड़ों अन्य साइटों के साथ काम करता है।",
"urlSupportedSitesLink": "सभी समर्थित साइटें देखो",
"useThisUrl": "इस URL का इस्तेमाल करो"
},
"jobStatus": {
"settingUp": "सेटअप हो रहा है",
@@ -772,7 +776,17 @@
"undoFailed": "अनडू विफल रहा",
"redoFailed": "रीडू विफल रहा",
"restoreFailed": "रिस्टोर विफल रहा — कुछ एडिट्स लागू नहीं हुए होंगे",
"submitFailed": "सबमिट विफल रहा"
"submitFailed": "सबमिट विफल रहा",
"fadeIn": "फ़ेड इन",
"fadeInSelection": "चुने गए हिस्से पर फ़ेड इन करो",
"fadeOut": "फ़ेड आउट",
"fadeOutSelection": "चुने गए हिस्से पर फ़ेड आउट करो",
"fadeInDisabledHint": "फेड इन करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक की बिल्कुल शुरुआत से शुरू होता हो",
"fadeOutDisabledHint": "फेड आउट करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक के बिल्कुल अंत में खत्म होता हो",
"trimEndDisabledHint": "अंत को ट्रिम करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक के बिल्कुल अंत में खत्म होता हो",
"trimEndSelection": "चुने हुए हिस्से के बाद का सब कुछ हटा दो",
"trimStartDisabledHint": "शुरुआत को ट्रिम करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक की बिल्कुल शुरुआत से शुरू होता हो",
"trimStartSelection": "चुने हुए हिस्से से पहले का सब कुछ हटा दो"
},
"audioEditRestore": {
"title": "सेव किए गए ऑडियो एडिट सेशंस",
@@ -799,7 +813,7 @@
"acceptAll": "सभी एक्सेप्ट करो",
"revertAll": "सभी रिवर्ट करो",
"undoAll": "सभी अनडू करो",
"resetAllChanges": "सभी बदलावों को ओरिजिनल AI-करेक्टेड लिरिक्स पर रीसेट करो",
"resetAllChanges": "सभी बदलावों को वापस मूल सही किए गए लिरिक्स पर रीसेट करो",
"undo": "अनडू",
"redo": "रीडू",
"findReplace": "ढूंढो/बदलो",
@@ -809,7 +823,12 @@
"timingOffset": "टाइमिंग ऑफ़सेट",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "सभी शब्दों की टाइमिंग को आगे या पीछे शिफ्ट करो। अगर प्रीव्यू में लिरिक्स थोड़े जल्दी या देर से दिखाई देते हैं तो इसका उपयोग करो।",
"playback": "प्लेबैक"
"playback": "प्लेबैक",
"audioLoadError": "ऑडियो लोड नहीं हो सका",
"audioStillLoading": "ऑडियो अभी भी लोड हो रहा है...",
"loadingAudio": "ऑडियो लोड हो रहा है...",
"autoCorrect": "ऑटो-करेक्ट",
"autoCorrectDesc": "ट्रांसक्रिप्शन की तुलना रेफरेंस लिरिक्स से करके सुधार के सुझाव जनरेट करो। जब तक तुम हर सुझाव को स्वीकार नहीं करते, तब तक कुछ नहीं बदलता।"
},
"guidance": {
"showTips": "टिप्स दिखाओ",
@@ -983,7 +1002,9 @@
"loadingAll": "सभी शब्द लोड हो रहे हैं...",
"loadingSegment": "सेगमेंट लोड हो रहा है...",
"noData": "कोई सेगमेंट डेटा उपलब्ध नहीं है",
"unCorrect": "अन-करेक्ट करो"
"unCorrect": "अन-करेक्ट करो",
"timingClamped": "\"{word}\" की टाइमिंग सेगमेंट के बाहर थी — इसे {time}s पर सेट कर दिया गया है।",
"timingSanitized": "इस सेगमेंट के बाहर आने वाली {count} शब्द की टाइमिंग को ठीक किया गया।"
},
"findReplace": {
"title": "ढूंढो और बदलो",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "कस्टम लिरिक्स लागू हो गए। यह पक्का करने के लिए कि कस्टमाइज़्ड लिरिक्स के लिए शब्दों की टाइमिंग सही है, हर एडिट किए गए हिस्से को मैन्युअली सिंक करो।"
},
"autoCorrect": {
"accept": "सुझाव स्वीकार करो",
"acceptAll": "सभी स्वीकार करो",
"accepted": "स्वीकार किया गया",
"adlibRemovalHint": "उन सुझावों को अनुमति दो जो ऐसे बैकिंग वोकल्स को हटाते हैं जो रेफरेंस में नहीं हैं",
"adlibRemovalLabel": "एडलिब्स हटाने का सुझाव दो",
"category_adlib_removal": "एडलिब",
"category_formatting": "फॉर्मेट",
"category_grammar": "व्याकरण",
"category_mishearing": "गलत सुना गया",
"category_other": "अन्य",
"category_repeated_chorus_fix": "कोरस",
"collapse": "सुझाव छिपाओ",
"confidenceHint": "दिखाए जाने से पहले किसी सुझाव का कितना सटीक होना ज़रूरी है",
"confidenceLabel": "सुझाव फ़िल्टर",
"confidence_all": "सभी दिखाओ",
"confidence_high": "ज़्यादा आश्वस्त",
"description": "ऑटो-करेक्ट ट्रांसक्राइब किए गए लिरिक्स की तुलना रेफरेंस सोर्स से करता है और शब्दों को ठीक करने के सुझाव देता है। तुम हर सुझाव का रिव्यू कर सकते हो — जब तक तुम इसे स्वीकार नहीं करते, तब तक कुछ भी लागू नहीं होता।",
"dismiss": "सुझाव हटाओ",
"expand": "सुझाव पूरे दिखाओ",
"insertMarker": "जोड़ो:",
"insertionsHint": "उन सुझावों को अनुमति दो जो ट्रांसक्रिप्शन में छूटे हुए शब्दों को जोड़ते हैं",
"insertionsLabel": "छूटे हुए शब्दों का सुझाव दो",
"noReferences": "इस गाने के लिए कोई रेफरेंस लिरिक्स उपलब्ध नहीं हैं, इसलिए सुझाव जनरेट नहीं किए जा सकते। पहले रेफरेंस पैनल से लिरिक्स जोड़ो।",
"noSuggestions": "कोई समस्या नहीं मिली — बदलाव के लिए कोई सुझाव नहीं हैं।",
"reject": "सुझाव अस्वीकार करो",
"rejectAll": "सभी अस्वीकार करो",
"rejected": "अस्वीकार किया गया",
"runButton": "सुझाव प्राप्त करो",
"running": "लिरिक्स का विश्लेषण हो रहा है… इसमें आमतौर पर 15–60 सेकंड लगते हैं।",
"staleHint": "सुझाव आने के बाद इन शब्दों को एडिट किया गया था, इसलिए यह सुझाव अब लागू नहीं होता।",
"summary": "{total} सुझाव · {pending} लंबित · {accepted} स्वीकार किए गए",
"title": "ऑटो-करेक्ट सुझाव",
"undo": "इस सुझाव को पूर्ववत करो",
"cancel": "कैंसल",
"close": "बंद करो",
"confidence_balanced": "संतुलित",
"compareHint": "यह धीमा है और इसमें ज़्यादा खर्च आता है, लेकिन यह दिखाता है कि किन सुझावों पर कई मॉडल सहमत हैं",
"compareLabel": "कई AI मॉडलों की तुलना करो",
"conflictBadge": "विकल्प",
"conflictTooltip": "इन शब्दों के लिए अलग-अलग सुझाव हैं — एक विकल्प को स्वीकार करने पर बाकी अस्वीकार हो जाएंगे।",
"consensusBadge": "{consensus}/{total} मॉडल",
"consensusTooltip": "इनके द्वारा प्रस्तावित: {models}",
"cachedBadge": "कैश्ड",
"cachedTooltip": "इन्हीं लिरिक्स पर पिछले रन से रीस्टोर किया गया — कोई AI लागत नहीं आई।"
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail kada bude spremno",
"afterApproval": "Nakon odobrenja, tvoj karaoke video se renderira i isporučuje. ~10 minuta",
"trackProgressTenant": "Prati napredak na popisu Nedavni poslovi.",
"submitAnother": "Pošalji još jednu pjesmu"
"submitAnother": "Pošalji još jednu pjesmu",
"pasteUrlButton": "Zalijepi poveznicu",
"urlSupportedSitesHint": "Radi s platformama YouTube, Facebook, SoundCloud, TikTok, Vimeo i stotinama drugih stranica.",
"urlSupportedSitesLink": "Pogledaj sve podržane stranice",
"useThisUrl": "Upotrijebi ovaj URL"
},
"jobStatus": {
"settingUp": "Postavljanje",
@@ -772,7 +776,17 @@
"undoFailed": "Poništavanje nije uspjelo",
"redoFailed": "Ponavljanje nije uspjelo",
"restoreFailed": "Vraćanje nije uspjelo — neka uređivanja možda nisu primijenjena",
"submitFailed": "Slanje nije uspjelo"
"submitFailed": "Slanje nije uspjelo",
"fadeIn": "Postupno pojačavanje",
"fadeInSelection": "Postupno pojačaj odabrano područje",
"fadeOut": "Postupno stišavanje",
"fadeOutSelection": "Postupno stišaj odabrano područje",
"fadeInDisabledHint": "Za postepeno pojačavanje zvuka, odaberi dio koji počinje na samom početku trake",
"fadeOutDisabledHint": "Za postepeno stišavanje zvuka, odaberi dio koji završava na samom kraju trake",
"trimEndDisabledHint": "Za skraćivanje kraja, odaberi dio koji završava na samom kraju trake",
"trimEndSelection": "Ukloni sve nakon odabira",
"trimStartDisabledHint": "Za skraćivanje početka, odaberi dio koji počinje na samom početku trake",
"trimStartSelection": "Ukloni sve prije odabira"
},
"audioEditRestore": {
"title": "Spremljene sesije uređivanja zvuka",
@@ -799,7 +813,7 @@
"acceptAll": "Prihvati sve",
"revertAll": "Vrati sve",
"undoAll": "Poništi sve",
"resetAllChanges": "Poništi sve promjene natrag na originalni AI-ispravljeni tekst",
"resetAllChanges": "Poništi sve promjene i vrati na izvorni ispravljeni tekst",
"undo": "Poništi",
"redo": "Ponovi",
"findReplace": "Pronađi/Zamijeni",
@@ -809,7 +823,12 @@
"timingOffset": "Pomak tempiranja",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Pomakni sva tempiranja riječi naprijed ili natrag. Koristi ako se tekst pojavljuje malo prerano ili prekasno u pregledu.",
"playback": "Reprodukcija"
"playback": "Reprodukcija",
"audioLoadError": "Nije moguće učitati audio",
"audioStillLoading": "Audio se još uvijek učitava...",
"loadingAudio": "Učitavanje audija...",
"autoCorrect": "Automatski ispravak",
"autoCorrectDesc": "Generiraj prijedloge za ispravak usporedbom transkripcije s referentnim tekstom. Ništa se ne mijenja dok ne prihvatiš svaki prijedlog."
},
"guidance": {
"showTips": "Prikaži savjete",
@@ -983,7 +1002,9 @@
"loadingAll": "Učitavanje svih riječi...",
"loadingSegment": "Učitavanje segmenta...",
"noData": "Nema dostupnih podataka o segmentu",
"unCorrect": "Poništi ispravak"
"unCorrect": "Poništi ispravak",
"timingClamped": "Tajming za \"{word}\" bio je izvan segmenta — postavljen na {time} s.",
"timingSanitized": "Ispravljen je tajming za {count} riječ(i) koje su bile izvan ovog segmenta."
},
"findReplace": {
"title": "Pronađi i zamijeni",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Prilagođeni tekst je primijenjen. Ručno sinkroniziraj svaki uređeni segment kako bi tempiranje riječi bilo točno za prilagođeni tekst."
},
"autoCorrect": {
"accept": "Prihvati prijedlog",
"acceptAll": "Prihvati sve",
"accepted": "Prihvaćeno",
"adlibRemovalHint": "Dopusti prijedloge za brisanje pratećih vokala kojih nema u referentnom tekstu",
"adlibRemovalLabel": "Predloži uklanjanje adlibova",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "gramatika",
"category_mishearing": "pogrešno prepoznato",
"category_other": "ostalo",
"category_repeated_chorus_fix": "refren",
"collapse": "Sažmi prijedloge",
"confidenceHint": "Koliko prijedlog mora biti pouzdan prije nego što se prikaže",
"confidenceLabel": "Filtar prijedloga",
"confidence_all": "Prikaži sve",
"confidence_high": "Visoka pouzdanost",
"description": "Automatski ispravak uspoređuje transkribirani tekst s referentnim izvorima i predlaže ispravke na razini riječi. Pregledavaš svaki prijedlog — ništa se ne primjenjuje dok ga ne prihvatiš.",
"dismiss": "Odbaci prijedloge",
"expand": "Proširi prijedloge",
"insertMarker": "umetni:",
"insertionsHint": "Dopusti prijedloge za umetanje riječi koje nedostaju u transkripciji",
"insertionsLabel": "Predloži riječi koje nedostaju",
"noReferences": "Za ovu pjesmu nema dostupnog referentnog teksta, pa se prijedlozi ne mogu generirati. Prvo dodaj tekst iz referentnog panela.",
"noSuggestions": "Nisu pronađeni problemi — nema predloženih promjena.",
"reject": "Odbij prijedlog",
"rejectAll": "Odbij sve",
"rejected": "Odbijeno",
"runButton": "Dohvati prijedloge",
"running": "Analiziram tekst… ovo obično traje 15–60 sekundi.",
"staleHint": "Ove su riječi uređene nakon generiranja prijedloga, pa ovaj prijedlog više ne vrijedi.",
"summary": "{total} prijedloga · {pending} na čekanju · {accepted} prihvaćeno",
"title": "Prijedlozi automatskog ispravka",
"undo": "Poništi ovaj prijedlog",
"cancel": "Odustani",
"close": "Zatvori",
"confidence_balanced": "Uravnoteženo",
"compareHint": "Sporije je i košta više, ali pokazuje oko kojih se prijedloga slaže više modela",
"compareLabel": "Usporedi više AI modela",
"conflictBadge": "varijanta",
"conflictTooltip": "Postoje različiti prijedlozi za ove riječi — prihvaćanjem jedne varijante odbacuješ ostale.",
"consensusBadge": "{consensus}/{total} modela",
"consensusTooltip": "Predložili: {models}",
"cachedBadge": "predmemorirano",
"cachedTooltip": "Obnovljeno iz prethodnog pokretanja s istim tekstom pjesme — nije bilo troškova za AI."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, ha kész",
"afterApproval": "A jóváhagyás után a karaoke videód renderelésre és kézbesítésre kerül. ~10 perc",
"trackProgressTenant": "Kövesd a folyamatot a Legutóbbi projektek listában.",
"submitAnother": "Másik dal beküldése"
"submitAnother": "Másik dal beküldése",
"pasteUrlButton": "Illessz be egy linket",
"urlSupportedSitesHint": "Működik a YouTube, Facebook, SoundCloud, TikTok, Vimeo és több száz más oldallal.",
"urlSupportedSitesLink": "Nézd meg az összes támogatott oldalt",
"useThisUrl": "Használd ezt az URL-t"
},
"jobStatus": {
"settingUp": "Beállítás",
@@ -772,7 +776,17 @@
"undoFailed": "Visszavonás sikertelen",
"redoFailed": "Újra sikertelen",
"restoreFailed": "Visszaállítás sikertelen — előfordulhat, hogy néhány szerkesztés nem lett alkalmazva",
"submitFailed": "Beküldés sikertelen"
"submitFailed": "Beküldés sikertelen",
"fadeIn": "Felerősítés",
"fadeInSelection": "Felerősítés a kijelölt szakaszon",
"fadeOut": "Elhalkítás",
"fadeOutSelection": "Elhalkítás a kijelölt szakaszon",
"fadeInDisabledHint": "A felerősítéshez jelölj ki egy olyan részt, amely pontosan a sáv legeléjén kezdődik",
"fadeOutDisabledHint": "Az elhalkításhoz jelölj ki egy olyan részt, amely pontosan a sáv legvégéig tart",
"trimEndDisabledHint": "A végének levágásához jelölj ki egy olyan részt, amely pontosan a sáv legvégéig tart",
"trimEndSelection": "Minden eltávolítása a kijelölés után",
"trimStartDisabledHint": "Az elejének levágásához jelölj ki egy olyan részt, amely pontosan a sáv legeléjén kezdődik",
"trimStartSelection": "Minden eltávolítása a kijelölés előtt"
},
"audioEditRestore": {
"title": "Mentett hangszerkesztési munkamenetek",
@@ -799,7 +813,7 @@
"acceptAll": "Összes elfogadása",
"revertAll": "Összes visszaállítása",
"undoAll": "Összes visszavonása",
"resetAllChanges": "Minden változtatás visszaállítása az eredeti AI által javított dalszövegre",
"resetAllChanges": "Minden módosítás visszaállítása az eredeti, javított dalszövegre",
"undo": "Visszavonás",
"redo": "Újra",
"findReplace": "Keresés/Csere",
@@ -809,7 +823,12 @@
"timingOffset": "Időzítés eltolása",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Tolja el az összes szó időzítését előre vagy hátra. Használd, ha a dalszöveg kissé korán vagy későn jelenik meg az előnézetben.",
"playback": "Lejátszás"
"playback": "Lejátszás",
"audioLoadError": "Nem sikerült betölteni a hanganyagot",
"audioStillLoading": "A hanganyag még töltődik...",
"loadingAudio": "Hanganyag betöltése...",
"autoCorrect": "Automatikus javítás",
"autoCorrectDesc": "Javítási javaslatok generálása a leírt és a referencia-dalszöveg összehasonlításával. Semmi sem módosul, amíg el nem fogadod az egyes javaslatokat."
},
"guidance": {
"showTips": "Tippek mutatása",
@@ -983,7 +1002,9 @@
"loadingAll": "Összes szó betöltése...",
"loadingSegment": "Szegmens betöltése...",
"noData": "Nincsenek elérhető szegmens adatok",
"unCorrect": "Javítás visszavonása"
"unCorrect": "Javítás visszavonása",
"timingClamped": "A(z) \"{word}\" időzítése a szegmensen kívül esett — {time}s-re igazítva.",
"timingSanitized": "{count} szó időzítése javítva, amely ezen a szegmensen kívül esett."
},
"findReplace": {
"title": "Keresés és csere",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Egyedi dalszöveg alkalmazva. Szinkronizáld manuálisan az összes szerkesztett szegmenst, hogy a szavak időzítése megfelelő legyen a testreszabott dalszöveghez."
},
"autoCorrect": {
"accept": "Javaslat elfogadása",
"acceptAll": "Összes elfogadása",
"accepted": "Elfogadva",
"adlibRemovalHint": "Engedélyezd az olyan javaslatokat, amelyek törlik a referenciákban nem szereplő háttérvokálokat",
"adlibRemovalLabel": "Adlibek eltávolításának javaslata",
"category_adlib_removal": "adlib",
"category_formatting": "formátum",
"category_grammar": "nyelvtan",
"category_mishearing": "félrehallás",
"category_other": "egyéb",
"category_repeated_chorus_fix": "refrén",
"collapse": "Javaslatok összecsukása",
"confidenceHint": "Mennyire legyen biztos a javaslat, mielőtt megjelenik",
"confidenceLabel": "Javaslatszűrő",
"confidence_all": "Összes megjelenítése",
"confidence_high": "Nagy bizonyosság",
"description": "Az automatikus javítás összehasonlítja a leírt dalszöveget a referenciaforrásokkal, és szavankénti javításokat javasol. Minden javaslatot átnézhetsz — semmi sem módosul, amíg el nem fogadod.",
"dismiss": "Javaslatok elvetése",
"expand": "Javaslatok kibontása",
"insertMarker": "beszúrás:",
"insertionsHint": "Engedélyezd az olyan javaslatokat, amelyek beszúrják az átírásból kimaradt szavakat",
"insertionsLabel": "Hiányzó szavak javaslata",
"noReferences": "Ehhez a dalhoz nincs elérhető referencia-dalszöveg, így nem tudunk javaslatokat generálni. Először adj hozzá dalszöveget a referenciapanelen.",
"noSuggestions": "Nem találtunk problémát — nincsenek javasolt módosítások.",
"reject": "Javaslat elutasítása",
"rejectAll": "Összes elutasítása",
"rejected": "Elutasítva",
"runButton": "Javaslatok kérése",
"running": "Dalszöveg elemzése… ez általában 15–60 másodpercet vesz igénybe.",
"staleHint": "Ezeket a szavakat módosítottad a javaslatok generálása óta, így ez a javaslat már nem érvényes.",
"summary": "{total} javaslat · {pending} függőben · {accepted} elfogadva",
"title": "Automatikus javítási javaslatok",
"undo": "Javaslat visszavonása",
"cancel": "Mégse",
"close": "Bezárás",
"confidence_balanced": "Kiegyensúlyozott",
"compareHint": "Lassabb és többe kerül, de megmutatja, mely javaslatokban ért egyet több modell.",
"compareLabel": "Több MI-modell összehasonlítása",
"conflictBadge": "változat",
"conflictTooltip": "Több különböző javaslat is van ezekre a szavakra — az egyik változat elfogadásával elutasítod a többit.",
"consensusBadge": "{consensus}/{total} modell",
"consensusTooltip": "Javasolta: {models}",
"cachedBadge": "gyorsítótárazott",
"cachedTooltip": "Egy korábbi, azonos dalszövegen végzett futtatásból visszaállítva — nem merült fel AI-költség."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email saat siap",
"afterApproval": "Setelah persetujuan, video karaoke Anda dirender dan dikirim. ~10 menit",
"trackProgressTenant": "Lacak kemajuan di daftar Proyek Terbaru.",
"submitAnother": "Kirim Track Lain"
"submitAnother": "Kirim Track Lain",
"pasteUrlButton": "Tempel tautan",
"urlSupportedSitesHint": "Berfungsi dengan YouTube, Facebook, SoundCloud, TikTok, Vimeo, dan ratusan situs lainnya.",
"urlSupportedSitesLink": "Lihat semua situs yang didukung",
"useThisUrl": "Gunakan URL Ini"
},
"jobStatus": {
"settingUp": "Menyiapkan",
@@ -772,7 +776,17 @@
"undoFailed": "Gagal mengurungkan",
"redoFailed": "Gagal mengulangi",
"restoreFailed": "Gagal memulihkan — beberapa editan mungkin tidak diterapkan",
"submitFailed": "Gagal mengirim"
"submitFailed": "Gagal mengirim",
"fadeIn": "Fade In",
"fadeInSelection": "Terapkan fade in pada bagian yang dipilih",
"fadeOut": "Fade Out",
"fadeOutSelection": "Terapkan fade out pada bagian yang dipilih",
"fadeInDisabledHint": "Untuk menerapkan fade in, pilih bagian yang dimulai tepat dari awal trek",
"fadeOutDisabledHint": "Untuk menerapkan fade out, pilih bagian yang berakhir tepat di akhir trek",
"trimEndDisabledHint": "Untuk memotong bagian akhir, pilih bagian yang berakhir tepat di akhir trek",
"trimEndSelection": "Hapus semua setelah bagian yang dipilih",
"trimStartDisabledHint": "Untuk memotong bagian awal, pilih bagian yang dimulai tepat dari awal trek",
"trimStartSelection": "Hapus semua sebelum bagian yang dipilih"
},
"audioEditRestore": {
"title": "Sesi Edit Audio Tersimpan",
@@ -799,7 +813,7 @@
"acceptAll": "Terima Semua",
"revertAll": "Kembalikan Semua",
"undoAll": "Batalkan Semua",
"resetAllChanges": "Atur ulang semua perubahan kembali ke lirik asli yang dikoreksi AI",
"resetAllChanges": "Kembalikan semua perubahan ke lirik asli yang telah dikoreksi",
"undo": "Urungkan",
"redo": "Ulangi",
"findReplace": "Cari/Ganti",
@@ -809,7 +823,12 @@
"timingOffset": "Offset Waktu",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Geser semua waktu kata maju atau mundur. Gunakan jika lirik muncul sedikit lebih awal atau terlambat di pratinjau.",
"playback": "Pemutaran"
"playback": "Pemutaran",
"audioLoadError": "Gagal memuat audio",
"audioStillLoading": "Audio masih dimuat...",
"loadingAudio": "Memuat audio...",
"autoCorrect": "Koreksi otomatis",
"autoCorrectDesc": "Hasilkan saran koreksi dengan membandingkan transkripsi dengan lirik referensi. Tidak ada perubahan yang diterapkan sampai Anda menyetujui setiap saran."
},
"guidance": {
"showTips": "Tampilkan tips",
@@ -983,7 +1002,9 @@
"loadingAll": "Memuat semua kata...",
"loadingSegment": "Memuat segmen...",
"noData": "Tidak ada data segmen yang tersedia",
"unCorrect": "Batalkan Koreksi"
"unCorrect": "Batalkan Koreksi",
"timingClamped": "Waktu \"{word}\" berada di luar segmen — disesuaikan ke {time}s.",
"timingSanitized": "Memperbaiki waktu {count} kata yang berada di luar segmen ini."
},
"findReplace": {
"title": "Cari dan Ganti",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Lirik kustom berhasil diterapkan. Sinkronkan setiap segmen yang diedit secara manual untuk memastikan ketepatan waktu lirik yang baru."
},
"autoCorrect": {
"accept": "Terima saran",
"acceptAll": "Terima semua",
"accepted": "Diterima",
"adlibRemovalHint": "Izinkan saran yang menghapus vokal latar yang tidak ada di referensi",
"adlibRemovalLabel": "Sarankan penghapusan adlib",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "tata bahasa",
"category_mishearing": "salah dengar",
"category_other": "lainnya",
"category_repeated_chorus_fix": "korus",
"collapse": "Perkecil saran",
"confidenceHint": "Tingkat keyakinan minimum sebelum saran ditampilkan",
"confidenceLabel": "Filter saran",
"confidence_all": "Tampilkan semua",
"confidence_high": "Keyakinan tinggi",
"description": "Koreksi otomatis membandingkan lirik yang ditranskripsi dengan sumber referensi dan menyarankan perbaikan per kata. Anda dapat meninjau setiap saran — tidak ada perubahan yang diterapkan sampai Anda menyetujuinya.",
"dismiss": "Abaikan saran",
"expand": "Perluas saran",
"insertMarker": "sisipkan:",
"insertionsHint": "Izinkan saran untuk menyisipkan kata yang terlewat dalam transkripsi",
"insertionsLabel": "Sarankan kata yang hilang",
"noReferences": "Tidak ada lirik referensi yang tersedia untuk lagu ini, sehingga saran tidak dapat dibuat. Tambahkan lirik dari panel referensi terlebih dahulu.",
"noSuggestions": "Tidak ada masalah yang ditemukan — tidak ada perubahan yang disarankan.",
"reject": "Tolak saran",
"rejectAll": "Tolak semua",
"rejected": "Ditolak",
"runButton": "Dapatkan saran",
"running": "Menganalisis lirik… biasanya memakan waktu 15–60 detik.",
"staleHint": "Kata-kata ini telah diedit sejak saran dibuat, sehingga saran ini tidak lagi berlaku.",
"summary": "{total} saran · {pending} tertunda · {accepted} diterima",
"title": "Saran koreksi otomatis",
"undo": "Batalkan saran ini",
"cancel": "Batal",
"close": "Tutup",
"confidence_balanced": "Seimbang",
"compareHint": "Lebih lambat dan lebih mahal, tapi menunjukkan saran mana yang disetujui oleh beberapa model",
"compareLabel": "Bandingkan beberapa model AI",
"conflictBadge": "varian",
"conflictTooltip": "Ada beberapa saran berbeda untuk kata-kata ini — menerima satu varian akan mengabaikan varian lainnya.",
"consensusBadge": "{consensus}/{total} model",
"consensusTooltip": "Diusulkan oleh: {models}",
"cachedBadge": "di-cache",
"cachedTooltip": "Dipulihkan dari proses sebelumnya untuk lirik yang sama — tidak ada biaya AI yang dikenakan."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email quando pronto",
"afterApproval": "Dopo l'approvazione, il tuo video karaoke viene renderizzato e consegnato. ~10 minuti",
"trackProgressTenant": "Segui i progressi nell'elenco Lavori recenti.",
"submitAnother": "Invia un'altra traccia"
"submitAnother": "Invia un'altra traccia",
"pasteUrlButton": "Incolla un link",
"urlSupportedSitesHint": "Funziona con YouTube, Facebook, SoundCloud, TikTok, Vimeo e centinaia di altri siti.",
"urlSupportedSitesLink": "Vedi tutti i siti supportati",
"useThisUrl": "Usa questo URL"
},
"jobStatus": {
"settingUp": "Configurazione",
@@ -772,7 +776,17 @@
"undoFailed": "Annullamento fallito",
"redoFailed": "Ripetizione fallita",
"restoreFailed": "Ripristino fallito — alcune modifiche potrebbero non essere state applicate",
"submitFailed": "Invio fallito"
"submitFailed": "Invio fallito",
"fadeIn": "Dissolvenza in entrata",
"fadeInSelection": "Dissolvenza in entrata sulla regione selezionata",
"fadeOut": "Dissolvenza in uscita",
"fadeOutSelection": "Dissolvenza in uscita sulla regione selezionata",
"fadeInDisabledHint": "Per la dissolvenza in entrata, seleziona una regione che parta esattamente dall'inizio della traccia",
"fadeOutDisabledHint": "Per la dissolvenza in uscita, seleziona una regione che termini esattamente alla fine della traccia",
"trimEndDisabledHint": "Per tagliare la fine, seleziona una regione che termini esattamente alla fine della traccia",
"trimEndSelection": "Rimuovi tutto dopo la selezione",
"trimStartDisabledHint": "Per tagliare l'inizio, seleziona una regione che parta esattamente dall'inizio della traccia",
"trimStartSelection": "Rimuovi tutto prima della selezione"
},
"audioEditRestore": {
"title": "Sessioni di modifica audio salvate",
@@ -799,7 +813,7 @@
"acceptAll": "Accetta tutto",
"revertAll": "Ripristina tutto",
"undoAll": "Annulla tutto",
"resetAllChanges": "Reimposta tutte le modifiche al testo originale corretto dall'IA",
"resetAllChanges": "Annulla tutte le modifiche e torna al testo corretto originale",
"undo": "Annulla",
"redo": "Ripeti",
"findReplace": "Trova/Sostituisci",
@@ -809,7 +823,12 @@
"timingOffset": "Offset temporale",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Sposta tutti i tempi delle parole in avanti o all'indietro. Usalo se il testo appare leggermente in anticipo o in ritardo nell'anteprima.",
"playback": "Riproduzione"
"playback": "Riproduzione",
"audioLoadError": "Impossibile caricare l'audio",
"audioStillLoading": "L'audio è ancora in caricamento...",
"loadingAudio": "Caricamento audio...",
"autoCorrect": "Correzione automatica",
"autoCorrectDesc": "Genera suggerimenti di correzione confrontando la trascrizione con il testo di riferimento. Non viene modificato nulla finché non accetti ogni suggerimento."
},
"guidance": {
"showTips": "Mostra suggerimenti",
@@ -983,7 +1002,9 @@
"loadingAll": "Caricamento di tutte le parole...",
"loadingSegment": "Caricamento segmento...",
"noData": "Nessun dato del segmento disponibile",
"unCorrect": "Annulla correzione"
"unCorrect": "Annulla correzione",
"timingClamped": "Il tempismo di \"{word}\" era fuori dal segmento — allineato a {time}s.",
"timingSanitized": "Corretti {count} tempismi delle parole che cadevano fuori da questo segmento."
},
"findReplace": {
"title": "Trova e sostituisci",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Testo personalizzato applicato. Sincronizza manualmente ogni segmento modificato per assicurarti che il tempismo delle parole sia corretto per il testo personalizzato."
},
"autoCorrect": {
"accept": "Accetta suggerimento",
"acceptAll": "Accetta tutti",
"accepted": "Accettato",
"adlibRemovalHint": "Consenti suggerimenti che eliminano le voci di sottofondo non presenti nei riferimenti",
"adlibRemovalLabel": "Suggerisci di rimuovere gli adlib",
"category_adlib_removal": "adlib",
"category_formatting": "formattazione",
"category_grammar": "grammatica",
"category_mishearing": "fraintendimento",
"category_other": "altro",
"category_repeated_chorus_fix": "ritornello",
"collapse": "Comprimi suggerimenti",
"confidenceHint": "Quanto deve essere attendibile un suggerimento prima di essere mostrato",
"confidenceLabel": "Filtro suggerimenti",
"confidence_all": "Mostra tutti",
"confidence_high": "Alta sicurezza",
"description": "La correzione automatica confronta il testo trascritto con le fonti di riferimento e suggerisce correzioni a livello di singola parola. Puoi rivedere ogni suggerimento — non verrà applicato nulla finché non lo accetti.",
"dismiss": "Ignora suggerimenti",
"expand": "Espandi suggerimenti",
"insertMarker": "inserisci:",
"insertionsHint": "Consenti suggerimenti che inseriscono le parole omesse nella trascrizione",
"insertionsLabel": "Suggerisci parole mancanti",
"noReferences": "Non ci sono testi di riferimento disponibili per questa canzone, quindi non è possibile generare suggerimenti. Aggiungi prima il testo dal pannello di riferimento.",
"noSuggestions": "Nessun problema trovato — non ci sono modifiche suggerite.",
"reject": "Rifiuta suggerimento",
"rejectAll": "Rifiuta tutti",
"rejected": "Rifiutato",
"runButton": "Ottieni suggerimenti",
"running": "Analisi del testo in corso… di solito richiede dai 15 ai 60 secondi.",
"staleHint": "Queste parole sono state modificate dopo la generazione dei suggerimenti, quindi questo suggerimento non è più valido.",
"summary": "{total} suggerimenti · {pending} in attesa · {accepted} accettati",
"title": "Suggerimenti di correzione automatica",
"undo": "Annulla questo suggerimento",
"cancel": "Annulla",
"close": "Chiudi",
"confidence_balanced": "Bilanciato",
"compareHint": "Più lento e costoso, ma mostra su quali suggerimenti concordano più modelli",
"compareLabel": "Confronta più modelli IA",
"conflictBadge": "variante",
"conflictTooltip": "Ci sono diversi suggerimenti per queste parole — accettando una variante rifiuterai le altre.",
"consensusBadge": "{consensus}/{total} modelli",
"consensusTooltip": "Proposto da: {models}",
"cachedBadge": "in cache",
"cachedTooltip": "Ripristinato da un'elaborazione precedente dello stesso testo — non ha comportato alcun costo per l'IA."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "準備完了時にメールでお知らせ",
"afterApproval": "承認後、カラオケ動画がレンダリングされ納品されます。約10分",
"trackProgressTenant": "最近のジョブリストで進捗を追跡します。",
"submitAnother": "別のトラックを送信"
"submitAnother": "別のトラックを送信",
"pasteUrlButton": "リンクを貼り付ける",
"urlSupportedSitesHint": "YouTube、Facebook、SoundCloud、TikTok、Vimeoなど、数百ものサイトに対応しています。",
"urlSupportedSitesLink": "対応サイト一覧を見る",
"useThisUrl": "このURLを使用する"
},
"jobStatus": {
"settingUp": "セットアップ中",
@@ -772,7 +776,17 @@
"undoFailed": "元に戻す操作に失敗しました",
"redoFailed": "やり直し操作に失敗しました",
"restoreFailed": "復元に失敗しました — 一部の編集が適用されていない可能性があります",
"submitFailed": "送信に失敗しました"
"submitFailed": "送信に失敗しました",
"fadeIn": "フェードイン",
"fadeInSelection": "選択した範囲をフェードイン",
"fadeOut": "フェードアウト",
"fadeOutSelection": "選択した範囲をフェードアウト",
"fadeInDisabledHint": "フェードインするには、トラックの先頭から始まる範囲を選択してください",
"fadeOutDisabledHint": "フェードアウトするには、トラックの末尾で終わる範囲を選択してください",
"trimEndDisabledHint": "末尾をトリミングするには、トラックの末尾で終わる範囲を選択してください",
"trimEndSelection": "選択範囲より後の部分をすべて削除します",
"trimStartDisabledHint": "先頭をトリミングするには、トラックの先頭から始まる範囲を選択してください",
"trimStartSelection": "選択範囲より前の部分をすべて削除します"
},
"audioEditRestore": {
"title": "保存されたオーディオ編集セッション",
@@ -799,7 +813,7 @@
"acceptAll": "すべて承認",
"revertAll": "すべて元に戻す",
"undoAll": "すべて取り消す",
"resetAllChanges": "すべての変更を元のAI修正済み歌詞にリセット",
"resetAllChanges": "すべての変更をリセットして、元の修正済み歌詞に戻す",
"undo": "元に戻す",
"redo": "やり直し",
"findReplace": "検索/置換",
@@ -809,7 +823,12 @@
"timingOffset": "タイミングオフセット",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "すべての単語のタイミングを前後にシフトします。プレビューで歌詞がわずかに早い、または遅い場合に使用します。",
"playback": "再生"
"playback": "再生",
"audioLoadError": "音声を読み込めませんでした",
"audioStillLoading": "音声はまだ読み込み中です...",
"loadingAudio": "音声を読み込み中...",
"autoCorrect": "自動補正",
"autoCorrectDesc": "文字起こしした歌詞と参照用の歌詞を比較して、修正の提案を生成します。各提案を承認するまで変更は適用されません。"
},
"guidance": {
"showTips": "ヒントを表示",
@@ -983,7 +1002,9 @@
"loadingAll": "すべての単語を読み込み中...",
"loadingSegment": "セグメントを読み込み中...",
"noData": "利用可能なセグメントデータがありません",
"unCorrect": "修正を取り消す"
"unCorrect": "修正を取り消す",
"timingClamped": "\"{word}\" のタイミングがセグメント外だったため、{time}秒に調整されました。",
"timingSanitized": "このセグメント外にあった {count} 個の単語のタイミングを修正しました。"
},
"findReplace": {
"title": "検索と置換",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "カスタム歌詞を適用しました。カスタマイズした歌詞のタイミングが合うように、編集した各セグメントを手動で同期してください。"
},
"autoCorrect": {
"accept": "提案を採用する",
"acceptAll": "すべて採用する",
"accepted": "採用済み",
"adlibRemovalHint": "リファレンスにないバックボーカルを削除する提案を表示します。",
"adlibRemovalLabel": "アドリブの削除を提案",
"category_adlib_removal": "アドリブ",
"category_formatting": "フォーマット",
"category_grammar": "文法",
"category_mishearing": "聞き間違い",
"category_other": "その他",
"category_repeated_chorus_fix": "コーラス",
"collapse": "提案を折りたたむ",
"confidenceHint": "提案を表示するために必要な信頼度の基準",
"confidenceLabel": "提案フィルター",
"confidence_all": "すべて表示",
"confidence_high": "高い確信度",
"description": "自動補正は、文字起こしした歌詞を参照用の歌詞と比較し、単語レベルで修正を提案します。すべての提案はご自身で確認でき、承認するまで適用されることはありません。",
"dismiss": "提案を非表示にする",
"expand": "提案を展開する",
"insertMarker": "挿入:",
"insertionsHint": "文字起こしで抜けている単語を追加する提案を表示します。",
"insertionsLabel": "不足している単語の追加を提案",
"noReferences": "この曲には参照用の歌詞がないため、提案を生成できません。まずは参照パネルから歌詞を追加してください。",
"noSuggestions": "問題は見つかりませんでした。修正の提案はありません。",
"reject": "提案を却下する",
"rejectAll": "すべて却下する",
"rejected": "却下済み",
"runButton": "提案を取得する",
"running": "歌詞を分析しています… 通常15〜60秒かかります。",
"staleHint": "提案の生成後に歌詞が編集されたため、この提案は無効になりました。",
"summary": "{total}件の提案 · 保留中 {pending}件 · 採用済み {accepted}件",
"title": "自動補正の提案",
"undo": "この提案を元に戻す",
"cancel": "キャンセル",
"close": "閉じる",
"confidence_balanced": "バランス",
"compareHint": "時間とコストはかかりますが、複数のモデルで一致した提案を確認できます。",
"compareLabel": "複数のAIモデルを比較する",
"conflictBadge": "別案",
"conflictTooltip": "これらの単語には複数の修正候補があります。1つの候補を承認すると、他の候補は破棄されます。",
"consensusBadge": "{consensus}/{total} モデル",
"consensusTooltip": "提案元: {models}",
"cachedBadge": "キャッシュ済み",
"cachedTooltip": "同じ歌詞の過去のデータから復元されました。AIのコストは発生していません。"
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "준비 시 이메일 알림",
"afterApproval": "승인 후 노래방 비디오가 렌더링되어 전달됩니다. 약 10분 소요",
"trackProgressTenant": "최근 작업 목록에서 진행 상황을 추적하세요.",
"submitAnother": "다른 트랙 제출"
"submitAnother": "다른 트랙 제출",
"pasteUrlButton": "링크 붙여넣기",
"urlSupportedSitesHint": "YouTube, Facebook, SoundCloud, TikTok, Vimeo 등 수백 개의 사이트에서 사용할 수 있습니다.",
"urlSupportedSitesLink": "지원되는 모든 사이트 보기",
"useThisUrl": "이 URL 사용하기"
},
"jobStatus": {
"settingUp": "설정 중",
@@ -772,7 +776,17 @@
"undoFailed": "실행 취소 실패",
"redoFailed": "다시 실행 실패",
"restoreFailed": "복원 실패 — 일부 편집 내용이 적용되지 않았을 수 있습니다",
"submitFailed": "제출 실패"
"submitFailed": "제출 실패",
"fadeIn": "페이드 인",
"fadeInSelection": "선택한 영역에 페이드 인 적용",
"fadeOut": "페이드 아웃",
"fadeOutSelection": "선택한 영역에 페이드 아웃 적용",
"fadeInDisabledHint": "페이드 인을 적용하려면 트랙의 맨 처음부터 시작하는 영역을 선택하세요.",
"fadeOutDisabledHint": "페이드 아웃을 적용하려면 트랙의 맨 끝까지 이어지는 영역을 선택하세요.",
"trimEndDisabledHint": "끝부분을 자르려면 트랙의 맨 끝까지 이어지는 영역을 선택하세요.",
"trimEndSelection": "선택 영역 이후의 모든 구간 제거",
"trimStartDisabledHint": "시작 부분을 자르려면 트랙의 맨 처음부터 시작하는 영역을 선택하세요.",
"trimStartSelection": "선택 영역 이전의 모든 구간 제거"
},
"audioEditRestore": {
"title": "저장된 오디오 편집 세션",
@@ -799,7 +813,7 @@
"acceptAll": "모두 수락",
"revertAll": "모두 되돌리기",
"undoAll": "모두 실행 취소",
"resetAllChanges": "모든 변경 사항을 원래 AI가 수정한 가사로 초기화",
"resetAllChanges": "모든 변경 사항을 취소하고 원래 수정된 가사로 되돌립니다",
"undo": "실행 취소",
"redo": "다시 실행",
"findReplace": "찾기/바꾸기",
@@ -809,7 +823,12 @@
"timingOffset": "타이밍 오프셋",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "모든 단어 타이밍을 앞이나 뒤로 이동합니다. 미리보기에서 가사가 약간 빠르거나 늦게 나타날 때 사용하세요.",
"playback": "재생"
"playback": "재생",
"audioLoadError": "오디오를 불러올 수 없습니다",
"audioStillLoading": "아직 오디오를 불러오는 중입니다...",
"loadingAudio": "오디오를 불러오는 중입니다...",
"autoCorrect": "자동 수정",
"autoCorrectDesc": "추출된 가사를 참조 가사와 비교하여 수정 제안을 생성합니다. 각 제안을 수락하기 전까지는 아무것도 변경되지 않습니다."
},
"guidance": {
"showTips": "팁 표시",
@@ -983,7 +1002,9 @@
"loadingAll": "모든 단어 불러오는 중...",
"loadingSegment": "세그먼트 불러오는 중...",
"noData": "세그먼트 데이터가 없습니다",
"unCorrect": "수정 취소"
"unCorrect": "수정 취소",
"timingClamped": "\"{word}\" 타이밍이 구간을 벗어나 {time}초로 조정되었습니다.",
"timingSanitized": "이 구간을 벗어난 단어 타이밍 {count}개를 수정했습니다."
},
"findReplace": {
"title": "찾기 및 바꾸기",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "맞춤형 가사가 적용되었습니다. 단어 타이밍이 잘 맞도록 편집된 각 구간을 수동으로 동기화해 주세요."
},
"autoCorrect": {
"accept": "제안 수락",
"acceptAll": "모두 수락",
"accepted": "수락됨",
"adlibRemovalHint": "참조 가사에 없는 백보컬을 삭제하는 제안 허용",
"adlibRemovalLabel": "애드리브 제거 제안",
"category_adlib_removal": "애드리브",
"category_formatting": "형식",
"category_grammar": "문법",
"category_mishearing": "오인식",
"category_other": "기타",
"category_repeated_chorus_fix": "코러스",
"collapse": "제안 접기",
"confidenceHint": "제안을 표시할 신뢰도 수준",
"confidenceLabel": "제안 필터",
"confidence_all": "모두 보기",
"confidence_high": "높은 확신도",
"description": "자동 수정은 추출된 가사를 참조 소스와 비교하여 단어 단위로 수정 사항을 제안합니다. 모든 제안은 직접 검토하실 수 있으며, 수락하기 전까지는 아무것도 적용되지 않습니다.",
"dismiss": "제안 무시",
"expand": "제안 펼치기",
"insertMarker": "삽입:",
"insertionsHint": "변환 과정에서 누락된 단어를 삽입하는 제안 허용",
"insertionsLabel": "누락된 단어 제안",
"noReferences": "이 노래에 대한 참조 가사가 없어 제안을 생성할 수 없습니다. 먼저 참조 패널에서 가사를 추가해 주세요.",
"noSuggestions": "발견된 문제가 없습니다 — 제안할 변경 사항이 없습니다.",
"reject": "제안 거부",
"rejectAll": "모두 거부",
"rejected": "거부됨",
"runButton": "제안 받기",
"running": "가사 분석 중… 보통 15~60초 정도 걸립니다.",
"staleHint": "제안이 생성된 후 해당 단어가 수정되어 이 제안은 더 이상 유효하지 않습니다.",
"summary": "{total}개 제안 · {pending}개 대기 중 · {accepted}개 수락됨",
"title": "자동 수정 제안",
"undo": "이 제안 실행 취소",
"cancel": "취소",
"close": "닫기",
"confidence_balanced": "균형",
"compareHint": "시간과 비용이 더 들지만, 여러 모델이 공통으로 제안하는 내용을 확인할 수 있어요.",
"compareLabel": "여러 AI 모델 비교하기",
"conflictBadge": "다른 버전",
"conflictTooltip": "이 단어들에 대해 여러 제안이 있습니다 — 하나를 수락하면 나머지는 적용되지 않습니다.",
"consensusBadge": "{consensus}/{total}개 모델",
"consensusTooltip": "제안한 모델: {models}",
"cachedBadge": "캐시됨",
"cachedTooltip": "동일한 가사로 진행한 이전 작업에서 복원되었습니다 — AI 비용이 발생하지 않았습니다."
}
},
"instrumentalReview": {
+72 -5
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mel apabila sedia",
"afterApproval": "Selepas kelulusan, video karaoke anda dirender dan dihantar. ~10 minit",
"trackProgressTenant": "Jejaki kemajuan dalam senarai Kerja Terkini.",
"submitAnother": "Hantar Trek Lain"
"submitAnother": "Hantar Trek Lain",
"pasteUrlButton": "Tampal pautan",
"urlSupportedSitesHint": "Berfungsi dengan YouTube, Facebook, SoundCloud, TikTok, Vimeo dan beratus-ratus laman web lain.",
"urlSupportedSitesLink": "Lihat semua laman web yang disokong",
"useThisUrl": "Gunakan URL Ini"
},
"jobStatus": {
"settingUp": "Menyediakan",
@@ -772,7 +776,17 @@
"undoFailed": "Gagal buat asal",
"redoFailed": "Gagal buat semula",
"restoreFailed": "Gagal memulihkan — beberapa suntingan mungkin tidak digunakan",
"submitFailed": "Gagal menghantar"
"submitFailed": "Gagal menghantar",
"fadeIn": "Pudar Masuk",
"fadeInSelection": "Pudar masuk pada bahagian yang dipilih",
"fadeOut": "Pudar Keluar",
"fadeOutSelection": "Pudar keluar pada bahagian yang dipilih",
"fadeInDisabledHint": "Untuk fade in, pilih bahagian yang bermula tepat pada permulaan trek",
"fadeOutDisabledHint": "Untuk fade out, pilih bahagian yang berakhir tepat pada penghujung trek",
"trimEndDisabledHint": "Untuk memotong bahagian akhir, pilih bahagian yang berakhir tepat pada penghujung trek",
"trimEndSelection": "Buang semua bahagian selepas pilihan",
"trimStartDisabledHint": "Untuk memotong bahagian awal, pilih bahagian yang bermula tepat pada permulaan trek",
"trimStartSelection": "Buang semua bahagian sebelum pilihan"
},
"audioEditRestore": {
"title": "Sesi Suntingan Audio Disimpan",
@@ -799,7 +813,7 @@
"acceptAll": "Terima Semua",
"revertAll": "Kembalikan Semua",
"undoAll": "Buat Asal Semua",
"resetAllChanges": "Tetapkan semula semua perubahan kembali kepada lirik asal yang dibetulkan AI",
"resetAllChanges": "Tetapkan semula semua perubahan kepada lirik asal yang telah dibetulkan",
"undo": "Buat Asal",
"redo": "Buat Semula",
"findReplace": "Cari/Ganti",
@@ -809,7 +823,12 @@
"timingOffset": "Ofset Pemasaan",
"timingOffsetValue": "{ms}ms",
"timingOffsetDesc": "Anjakkan semua pemasaan perkataan ke hadapan atau ke belakang. Gunakan jika lirik muncul sedikit awal atau lewat dalam pratonton.",
"playback": "Main Balik"
"playback": "Main Balik",
"audioLoadError": "Tidak dapat memuatkan audio",
"audioStillLoading": "Audio masih dimuatkan...",
"loadingAudio": "Memuatkan audio...",
"autoCorrect": "Pembetulan automatik",
"autoCorrectDesc": "Jana cadangan pembetulan dengan membandingkan transkripsi dengan lirik rujukan. Tiada perubahan akan dibuat sehingga anda menerima setiap cadangan."
},
"guidance": {
"showTips": "Tunjukkan petua",
@@ -983,7 +1002,9 @@
"loadingAll": "Memuatkan semua perkataan...",
"loadingSegment": "Memuatkan segmen...",
"noData": "Tiada data segmen tersedia",
"unCorrect": "Nyah-Betulkan"
"unCorrect": "Nyah-Betulkan",
"timingClamped": "Pemasaan \"{word}\" berada di luar segmen — diselaraskan kepada {time}s.",
"timingSanitized": "Membetulkan pemasaan {count} perkataan yang berada di luar segmen ini."
},
"findReplace": {
"title": "Cari dan Ganti",
@@ -1265,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Lirik tersuai digunakan. Segerakkan setiap segmen yang disunting secara manual untuk memastikan pemasaan perkataan adalah tepat untuk lirik tersuai."
},
"autoCorrect": {
"accept": "Terima cadangan",
"acceptAll": "Terima semua",
"accepted": "Diterima",
"adlibRemovalHint": "Benarkan cadangan yang memadam vokal latar yang tidak ada dalam rujukan",
"adlibRemovalLabel": "Cadangkan pemadaman adlib",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "tatabahasa",
"category_mishearing": "salah dengar",
"category_other": "lain-lain",
"category_repeated_chorus_fix": "korus",
"collapse": "Tutup cadangan",
"confidenceHint": "Tahap keyakinan sesuatu cadangan sebelum ia dipaparkan",
"confidenceLabel": "Penapis cadangan",
"confidence_all": "Tunjukkan semua",
"confidence_high": "Keyakinan tinggi",
"description": "Pembetulan automatik membandingkan lirik yang ditranskrip dengan sumber rujukan dan mencadangkan pembetulan pada peringkat perkataan. Anda boleh menyemak setiap cadangan — tiada perubahan akan dibuat sehingga anda menerimanya.",
"dismiss": "Abaikan cadangan",
"expand": "Kembangkan cadangan",
"insertMarker": "masukkan:",
"insertionsHint": "Benarkan cadangan yang memasukkan perkataan yang tertinggal dalam transkripsi",
"insertionsLabel": "Cadangkan perkataan yang tertinggal",
"noReferences": "Tiada lirik rujukan tersedia untuk lagu ini, jadi cadangan tidak dapat dijana. Tambahkan lirik dari panel rujukan terlebih dahulu.",
"noSuggestions": "Tiada isu ditemui — tiada perubahan yang dicadangkan.",
"reject": "Tolak cadangan",
"rejectAll": "Tolak semua",
"rejected": "Ditolak",
"runButton": "Dapatkan cadangan",
"running": "Menganalisis lirik… ini biasanya mengambil masa 15–60 saat.",
"staleHint": "Perkataan ini telah diedit sejak cadangan dijana, jadi cadangan ini tidak lagi terpakai.",
"summary": "{total} cadangan · {pending} belum selesai · {accepted} diterima",
"title": "Cadangan pembetulan automatik",
"undo": "Buat asal cadangan ini",
"cancel": "Batal",
"close": "Tutup",
"confidence_balanced": "Seimbang",
"compareHint": "Lebih perlahan dan kos lebih tinggi, tetapi menunjukkan cadangan yang dipersetujui oleh berbilang model",
"compareLabel": "Bandingkan berbilang model AI",
"conflictBadge": "varian",
"conflictTooltip": "Terdapat cadangan yang berbeza untuk perkataan ini — menerima satu varian akan menolak yang lain.",
"consensusBadge": "{consensus}/{total} model",
"consensusTooltip": "Dicadangkan oleh: {models}",
"cachedBadge": "dicache",
"cachedTooltip": "Dipulihkan daripada proses sebelumnya untuk lirik yang sama — tiada kos AI dikenakan."
}
},
"instrumentalReview": {
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more