Compare commits

...
19 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
120 changed files with 10061 additions and 227 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 \
+32 -11
View File
@@ -57,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
router = APIRouter(tags=["jobs"])
def _select_mixed_audio_files(files):
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
the instrumental — so transcription would run on the backing track instead of the
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
"""
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
def _apply_tenant_overrides(
dist: EffectiveDistributionSettings,
tenant_config,
@@ -67,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)
@@ -81,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
@@ -1382,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]
+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.
+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
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)
@@ -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."""
+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,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()
})
})
@@ -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} />)
@@ -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]
@@ -1299,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}
@@ -1509,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}
@@ -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'
@@ -13,6 +14,7 @@ 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
@@ -56,6 +58,7 @@ export default function EditModal({
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)
@@ -65,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
@@ -97,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,
@@ -112,6 +129,7 @@ export default function EditModal({
currentTime,
onPlaySegment,
updateSegment,
onTimingClamped: handleTimingClamped,
})
// Wire up spacebar handler - use setModalHandler directly for proper modal state
@@ -267,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(() => {
@@ -389,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,
}
}
@@ -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,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.
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "فشل التراجع",
"redoFailed": "فشلت الإعادة",
"restoreFailed": "فشلت الاستعادة — قد لا يتم تطبيق بعض التعديلات",
"submitFailed": "فشل الإرسال"
"submitFailed": "فشل الإرسال",
"fadeIn": "ظهور تدريجي",
"fadeInSelection": "ظهور تدريجي في المنطقة المحددة",
"fadeOut": "تلاشي تدريجي",
"fadeOutSelection": "تلاشي تدريجي في المنطقة المحددة",
"fadeInDisabledHint": "لإضافة تأثير الظهور التدريجي، حدد منطقة تبدأ من بداية المسار تماماً",
"fadeOutDisabledHint": "لإضافة تأثير التلاشي التدريجي، حدد منطقة تنتهي عند نهاية المسار تماماً",
"trimEndDisabledHint": "لقص النهاية، حدد منطقة تنتهي عند نهاية المسار تماماً",
"trimEndSelection": "إزالة كل شيء بعد التحديد",
"trimStartDisabledHint": "لقص البداية، حدد منطقة تبدأ من بداية المسار تماماً",
"trimStartSelection": "إزالة كل شيء قبل التحديد"
},
"audioEditRestore": {
"title": "جلسات تعديل الصوت المحفوظة",
@@ -803,7 +813,7 @@
"acceptAll": "قبول الكل",
"revertAll": "تراجع عن الكل",
"undoAll": "تراجع عن الكل",
"resetAllChanges": "إعادة تعيين جميع التغييرات إلى الكلمات الأصلية المصححة بالذكاء الاصطناعي",
"resetAllChanges": "إعادة تعيين جميع التغييرات والعودة إلى الكلمات المصححة الأصلية",
"undo": "تراجع",
"redo": "إعادة",
"findReplace": "بحث/استبدال",
@@ -816,7 +826,9 @@
"playback": "التشغيل",
"audioLoadError": "تعذر تحميل الصوت",
"audioStillLoading": "لا يزال الصوت قيد التحميل...",
"loadingAudio": "جاري تحميل الصوت..."
"loadingAudio": "جاري تحميل الصوت...",
"autoCorrect": "التصحيح التلقائي",
"autoCorrectDesc": "إنشاء اقتراحات تصحيح من خلال مقارنة التفريغ الصوتي مع الكلمات المرجعية. لن يتم تغيير أي شيء حتى توافق على كل اقتراح."
},
"guidance": {
"showTips": "إظهار النصائح",
@@ -990,7 +1002,9 @@
"loadingAll": "جاري تحميل جميع الكلمات...",
"loadingSegment": "جاري تحميل المقطع...",
"noData": "لا تتوفر بيانات للمقطع",
"unCorrect": "إلغاء التصحيح"
"unCorrect": "إلغاء التصحيح",
"timingClamped": "توقيت \"{word}\" كان خارج المقطع — تم ضبطه إلى {time} ثانية.",
"timingSanitized": "تم إصلاح توقيت {count} كلمة وقعت خارج هذا المقطع."
},
"findReplace": {
"title": "بحث واستبدال",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Reproducció",
"audioLoadError": "No s'ha pogut carregar l'àudio",
"audioStillLoading": "L'àudio encara s'està carregant...",
"loadingAudio": "Carregant l'àudio..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Přehrávání",
"audioLoadError": "Nepodařilo se načíst audio",
"audioStillLoading": "Audio se stále načítá...",
"loadingAudio": "Načítání audia..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Afspilning",
"audioLoadError": "Kunne ikke indlæse lyd",
"audioStillLoading": "Lyden indlæses stadig...",
"loadingAudio": "Indlæser lyd..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Wiedergabe",
"audioLoadError": "Audio konnte nicht geladen werden",
"audioStillLoading": "Audio wird noch geladen...",
"loadingAudio": "Audio wird 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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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": "Αποθηκευμένες Συνεδρίες Επεξεργασίας Ήχου",
@@ -803,7 +813,7 @@
"acceptAll": "Αποδοχή Όλων",
"revertAll": "Επαναφορά Όλων",
"undoAll": "Αναίρεση Όλων",
"resetAllChanges": "Επαναφορά όλων των αλλαγών πίσω στους αρχικούς στίχους που διορθώθηκαν από το AI",
"resetAllChanges": "Επαναφορά όλων των αλλαγών στους αρχικούς διορθωμένους στίχους",
"undo": "Αναίρεση",
"redo": "Επανάληψη",
"findReplace": "Εύρεση/Αντικατάσταση",
@@ -816,7 +826,9 @@
"playback": "Αναπαραγωγή",
"audioLoadError": "Δεν ήταν δυνατή η φόρτωση του ήχου",
"audioStillLoading": "Ο ήχος φορτώνει ακόμα...",
"loadingAudio": "Φόρτωση ήχου..."
"loadingAudio": "Φόρτωση ήχου...",
"autoCorrect": "Αυτόματη διόρθωση",
"autoCorrectDesc": "Δημιούργησε προτάσεις διόρθωσης συγκρίνοντας τη μεταγραφή με τους στίχους αναφοράς. Τίποτα δεν αλλάζει μέχρι να αποδεχτείς κάθε πρόταση."
},
"guidance": {
"showTips": "Εμφάνιση συμβουλών",
@@ -990,7 +1002,9 @@
"loadingAll": "Φόρτωση όλων των λέξεων...",
"loadingSegment": "Φόρτωση τμήματος...",
"noData": "Δεν υπάρχουν διαθέσιμα δεδομένα τμήματος",
"unCorrect": "Αναίρεση Διόρθωσης"
"unCorrect": "Αναίρεση Διόρθωσης",
"timingClamped": "Ο χρονισμός του \"{word}\" ήταν εκτός του τμήματος — προσαρμόστηκε στα {time}s.",
"timingSanitized": "Διορθώθηκαν {count} χρονισμοί λέξεων που έπεφταν εκτός αυτού του τμήματος."
},
"findReplace": {
"title": "Εύρεση και Αντικατάσταση",
@@ -1272,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": {
+63 -3
View File
@@ -753,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)",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Playback",
"loadingAudio": "Loading audio...",
"audioStillLoading": "Audio is still loading...",
"audioLoadError": "Couldn't load audio"
"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",
@@ -993,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Reproducción",
"audioLoadError": "No se pudo cargar el audio",
"audioStillLoading": "El audio aún se está cargando...",
"loadingAudio": "Cargando audio..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Toisto",
"audioLoadError": "Ääntä ei voitu ladata",
"audioStillLoading": "Ääni latautuu yhä...",
"loadingAudio": "Ladataan ääntä..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Lecture",
"audioLoadError": "Impossible de charger l'audio",
"audioStillLoading": "L'audio est toujours en cours de chargement...",
"loadingAudio": "Chargement de l'audio..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "ביטול נכשל",
"redoFailed": "ביצוע שוב נכשל",
"restoreFailed": "שחזור נכשל — ייתכן שחלק מהעריכות לא הוחלו",
"submitFailed": "שליחה נכשלה"
"submitFailed": "שליחה נכשלה",
"fadeIn": "פייד אין",
"fadeInSelection": "החלת פייד אין על האזור הנבחר",
"fadeOut": "פייד אאוט",
"fadeOutSelection": "החלת פייד אאוט על האזור הנבחר",
"fadeInDisabledHint": "כדי לבצע הגברה הדרגתית, בחרו אזור שמתחיל בדיוק בתחילת הרצועה",
"fadeOutDisabledHint": "כדי לבצע הנמכה הדרגתית, בחרו אזור שמסתיים בדיוק בסוף הרצועה",
"trimEndDisabledHint": "כדי לחתוך את הסוף, בחרו אזור שמסתיים בדיוק בסוף הרצועה",
"trimEndSelection": "הסירו הכל אחרי האזור הנבחר",
"trimStartDisabledHint": "כדי לחתוך את ההתחלה, בחרו אזור שמתחיל בדיוק בתחילת הרצועה",
"trimStartSelection": "הסירו הכל לפני האזור הנבחר"
},
"audioEditRestore": {
"title": "הפעלות עריכת אודיו שמורות",
@@ -803,7 +813,7 @@
"acceptAll": "אשר הכל",
"revertAll": "החזר הכל",
"undoAll": "בטל הכל",
"resetAllChanges": "אפס את כל השינויים חזרה למילים המקוריות שתוקנו על ידי AI",
"resetAllChanges": "איפוס כל השינויים בחזרה למילים המתוקנות המקוריות",
"undo": "בטל",
"redo": "בצע שוב",
"findReplace": "חפש/החלף",
@@ -816,7 +826,9 @@
"playback": "השמעה",
"audioLoadError": "לא הצלחנו לטעון את האודיו",
"audioStillLoading": "האודיו עדיין נטען...",
"loadingAudio": "טוען אודיו..."
"loadingAudio": "טוען אודיו...",
"autoCorrect": "תיקון אוטומטי",
"autoCorrectDesc": "הפקת הצעות לתיקון על ידי השוואת התמלול למילות הייחוס. שום שינוי לא יחול עד לאישור כל הצעה."
},
"guidance": {
"showTips": "הצג טיפים",
@@ -990,7 +1002,9 @@
"loadingAll": "טוען את כל המילים...",
"loadingSegment": "טוען מקטע...",
"noData": "אין נתוני מקטע זמינים",
"unCorrect": "בטל תיקון"
"unCorrect": "בטל תיקון",
"timingClamped": "התזמון של \"{word}\" היה מחוץ למקטע — הוצמד ל-{time} שניות.",
"timingSanitized": "תוקנו {count} תזמוני מילים שחרגו מהמקטע הזה."
},
"findReplace": {
"title": "חפש והחלף",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "अनडू विफल रहा",
"redoFailed": "रीडू विफल रहा",
"restoreFailed": "रिस्टोर विफल रहा — कुछ एडिट्स लागू नहीं हुए होंगे",
"submitFailed": "सबमिट विफल रहा"
"submitFailed": "सबमिट विफल रहा",
"fadeIn": "फ़ेड इन",
"fadeInSelection": "चुने गए हिस्से पर फ़ेड इन करो",
"fadeOut": "फ़ेड आउट",
"fadeOutSelection": "चुने गए हिस्से पर फ़ेड आउट करो",
"fadeInDisabledHint": "फेड इन करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक की बिल्कुल शुरुआत से शुरू होता हो",
"fadeOutDisabledHint": "फेड आउट करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक के बिल्कुल अंत में खत्म होता हो",
"trimEndDisabledHint": "अंत को ट्रिम करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक के बिल्कुल अंत में खत्म होता हो",
"trimEndSelection": "चुने हुए हिस्से के बाद का सब कुछ हटा दो",
"trimStartDisabledHint": "शुरुआत को ट्रिम करने के लिए, एक ऐसा हिस्सा चुनो जो ट्रैक की बिल्कुल शुरुआत से शुरू होता हो",
"trimStartSelection": "चुने हुए हिस्से से पहले का सब कुछ हटा दो"
},
"audioEditRestore": {
"title": "सेव किए गए ऑडियो एडिट सेशंस",
@@ -803,7 +813,7 @@
"acceptAll": "सभी एक्सेप्ट करो",
"revertAll": "सभी रिवर्ट करो",
"undoAll": "सभी अनडू करो",
"resetAllChanges": "सभी बदलावों को ओरिजिनल AI-करेक्टेड लिरिक्स पर रीसेट करो",
"resetAllChanges": "सभी बदलावों को वापस मूल सही किए गए लिरिक्स पर रीसेट करो",
"undo": "अनडू",
"redo": "रीडू",
"findReplace": "ढूंढो/बदलो",
@@ -816,7 +826,9 @@
"playback": "प्लेबैक",
"audioLoadError": "ऑडियो लोड नहीं हो सका",
"audioStillLoading": "ऑडियो अभी भी लोड हो रहा है...",
"loadingAudio": "ऑडियो लोड हो रहा है..."
"loadingAudio": "ऑडियो लोड हो रहा है...",
"autoCorrect": "ऑटो-करेक्ट",
"autoCorrectDesc": "ट्रांसक्रिप्शन की तुलना रेफरेंस लिरिक्स से करके सुधार के सुझाव जनरेट करो। जब तक तुम हर सुझाव को स्वीकार नहीं करते, तब तक कुछ नहीं बदलता।"
},
"guidance": {
"showTips": "टिप्स दिखाओ",
@@ -990,7 +1002,9 @@
"loadingAll": "सभी शब्द लोड हो रहे हैं...",
"loadingSegment": "सेगमेंट लोड हो रहा है...",
"noData": "कोई सेगमेंट डेटा उपलब्ध नहीं है",
"unCorrect": "अन-करेक्ट करो"
"unCorrect": "अन-करेक्ट करो",
"timingClamped": "\"{word}\" की टाइमिंग सेगमेंट के बाहर थी — इसे {time}s पर सेट कर दिया गया है।",
"timingSanitized": "इस सेगमेंट के बाहर आने वाली {count} शब्द की टाइमिंग को ठीक किया गया।"
},
"findReplace": {
"title": "ढूंढो और बदलो",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Reprodukcija",
"audioLoadError": "Nije moguće učitati audio",
"audioStillLoading": "Audio se još uvijek učitava...",
"loadingAudio": "Učitavanje audija..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"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..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Pemutaran",
"audioLoadError": "Gagal memuat audio",
"audioStillLoading": "Audio masih dimuat...",
"loadingAudio": "Memuat audio..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Riproduzione",
"audioLoadError": "Impossibile caricare l'audio",
"audioStillLoading": "L'audio è ancora in caricamento...",
"loadingAudio": "Caricamento audio..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "元に戻す操作に失敗しました",
"redoFailed": "やり直し操作に失敗しました",
"restoreFailed": "復元に失敗しました — 一部の編集が適用されていない可能性があります",
"submitFailed": "送信に失敗しました"
"submitFailed": "送信に失敗しました",
"fadeIn": "フェードイン",
"fadeInSelection": "選択した範囲をフェードイン",
"fadeOut": "フェードアウト",
"fadeOutSelection": "選択した範囲をフェードアウト",
"fadeInDisabledHint": "フェードインするには、トラックの先頭から始まる範囲を選択してください",
"fadeOutDisabledHint": "フェードアウトするには、トラックの末尾で終わる範囲を選択してください",
"trimEndDisabledHint": "末尾をトリミングするには、トラックの末尾で終わる範囲を選択してください",
"trimEndSelection": "選択範囲より後の部分をすべて削除します",
"trimStartDisabledHint": "先頭をトリミングするには、トラックの先頭から始まる範囲を選択してください",
"trimStartSelection": "選択範囲より前の部分をすべて削除します"
},
"audioEditRestore": {
"title": "保存されたオーディオ編集セッション",
@@ -803,7 +813,7 @@
"acceptAll": "すべて承認",
"revertAll": "すべて元に戻す",
"undoAll": "すべて取り消す",
"resetAllChanges": "すべての変更を元のAI修正済み歌詞にリセット",
"resetAllChanges": "すべての変更をリセットして、元の修正済み歌詞に戻す",
"undo": "元に戻す",
"redo": "やり直し",
"findReplace": "検索/置換",
@@ -816,7 +826,9 @@
"playback": "再生",
"audioLoadError": "音声を読み込めませんでした",
"audioStillLoading": "音声はまだ読み込み中です...",
"loadingAudio": "音声を読み込み中..."
"loadingAudio": "音声を読み込み中...",
"autoCorrect": "自動補正",
"autoCorrectDesc": "文字起こしした歌詞と参照用の歌詞を比較して、修正の提案を生成します。各提案を承認するまで変更は適用されません。"
},
"guidance": {
"showTips": "ヒントを表示",
@@ -990,7 +1002,9 @@
"loadingAll": "すべての単語を読み込み中...",
"loadingSegment": "セグメントを読み込み中...",
"noData": "利用可能なセグメントデータがありません",
"unCorrect": "修正を取り消す"
"unCorrect": "修正を取り消す",
"timingClamped": "\"{word}\" のタイミングがセグメント外だったため、{time}秒に調整されました。",
"timingSanitized": "このセグメント外にあった {count} 個の単語のタイミングを修正しました。"
},
"findReplace": {
"title": "検索と置換",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "실행 취소 실패",
"redoFailed": "다시 실행 실패",
"restoreFailed": "복원 실패 — 일부 편집 내용이 적용되지 않았을 수 있습니다",
"submitFailed": "제출 실패"
"submitFailed": "제출 실패",
"fadeIn": "페이드 인",
"fadeInSelection": "선택한 영역에 페이드 인 적용",
"fadeOut": "페이드 아웃",
"fadeOutSelection": "선택한 영역에 페이드 아웃 적용",
"fadeInDisabledHint": "페이드 인을 적용하려면 트랙의 맨 처음부터 시작하는 영역을 선택하세요.",
"fadeOutDisabledHint": "페이드 아웃을 적용하려면 트랙의 맨 끝까지 이어지는 영역을 선택하세요.",
"trimEndDisabledHint": "끝부분을 자르려면 트랙의 맨 끝까지 이어지는 영역을 선택하세요.",
"trimEndSelection": "선택 영역 이후의 모든 구간 제거",
"trimStartDisabledHint": "시작 부분을 자르려면 트랙의 맨 처음부터 시작하는 영역을 선택하세요.",
"trimStartSelection": "선택 영역 이전의 모든 구간 제거"
},
"audioEditRestore": {
"title": "저장된 오디오 편집 세션",
@@ -803,7 +813,7 @@
"acceptAll": "모두 수락",
"revertAll": "모두 되돌리기",
"undoAll": "모두 실행 취소",
"resetAllChanges": "모든 변경 사항을 원래 AI가 수정한 가사로 초기화",
"resetAllChanges": "모든 변경 사항을 취소하고 원래 수정된 가사로 되돌립니다",
"undo": "실행 취소",
"redo": "다시 실행",
"findReplace": "찾기/바꾸기",
@@ -816,7 +826,9 @@
"playback": "재생",
"audioLoadError": "오디오를 불러올 수 없습니다",
"audioStillLoading": "아직 오디오를 불러오는 중입니다...",
"loadingAudio": "오디오를 불러오는 중입니다..."
"loadingAudio": "오디오를 불러오는 중입니다...",
"autoCorrect": "자동 수정",
"autoCorrectDesc": "추출된 가사를 참조 가사와 비교하여 수정 제안을 생성합니다. 각 제안을 수락하기 전까지는 아무것도 변경되지 않습니다."
},
"guidance": {
"showTips": "팁 표시",
@@ -990,7 +1002,9 @@
"loadingAll": "모든 단어 불러오는 중...",
"loadingSegment": "세그먼트 불러오는 중...",
"noData": "세그먼트 데이터가 없습니다",
"unCorrect": "수정 취소"
"unCorrect": "수정 취소",
"timingClamped": "\"{word}\" 타이밍이 구간을 벗어나 {time}초로 조정되었습니다.",
"timingSanitized": "이 구간을 벗어난 단어 타이밍 {count}개를 수정했습니다."
},
"findReplace": {
"title": "찾기 및 바꾸기",
@@ -1272,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": {
+64 -4
View File
@@ -776,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",
@@ -803,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",
@@ -816,7 +826,9 @@
"playback": "Main Balik",
"audioLoadError": "Tidak dapat memuatkan audio",
"audioStillLoading": "Audio masih dimuatkan...",
"loadingAudio": "Memuatkan audio..."
"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",
@@ -990,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",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Angre mislyktes",
"redoFailed": "Gjør om mislyktes",
"restoreFailed": "Gjenoppretting mislyktes — noen redigeringer kan ha blitt utelatt",
"submitFailed": "Innsending mislyktes"
"submitFailed": "Innsending mislyktes",
"fadeIn": "Ton inn",
"fadeInSelection": "Ton inn over det valgte området",
"fadeOut": "Ton ut",
"fadeOutSelection": "Ton ut over det valgte området",
"fadeInDisabledHint": "For å tone inn, velg et område som starter helt i begynnelsen av sporet",
"fadeOutDisabledHint": "For å tone ut, velg et område som går helt til slutten av sporet",
"trimEndDisabledHint": "For å trimme slutten, velg et område som går helt til slutten av sporet",
"trimEndSelection": "Fjern alt etter markeringen",
"trimStartDisabledHint": "For å trimme starten, velg et område som starter helt i begynnelsen av sporet",
"trimStartSelection": "Fjern alt før markeringen"
},
"audioEditRestore": {
"title": "Lagrede lydredigeringsøkter",
@@ -803,7 +813,7 @@
"acceptAll": "Godta alle",
"revertAll": "Tilbakestill alle",
"undoAll": "Angre alle",
"resetAllChanges": "Tilbakestill alle endringer til den originale AI-korrigerte teksten",
"resetAllChanges": "Tilbakestill alle endringer til den opprinnelige korrigerte teksten",
"undo": "Angre",
"redo": "Gjør om",
"findReplace": "Finn/Erstatt",
@@ -816,7 +826,9 @@
"playback": "Avspilling",
"audioLoadError": "Kunne ikke laste inn lyd",
"audioStillLoading": "Lyden laster fortsatt inn...",
"loadingAudio": "Laster inn lyd..."
"loadingAudio": "Laster inn lyd...",
"autoCorrect": "Autokorrektur",
"autoCorrectDesc": "Generer forslag til rettelser ved å sammenligne transkripsjonen med referanseteksten. Ingenting endres før du godtar hvert forslag."
},
"guidance": {
"showTips": "Vis tips",
@@ -990,7 +1002,9 @@
"loadingAll": "Laster inn alle ord...",
"loadingSegment": "Laster inn segment...",
"noData": "Ingen segmentdata tilgjengelig",
"unCorrect": "Fjern korrigering"
"unCorrect": "Fjern korrigering",
"timingClamped": "Timingen for \"{word}\" var utenfor segmentet — justert til {time}s.",
"timingSanitized": "Rettet {count} ord-timing(er) som falt utenfor dette segmentet."
},
"findReplace": {
"title": "Finn og erstatt",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Egendefinert tekst er lagt til. Synkroniser hvert redigerte segment manuelt for å sikre at timingen av ordene stemmer for den tilpassede teksten."
},
"autoCorrect": {
"accept": "Godta forslag",
"acceptAll": "Godta alle",
"accepted": "Godtatt",
"adlibRemovalHint": "Tillat forslag som fjerner bakgrunnsvokal som ikke finnes i referanseteksten",
"adlibRemovalLabel": "Foreslå å fjerne adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "formatering",
"category_grammar": "grammatikk",
"category_mishearing": "feilhørt",
"category_other": "annet",
"category_repeated_chorus_fix": "refreng",
"collapse": "Skjul forslag",
"confidenceHint": "Hvor sikkert et forslag må være før det vises",
"confidenceLabel": "Forslagsfilter",
"confidence_all": "Vis alle",
"confidence_high": "Høy sikkerhet",
"description": "Autokorrektur sammenligner den transkriberte teksten med referansekildene og foreslår rettelser på ordnivå. Du går gjennom hvert forslag — ingenting tas i bruk før du godtar det.",
"dismiss": "Lukk forslag",
"expand": "Utvid forslag",
"insertMarker": "sett inn:",
"insertionsHint": "Tillat forslag som setter inn ord som mangler i transkripsjonen",
"insertionsLabel": "Foreslå manglende ord",
"noReferences": "Ingen referansetekst er tilgjengelig for denne sangen, så det kan ikke genereres forslag. Legg til tekst fra referansepanelet først.",
"noSuggestions": "Ingen problemer funnet — det er ingen foreslåtte endringer.",
"reject": "Avvis forslag",
"rejectAll": "Avvis alle",
"rejected": "Avvist",
"runButton": "Hent forslag",
"running": "Analyserer tekst… dette tar vanligvis 15–60 sekunder.",
"staleHint": "Disse ordene ble redigert etter at forslagene ble generert, så dette forslaget gjelder ikke lenger.",
"summary": "{total} forslag · {pending} ventende · {accepted} godtatt",
"title": "Forslag til autokorrektur",
"undo": "Angre dette forslaget",
"cancel": "Avbryt",
"close": "Lukk",
"confidence_balanced": "Balansert",
"compareHint": "Tar lengre tid og koster mer, men viser hvilke forslag flere modeller er enige om",
"compareLabel": "Sammenlign flere AI-modeller",
"conflictBadge": "variant",
"conflictTooltip": "Det finnes forskjellige forslag for disse ordene — hvis du godtar én variant, avvises de andre.",
"consensusBadge": "{consensus}/{total} modeller",
"consensusTooltip": "Foreslått av: {models}",
"cachedBadge": "bufret",
"cachedTooltip": "Hentet fra en tidligere kjøring på samme sangtekst — det påløp ingen AI-kostnader."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Ongedaan maken mislukt",
"redoFailed": "Opnieuw uitvoeren mislukt",
"restoreFailed": "Herstellen mislukt — sommige bewerkingen zijn mogelijk niet toegepast",
"submitFailed": "Indienen mislukt"
"submitFailed": "Indienen mislukt",
"fadeIn": "Fade-in",
"fadeInSelection": "Fade-in over het geselecteerde gedeelte",
"fadeOut": "Fade-out",
"fadeOutSelection": "Fade-out over het geselecteerde gedeelte",
"fadeInDisabledHint": "Om in te faden, selecteer je een gedeelte dat helemaal aan het begin van de track begint",
"fadeOutDisabledHint": "Om uit te faden, selecteer je een gedeelte dat helemaal aan het einde van de track eindigt",
"trimEndDisabledHint": "Om het einde bij te knippen, selecteer je een gedeelte dat helemaal aan het einde van de track eindigt",
"trimEndSelection": "Verwijder alles na de selectie",
"trimStartDisabledHint": "Om het begin bij te knippen, selecteer je een gedeelte dat helemaal aan het begin van de track begint",
"trimStartSelection": "Verwijder alles voor de selectie"
},
"audioEditRestore": {
"title": "Opgeslagen Audio Bewerkingssessies",
@@ -803,7 +813,7 @@
"acceptAll": "Accepteer alles",
"revertAll": "Draai alles terug",
"undoAll": "Maak alles ongedaan",
"resetAllChanges": "Reset alle wijzigingen terug naar de originele AI-gecorrigeerde songteksten",
"resetAllChanges": "Zet alle wijzigingen terug naar de oorspronkelijke gecorrigeerde songtekst",
"undo": "Ongedaan maken",
"redo": "Opnieuw uitvoeren",
"findReplace": "Zoeken/Vervangen",
@@ -816,7 +826,9 @@
"playback": "Afspelen",
"audioLoadError": "Kon audio niet laden",
"audioStillLoading": "Audio is nog aan het laden...",
"loadingAudio": "Audio laden..."
"loadingAudio": "Audio laden...",
"autoCorrect": "Autocorrectie",
"autoCorrectDesc": "Genereer correctiesuggesties door de transcriptie te vergelijken met de referentiesongtekst. Er wordt niets gewijzigd totdat je elke suggestie accepteert."
},
"guidance": {
"showTips": "Toon tips",
@@ -990,7 +1002,9 @@
"loadingAll": "Alle woorden laden...",
"loadingSegment": "Segment laden...",
"noData": "Geen segmentgegevens beschikbaar",
"unCorrect": "Correctie ongedaan maken"
"unCorrect": "Correctie ongedaan maken",
"timingClamped": "\"{word}\" timing viel buiten het segment — aangepast naar {time}s.",
"timingSanitized": "{count} woordtiming(s) gecorrigeerd die buiten dit segment viel(en)."
},
"findReplace": {
"title": "Zoeken en vervangen",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Aangepaste songtekst toegepast. Synchroniseer elk bewerkt segment handmatig zodat de timing van de woorden perfect aansluit op de nieuwe songtekst."
},
"autoCorrect": {
"accept": "Accepteer suggestie",
"acceptAll": "Accepteer alles",
"accepted": "Geaccepteerd",
"adlibRemovalHint": "Sta suggesties toe die achtergrondzang verwijderen die niet in de referenties voorkomt",
"adlibRemovalLabel": "Stel voor om adlibs te verwijderen",
"category_adlib_removal": "adlib",
"category_formatting": "opmaak",
"category_grammar": "grammatica",
"category_mishearing": "verkeerd verstaan",
"category_other": "overig",
"category_repeated_chorus_fix": "refrein",
"collapse": "Suggesties inklappen",
"confidenceHint": "Hoe zeker een suggestie moet zijn voordat deze wordt getoond",
"confidenceLabel": "Suggestiefilter",
"confidence_all": "Toon alles",
"confidence_high": "Hoge zekerheid",
"description": "Autocorrectie vergelijkt de getranscribeerde songtekst met de referentiebronnen en stelt correcties op woordniveau voor. Je beoordeelt elke suggestie — er wordt niets toegepast totdat je deze accepteert.",
"dismiss": "Suggesties negeren",
"expand": "Suggesties uitklappen",
"insertMarker": "invoegen:",
"insertionsHint": "Sta suggesties toe die woorden invoegen die in de transcriptie ontbreken",
"insertionsLabel": "Stel ontbrekende woorden voor",
"noReferences": "Er is geen referentiesongtekst beschikbaar voor dit nummer, dus er kunnen geen suggesties worden gegenereerd. Voeg eerst een songtekst toe via het referentiepaneel.",
"noSuggestions": "Geen problemen gevonden — er zijn geen voorgestelde wijzigingen.",
"reject": "Wijs suggestie af",
"rejectAll": "Wijs alles af",
"rejected": "Afgewezen",
"runButton": "Suggesties ophalen",
"running": "Songtekst analyseren… dit duurt meestal 15–60 seconden.",
"staleHint": "Deze woorden zijn bewerkt nadat de suggesties zijn gegenereerd, dus deze suggestie is niet meer van toepassing.",
"summary": "{total} suggesties · {pending} in afwachting · {accepted} geaccepteerd",
"title": "Suggesties voor autocorrectie",
"undo": "Maak deze suggestie ongedaan",
"cancel": "Annuleren",
"close": "Sluiten",
"confidence_balanced": "Gebalanceerd",
"compareHint": "Langzamer en kost meer, maar laat zien over welke suggesties meerdere modellen het eens zijn",
"compareLabel": "Vergelijk meerdere AI-modellen",
"conflictBadge": "variant",
"conflictTooltip": "Er zijn verschillende suggesties voor deze woorden — als je één variant accepteert, worden de andere afgewezen.",
"consensusBadge": "{consensus}/{total} modellen",
"consensusTooltip": "Voorgesteld door: {models}",
"cachedBadge": "gecached",
"cachedTooltip": "Hersteld uit een eerdere verwerking van dezelfde songtekst — er zijn geen AI-kosten gemaakt."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Cofanie nie powiodło się",
"redoFailed": "Ponawianie nie powiodło się",
"restoreFailed": "Przywracanie nie powiodło się — niektóre edycje mogły nie zostać zastosowane",
"submitFailed": "Przesyłanie nie powiodło się"
"submitFailed": "Przesyłanie nie powiodło się",
"fadeIn": "Płynne pogłaśnianie",
"fadeInSelection": "Płynnie pogłośnij zaznaczony fragment",
"fadeOut": "Płynne wyciszanie",
"fadeOutSelection": "Płynnie wycisz zaznaczony fragment",
"fadeInDisabledHint": "Aby płynnie zgłośnić, zaznacz fragment, który zaczyna się na samym początku utworu",
"fadeOutDisabledHint": "Aby płynnie wyciszyć, zaznacz fragment, który kończy się na samym końcu utworu",
"trimEndDisabledHint": "Aby przyciąć koniec, zaznacz fragment, który kończy się na samym końcu utworu",
"trimEndSelection": "Usuń wszystko po zaznaczeniu",
"trimStartDisabledHint": "Aby przyciąć początek, zaznacz fragment, który zaczyna się na samym początku utworu",
"trimStartSelection": "Usuń wszystko przed zaznaczeniem"
},
"audioEditRestore": {
"title": "Zapisane sesje edycji dźwięku",
@@ -803,7 +813,7 @@
"acceptAll": "Akceptuj wszystko",
"revertAll": "Cofnij wszystko",
"undoAll": "Cofnij wszystko",
"resetAllChanges": "Zresetuj wszystkie zmiany z powrotem do oryginalnego tekstu poprawionego przez AI",
"resetAllChanges": "Cofnij wszystkie zmiany i przywróć oryginalny, poprawiony tekst",
"undo": "Cofnij",
"redo": "Ponów",
"findReplace": "Znajdź/Zamień",
@@ -816,7 +826,9 @@
"playback": "Odtwarzanie",
"audioLoadError": "Nie udało się załadować audio",
"audioStillLoading": "Audio wciąż się ładuje...",
"loadingAudio": "Ładowanie audio..."
"loadingAudio": "Ładowanie audio...",
"autoCorrect": "Autokorekta",
"autoCorrectDesc": "Wygeneruj sugestie poprawek, porównując transkrypcję z tekstem referencyjnym. Żadna zmiana nie zostanie wprowadzona, dopóki jej nie zaakceptujesz."
},
"guidance": {
"showTips": "Pokaż wskazówki",
@@ -990,7 +1002,9 @@
"loadingAll": "Wczytywanie wszystkich słów...",
"loadingSegment": "Wczytywanie segmentu...",
"noData": "Brak danych segmentu",
"unCorrect": "Cofnij poprawkę"
"unCorrect": "Cofnij poprawkę",
"timingClamped": "Czas słowa \"{word}\" wykraczał poza segment — wyrównano do {time}s.",
"timingSanitized": "Poprawiono czas dla {count} słów, które wykraczały poza ten segment."
},
"findReplace": {
"title": "Znajdź i zamień",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Zastosowano własny tekst. Zsynchronizuj ręcznie każdy edytowany segment, aby upewnić się, że czas wyświetlania słów pasuje do nowego tekstu."
},
"autoCorrect": {
"accept": "Zaakceptuj sugestię",
"acceptAll": "Zaakceptuj wszystkie",
"accepted": "Zaakceptowane",
"adlibRemovalHint": "Zezwalaj na sugestie usuwające chórki, których nie ma w tekście referencyjnym",
"adlibRemovalLabel": "Sugeruj usunięcie wstawek",
"category_adlib_removal": "wstawka",
"category_formatting": "format",
"category_grammar": "gramatyka",
"category_mishearing": "przesłyszenie",
"category_other": "inne",
"category_repeated_chorus_fix": "refren",
"collapse": "Zwiń sugestie",
"confidenceHint": "Wymagany poziom pewności, aby wyświetlić sugestię",
"confidenceLabel": "Filtr sugestii",
"confidence_all": "Pokaż wszystkie",
"confidence_high": "Wysoka pewność",
"description": "Autokorekta porównuje tekst z transkrypcji ze źródłami referencyjnymi i sugeruje poprawki poszczególnych słów. Samodzielnie przeglądasz każdą sugestię — żadna zmiana nie zostanie wprowadzona, dopóki jej nie zaakceptujesz.",
"dismiss": "Odrzuć sugestie",
"expand": "Rozwiń sugestie",
"insertMarker": "wstaw:",
"insertionsHint": "Zezwalaj na sugestie wstawiające słowa, które pominięto w transkrypcji",
"insertionsLabel": "Sugeruj brakujące słowa",
"noReferences": "Dla tego utworu brakuje tekstów referencyjnych, dlatego nie można wygenerować sugestii. Najpierw dodaj tekst w panelu referencyjnym.",
"noSuggestions": "Nie znaleziono problemów — brak sugerowanych zmian.",
"reject": "Odrzuć sugestię",
"rejectAll": "Odrzuć wszystkie",
"rejected": "Odrzucone",
"runButton": "Wygeneruj sugestie",
"running": "Analizowanie tekstu… zazwyczaj zajmuje to 15–60 sekund.",
"staleHint": "Te słowa zostały edytowane od czasu wygenerowania sugestii, więc ta sugestia nie ma już zastosowania.",
"summary": "{total} sugestii · {pending} oczekujących · {accepted} zaakceptowanych",
"title": "Sugestie autokorekty",
"undo": "Cofnij tę sugestię",
"cancel": "Anuluj",
"close": "Zamknij",
"confidence_balanced": "Zrównoważona",
"compareHint": "Działa wolniej i kosztuje więcej, ale pokazuje, co do których sugestii zgadza się kilka modeli",
"compareLabel": "Porównaj kilka modeli AI",
"conflictBadge": "wariant",
"conflictTooltip": "Dla tych słów dostępne są różne sugestie — zaakceptowanie jednego wariantu odrzuca pozostałe.",
"consensusBadge": "{consensus}/{total} modeli",
"consensusTooltip": "Zaproponowane przez: {models}",
"cachedBadge": "zbuforowane",
"cachedTooltip": "Przywrócono z poprzedniego przetworzenia tego samego tekstu — nie poniesiono kosztów AI."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Falha ao desfazer",
"redoFailed": "Falha ao refazer",
"restoreFailed": "Falha ao restaurar — algumas edições podem não ter sido aplicadas",
"submitFailed": "Falha ao enviar"
"submitFailed": "Falha ao enviar",
"fadeIn": "Fade In",
"fadeInSelection": "Aplicar fade in na região selecionada",
"fadeOut": "Fade Out",
"fadeOutSelection": "Aplicar fade out na região selecionada",
"fadeInDisabledHint": "Para aplicar fade in, selecione uma região que comece bem no início da faixa",
"fadeOutDisabledHint": "Para aplicar fade out, selecione uma região que termine bem no final da faixa",
"trimEndDisabledHint": "Para cortar o final, selecione uma região que termine bem no final da faixa",
"trimEndSelection": "Remover tudo após a seleção",
"trimStartDisabledHint": "Para cortar o início, selecione uma região que comece bem no início da faixa",
"trimStartSelection": "Remover tudo antes da seleção"
},
"audioEditRestore": {
"title": "Sessões de Edição de Áudio Salvas",
@@ -803,7 +813,7 @@
"acceptAll": "Aceitar Tudo",
"revertAll": "Reverter Tudo",
"undoAll": "Desfazer Tudo",
"resetAllChanges": "Redefinir todas as alterações de volta para as letras originais corrigidas por IA",
"resetAllChanges": "Redefinir todas as alterações para a letra original corrigida",
"undo": "Desfazer",
"redo": "Refazer",
"findReplace": "Localizar/Substituir",
@@ -816,7 +826,9 @@
"playback": "Reprodução",
"audioLoadError": "Não foi possível carregar o áudio",
"audioStillLoading": "O áudio ainda está carregando...",
"loadingAudio": "Carregando áudio..."
"loadingAudio": "Carregando áudio...",
"autoCorrect": "Autocorreção",
"autoCorrectDesc": "Gere sugestões de correção comparando a transcrição com a letra de referência. Nada é alterado até que você aceite cada sugestão."
},
"guidance": {
"showTips": "Mostrar dicas",
@@ -990,7 +1002,9 @@
"loadingAll": "Carregando todas as palavras...",
"loadingSegment": "Carregando segmento...",
"noData": "Nenhum dado de segmento disponível",
"unCorrect": "Desfazer Correção"
"unCorrect": "Desfazer Correção",
"timingClamped": "O tempo de \"{word}\" estava fora do segmento — ajustado para {time}s.",
"timingSanitized": "Corrigido o tempo de {count} palavra(s) que estava(m) fora deste segmento."
},
"findReplace": {
"title": "Localizar e Substituir",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Letras personalizadas aplicadas. Sincronize manualmente cada segmento editado para garantir que o tempo das palavras fique adequado para as novas letras."
},
"autoCorrect": {
"accept": "Aceitar sugestão",
"acceptAll": "Aceitar todas",
"accepted": "Aceita",
"adlibRemovalHint": "Permitir sugestões que removam vocais de apoio que as referências não têm",
"adlibRemovalLabel": "Sugerir remoção de adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "formatação",
"category_grammar": "gramática",
"category_mishearing": "erro de escuta",
"category_other": "outro",
"category_repeated_chorus_fix": "refrão",
"collapse": "Recolher sugestões",
"confidenceHint": "Nível de confiança necessário para que uma sugestão seja exibida",
"confidenceLabel": "Filtro de sugestões",
"confidence_all": "Mostrar todas",
"confidence_high": "Alta confiança",
"description": "A autocorreção compara a letra transcrita com as fontes de referência e sugere correções palavra por palavra. Você revisa cada sugestão — nada é aplicado até que você aceite.",
"dismiss": "Descartar sugestões",
"expand": "Expandir sugestões",
"insertMarker": "inserir:",
"insertionsHint": "Permitir sugestões que insiram palavras que faltaram na transcrição",
"insertionsLabel": "Sugerir palavras ausentes",
"noReferences": "Não há letras de referência disponíveis para esta música, então não é possível gerar sugestões. Primeiro, adicione a letra no painel de referência.",
"noSuggestions": "Nenhum problema encontrado — não há alterações sugeridas.",
"reject": "Rejeitar sugestão",
"rejectAll": "Rejeitar todas",
"rejected": "Rejeitada",
"runButton": "Obter sugestões",
"running": "Analisando a letra… isso geralmente leva de 15 a 60 segundos.",
"staleHint": "Estas palavras foram editadas desde que as sugestões foram geradas, então esta sugestão não se aplica mais.",
"summary": "{total} sugestões · {pending} pendentes · {accepted} aceitas",
"title": "Sugestões de autocorreção",
"undo": "Desfazer esta sugestão",
"cancel": "Cancelar",
"close": "Fechar",
"confidence_balanced": "Equilibrado",
"compareHint": "Mais lento e mais caro, mas mostra em quais sugestões vários modelos concordam",
"compareLabel": "Comparar vários modelos de IA",
"conflictBadge": "variante",
"conflictTooltip": "Há sugestões diferentes para estas palavras — aceitar uma variante rejeita as outras.",
"consensusBadge": "{consensus}/{total} modelos",
"consensusTooltip": "Proposto por: {models}",
"cachedBadge": "em cache",
"cachedTooltip": "Restaurado de uma execução anterior da mesma letra — nenhum custo de IA foi gerado."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Anularea a eșuat",
"redoFailed": "Refacerea a eșuat",
"restoreFailed": "Restaurarea a eșuat — este posibil ca unele editări să nu fi fost aplicate",
"submitFailed": "Trimiterea a eșuat"
"submitFailed": "Trimiterea a eșuat",
"fadeIn": "Fade In",
"fadeInSelection": "Aplică fade in pe regiunea selectată",
"fadeOut": "Fade Out",
"fadeOutSelection": "Aplică fade out pe regiunea selectată",
"fadeInDisabledHint": "Pentru fade in, selectează o regiune care începe chiar de la începutul piesei",
"fadeOutDisabledHint": "Pentru fade out, selectează o regiune care se termină chiar la sfârșitul piesei",
"trimEndDisabledHint": "Pentru a tăia sfârșitul, selectează o regiune care se termină chiar la sfârșitul piesei",
"trimEndSelection": "Elimină totul de după selecție",
"trimStartDisabledHint": "Pentru a tăia începutul, selectează o regiune care începe chiar de la începutul piesei",
"trimStartSelection": "Elimină totul dinaintea selecției"
},
"audioEditRestore": {
"title": "Sesiuni de editare audio salvate",
@@ -803,7 +813,7 @@
"acceptAll": "Acceptă tot",
"revertAll": "Revino la tot",
"undoAll": "Anulează tot",
"resetAllChanges": "Resetează toate modificările înapoi la versurile originale corectate de AI",
"resetAllChanges": "Resetează toate modificările la versurile corectate inițial",
"undo": "Anulează",
"redo": "Refă",
"findReplace": "Caută/Înlocuiește",
@@ -816,7 +826,9 @@
"playback": "Redare",
"audioLoadError": "Nu s-a putut încărca fișierul audio",
"audioStillLoading": "Fișierul audio încă se încarcă...",
"loadingAudio": "Se încarcă fișierul audio..."
"loadingAudio": "Se încarcă fișierul audio...",
"autoCorrect": "Autocorectare",
"autoCorrectDesc": "Generează sugestii de corectare comparând transcrierea cu versurile de referință. Nimic nu este modificat până când nu accepți fiecare sugestie."
},
"guidance": {
"showTips": "Arată sfaturi",
@@ -990,7 +1002,9 @@
"loadingAll": "Se încarcă toate cuvintele...",
"loadingSegment": "Se încarcă segmentul...",
"noData": "Nu există date disponibile pentru segment",
"unCorrect": "Anulează corectura"
"unCorrect": "Anulează corectura",
"timingClamped": "Sincronizarea pentru \"{word}\" era în afara segmentului — a fost ajustată la {time}s.",
"timingSanitized": "Au fost corectate {count} sincronizări de cuvinte care se aflau în afara acestui segment."
},
"findReplace": {
"title": "Caută și înlocuiește",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Versurile personalizate au fost aplicate. Sincronizează manual fiecare segment editat pentru a te asigura că temporizarea cuvintelor este corectă pentru versurile personalizate."
},
"autoCorrect": {
"accept": "Acceptă sugestia",
"acceptAll": "Acceptă toate",
"accepted": "Acceptat",
"adlibRemovalHint": "Permite sugestii care elimină vocile de fundal care nu apar în referințe",
"adlibRemovalLabel": "Sugerează eliminarea adlib-urilor",
"category_adlib_removal": "adlib",
"category_formatting": "formatare",
"category_grammar": "gramatică",
"category_mishearing": "auzite greșit",
"category_other": "altele",
"category_repeated_chorus_fix": "refren",
"collapse": "Restrânge sugestiile",
"confidenceHint": "Cât de sigură trebuie să fie o sugestie înainte de a fi afișată",
"confidenceLabel": "Filtru de sugestii",
"confidence_all": "Afișează toate",
"confidence_high": "Încredere ridicată",
"description": "Autocorectarea compară versurile transcrise cu sursele de referință și sugerează corecturi la nivel de cuvânt. Tu revizuiești fiecare sugestie — nimic nu este aplicat până nu o accepți.",
"dismiss": "Ignoră sugestiile",
"expand": "Extinde sugestiile",
"insertMarker": "inserează:",
"insertionsHint": "Permite sugestii care inserează cuvinte pe care transcrierea le-a omis",
"insertionsLabel": "Sugerează cuvintele lipsă",
"noReferences": "Nu există versuri de referință disponibile pentru această melodie, așa că nu pot fi generate sugestii. Adaugă mai întâi versuri din panoul de referință.",
"noSuggestions": "Nu s-au găsit probleme — nu există modificări sugerate.",
"reject": "Respinge sugestia",
"rejectAll": "Respinge toate",
"rejected": "Respins",
"runButton": "Obține sugestii",
"running": "Se analizează versurile… de obicei durează 15–60 de secunde.",
"staleHint": "Aceste cuvinte au fost editate după generarea sugestiilor, așa că această sugestie nu se mai aplică.",
"summary": "{total} sugestii · {pending} în așteptare · {accepted} acceptate",
"title": "Sugestii de autocorectare",
"undo": "Anulează această sugestie",
"cancel": "Anulează",
"close": "Închide",
"confidence_balanced": "Echilibrat",
"compareHint": "Mai lent și costă mai mult, dar îți arată cu ce sugestii sunt de acord mai multe modele",
"compareLabel": "Compară mai multe modele AI",
"conflictBadge": "variantă",
"conflictTooltip": "Există sugestii diferite pentru aceste cuvinte — acceptarea unei variante le respinge pe celelalte.",
"consensusBadge": "{consensus}/{total} modele",
"consensusTooltip": "Propus de: {models}",
"cachedBadge": "din cache",
"cachedTooltip": "Restaurat dintr-o rulare anterioară pentru aceleași versuri — nu a generat niciun cost AI."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Ошибка отмены",
"redoFailed": "Ошибка повтора",
"restoreFailed": "Ошибка восстановления — некоторые правки могли быть не применены",
"submitFailed": "Ошибка отправки"
"submitFailed": "Ошибка отправки",
"fadeIn": "Плавное нарастание",
"fadeInSelection": "Плавное нарастание в выделенной области",
"fadeOut": "Плавное затухание",
"fadeOutSelection": "Плавное затухание в выделенной области",
"fadeInDisabledHint": "Для плавного нарастания звука выбери область, которая начинается в самом начале трека",
"fadeOutDisabledHint": "Для плавного затухания звука выбери область, которая заканчивается в самом конце трека",
"trimEndDisabledHint": "Чтобы обрезать конец, выбери область, которая заканчивается в самом конце трека",
"trimEndSelection": "Удалить всё после выделения",
"trimStartDisabledHint": "Чтобы обрезать начало, выбери область, которая начинается в самом начале трека",
"trimStartSelection": "Удалить всё до выделения"
},
"audioEditRestore": {
"title": "Сохраненные сессии редактирования аудио",
@@ -803,7 +813,7 @@
"acceptAll": "Принять все",
"revertAll": "Отменить все",
"undoAll": "Отменить все действия",
"resetAllChanges": "Сбросить все изменения до оригинального текста, исправленного ИИ",
"resetAllChanges": "Сбросить все изменения и вернуть исходный исправленный текст",
"undo": "Отменить",
"redo": "Повторить",
"findReplace": "Найти/Заменить",
@@ -816,7 +826,9 @@
"playback": "Воспроизведение",
"audioLoadError": "Не удалось загрузить аудио",
"audioStillLoading": "Аудио всё ещё загружается...",
"loadingAudio": "Загрузка аудио..."
"loadingAudio": "Загрузка аудио...",
"autoCorrect": "Автоисправление",
"autoCorrectDesc": "Сгенерируй варианты исправлений, сравнив распознанный текст с эталонным. Ничего не изменится, пока ты не примешь каждый вариант."
},
"guidance": {
"showTips": "Показать советы",
@@ -990,7 +1002,9 @@
"loadingAll": "Загрузка всех слов...",
"loadingSegment": "Загрузка сегмента...",
"noData": "Нет данных сегмента",
"unCorrect": "Отменить исправление"
"unCorrect": "Отменить исправление",
"timingClamped": "Тайминг \"{word}\" выходил за пределы сегмента — установлен на {time} с.",
"timingSanitized": "Исправлено {count} таймингов слов, выходивших за пределы этого сегмента."
},
"findReplace": {
"title": "Найти и заменить",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Krok späť zlyhal",
"redoFailed": "Krok znova zlyhal",
"restoreFailed": "Obnovenie zlyhalo — niektoré úpravy sa možno neaplikovali",
"submitFailed": "Odoslanie zlyhalo"
"submitFailed": "Odoslanie zlyhalo",
"fadeIn": "Postupné zosilnenie",
"fadeInSelection": "Postupné zosilnenie vo vybranej oblasti",
"fadeOut": "Postupné stíšenie",
"fadeOutSelection": "Postupné stíšenie vo vybranej oblasti",
"fadeInDisabledHint": "Ak chceš použiť postupné zosilnenie, vyber oblasť, ktorá sa začína na úplnom začiatku stopy",
"fadeOutDisabledHint": "Ak chceš použiť postupné zoslabenie, vyber oblasť, ktorá sa končí na úplnom konci stopy",
"trimEndDisabledHint": "Ak chceš orezať koniec, vyber oblasť, ktorá sa končí na úplnom konci stopy",
"trimEndSelection": "Odstrániť všetko za výberom",
"trimStartDisabledHint": "Ak chceš orezať začiatok, vyber oblasť, ktorá sa začína na úplnom začiatku stopy",
"trimStartSelection": "Odstrániť všetko pred výberom"
},
"audioEditRestore": {
"title": "Uložené relácie úprav zvuku",
@@ -803,7 +813,7 @@
"acceptAll": "Prijať všetky",
"revertAll": "Vrátiť všetky",
"undoAll": "Vrátiť späť všetky",
"resetAllChanges": "Obnoviť všetky zmeny späť na pôvodný text opravený AI",
"resetAllChanges": "Vrátiť všetky zmeny späť na pôvodný opravený text",
"undo": "Späť",
"redo": "Znova",
"findReplace": "Nájsť/Nahradiť",
@@ -816,7 +826,9 @@
"playback": "Prehrávanie",
"audioLoadError": "Nepodarilo sa načítať audio",
"audioStillLoading": "Audio sa stále načítava...",
"loadingAudio": "Načítava sa audio..."
"loadingAudio": "Načítava sa audio...",
"autoCorrect": "Automatická oprava",
"autoCorrectDesc": "Vygeneruj návrhy na opravu porovnaním prepisu s referenčným textom. Nič sa nezmení, kým neschváliš každý návrh."
},
"guidance": {
"showTips": "Zobraziť tipy",
@@ -990,7 +1002,9 @@
"loadingAll": "Načítavajú sa všetky slová...",
"loadingSegment": "Načítava sa segment...",
"noData": "Nie sú k dispozícii žiadne dáta segmentu",
"unCorrect": "Zrušiť opravu"
"unCorrect": "Zrušiť opravu",
"timingClamped": "Časovanie \"{word}\" bolo mimo segmentu — zarovnané na {time} s.",
"timingSanitized": "Opravené časovanie pre {count} slov, ktoré boli mimo tohto segmentu."
},
"findReplace": {
"title": "Nájsť a nahradiť",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Vlastný text bol aplikovaný. Manuálne synchronizuj každý upravený segment, aby sa zabezpečilo správne načasovanie slov pre prispôsobený text."
},
"autoCorrect": {
"accept": "Prijať návrh",
"acceptAll": "Prijať všetko",
"accepted": "Prijaté",
"adlibRemovalHint": "Povoliť návrhy, ktoré vymažú sprievodné vokály, ak nie sú v referenčnom texte",
"adlibRemovalLabel": "Navrhnúť odstránenie adlibov",
"category_adlib_removal": "adlib",
"category_formatting": "formátovanie",
"category_grammar": "gramatika",
"category_mishearing": "prepočutie",
"category_other": "iné",
"category_repeated_chorus_fix": "refrén",
"collapse": "Zbaliť návrhy",
"confidenceHint": "Aká vysoká musí byť miera istoty návrhu, aby sa zobrazil",
"confidenceLabel": "Filter návrhov",
"confidence_all": "Zobraziť všetko",
"confidence_high": "Vysoká istota",
"description": "Automatická oprava porovnáva prepísaný text s referenčnými zdrojmi a navrhuje opravy na úrovni slov. Každý návrh skontroluješ — nič sa neaplikuje, kým ho neschváliš.",
"dismiss": "Zahodiť návrhy",
"expand": "Rozbaliť návrhy",
"insertMarker": "vložiť:",
"insertionsHint": "Povoliť návrhy na vloženie slov, ktoré v prepise chýbajú",
"insertionsLabel": "Navrhnúť chýbajúce slová",
"noReferences": "Pre túto pieseň nie je k dispozícii žiadny referenčný text, takže návrhy nie je možné vygenerovať. Najprv pridaj text z referenčného panela.",
"noSuggestions": "Nenašli sa žiadne problémy — nie sú tu žiadne navrhované zmeny.",
"reject": "Odmietnuť návrh",
"rejectAll": "Odmietnuť všetko",
"rejected": "Odmietnuté",
"runButton": "Získať návrhy",
"running": "Analyzuje sa text… zvyčajne to trvá 15 – 60 sekúnd.",
"staleHint": "Tieto slová boli od vygenerovania návrhov upravené, takže tento návrh už neplatí.",
"summary": "{total} návrhov · {pending} čakajúcich · {accepted} prijatých",
"title": "Návrhy automatickej opravy",
"undo": "Vrátiť späť tento návrh",
"cancel": "Zrušiť",
"close": "Zavrieť",
"confidence_balanced": "Vyvážená",
"compareHint": "Je to pomalšie a stojí to viac, ale ukáže, na ktorých návrhoch sa zhoduje viacero modelov",
"compareLabel": "Porovnať viacero AI modelov",
"conflictBadge": "variant",
"conflictTooltip": "Pre tieto slová existujú rôzne návrhy — prijatím jedného variantu odmietneš ostatné.",
"consensusBadge": "{consensus}/{total} modelov",
"consensusTooltip": "Navrhli: {models}",
"cachedBadge": "z cache",
"cachedTooltip": "Obnovené z predchádzajúceho spustenia na rovnakom texte — nevznikli žiadne náklady na AI."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Kunde inte ångra",
"redoFailed": "Kunde inte göra om",
"restoreFailed": "Kunde inte återställa — vissa redigeringar kanske inte har tillämpats",
"submitFailed": "Kunde inte skicka in"
"submitFailed": "Kunde inte skicka in",
"fadeIn": "Tona in",
"fadeInSelection": "Tona in över det markerade området",
"fadeOut": "Tona ut",
"fadeOutSelection": "Tona ut över det markerade området",
"fadeInDisabledHint": "För att tona in, markera ett område som börjar precis i början av spåret",
"fadeOutDisabledHint": "För att tona ut, markera ett område som slutar precis i slutet av spåret",
"trimEndDisabledHint": "För att trimma slutet, markera ett område som slutar precis i slutet av spåret",
"trimEndSelection": "Ta bort allt efter markeringen",
"trimStartDisabledHint": "För att trimma början, markera ett område som börjar precis i början av spåret",
"trimStartSelection": "Ta bort allt före markeringen"
},
"audioEditRestore": {
"title": "Sparade ljudredigeringssessioner",
@@ -803,7 +813,7 @@
"acceptAll": "Acceptera alla",
"revertAll": "Återställ alla",
"undoAll": "Ångra alla",
"resetAllChanges": "Återställ alla ändringar tillbaka till den ursprungliga AI-korrigerade texten",
"resetAllChanges": "Återställ alla ändringar till den ursprungliga korrigerade låttexten",
"undo": "Ångra",
"redo": "Gör om",
"findReplace": "Sök/Ersätt",
@@ -816,7 +826,9 @@
"playback": "Uppspelning",
"audioLoadError": "Kunde inte ladda ljudet",
"audioStillLoading": "Ljudet laddas fortfarande...",
"loadingAudio": "Laddar ljud..."
"loadingAudio": "Laddar ljud...",
"autoCorrect": "Autokorrigering",
"autoCorrectDesc": "Generera korrigeringsförslag genom att jämföra transkriptionen med referenstexten. Ingenting ändras förrän du accepterar varje förslag."
},
"guidance": {
"showTips": "Visa tips",
@@ -990,7 +1002,9 @@
"loadingAll": "Laddar alla ord...",
"loadingSegment": "Laddar segment...",
"noData": "Ingen segmentdata tillgänglig",
"unCorrect": "Av-korrigera"
"unCorrect": "Av-korrigera",
"timingClamped": "Tajmingen för \"{word}\" var utanför segmentet — justerades till {time}s.",
"timingSanitized": "Åtgärdade tajmingen för {count} ord som hamnade utanför detta segment."
},
"findReplace": {
"title": "Sök och ersätt",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Anpassad låttext tillämpad. Synkronisera varje redigerat segment manuellt för att säkerställa att tajmingen stämmer för den anpassade låttexten."
},
"autoCorrect": {
"accept": "Acceptera förslag",
"acceptAll": "Acceptera alla",
"accepted": "Accepterat",
"adlibRemovalHint": "Tillåt förslag som tar bort bakgrundssång som referenserna inte har",
"adlibRemovalLabel": "Föreslå borttagning av adlibs",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "grammatik",
"category_mishearing": "felhört",
"category_other": "annat",
"category_repeated_chorus_fix": "refräng",
"collapse": "Fäll ihop förslag",
"confidenceHint": "Hur säkert ett förslag måste vara innan det visas",
"confidenceLabel": "Förslagsfilter",
"confidence_all": "Visa alla",
"confidence_high": "Hög säkerhet",
"description": "Autokorrigering jämför den transkriberade låttexten med referenskällorna och föreslår rättningar på ordnivå. Du granskar varje förslag — ingenting tillämpas förrän du accepterar det.",
"dismiss": "Avfärda förslag",
"expand": "Fäll ut förslag",
"insertMarker": "infoga:",
"insertionsHint": "Tillåt förslag som infogar ord som transkriberingen missade",
"insertionsLabel": "Föreslå saknade ord",
"noReferences": "Det finns inga referenstexter för den här låten, så det går inte att generera några förslag. Lägg till en text från referenspanelen först.",
"noSuggestions": "Inga problem hittades — det finns inga föreslagna ändringar.",
"reject": "Avvisa förslag",
"rejectAll": "Avvisa alla",
"rejected": "Avvisat",
"runButton": "Hämta förslag",
"running": "Analyserar låttext… detta tar vanligtvis 15–60 sekunder.",
"staleHint": "Dessa ord har redigerats sedan förslagen genererades, så detta förslag gäller inte längre.",
"summary": "{total} förslag · {pending} väntande · {accepted} accepterade",
"title": "Autokorrigeringsförslag",
"undo": "Ångra detta förslag",
"cancel": "Avbryt",
"close": "Stäng",
"confidence_balanced": "Balanserad",
"compareHint": "Långsammare och kostar mer, men visar vilka förslag flera modeller är överens om",
"compareLabel": "Jämför flera AI-modeller",
"conflictBadge": "variant",
"conflictTooltip": "Det finns olika förslag för dessa ord — om du accepterar en variant avvisas de andra.",
"consensusBadge": "{consensus}/{total} modeller",
"consensusTooltip": "Föreslaget av: {models}",
"cachedBadge": "cachad",
"cachedTooltip": "Återställd från en tidigare körning på samma låttext — ingen AI-kostnad tillkom."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "การเลิกทำล้มเหลว",
"redoFailed": "การทำซ้ำล้มเหลว",
"restoreFailed": "การกู้คืนล้มเหลว — การแก้ไขบางอย่างอาจไม่ถูกนำไปใช้",
"submitFailed": "การส่งล้มเหลว"
"submitFailed": "การส่งล้มเหลว",
"fadeIn": "เฟดอิน",
"fadeInSelection": "เฟดอินในส่วนที่เลือก",
"fadeOut": "เฟดเอาต์",
"fadeOutSelection": "เฟดเอาต์ในส่วนที่เลือก",
"fadeInDisabledHint": "หากต้องการเฟดอิน ให้เลือกช่วงที่เริ่มตั้งแต่จุดแรกสุดของแทร็ก",
"fadeOutDisabledHint": "หากต้องการเฟดเอาต์ ให้เลือกช่วงที่สิ้นสุดตรงจุดท้ายสุดของแทร็ก",
"trimEndDisabledHint": "หากต้องการตัดส่วนท้ายออก ให้เลือกช่วงที่สิ้นสุดตรงจุดท้ายสุดของแทร็ก",
"trimEndSelection": "ลบทุกอย่างที่อยู่หลังส่วนที่เลือก",
"trimStartDisabledHint": "หากต้องการตัดส่วนต้นออก ให้เลือกช่วงที่เริ่มตั้งแต่จุดแรกสุดของแทร็ก",
"trimStartSelection": "ลบทุกอย่างที่อยู่ก่อนส่วนที่เลือก"
},
"audioEditRestore": {
"title": "เซสชันการแก้ไขเสียงที่บันทึกไว้",
@@ -803,7 +813,7 @@
"acceptAll": "ยอมรับทั้งหมด",
"revertAll": "ย้อนกลับทั้งหมด",
"undoAll": "เลิกทำทั้งหมด",
"resetAllChanges": "รีเซ็ตการเปลี่ยนแปลงทั้งหมดกลับไปเป็นเนื้อเพลงที่แก้ไขโดย AI ต้นฉบับ",
"resetAllChanges": "รีเซ็ตการเปลี่ยนแปลงทั้งหมดกลับไปเป็นเนื้อเพลงที่แก้ไขไว้ตอนแรก",
"undo": "เลิกทำ",
"redo": "ทำซ้ำ",
"findReplace": "ค้นหา/แทนที่",
@@ -816,7 +826,9 @@
"playback": "การเล่น",
"audioLoadError": "ไม่สามารถโหลดเสียงได้",
"audioStillLoading": "ไฟล์เสียงยังโหลดอยู่...",
"loadingAudio": "กำลังโหลดไฟล์เสียง..."
"loadingAudio": "กำลังโหลดไฟล์เสียง...",
"autoCorrect": "แก้ไขอัตโนมัติ",
"autoCorrectDesc": "สร้างคำแนะนำการแก้ไขโดยเปรียบเทียบการถอดเสียงกับเนื้อเพลงอ้างอิง จะไม่มีการเปลี่ยนแปลงใดๆ จนกว่าคุณจะยอมรับแต่ละคำแนะนำ"
},
"guidance": {
"showTips": "แสดงเคล็ดลับ",
@@ -990,7 +1002,9 @@
"loadingAll": "กำลังโหลดคำทั้งหมด...",
"loadingSegment": "กำลังโหลดส่วน...",
"noData": "ไม่มีข้อมูลส่วน",
"unCorrect": "ยกเลิกการแก้ไข"
"unCorrect": "ยกเลิกการแก้ไข",
"timingClamped": "เวลาของ \"{word}\" อยู่นอกช่วง — ปรับไปที่ {time} วินาที",
"timingSanitized": "แก้ไขเวลาของคำจำนวน {count} คำที่อยู่นอกช่วงนี้"
},
"findReplace": {
"title": "ค้นหาและแทนที่",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Nabigo ang pag-undo",
"redoFailed": "Nabigo ang pag-redo",
"restoreFailed": "Nabigo ang pag-restore — maaaring hindi nailapat ang ilang edit",
"submitFailed": "Nabigo ang pag-submit"
"submitFailed": "Nabigo ang pag-submit",
"fadeIn": "Fade In",
"fadeInSelection": "Mag-fade in sa napiling bahagi",
"fadeOut": "Fade Out",
"fadeOutSelection": "Mag-fade out sa napiling bahagi",
"fadeInDisabledHint": "Para mag-fade in, pumili ng bahagi na nagsisimula sa mismong simula ng track",
"fadeOutDisabledHint": "Para mag-fade out, pumili ng bahagi na nagtatapos sa mismong dulo ng track",
"trimEndDisabledHint": "Para i-trim ang dulo, pumili ng bahagi na nagtatapos sa mismong dulo ng track",
"trimEndSelection": "Alisin ang lahat pagkatapos ng napiling bahagi",
"trimStartDisabledHint": "Para i-trim ang simula, pumili ng bahagi na nagsisimula sa mismong simula ng track",
"trimStartSelection": "Alisin ang lahat bago ang napiling bahagi"
},
"audioEditRestore": {
"title": "Mga Naka-save na Audio Edit Session",
@@ -803,7 +813,7 @@
"acceptAll": "Tanggapin Lahat",
"revertAll": "I-revert Lahat",
"undoAll": "I-undo Lahat",
"resetAllChanges": "I-reset ang lahat ng pagbabago pabalik sa orihinal na AI-corrected lyrics",
"resetAllChanges": "I-reset ang lahat ng pagbabago pabalik sa orihinal na naiwastong lyrics",
"undo": "I-undo",
"redo": "I-redo",
"findReplace": "Hanapin/Palitan",
@@ -816,7 +826,9 @@
"playback": "Playback",
"audioLoadError": "Hindi ma-load ang audio",
"audioStillLoading": "Naglo-load pa rin ang audio...",
"loadingAudio": "Naglo-load ang audio..."
"loadingAudio": "Naglo-load ang audio...",
"autoCorrect": "Auto-correct",
"autoCorrectDesc": "Bumuo ng mga mungkahi sa pagwawasto sa pamamagitan ng paghahambing ng transcription sa reference lyrics. Walang mababago hangga't hindi mo tinatanggap ang bawat mungkahi."
},
"guidance": {
"showTips": "Ipakita ang mga tip",
@@ -990,7 +1002,9 @@
"loadingAll": "Nilo-load ang lahat ng salita...",
"loadingSegment": "Nilo-load ang segment...",
"noData": "Walang available na segment data",
"unCorrect": "I-un-Correct"
"unCorrect": "I-un-Correct",
"timingClamped": "Ang timing ng \"{word}\" ay nasa labas ng segment — inilapat sa {time}s.",
"timingSanitized": "Inayos ang {count} timing ng salita na nasa labas ng segment na ito."
},
"findReplace": {
"title": "Hanapin at Palitan",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Nailapat na ang custom na lyrics. I-sync nang manu-mano ang bawat na-edit na segment para masigurong maayos ang timing ng mga salita sa na-customize na lyrics."
},
"autoCorrect": {
"accept": "Tanggapin ang mungkahi",
"acceptAll": "Tanggapin lahat",
"accepted": "Tinanggap",
"adlibRemovalHint": "Payagan ang mga mungkahi na magtanggal ng mga backing vocal na wala sa mga reference",
"adlibRemovalLabel": "I-suggest na tanggalin ang mga adlib",
"category_adlib_removal": "adlib",
"category_formatting": "format",
"category_grammar": "grammar",
"category_mishearing": "maling dinig",
"category_other": "iba pa",
"category_repeated_chorus_fix": "chorus",
"collapse": "I-collapse ang mga mungkahi",
"confidenceHint": "Kung gaano katiyak ang isang mungkahi bago ito ipakita",
"confidenceLabel": "Filter ng mungkahi",
"confidence_all": "Ipakita lahat",
"confidence_high": "Mataas na kasiguraduhan",
"description": "Inihahambing ng auto-correct ang mga na-transcribe na lyrics sa mga reference source at nagmumungkahi ng mga pag-aayos sa bawat salita. Susuriin mo ang bawat mungkahi — walang ilalapat hangga't hindi mo ito tinatanggap.",
"dismiss": "I-dismiss ang mga mungkahi",
"expand": "I-expand ang mga mungkahi",
"insertMarker": "idagdag:",
"insertionsHint": "Payagan ang mga mungkahi na magdagdag ng mga salitang nakaligtaan sa transcription",
"insertionsLabel": "I-suggest ang mga nawawalang salita",
"noReferences": "Walang available na reference lyrics para sa kantang ito, kaya hindi makabuo ng mga mungkahi. Magdagdag muna ng lyrics mula sa reference panel.",
"noSuggestions": "Walang nakitang isyu — walang mga iminungkahing pagbabago.",
"reject": "Tanggihan ang mungkahi",
"rejectAll": "Tanggihan lahat",
"rejected": "Tinanggihan",
"runButton": "Kumuha ng mga mungkahi",
"running": "Sinusuri ang lyrics… karaniwang tumatagal ito ng 15–60 segundo.",
"staleHint": "Na-edit na ang mga salitang ito simula nang ginawa ang mga mungkahi, kaya hindi na naaangkop ang mungkahing ito.",
"summary": "{total} mungkahi · {pending} nakabinbin · {accepted} tinanggap",
"title": "Mga mungkahi ng auto-correct",
"undo": "I-undo ang mungkahing ito",
"cancel": "Kanselahin",
"close": "Isara",
"confidence_balanced": "Balanse",
"compareHint": "Mas mabagal at mas mahal, pero ipinapakita nito kung aling mga mungkahi ang sinasang-ayunan ng iba't ibang modelo",
"compareLabel": "Paghambingin ang iba't ibang AI model",
"conflictBadge": "variant",
"conflictTooltip": "May iba't ibang mungkahi para sa mga salitang ito — ang pagtanggap sa isang variant ay magbabalewala sa iba.",
"consensusBadge": "{consensus}/{total} modelo",
"consensusTooltip": "Iminungkahi ng: {models}",
"cachedBadge": "naka-cache",
"cachedTooltip": "Na-restore mula sa nakaraang pag-proseso ng parehong lyrics — walang nagastos na AI cost."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Geri alma başarısız oldu",
"redoFailed": "Yineleme başarısız oldu",
"restoreFailed": "Geri yükleme başarısız oldu — bazı düzenlemeler uygulanmamış olabilir",
"submitFailed": "Gönderme başarısız oldu"
"submitFailed": "Gönderme başarısız oldu",
"fadeIn": "Sesi Kademeli Artır",
"fadeInSelection": "Seçili bölgede sesi kademeli artır",
"fadeOut": "Sesi Kademeli Azalt",
"fadeOutSelection": "Seçili bölgede sesi kademeli azalt",
"fadeInDisabledHint": "Sesi yavaşça açmak için parçanın en başından başlayan bir bölge seç",
"fadeOutDisabledHint": "Sesi yavaşça kısmak için parçanın en sonunda biten bir bölge seç",
"trimEndDisabledHint": "Sonu kırpmak için parçanın en sonunda biten bir bölge seç",
"trimEndSelection": "Seçimden sonraki her şeyi kaldır",
"trimStartDisabledHint": "Başlangıcı kırpmak için parçanın en başından başlayan bir bölge seç",
"trimStartSelection": "Seçimden önceki her şeyi kaldır"
},
"audioEditRestore": {
"title": "Kaydedilmiş Ses Düzenleme Oturumları",
@@ -803,7 +813,7 @@
"acceptAll": "Tümünü Kabul Et",
"revertAll": "Tümünü Geri Al",
"undoAll": "Tümünü Geri Al",
"resetAllChanges": "Tüm değişiklikleri orijinal yapay zeka düzeltmeli sözlere sıfırla",
"resetAllChanges": "Tüm değişiklikleri sıfırla ve orijinal düzeltilmiş şarkı sözlerine geri dön",
"undo": "Geri Al",
"redo": "Yinele",
"findReplace": "Bul/Değiştir",
@@ -816,7 +826,9 @@
"playback": "Oynatma",
"audioLoadError": "Ses yüklenemedi",
"audioStillLoading": "Ses hâlâ yükleniyor...",
"loadingAudio": "Ses yükleniyor..."
"loadingAudio": "Ses yükleniyor...",
"autoCorrect": "Otomatik düzeltme",
"autoCorrectDesc": "Yazıya dökülen metni referans şarkı sözleriyle karşılaştırarak düzeltme önerileri oluştur. Sen her bir öneriyi onaylamadan hiçbir şey değiştirilmez."
},
"guidance": {
"showTips": "İpuçlarını göster",
@@ -990,7 +1002,9 @@
"loadingAll": "Tüm kelimeler yükleniyor...",
"loadingSegment": "Segment yükleniyor...",
"noData": "Segment verisi mevcut değil",
"unCorrect": "Düzeltmeyi Geri Al"
"unCorrect": "Düzeltmeyi Geri Al",
"timingClamped": "\"{word}\" zamanlaması bölümün dışındaydı — {time}s'ye hizalandı.",
"timingSanitized": "Bu bölümün dışına çıkan {count} kelime zamanlaması düzeltildi."
},
"findReplace": {
"title": "Bul ve Değiştir",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Özel şarkı sözleri uygulandı. Özelleştirilmiş sözlerde kelime zamanlamalarının doğru olduğundan emin olmak için düzenlenen her bölümü manuel olarak senkronize et."
},
"autoCorrect": {
"accept": "Öneriyi kabul et",
"acceptAll": "Tümünü kabul et",
"accepted": "Kabul edildi",
"adlibRemovalHint": "Referanslarda olmayan geri vokalleri silen önerilere izin ver",
"adlibRemovalLabel": "Adlib'leri kaldırmayı öner",
"category_adlib_removal": "adlib",
"category_formatting": "biçim",
"category_grammar": "dilbilgisi",
"category_mishearing": "yanlış duyma",
"category_other": "diğer",
"category_repeated_chorus_fix": "nakarat",
"collapse": "Önerileri daralt",
"confidenceHint": "Bir önerinin gösterilmesi için gereken güvenilirlik seviyesi",
"confidenceLabel": "Öneri filtresi",
"confidence_all": "Tümünü göster",
"confidence_high": "Yüksek güven",
"description": "Otomatik düzeltme, yazıya dökülen şarkı sözlerini referans kaynaklarla karşılaştırır ve kelime bazında düzeltmeler önerir. Tüm önerileri sen incelersin — sen onaylamadan hiçbir değişiklik uygulanmaz.",
"dismiss": "Önerileri yoksay",
"expand": "Önerileri genişlet",
"insertMarker": "ekle:",
"insertionsHint": "Deşifrede eksik olan kelimeleri ekleyen önerilere izin ver",
"insertionsLabel": "Eksik kelimeleri öner",
"noReferences": "Bu şarkı için referans şarkı sözleri bulunmuyor, bu yüzden öneriler oluşturulamıyor. Önce referans panelinden şarkı sözlerini ekle.",
"noSuggestions": "Sorun bulunamadı — önerilen bir değişiklik yok.",
"reject": "Öneriyi reddet",
"rejectAll": "Tümünü reddet",
"rejected": "Reddedildi",
"runButton": "Önerileri al",
"running": "Şarkı sözleri analiz ediliyor… bu genellikle 15–60 saniye sürer.",
"staleHint": "Bu kelimeler öneriler oluşturulduktan sonra düzenlendi, bu yüzden bu öneri artık geçerli değil.",
"summary": "{total} öneri · {pending} bekleyen · {accepted} kabul edilen",
"title": "Otomatik düzeltme önerileri",
"undo": "Bu öneriyi geri al",
"cancel": "İptal",
"close": "Kapat",
"confidence_balanced": "Dengeli",
"compareHint": "Daha yavaş ve daha maliyetli, ancak birden fazla modelin hangi önerilerde uzlaştığını gösterir",
"compareLabel": "Birden fazla yapay zeka modelini karşılaştır",
"conflictBadge": "varyant",
"conflictTooltip": "Bu kelimeler için farklı öneriler var — bir seçeneği kabul ettiğinde diğerleri reddedilir.",
"consensusBadge": "{consensus}/{total} model",
"consensusTooltip": "Öneren: {models}",
"cachedBadge": "önbellekten",
"cachedTooltip": "Aynı şarkı sözleriyle yapılan önceki bir işlemden geri yüklendi — yapay zeka maliyeti oluşmadı."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Помилка скасування",
"redoFailed": "Помилка повторення",
"restoreFailed": "Помилка відновлення — деякі редагування могли не застосуватися",
"submitFailed": "Помилка надсилання"
"submitFailed": "Помилка надсилання",
"fadeIn": "Плавне наростання",
"fadeInSelection": "Плавне наростання у виділеному фрагменті",
"fadeOut": "Плавне згасання",
"fadeOutSelection": "Плавне згасання у виділеному фрагменті",
"fadeInDisabledHint": "Щоб зробити плавне наростання звуку, виділи ділянку, яка починається із самого початку треку",
"fadeOutDisabledHint": "Щоб зробити плавне затухання звуку, виділи ділянку, яка закінчується у самому кінці треку",
"trimEndDisabledHint": "Щоб обрізати кінець, виділи ділянку, яка закінчується у самому кінці треку",
"trimEndSelection": "Видалити все після виділеної ділянки",
"trimStartDisabledHint": "Щоб обрізати початок, виділи ділянку, яка починається із самого початку треку",
"trimStartSelection": "Видалити все до виділеної ділянки"
},
"audioEditRestore": {
"title": "Збережені сеанси редагування аудіо",
@@ -803,7 +813,7 @@
"acceptAll": "Прийняти всі",
"revertAll": "Повернути всі",
"undoAll": "Скасувати всі",
"resetAllChanges": "Скинути всі зміни до оригінального тексту, виправленого ШІ",
"resetAllChanges": "Скинути всі зміни до початкового виправленого тексту",
"undo": "Скасувати",
"redo": "Повторити",
"findReplace": "Знайти/Замінити",
@@ -816,7 +826,9 @@
"playback": "Відтворення",
"audioLoadError": "Не вдалося завантажити аудіо",
"audioStillLoading": "Аудіо ще завантажується...",
"loadingAudio": "Завантаження аудіо..."
"loadingAudio": "Завантаження аудіо...",
"autoCorrect": "Автовиправлення",
"autoCorrectDesc": "Згенеруй пропозиції виправлень, порівнявши транскрипцію з еталонним текстом. Нічого не зміниться, поки ти не приймеш кожну пропозицію."
},
"guidance": {
"showTips": "Показати підказки",
@@ -990,7 +1002,9 @@
"loadingAll": "Завантаження всіх слів...",
"loadingSegment": "Завантаження сегмента...",
"noData": "Дані сегмента недоступні",
"unCorrect": "Скасувати виправлення"
"unCorrect": "Скасувати виправлення",
"timingClamped": "Таймінг \"{word}\" виходив за межі сегмента — прив'язано до {time} с.",
"timingSanitized": "Виправлено {count} таймінг(ів) слів, що виходили за межі цього сегмента."
},
"findReplace": {
"title": "Знайти та замінити",
@@ -1272,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": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "Hoàn tác thất bại",
"redoFailed": "Làm lại thất bại",
"restoreFailed": "Khôi phục thất bại — một số chỉnh sửa có thể chưa được áp dụng",
"submitFailed": "Gửi thất bại"
"submitFailed": "Gửi thất bại",
"fadeIn": "Tăng dần âm lượng",
"fadeInSelection": "Tăng dần âm lượng trong vùng đã chọn",
"fadeOut": "Giảm dần âm lượng",
"fadeOutSelection": "Giảm dần âm lượng trong vùng đã chọn",
"fadeInDisabledHint": "Để tăng dần âm lượng, hãy chọn một đoạn bắt đầu ngay từ đầu bản nhạc",
"fadeOutDisabledHint": "Để giảm dần âm lượng, hãy chọn một đoạn kết thúc ngay ở cuối bản nhạc",
"trimEndDisabledHint": "Để cắt phần cuối, hãy chọn một đoạn kết thúc ngay ở cuối bản nhạc",
"trimEndSelection": "Xóa mọi thứ sau phần được chọn",
"trimStartDisabledHint": "Để cắt phần đầu, hãy chọn một đoạn bắt đầu ngay từ đầu bản nhạc",
"trimStartSelection": "Xóa mọi thứ trước phần được chọn"
},
"audioEditRestore": {
"title": "Các phiên chỉnh sửa âm thanh đã lưu",
@@ -803,7 +813,7 @@
"acceptAll": "Chấp nhận tất cả",
"revertAll": "Hoàn nguyên tất cả",
"undoAll": "Hoàn tác tất cả",
"resetAllChanges": "Khôi phục tất cả thay đổi về lời bài hát gốc do AI tạo",
"resetAllChanges": "Khôi phục tất cả thay đổi về lời bài hát đã sửa ban đầu",
"undo": "Hoàn tác",
"redo": "Làm lại",
"findReplace": "Tìm/Thay thế",
@@ -816,7 +826,9 @@
"playback": "Phát lại",
"audioLoadError": "Không thể tải âm thanh",
"audioStillLoading": "Âm thanh vẫn đang tải...",
"loadingAudio": "Đang tải âm thanh..."
"loadingAudio": "Đang tải âm thanh...",
"autoCorrect": "Tự động sửa lỗi",
"autoCorrectDesc": "Tạo các đề xuất sửa lỗi bằng cách so sánh bản chép lời với lời bài hát tham khảo. Sẽ không có thay đổi nào được áp dụng cho đến khi bạn chấp nhận từng đề xuất."
},
"guidance": {
"showTips": "Hiện mẹo",
@@ -990,7 +1002,9 @@
"loadingAll": "Đang tải tất cả các từ...",
"loadingSegment": "Đang tải phân đoạn...",
"noData": "Không có dữ liệu phân đoạn",
"unCorrect": "Bỏ sửa"
"unCorrect": "Bỏ sửa",
"timingClamped": "Thời gian của \"{word}\" nằm ngoài phân đoạn — đã được điều chỉnh về {time}s.",
"timingSanitized": "Đã sửa thời gian của {count} từ nằm ngoài phân đoạn này."
},
"findReplace": {
"title": "Tìm và Thay thế",
@@ -1272,6 +1286,52 @@
},
"toasts": {
"customLyricsSaved": "Đã áp dụng lời bài hát tùy chỉnh. Hãy đồng bộ hóa thủ công từng phân đoạn đã chỉnh sửa để đảm bảo nhịp điệu hiển thị từ khớp với lời bài hát tùy chỉnh."
},
"autoCorrect": {
"accept": "Chấp nhận đề xuất",
"acceptAll": "Chấp nhận tất cả",
"accepted": "Đã chấp nhận",
"adlibRemovalHint": "Cho phép các đề xuất xóa phần hát bè mà bản tham khảo không có",
"adlibRemovalLabel": "Đề xuất xóa hát bè",
"category_adlib_removal": "hát bè",
"category_formatting": "định dạng",
"category_grammar": "ngữ pháp",
"category_mishearing": "nghe nhầm",
"category_other": "khác",
"category_repeated_chorus_fix": "điệp khúc",
"collapse": "Thu gọn đề xuất",
"confidenceHint": "Mức độ tin cậy cần thiết để hiển thị đề xuất",
"confidenceLabel": "Bộ lọc đề xuất",
"confidence_all": "Hiển thị tất cả",
"confidence_high": "Độ chắc chắn cao",
"description": "Tính năng Tự động sửa lỗi sẽ so sánh bản chép lời với các nguồn tham khảo và đề xuất sửa lỗi cho từng từ. Bạn có thể xem xét từng đề xuất — sẽ không có thay đổi nào được áp dụng cho đến khi bạn chấp nhận.",
"dismiss": "Bỏ qua đề xuất",
"expand": "Mở rộng đề xuất",
"insertMarker": "chèn:",
"insertionsHint": "Cho phép các đề xuất chèn những từ mà bản chép lời bỏ sót",
"insertionsLabel": "Đề xuất các từ còn thiếu",
"noReferences": "Không có lời bài hát tham khảo nào cho bài hát này, vì vậy không thể tạo đề xuất. Hãy thêm lời bài hát từ bảng tham khảo trước.",
"noSuggestions": "Không tìm thấy vấn đề nào — không có thay đổi nào được đề xuất.",
"reject": "Từ chối đề xuất",
"rejectAll": "Từ chối tất cả",
"rejected": "Đã từ chối",
"runButton": "Nhận đề xuất",
"running": "Đang phân tích lời bài hát… quá trình này thường mất 15–60 giây.",
"staleHint": "Những từ này đã được chỉnh sửa sau khi đề xuất được tạo, nên đề xuất này không còn phù hợp nữa.",
"summary": "{total} đề xuất · {pending} đang chờ · {accepted} đã chấp nhận",
"title": "Đề xuất tự động sửa lỗi",
"undo": "Hoàn tác đề xuất này",
"cancel": "Hủy",
"close": "Đóng",
"confidence_balanced": "Cân bằng",
"compareHint": "Chậm hơn và tốn phí hơn, nhưng cho thấy các gợi ý được nhiều mô hình cùng đồng thuận",
"compareLabel": "So sánh nhiều mô hình AI",
"conflictBadge": "biến thể",
"conflictTooltip": "Có nhiều đề xuất khác nhau cho những từ này — khi chấp nhận một phương án, các phương án khác sẽ bị loại bỏ.",
"consensusBadge": "{consensus}/{total} mô hình",
"consensusTooltip": "Đề xuất bởi: {models}",
"cachedBadge": "đã lưu cache",
"cachedTooltip": "Được khôi phục từ lần chạy trước với cùng lời bài hát — không phát sinh chi phí AI."
}
},
"instrumentalReview": {
+64 -4
View File
@@ -776,7 +776,17 @@
"undoFailed": "撤销失败",
"redoFailed": "重做失败",
"restoreFailed": "恢复失败——某些编辑可能未应用",
"submitFailed": "提交失败"
"submitFailed": "提交失败",
"fadeIn": "淡入",
"fadeInSelection": "在选定区域淡入",
"fadeOut": "淡出",
"fadeOutSelection": "在选定区域淡出",
"fadeInDisabledHint": "如需添加淡入效果,请选择从音轨最开头开始的区域",
"fadeOutDisabledHint": "如需添加淡出效果,请选择在音轨最末尾结束的区域",
"trimEndDisabledHint": "如需裁剪结尾,请选择在音轨最末尾结束的区域",
"trimEndSelection": "移除所选区域之后的所有内容",
"trimStartDisabledHint": "如需裁剪开头,请选择从音轨最开头开始的区域",
"trimStartSelection": "移除所选区域之前的所有内容"
},
"audioEditRestore": {
"title": "已保存的音频编辑会话",
@@ -803,7 +813,7 @@
"acceptAll": "全部接受",
"revertAll": "全部还原",
"undoAll": "全部撤销",
"resetAllChanges": "将所有更改重置回原始的 AI 校对歌词",
"resetAllChanges": "将所有更改重置为最初的纠错歌词",
"undo": "撤销",
"redo": "重做",
"findReplace": "查找/替换",
@@ -816,7 +826,9 @@
"playback": "播放",
"audioLoadError": "无法加载音频",
"audioStillLoading": "音频仍在加载中...",
"loadingAudio": "正在加载音频..."
"loadingAudio": "正在加载音频...",
"autoCorrect": "自动纠错",
"autoCorrectDesc": "通过将转录内容与参考歌词进行比较来生成纠错建议。在您接受每条建议之前,不会进行任何更改。"
},
"guidance": {
"showTips": "显示提示",
@@ -990,7 +1002,9 @@
"loadingAll": "正在加载所有单词...",
"loadingSegment": "正在加载片段...",
"noData": "无可用片段数据",
"unCorrect": "取消校对"
"unCorrect": "取消校对",
"timingClamped": "\"{word}\" 的时间点超出了片段范围 — 已调整至 {time} 秒。",
"timingSanitized": "已修复 {count} 个超出此片段范围的单词时间点。"
},
"findReplace": {
"title": "查找和替换",
@@ -1272,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": {
@@ -50,6 +50,18 @@ def create_encoding_worker_vms(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
# NOTE: Hyperdisk provisioned IOPS/throughput are deliberately
# NOT set here. Specifying them forces a full VM *replacement*
# (the provider treats boot-disk init params as immutable), and
# recreating a primary depends on us-central1-c capacity — the
# exact shortage the fallback fleet exists to absorb. So the
# disks are pinned to the Hyperdisk Balanced free baseline
# (3000 IOPS / 140 MB/s) live via `gcloud compute disks update`
# instead — non-disruptive, and pulumi does not manage this
# attribute so there is no drift. They were over-provisioned at
# 3600 IOPS / 290 MB/s (~$8.70/disk/mo wasted). Re-apply the
# gcloud tune after any worker-image rebuild that recreates the
# disks. See docs/archive/2026-06-14-gcp-cost-reduction-plan.md.
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
@@ -127,6 +139,18 @@ def create_encoding_worker_fallback_vms(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
# NOTE: Hyperdisk provisioned IOPS/throughput are deliberately
# NOT set here. Specifying them forces a full VM *replacement*
# (the provider treats boot-disk init params as immutable), and
# recreating a primary depends on us-central1-c capacity — the
# exact shortage the fallback fleet exists to absorb. So the
# disks are pinned to the Hyperdisk Balanced free baseline
# (3000 IOPS / 140 MB/s) live via `gcloud compute disks update`
# instead — non-disruptive, and pulumi does not manage this
# attribute so there is no drift. They were over-provisioned at
# 3600 IOPS / 290 MB/s (~$8.70/disk/mo wasted). Re-apply the
# gcloud tune after any worker-image rebuild that recreates the
# disks. See docs/archive/2026-06-14-gcp-cost-reduction-plan.md.
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
@@ -1,11 +1,36 @@
"""Firestore export to GCS staging bucket."""
import logging
from google.cloud import firestore_admin_v1
from google.cloud import firestore_admin_v1, storage
logger = logging.getLogger(__name__)
def _clear_prior_exports(staging_bucket: str, keep_date: str) -> None:
"""Delete prior firestore/ exports in staging except the keep_date one.
The Firestore export runs nightly to provide a fresh daily local (GCS)
restore point, but is only uploaded to S3 weekly (to cut egress). On
non-weekly days the export is held back from S3 and left in staging, so
without this cleanup a week of exports would pile up and the weekly upload
would ship all of them at once — defeating the saving. Keeping only the
latest export means the weekly upload ships exactly one.
"""
keep_prefix = f"firestore/{keep_date}"
try:
client = storage.Client()
bucket = client.bucket(staging_bucket)
for blob in bucket.list_blobs(prefix="firestore/"):
if not blob.name.startswith(keep_prefix):
try:
blob.delete()
except Exception as e:
logger.warning(f"Failed to delete stale firestore export {blob.name}: {e}")
except Exception as e:
# Best-effort cleanup — the export already succeeded, so never fail on it.
logger.warning(f"Failed to list/clear prior firestore exports: {e}")
def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
"""Export all Firestore collections to GCS.
@@ -32,5 +57,8 @@ def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
result = operation.result(timeout=1800) # 30 min timeout
# Keep only this export in staging so the weekly S3 upload ships exactly one.
_clear_prior_exports(staging_bucket, date_str)
logger.info(f"Firestore export complete: {output_uri}")
return f"Exported to {output_uri} ({date_str})"
+16 -4
View File
@@ -2,14 +2,18 @@
Backup to AWS Cloud Function.
Nightly backup pipeline:
1. Firestore export to GCS staging
1. Firestore export to GCS staging (nightly; uploaded to S3 weekly on Sundays)
2. BigQuery export to GCS staging (weekly/monthly schedule)
3. GCS job files delta sync to staging
4. Secret Manager export (encrypted with sealed-box public key) to staging
5. Upload staging files to S3
5. Upload staging files to S3 (Firestore export held back except Sundays)
6. Discord alert
Triggered by Cloud Scheduler at 1:00 AM ET daily.
Firestore is the bulk of the cross-cloud egress. Exporting it nightly to GCS
keeps a 1-day local restore point, while uploading to S3 only weekly keeps a
1-week off-site RPO at ~1/7th the egress cost.
"""
import datetime
@@ -59,7 +63,13 @@ def backup_to_aws(request):
results = {}
errors = []
logger.info(f"Starting backup for {date_str}")
# The Firestore export runs nightly (daily local restore point in GCS) but
# is only pushed off-site to S3 weekly, on Sundays — matching the BigQuery
# weekly cadence. This is the bulk of the cross-cloud egress, so weekly
# off-site keeps a 1-week off-site RPO while a 1-day local RPO is retained.
firestore_to_s3_today = today.weekday() == 6 # Sunday
logger.info(f"Starting backup for {date_str} (firestore->S3: {firestore_to_s3_today})")
# Step 1: Firestore export (nightly)
try:
@@ -123,11 +133,13 @@ def backup_to_aws(request):
logger.error(f"Secrets export failed: {e}")
errors.append(f"Secrets: {e}")
# Step 5: Upload to S3
# Step 5: Upload to S3. On non-Sundays, hold the Firestore export back
# (it stays in GCS staging as a daily local backup); it ships to S3 weekly.
try:
results["s3_upload"] = upload_staging_to_s3(
staging_bucket=STAGING_BUCKET,
s3_bucket=S3_BUCKET,
exclude_prefixes=[] if firestore_to_s3_today else ["firestore/"],
)
except Exception as e:
logger.error(f"S3 upload failed: {e}")
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more