Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Fable 5 0c6b471e59 fix: clamp AI suggestions list to panel with native scroll
The repo's ScrollArea root has no overflow-hidden, so max-h-64 on it
never clipped the Radix viewport and long suggestion lists spilled
over the panel border onto the content below. Use a plain
overflow-y-auto div instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 13:30:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a0e61d9e21 feat(audio-editor): add Fade In / Fade Out buttons for selected region (#813)
## Summary

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

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

## UX

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

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

## Changes

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

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

## Testing

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

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

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

@coderabbitai ignore

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

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

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

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

## Summary

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

## Changes

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

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

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

## Testing

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

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

---------

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

## Summary

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

## Changes

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

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

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

## Testing

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

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

---------

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

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

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

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

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

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

## Review
- [x] Local CodeRabbit review completed

@coderabbitai ignore

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

---------

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

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

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

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

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

@coderabbitai ignore

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

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

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

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

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

## Testing

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

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

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

@coderabbitai ignore

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

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

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

## Changes

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

Net **−331 lines**.

## Testing

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

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

@coderabbitai ignore

---------

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

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

## Changes

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

## Testing

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

## Notes

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

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:31:31 -04:00
95 changed files with 7906 additions and 704 deletions

No files matched your search

+2 -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-fable-5,AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview,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: |
+40 -59
View File
@@ -10,12 +10,11 @@ Supports two upload flows:
- Client uploads files directly to GCS using signed URLs (no size limit)
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
"""
import asyncio
import json
import logging
import tempfile
import os
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
from pathlib import Path
from typing import Optional, List, Dict, Any, Tuple
@@ -338,16 +337,6 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
async def _trigger_audio_worker_only(job_id: str) -> None:
"""
Trigger only the audio worker.
Used for URL jobs where audio needs to be downloaded first.
The audio worker will trigger the lyrics worker after download completes.
"""
await worker_service.trigger_audio_worker(job_id)
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
@@ -1784,55 +1773,47 @@ async def create_job_from_url(
if title:
logger.info(f" Title: {title}")
# For YouTube URLs, download audio NOW using YouTubeDownloadService
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
if _is_youtube_url(body.url):
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
try:
youtube_service = get_youtube_download_service()
audio_gcs_path = await youtube_service.download(
url=body.url,
job_id=job_id,
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"YouTube download failed: {e}")
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
else:
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
# The audio worker will download the URL and trigger lyrics worker after
job_manager.transition_to_state(
# Download audio NOW via the flacfetch service for ALL URLs (YouTube and
# any other yt-dlp-supported site, e.g. Facebook/SoundCloud/TikTok).
# flacfetch is the sole downloader — no yt-dlp ever runs on Cloud Run.
# Downloading up front (before the GPU worker starts) also keeps the GPU
# idle until the audio is in GCS.
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
try:
download_service = get_youtube_download_service()
audio_gcs_path = await download_service.download(
url=body.url,
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=5,
message="Starting audio download from URL"
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"Audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"URL download failed: {e}")
job_manager.fail_job(job_id, f"Download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
background_tasks.add_task(_trigger_audio_worker_only, job_id)
return CreateJobFromUrlResponse(
status="success",
+12
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)
+117 -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,48 @@ 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]
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 +678,78 @@ 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,
)
@router.post("/{job_id}/handlers")
async def update_handlers(
job_id: str,
@@ -1817,7 +1931,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 +1946,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}")
+8
View File
@@ -88,6 +88,14 @@ 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", "")
# 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",
]
+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)
+429
View File
@@ -0,0 +1,429 @@
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
from __future__ import annotations
import json
import logging
import time
import uuid
from dataclasses import 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.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)
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)
t0 = time.time()
per_model: dict[str, list[Suggestion]] = {}
warnings: list[str] = []
if len(models) == 1:
raw = 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
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 = 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
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,
)
return AutoCorrectResult(
suggestions=merged,
model=model_label,
elapsed_seconds=round(elapsed, 1),
settings_applied=settings,
warnings=warnings,
)
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
) -> Any:
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)
def _call_anthropic(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> Any:
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
try:
text = next(b.text for b in response.content if b.type == "text")
return json.loads(text)
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
) -> Any:
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
try:
return json.loads(response.text)
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
+64 -92
View File
@@ -13,16 +13,11 @@ The flow is:
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
"""
import asyncio
import logging
import mimetypes
import os
import re
import tempfile
from typing import Optional
from .flacfetch_client import get_flacfetch_client, FlacfetchServiceError
from .storage_service import StorageService
logger = logging.getLogger(__name__)
@@ -54,14 +49,13 @@ class YouTubeDownloadService:
def __init__(self):
self._flacfetch_client = get_flacfetch_client()
self._storage_service = StorageService()
if self._flacfetch_client:
logger.info("YouTubeDownloadService using REMOTE flacfetch (recommended)")
logger.info("YouTubeDownloadService using REMOTE flacfetch")
else:
logger.warning(
"YouTubeDownloadService using LOCAL yt_dlp - "
"downloads may fail due to YouTube bot detection on Cloud Run IPs"
"YouTubeDownloadService: remote flacfetch NOT configured "
"(FLACFETCH_API_URL) - URL downloads will fail until it is set"
)
def is_remote_enabled(self) -> bool:
@@ -121,20 +115,24 @@ class YouTubeDownloadService:
Raises:
YouTubeDownloadError: If download fails
"""
video_id = self._extract_video_id(url)
if not video_id:
raise YouTubeDownloadError(f"Could not extract video ID from URL: {url}")
logger.info(f"YouTube download: video_id={video_id}, job_id={job_id}")
if self._flacfetch_client:
return await self._download_remote(video_id, job_id, artist, title)
else:
logger.warning(
"Remote flacfetch not configured. Attempting local download, "
"but this may fail due to YouTube bot detection on Cloud Run IPs."
# flacfetch is the SOLE downloader — never run yt-dlp on Cloud Run.
# If it isn't configured, fail loudly rather than silently falling back
# to a local download (which is blocked by bot detection on Cloud Run
# IPs anyway).
if not self._flacfetch_client:
raise YouTubeDownloadError(
"Remote flacfetch is not configured (FLACFETCH_API_URL). "
"URL downloads require the flacfetch service."
)
return await self._download_local(url, job_id, artist, title)
video_id = self._extract_video_id(url)
if video_id:
logger.info(f"URL download (YouTube): video_id={video_id}, job_id={job_id}")
return await self._download_remote(video_id, job_id, artist, title)
# Any other yt-dlp-supported site (Facebook, SoundCloud, TikTok, ...).
logger.info(f"URL download (generic): url={url}, job_id={job_id}")
return await self._download_remote_url(url, job_id, artist, title)
async def download_by_id(
self,
@@ -265,7 +263,7 @@ class YouTubeDownloadService:
logger.error(f"Remote YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
async def _download_local(
async def _download_remote_url(
self,
url: str,
job_id: str,
@@ -273,92 +271,66 @@ class YouTubeDownloadService:
title: Optional[str] = None,
) -> str:
"""
Download using local yt_dlp (fallback when remote not configured).
Download an arbitrary yt-dlp-supported URL via remote flacfetch.
Warning: This may fail on Cloud Run due to YouTube bot detection.
Used for non-YouTube sites (Facebook, SoundCloud, TikTok, Vimeo, ...).
The URL is handed to flacfetch's generic "URL" source, which downloads
on the VM and uploads to GCS.
"""
temp_dir = tempfile.mkdtemp(prefix=f"youtube_{job_id}_")
gcs_destination = f"uploads/{job_id}/audio/"
output_filename = None
if artist and title:
from karaoke_gen.utils import sanitize_filename
output_filename = f"{sanitize_filename(artist)} - {sanitize_filename(title)}"
logger.info(
f"Remote URL download: url={url}, "
f"gcs_path={gcs_destination}, filename={output_filename}"
)
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
download_id = await self._flacfetch_client.download_by_id(
source_name="URL",
source_id=url,
download_url=url,
output_filename=output_filename,
gcs_path=gcs_destination,
)
# Build output filename
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(
temp_dir, f"{safe_artist} - {safe_title}"
logger.info(f"Remote URL download started: {download_id}")
def log_progress(status):
progress = status.get("progress", 0)
logger.debug(f"Download progress: {progress:.1f}%")
final_status = await self._flacfetch_client.wait_for_download(
download_id,
timeout=300,
progress_callback=log_progress,
)
# Get cookies from environment
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for local download")
# Download
logger.info(f"Local YouTube download: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if not downloaded_file or not os.path.exists(downloaded_file):
gcs_path = final_status.get("gcs_path")
if not gcs_path:
raise YouTubeDownloadError(
f"Local download failed - no file returned. "
"This is likely due to YouTube bot detection on Cloud Run IPs. "
"Configure FLACFETCH_API_URL for remote downloads."
"Remote download completed but no GCS path returned"
)
logger.info(f"Downloaded video: {downloaded_file}")
if gcs_path.startswith("gs://"):
parts = gcs_path.replace("gs://", "").split("/", 1)
if len(parts) == 2:
gcs_path = parts[1]
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if not wav_file or not os.path.exists(wav_file):
raise YouTubeDownloadError("WAV conversion failed")
logger.info(f"Converted to WAV: {wav_file}")
# Upload to GCS
filename = os.path.basename(wav_file)
gcs_path = f"uploads/{job_id}/audio/{filename}"
content_type, _ = mimetypes.guess_type(wav_file)
with open(wav_file, 'rb') as f:
self._storage_service.upload_fileobj(
f,
gcs_path,
content_type=content_type or 'audio/wav'
)
logger.info(f"Uploaded to GCS: {gcs_path}")
logger.info(f"Remote URL download complete: {gcs_path}")
return gcs_path
except FlacfetchServiceError as e:
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
except YouTubeDownloadError:
raise
except Exception as e:
logger.error(f"Local YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Local download failed: {e}") from e
finally:
# Cleanup temp directory
try:
import shutil
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
except Exception as cleanup_error:
logger.warning(f"Failed to cleanup temp dir: {cleanup_error}")
logger.error(f"Remote URL download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
# Singleton instance
+215
View File
@@ -0,0 +1,215 @@
"""Route-level tests for POST /api/jobs/{job_id}/corrections — timing sanitizer integration.
Verifies that out-of-bounds word timings submitted by the frontend are clamped
before corrections_updated.json is written to GCS.
"""
from __future__ import annotations
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, patch, call
from backend.models.job import Job, JobStatus
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def review_job():
"""A job in AWAITING_REVIEW state owned by the test admin user."""
job = Job(
job_id="review-job-001",
status=JobStatus.AWAITING_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
)
return job
@pytest.fixture
def mock_job_manager(review_job):
manager = MagicMock()
manager.get_job.return_value = review_job
manager.update_state_data.return_value = None
manager.update_file_url.return_value = None
manager.transition_to_state.return_value = None
return manager
@pytest.fixture
def mock_worker_service():
return MagicMock()
@pytest.fixture
def mock_theme_service():
svc = MagicMock()
svc.get_default_theme_id.return_value = "nomad"
svc.get_theme.return_value = None
return svc
@pytest.fixture
def client(mock_job_manager, mock_worker_service, mock_theme_service):
"""FastAPI TestClient with mocked dependencies."""
from fastapi.testclient import TestClient
mock_creds = MagicMock()
mock_creds.universe_domain = "googleapis.com"
def _jm_factory(*args, **kwargs):
return mock_job_manager
with patch("backend.api.routes.jobs.job_manager", mock_job_manager), \
patch("backend.api.routes.jobs.worker_service", mock_worker_service), \
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
patch("backend.services.job_manager.JobManager", _jm_factory), \
patch("backend.services.firestore_service.firestore"), \
patch("backend.services.storage_service.storage"), \
patch("google.auth.default", return_value=(mock_creds, "test-project")):
from backend.main import app
yield TestClient(app)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _bad_corrections():
"""Corrections payload whose words fall outside segment bounds (start=0, end<0).
Must include the 'lines' and 'metadata' keys required by CorrectionsSubmission
validation before the sanitizer runs.
"""
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": [
{
"id": "s1",
"text": "A whiskey and a beer,",
"start_time": 15.18,
"end_time": 18.04,
"words": [
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
],
}
]
}
def _good_corrections():
"""Corrections payload whose word timings are already valid."""
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": [
{
"id": "s1",
"text": "Filling up",
"start_time": 21.4,
"end_time": 22.1,
"words": [
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
],
}
]
}
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestSubmitCorrectionsTimingSanitizer:
"""Verify that submit_corrections clamps out-of-bounds word timings before GCS upload."""
def test_sanitized_timings_uploaded_to_gcs(self, client, auth_headers):
"""Words with start_time/end_time outside segment bounds must be clamped
before corrections_updated.json is written to GCS.
Patch StorageService at the class level in its source module so the local
import inside submit_corrections picks up the mock.
"""
uploaded_payload = {}
with patch("backend.services.storage_service.StorageService") as MockStorage:
storage_instance = MockStorage.return_value
# Capture what gets passed to upload_json
def capture_upload(path, data):
uploaded_payload.update(data)
storage_instance.upload_json.side_effect = capture_upload
response = client.post(
"/api/jobs/review-job-001/corrections",
json={"corrections": _bad_corrections()},
headers=auth_headers,
)
assert response.status_code == 200, response.text
assert uploaded_payload, "upload_json was never called — capture failed"
# All uploaded word timings must be within their segment bounds
words = uploaded_payload["corrected_segments"][0]["words"]
seg_start = 15.18
seg_end = 18.04
for w in words:
assert w["start_time"] >= seg_start, f"word start_time {w['start_time']} < seg start {seg_start}"
assert w["end_time"] >= w["start_time"], f"word end_time {w['end_time']} < start_time {w['start_time']}"
assert w["end_time"] <= seg_end + 1e-9, f"word end_time {w['end_time']} > seg end {seg_end}"
def test_valid_timings_uploaded_unchanged(self, client, auth_headers):
"""Word timings already within bounds must not be modified."""
uploaded_payload = {}
with patch("backend.services.storage_service.StorageService") as MockStorage:
storage_instance = MockStorage.return_value
def capture_upload(path, data):
uploaded_payload.update(data)
storage_instance.upload_json.side_effect = capture_upload
response = client.post(
"/api/jobs/review-job-001/corrections",
json={"corrections": _good_corrections()},
headers=auth_headers,
)
assert response.status_code == 200, response.text
assert uploaded_payload, "upload_json was never called — capture failed"
words = uploaded_payload["corrected_segments"][0]["words"]
assert words[0]["start_time"] == 21.4
assert words[0]["end_time"] == 21.82
assert words[1]["start_time"] == 21.86
assert words[1]["end_time"] == 22.1
class TestSubmitCorrectionsContract:
"""Minimal contract test — does not require the full FastAPI test harness."""
def test_sanitize_contract_bad_timings(self):
"""sanitize_corrections clamps words with start/end outside segment bounds."""
from backend.services.timing_sanitizer import sanitize_corrections
bad = {
"corrected_segments": [
{
"id": "s", "start_time": 15.18, "end_time": 18.04, "text": "A",
"words": [{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005}],
}
]
}
cleaned, count = sanitize_corrections(bad)
assert count >= 1
w = cleaned["corrected_segments"][0]["words"][0]
assert w["start_time"] >= 15.18
assert w["end_time"] >= w["start_time"]
@@ -0,0 +1,139 @@
"""Route tests for POST /api/review/{job_id}/auto-correct."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.services.auto_correct.service import (
AutoCorrectResult,
AutoCorrectServiceError,
Suggestion,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def bypass_auth(monkeypatch):
"""Bypass require_review_auth for these tests."""
from backend.api.dependencies import require_review_auth as real_dep
async def fake_dep():
return ("test-job", "full")
app.dependency_overrides[real_dep] = fake_dep
yield
app.dependency_overrides.pop(real_dep, None)
def _override_service(result_or_exc):
from backend.api.routes.review import _get_auto_correct_service_dep
mock_service = MagicMock()
if isinstance(result_or_exc, Exception):
mock_service.suggest.side_effect = result_or_exc
else:
mock_service.suggest.return_value = result_or_exc
app.dependency_overrides[_get_auto_correct_service_dep] = lambda: mock_service
return mock_service
def teardown_function(_): # noqa: ANN001
from backend.api.routes.review import _get_auto_correct_service_dep
app.dependency_overrides.pop(_get_auto_correct_service_dep, None)
def _make_result(suggestions=None) -> AutoCorrectResult:
return AutoCorrectResult(
suggestions=suggestions
if suggestions is not None
else [
Suggestion(
id="sug-1",
op="replace",
word_ids=["w3"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="matches reference",
category="mishearing",
confidence=0.95,
)
],
model="gemini-test",
elapsed_seconds=12.3,
settings_applied=AutoCorrectSettings(),
warnings=["dropped suggestion 3: out of range"],
)
BODY = {
"segments": [{"id": "seg-1", "words": [{"id": "w3", "text": "glory"}]}],
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
"artist": "Twenty One Pilots",
"title": "Chlorine",
}
def test_happy_path(client: TestClient) -> None:
mock = _override_service(_make_result())
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 200
data = resp.json()
assert data["model"] == "gemini-test"
assert len(data["suggestions"]) == 1
s = data["suggestions"][0]
assert s["op"] == "replace"
assert s["word_ids"] == ["w3"]
assert s["new_text"] == "chlorine"
assert data["warnings"] == ["dropped suggestion 3: out of range"]
assert data["settings_applied"]["suggest_adlib_removal"] is True
mock.suggest.assert_called_once()
def test_settings_passed_through(client: TestClient) -> None:
mock = _override_service(_make_result([]))
resp = client.post(
"/api/review/test-job/auto-correct",
json={**BODY, "settings": {"suggest_adlib_removal": False, "min_confidence": 0.8}},
)
assert resp.status_code == 200
settings = mock.suggest.call_args.kwargs["settings"]
assert settings.suggest_adlib_removal is False
assert settings.min_confidence == 0.8
def test_invalid_settings_400(client: TestClient) -> None:
_override_service(_make_result([]))
resp = client.post(
"/api/review/test-job/auto-correct",
json={**BODY, "settings": {"bogus_knob": True}},
)
assert resp.status_code == 400
assert "invalid settings" in resp.json()["detail"]
def test_no_references_422_propagates(client: TestClient) -> None:
_override_service(AutoCorrectServiceError("no reference lyrics", status_code=422))
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 422
def test_model_failure_502_propagates(client: TestClient) -> None:
_override_service(AutoCorrectServiceError("AI model call failed", status_code=502))
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 502
def test_missing_body_fields_422(client: TestClient) -> None:
_override_service(_make_result([]))
resp = client.post("/api/review/test-job/auto-correct", json={"segments": []})
assert resp.status_code == 422 # reference_lyrics is required
+21 -22
View File
@@ -241,10 +241,10 @@ class TestYouTubeDownloadErrorHandling:
assert "Remote download failed" in str(exc.value)
@pytest.mark.asyncio
async def test_invalid_youtube_url_raises_clear_error(self):
async def test_download_without_flacfetch_raises_clear_error(self):
"""
When given an invalid YouTube URL (no video ID extractable),
should raise a clear error.
With no flacfetch configured, download must fail clearly (no local
yt-dlp fallback on Cloud Run).
"""
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -261,11 +261,11 @@ class TestYouTubeDownloadErrorHandling:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="not-a-valid-youtube-url",
url="https://youtu.be/abcDEF12345",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
class TestRemoteVsLocalDownload:
@@ -306,13 +306,20 @@ class TestRemoteVsLocalDownload:
assert "uploads/job_test/audio/" in result
@pytest.mark.asyncio
async def test_local_download_when_remote_not_configured(self):
async def test_non_youtube_url_uses_generic_url_source(self):
"""
When FLACFETCH_API_URL is not configured, should fall back to local.
A non-YouTube URL is routed through flacfetch's generic 'URL' source.
"""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_test/audio/test.m4a",
})
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
return_value=mock_client
):
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -321,18 +328,10 @@ class TestRemoteVsLocalDownload:
reset_youtube_download_service()
service = YouTubeDownloadService()
assert service.is_remote_enabled() is False
sc_url = "https://soundcloud.com/forss/flickermood"
result = await service.download(url=sc_url, job_id="job_test")
# Mock the local download to avoid actually calling yt_dlp
with patch.object(
service, '_download_local',
new_callable=AsyncMock,
return_value="uploads/job/audio/test.wav"
) as mock_local:
result = await service.download(
url="https://youtu.be/abcDEF12345",
job_id="job_test",
)
mock_local.assert_called_once()
assert result == "uploads/job/audio/test.wav"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == sc_url
assert "uploads/job_test/audio/" in result
Whitespace-only changes.
@@ -0,0 +1,169 @@
"""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
return resp
with patch.object(
service.settings, "auto_correct_compare_models", compare_models_env
), patch.object(
service.settings, "auto_correct_model", single_model
), 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,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,279 @@
"""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):
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": []}) as anth, \
patch.object(service, "_call_gemini", return_value={"suggestions": []}) 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()
result = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
assert result == {"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")
+5 -55
View File
@@ -241,31 +241,14 @@ class TestUserEmailExtraction:
class TestUrlJobWorkerSequencing:
"""
Issue 2: YouTube URL download race condition.
URL job worker triggering.
Root cause: Both audio and lyrics workers were triggered in parallel.
For URL jobs, lyrics worker would timeout waiting for audio to download.
These tests verify that URL jobs trigger workers sequentially.
URL jobs are now downloaded by the flacfetch service in create_from_url
BEFORE any worker runs, so `input_media_gcs_path` is already set and both
workers can start in parallel (no sequential audio→lyrics handoff, no local
yt-dlp fallback in the worker).
"""
@pytest.mark.asyncio
async def test_url_job_triggers_only_audio_worker_initially(self):
"""
create-from-url must only trigger audio worker, not lyrics worker.
The audio worker will trigger lyrics after download completes.
"""
from backend.api.routes.file_upload import _trigger_audio_worker_only
with patch('backend.api.routes.file_upload.worker_service') as mock_ws:
mock_ws.trigger_audio_worker = AsyncMock()
mock_ws.trigger_lyrics_worker = AsyncMock()
await _trigger_audio_worker_only("test-job-id")
mock_ws.trigger_audio_worker.assert_called_once_with("test-job-id")
mock_ws.trigger_lyrics_worker.assert_not_called()
@pytest.mark.asyncio
async def test_parallel_worker_triggers_both_workers(self):
"""
@@ -284,39 +267,6 @@ class TestUrlJobWorkerSequencing:
mock_ws.trigger_audio_worker.assert_called_once_with("test-job-id")
mock_ws.trigger_lyrics_worker.assert_called_once_with("test-job-id")
@pytest.mark.asyncio
async def test_audio_worker_triggers_lyrics_after_url_download(self):
"""
Audio worker must trigger lyrics worker after successful URL download.
"""
from backend.workers.audio_worker import _trigger_lyrics_worker_after_url_download
# Mock at the source module where it's imported from
with patch('backend.services.worker_service.get_worker_service') as mock_get_ws:
mock_ws = Mock()
mock_ws.trigger_lyrics_worker = AsyncMock()
mock_get_ws.return_value = mock_ws
await _trigger_lyrics_worker_after_url_download("test-job-id")
mock_ws.trigger_lyrics_worker.assert_called_once_with("test-job-id")
@pytest.mark.asyncio
async def test_audio_worker_lyrics_trigger_handles_errors_gracefully(self):
"""
If lyrics worker trigger fails, audio processing should continue.
"""
from backend.workers.audio_worker import _trigger_lyrics_worker_after_url_download
# Mock at the source module where it's imported from
with patch('backend.services.worker_service.get_worker_service') as mock_get_ws:
mock_ws = Mock()
mock_ws.trigger_lyrics_worker = AsyncMock(side_effect=Exception("Network error"))
mock_get_ws.return_value = mock_ws
# Should not raise exception
await _trigger_lyrics_worker_after_url_download("test-job-id")
class TestAudioSearchCacheIndependence:
"""
+43 -98
View File
@@ -780,61 +780,16 @@ class TestAudioWorkerModelConfiguration:
assert call_kwargs['other_stems_models'] == []
class TestDownloadFromUrl:
"""Tests for download_from_url function - URL-based audio download."""
def test_download_from_url_function_exists(self):
"""Test that download_from_url function exists in audio_worker."""
from backend.workers.audio_worker import download_from_url
assert callable(download_from_url)
def test_download_from_url_signature(self):
"""Test that download_from_url has the expected signature."""
import inspect
from backend.workers.audio_worker import download_from_url
sig = inspect.signature(download_from_url)
params = list(sig.parameters.keys())
# Should have these parameters
assert 'url' in params
assert 'temp_dir' in params
assert 'artist' in params
assert 'title' in params
assert 'job_manager' in params
assert 'job_id' in params
def test_download_from_url_is_async(self):
"""Test that download_from_url is an async function."""
import inspect
from backend.workers.audio_worker import download_from_url
assert inspect.iscoroutinefunction(download_from_url)
@pytest.mark.asyncio
async def test_download_from_url_returns_none_for_invalid_url(self):
"""Test that download_from_url handles errors gracefully."""
from backend.workers.audio_worker import download_from_url
with tempfile.TemporaryDirectory() as temp_dir:
# This should fail gracefully (no yt-dlp in test env or invalid URL)
result = await download_from_url(
url='not-a-valid-url',
temp_dir=temp_dir,
artist='Test',
title='Test'
)
# Should return None on error (graceful failure)
assert result is None
class TestDownloadAudioWithUrl:
"""Tests for download_audio function with URL-based jobs."""
"""Tests for download_audio: it only ever consumes a pre-downloaded GCS file.
URLs are downloaded by the flacfetch service in create_job_from_url before
any worker runs — the audio worker never runs yt-dlp on Cloud Run.
"""
@pytest.fixture
def mock_job_with_url(self):
"""Create a mock job with a URL."""
"""A URL job that (incorrectly) reached the worker without a GCS path."""
return Job(
job_id="test123",
status=JobStatus.PROCESSING,
@@ -844,7 +799,7 @@ class TestDownloadAudioWithUrl:
title="Test Song",
url="https://www.youtube.com/watch?v=test123"
)
@pytest.fixture
def mock_job_manager(self, mock_job_with_url):
"""Create a mock JobManager."""
@@ -852,40 +807,34 @@ class TestDownloadAudioWithUrl:
manager.get_job.return_value = mock_job_with_url
manager.update_job.return_value = None
return manager
@pytest.fixture
def mock_storage(self):
"""Create a mock StorageService."""
storage = MagicMock()
return storage
@pytest.mark.asyncio
async def test_download_audio_from_url(self, mock_job_with_url, mock_job_manager, mock_storage):
"""Test download_audio routes to URL download when job has URL."""
with patch('backend.workers.audio_worker.download_from_url', return_value='/tmp/test.wav') as mock_download:
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Should have called download_from_url
mock_download.assert_called_once()
# Check positional args
args = mock_download.call_args[0]
assert args[0] == "https://www.youtube.com/watch?v=test123" # url
assert args[1] == temp_dir # temp_dir
assert args[2] == "Test Artist" # artist
assert args[3] == "Test Song" # title
async def test_download_audio_url_without_gcs_path_refuses(self, mock_job_with_url, mock_job_manager, mock_storage):
"""A URL job with no GCS file must fail (no local yt-dlp fallback)."""
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Refuses to download locally → returns None, never touches storage
assert result is None
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_download_audio_from_gcs_when_no_url(self, mock_job_manager, mock_storage):
"""Test download_audio downloads from GCS when job has no URL."""
async def test_download_audio_from_gcs(self, mock_job_manager, mock_storage):
"""Test download_audio downloads from GCS when input_media_gcs_path is set."""
mock_job_no_url = Job(
job_id="test123",
status=JobStatus.PROCESSING,
@@ -895,24 +844,20 @@ class TestDownloadAudioWithUrl:
title="Test Song",
input_media_gcs_path="uploads/test123/song.flac"
)
with patch('backend.workers.audio_worker.download_from_url') as mock_url_download:
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_no_url,
job_manager_instance=mock_job_manager
)
# Should NOT have called download_from_url
mock_url_download.assert_not_called()
# Should have called storage.download_file
mock_storage.download_file.assert_called()
from backend.workers.audio_worker import download_audio
with tempfile.TemporaryDirectory() as temp_dir:
await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_no_url,
job_manager_instance=mock_job_manager
)
# Should have downloaded the pre-existing GCS file
mock_storage.download_file.assert_called()
class TestBackingVocalsAnalysis:
+24 -26
View File
@@ -4,7 +4,6 @@ Unit tests for YouTubeDownloadService.
Tests the consolidated YouTube download service that handles all YouTube
downloads in the cloud backend.
"""
import os
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -179,43 +178,42 @@ class TestYouTubeDownloadService:
assert "Remote download failed" in str(exc.value)
# =========================================================================
# Local Fallback Tests
# Generic (non-YouTube) URL Tests
# =========================================================================
@pytest.mark.asyncio
async def test_download_falls_back_to_local_when_remote_disabled(self):
"""When remote not configured, should use local yt_dlp."""
mock_storage = MagicMock()
mock_storage.upload_fileobj = MagicMock()
mock_file_handler = MagicMock()
mock_file_handler.download_video = MagicMock(return_value="/tmp/test.webm")
mock_file_handler.convert_to_wav = MagicMock(return_value="/tmp/test.wav")
async def test_download_generic_url_uses_url_source(self):
"""Non-YouTube URLs route through flacfetch's generic 'URL' source."""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job123/audio/Artist - Title.m4a",
})
fb_url = "https://www.facebook.com/share/v/1EnC8Bi5Uq/"
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
), patch(
'backend.services.youtube_download_service.StorageService',
return_value=mock_storage
), patch(
'backend.services.youtube_download_service.YouTubeDownloadService._download_local',
new_callable=AsyncMock,
return_value="uploads/job123/audio/test.wav"
) as mock_local:
return_value=mock_client
):
service = YouTubeDownloadService()
result = await service.download(
url="https://youtu.be/dQw4w9WgXcQ",
url=fb_url,
job_id="job123",
artist="Artist",
title="Title",
)
assert result == "uploads/job123/audio/test.wav"
mock_local.assert_called_once()
assert result == "uploads/job123/audio/Artist - Title.m4a"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == fb_url
assert call_kwargs["source_id"] == fb_url
@pytest.mark.asyncio
async def test_download_invalid_url_raises_error(self):
"""Should raise error for URLs that can't extract video ID."""
async def test_download_raises_when_remote_not_configured(self):
"""No silent local fallback: hard-fail when flacfetch isn't configured."""
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None
@@ -224,11 +222,11 @@ class TestYouTubeDownloadService:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="https://vimeo.com/123456",
url="https://youtu.be/dQw4w9WgXcQ",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
# =========================================================================
# Singleton Tests
+21 -197
View File
@@ -21,9 +21,7 @@ import shutil
import tempfile
import time
from typing import Optional, Dict, Any
from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
@@ -40,29 +38,6 @@ from karaoke_gen.audio_processor import AudioProcessor
logger = logging.getLogger(__name__)
async def _trigger_lyrics_worker_after_url_download(job_id: str) -> None:
"""
Trigger lyrics worker after URL audio download completes.
For URL jobs, we use sequential triggering:
1. Audio worker downloads and uploads audio to GCS
2. Audio worker triggers lyrics worker (this function)
3. Both workers then proceed in parallel (audio separation + lyrics transcription)
This prevents the race condition where lyrics worker times out waiting for audio.
"""
from backend.services.worker_service import get_worker_service
try:
worker_service = get_worker_service()
await worker_service.trigger_lyrics_worker(job_id)
logger.info(f"Job {job_id}: Triggered lyrics worker after URL download")
except Exception as e:
# Log but don't fail - audio processing can still continue
# The job will eventually timeout if lyrics worker doesn't run
logger.error(f"Job {job_id}: Failed to trigger lyrics worker: {e}")
# Default ensemble presets — resolved by audio-separator package into models + algorithm.
# To change models, update ensemble_presets.json in audio-separator and release a new version.
DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean" # Fv7z + Resurrection, SDR ~17.5
@@ -80,126 +55,6 @@ AUDIO_WORKER_LOGGERS = [
]
async def download_from_url(url: str, temp_dir: str, artist: str, title: str, job_manager: JobManager = None, job_id: str = None) -> Optional[str]:
"""
Download audio from a URL using local yt_dlp.
IMPORTANT: This is a LEGACY FALLBACK for non-YouTube URLs only!
For YouTube URLs, use YouTubeDownloadService instead, which:
- Uses remote flacfetch when configured (avoids Cloud Run bot detection)
- Has proper error handling and GCS upload
This function uses local yt_dlp and will likely FAIL for YouTube URLs
on Cloud Run due to bot detection (YouTube blocks Cloud Run IP ranges).
Uses the FileHandler from karaoke_gen which includes:
- Anti-detection options (user agent, headers, delays)
- Cookie support for authenticated downloads
- Retry logic
If artist and/or title are not provided, attempts to extract them from
the URL metadata.
Args:
url: URL to download from (NOT recommended for YouTube - use YouTubeDownloadService)
temp_dir: Temporary directory to save to
artist: Artist name for filename (can be None for auto-detection)
title: Song title for filename (can be None for auto-detection)
job_manager: Optional JobManager to update job with detected metadata
job_id: Optional job ID to update
Returns:
Path to downloaded audio file, or None if failed
"""
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler instance
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
)
# Try to extract metadata if artist or title not provided
if not artist or not title:
logger.info(f"Extracting metadata from URL: {url}")
metadata = file_handler.extract_metadata_from_url(url)
if metadata:
if not artist:
artist = metadata.get('artist', 'Unknown')
logger.info(f"Auto-detected artist: {artist}")
if not title:
title = metadata.get('title', 'Unknown')
logger.info(f"Auto-detected title: {title}")
# Update job with detected metadata if job_manager provided
if job_manager and job_id:
update_data = {}
if artist:
update_data['artist'] = artist
if title:
update_data['title'] = title
if update_data:
job_manager.update_job(job_id, update_data)
logger.info(f"Updated job {job_id} with detected metadata")
else:
logger.warning("Could not extract metadata from URL, using defaults")
artist = artist or "Unknown"
title = title or "Unknown"
# Create output filename (without extension)
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(temp_dir, f"{safe_artist} - {safe_title}")
# Get YouTube cookies from environment variable if available
# This helps bypass "Sign in to confirm you're not a bot" errors
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for download authentication")
else:
logger.info("No YOUTUBE_COOKIES env var set - attempting download without cookies")
# Download using FileHandler (includes anti-detection features)
logger.info(f"Downloading from URL: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if downloaded_file and os.path.exists(downloaded_file):
logger.info(f"Downloaded video: {downloaded_file}")
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if wav_file and os.path.exists(wav_file):
logger.info(f"Converted to WAV: {wav_file}")
return wav_file
else:
logger.error("WAV conversion failed")
return None
else:
logger.error("Download failed - no file returned")
return None
except ImportError as e:
logger.error(f"Import error: {e}. Check karaoke_gen installation.")
return None
except Exception as e:
logger.error(f"Failed to download from URL {url}: {e}", exc_info=True)
return None
def create_audio_processor(
temp_dir: str,
model_file_dir: Optional[str] = None,
@@ -543,12 +398,16 @@ async def download_audio(
job_manager_instance: JobManager = None
) -> Optional[str]:
"""
Download or fetch audio file to local temp directory.
Handles two cases:
1. Uploaded file: Download from GCS using input_media_gcs_path
2. URL (YouTube, etc.): Download using yt-dlp or other tools
Fetch the job's audio file from GCS to a local temp directory.
All inputs are expected to already be in GCS by the time this worker runs:
- Uploaded files: at input_media_gcs_path
- URL jobs: downloaded by the flacfetch service in create_job_from_url
before any worker is triggered
This worker never downloads from a URL itself (no yt-dlp on Cloud Run); a
URL job arriving without a GCS file is treated as an upstream bug.
Args:
job_id: Job ID
temp_dir: Temporary directory to save to
@@ -594,55 +453,20 @@ async def download_audio(
logger.info(f"Job {job_id}: Downloaded audio from GCS: {input_url}")
return local_path
# Case 3: Fresh URL that needs downloading (legacy fallback)
# NOTE: YouTube URLs should be downloaded by YouTubeDownloadService in file_upload.py
# BEFORE triggering this worker. If we reach here with a YouTube URL, it means
# the download was not done upfront, which will likely fail due to bot detection.
# A URL job that reached this worker WITHOUT a pre-downloaded GCS file is
# an upstream bug: all URLs are downloaded by the flacfetch service in
# create_job_from_url before any worker runs. We never run yt-dlp on
# Cloud Run, so there is no local fallback — fail clearly instead.
if job.url:
# Check if this is a YouTube URL that should have been handled earlier
is_youtube = any(domain in job.url.lower() for domain in ['youtube.com', 'youtu.be'])
if is_youtube:
logger.warning(
f"Job {job_id}: YouTube URL reached download_audio() fallback. "
"This may fail due to bot detection. YouTube URLs should be "
"downloaded via YouTubeDownloadService before triggering workers."
)
logger.info(f"Job {job_id}: Downloading from URL: {job.url}")
# Use provided job_manager or create new one
jm = job_manager_instance or JobManager()
local_path = await download_from_url(
job.url,
temp_dir,
job.artist,
job.title,
job_manager=jm,
job_id=job_id
logger.error(
f"Job {job_id}: URL job reached the audio worker without a "
f"downloaded input_media_gcs_path (url={job.url}). URLs must be "
"fetched via the flacfetch service before processing; refusing to "
"download locally."
)
return None
if local_path and os.path.exists(local_path):
# Upload to GCS and update job
gcs_path = f"jobs/{job_id}/input/{os.path.basename(local_path)}"
url = storage.upload_file(local_path, gcs_path)
# Update job with GCS path for lyrics worker
jm.update_job(job_id, {'input_media_gcs_path': gcs_path})
jm.update_file_url(job_id, 'input', 'audio', url)
logger.info(f"Job {job_id}: Downloaded and uploaded audio to GCS: {gcs_path}")
# For URL jobs, trigger lyrics worker now that audio is available
# This is the sequential trigger pattern - audio first, then lyrics
await _trigger_lyrics_worker_after_url_download(job_id)
return local_path
else:
logger.error(f"Job {job_id}: Failed to download from URL: {job.url}")
return None
logger.error(f"Job {job_id}: No input source found (no GCS path, file_urls, or URL)")
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
return None
except Exception as e:
+71
View File
@@ -545,6 +545,77 @@ 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": false
}
}
```
Opt-in, user-triggered AI correction suggestions for the lyrics review UI.
Stateless: one whole-song LLM call per model (default model from
`AUTO_CORRECT_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.
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-fable-5", "gemini-3.1-pro-preview"],
"consensus": 2,
"total_models": 2,
"conflict_group": null
}
],
"model": "claude-fable-5, gemini-3.1-pro-preview",
"elapsed_seconds": 27.4,
"settings_applied": { "suggest_adlib_removal": true, "allow_insertions": true, "min_confidence": 0.0 },
"warnings": []
}
```
`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,78 @@
# Prompt: Audit karaoke-gen for legacy "fallback" logic
**Purpose:** A lot of this codebase was written by an earlier LLM that, when
unsure what should happen in some situation, tended to invent a silent
*fallback* path rather than (a) asking the human what the desired behaviour was,
or (b) failing loudly with a clear error. These fallbacks hide bugs: the system
appears to "work" while doing the wrong thing, and the real failure only surfaces
much later (or never).
**Motivating example (2026-06-08):** A job submitted from a Facebook share URL
failed with a generic `Failed to download audio file`. The non-YouTube URL path
silently fell back to running yt-dlp *locally inside the Cloud Run container*,
which then died in a buggy `convert_to_wav` (ffmpeg given both `-y` and `-n`).
The download had actually succeeded — the fallback path was both unintended
(flacfetch was supposed to be the sole downloader) and broken. See
`docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md` (workspace root) and
the memory note `project_flacfetch_sole_downloader`. The fix deleted the
fallback rather than patching it.
## Your task
Systematically find every "fallback" in karaoke-gen, and for each one bring it to
the user (Andrew) with a crisp question about intended behaviour. Do **not**
change any behaviour without his answer — fallbacks sometimes ARE the right call
(e.g. graceful degradation of an optional feature). The goal is to make each one
an explicit, intentional decision.
### 1. Discover candidates (cast a wide net)
Search code, comments, docstrings, and docs. Suggested sweeps (run several):
- Literal: `rg -in "fallback|fall back|fall-back" backend/ karaoke_gen/ frontend/`
- Intent words near logic: `rg -in "best effort|best-effort|silently|swallow|ignore (the )?error|just in case|legacy|deprecated path|for now|TODO|HACK|workaround"`
- Defensive swallowing: `except Exception` / bare `except:` that `pass`, `return None`, `return`, or log-and-continue without re-raising.
- Silent defaults: `\.get\(.*,\s*['\"]?(unknown|default|none)` style, `or "Unknown"`, `or {}`, env-var defaults that mask misconfiguration.
- "If not configured, do X instead" branches (the most dangerous class — like the yt-dlp one).
- Try-import / optional-dependency fallbacks that change behaviour rather than failing.
Record each candidate with `file:line`, a one-line description, and which class
it falls into.
### 2. Triage each candidate
For each, classify and note evidence:
- **A — Legitimate graceful degradation** (optional feature, clearly intended, fails safe and visible). Likely keep; confirm it's logged/observable.
- **B — Silent fallback masking a bug / misconfiguration** (like the yt-dlp case). Candidate for: delete, or convert to fail-fast with a clear error.
- **C — Ambiguous** — needs the user's intent.
Don't trust comments that *say* a path is a safe fallback — verify what actually
happens when it triggers (what does the user see? does the job silently produce
wrong output?).
### 3. Interview the user
Present findings grouped by class, B and C first. For each B/C item ask a
focused question, e.g.:
> `audio_worker.py:NN` falls back to <X> when <Y>. Today that means <observable
> consequence>. Should this (a) fail loudly with a clear error, (b) keep the
> fallback but log/alert, or (c) something else?
Batch related items. Capture his answers as direct quotes in a plan doc
(`docs/archive/YYYY-MM-DD-fallback-audit-plan.md`) — he values verbatim
decisions.
### 4. Execute
Implement the agreed changes in small, reviewable PRs (one logical area each),
with tests. Prefer fail-fast + clear error messages over silent fallbacks.
Update `docs/LESSONS-LEARNED.md` with the principle and notable examples.
## Guardrails
- This is an audit, not a rewrite — minimise behaviour change until the user
decides per item.
- Some "fallbacks" are load-bearing; deleting blindly will cause incidents.
- Pay special attention to anything touching: audio/lyrics download, payment,
job state transitions, and worker triggering — silent wrong behaviour there is
most costly.
@@ -0,0 +1,264 @@
# Lyrics Auto-Correction Re-Evaluation & Design Plan
**Date:** 2026-06-10
**Branch:** `feat/sess-20260610-2332-lyrics-auto-correction`
**Status:** Research complete, design proposed, awaiting Andrew's decisions on open questions
## 1. Why we're revisiting this
Auto-correction has been attempted and abandoned multiple times over 2 years. As of
PR #321 (Jan 20, 2026), **all auto-correction is disabled** (`SKIP_CORRECTION=true`):
raw AudioShake transcription goes straight to human review, with anchor/gap analysis
still computed for reviewer guidance (anchors preserved by commits 60baca42/414606e5).
New frontier models (e.g. Claude Fable 5, released 2026-06-09) are dramatically more
capable at exactly this task shape: long-context, multilingual, audio-capable,
structured-output reasoning over messy text. The proposal: reintroduce correction as a
**fully optional, user-triggered, transparent suggestion layer in the review UI** —
never silently applied, every change individually accept/undo-able.
## 2. Why past attempts failed (evidence from git/docs history)
Three compounding killers, all documented in `docs/archive/` and LESSONS-LEARNED.md:
1. **Pipeline blocking + latency.** Agentic correction ran *inside* the job pipeline,
one LLM call per gap (10–30s × 20–74 gaps = 5–37 min). Even after optimization
(~55s/20 gaps, PR around 2026-01-08) it added minutes and required timeout
band-aids (PR #149) that silently skipped correction anyway.
2. **Net-negative accuracy.** From PR #321: *"auto-correction was creating more work
for reviewers by introducing errors that needed manual correction."* Both rule
handlers and Gemini-Flash-per-gap corrections applied changes silently, so every
wrong correction was invisible work added.
3. **Operational fragility.** Gemini 2→3 breaking changes (location=global, multimodal
response format, 2025-12-30 doc), silent hangs, Langfuse/OTEL leakage.
Key insight: **the failures were architectural, not fundamental.** Per-gap calls with
tiny context windows, applied silently, in the critical path. None of those three
properties is necessary in 2026.
## 3. Evidence from 30 real production jobs
Dataset: `/Users/andrew/Projects/nomadkaraoke/lyrics-alignment-eval-dataset/` (built
2026-05-18 from GCS for the forced-alignment eval; 30 jobs, each with
`corrections.json` = state served to review UI, `corrections_updated.json` = human
ground truth, plus `vocals.flac` stem and reference-source metadata).
Analysis script: `analyze_human_edits.py` (added this session, same dir).
### Aggregate (word-level diff, pre- vs post-human-review)
- **9,877 words total; 10.0% text-edited** — 825 replaced, 153 deleted, 13 inserted
- Median job ~7% edits; range 0.4% (Juanes) to 45% (Saetia screamo)
- **Timing-only edits are rare**: ~1% of unchanged words, excluding one full-resync
job (568d4317, 100% = global re-sync) and one partial (9229d13c, 5%)
- Reference quality predicts edit volume: jobs with best-source Jaccard ≥0.9 cluster
at low edit rates; the heavy-rewrite jobs (Saetia 0.894-but-screamo, Bathory 0.693,
Playa Fly 0.448) are where transcription hallucinated against noisy/extreme vocals
### Edit taxonomy (from sampled diffs)
| Category | Examples | Auto-correctable? |
|---|---|---|
| Sound-alike mishearings (dominant) | `glory`→`chlorine`, `ladder`→`matter`, `sell`→`sail`, `reincarnation`→`red carnation`, `Recht`→`Reich` | ✅ trivial with reference in context |
| Repeated chorus errors (same fix ×12) | `Hold it up`→`Holding out` ×12 (Parcels) | ✅ one decision, propagate |
| Contractions / inflections | `Won`→`Won't`, `burn,`→`burned,`, `I'll`→`I'd` | ✅ |
| Adlib/backing-vocal deletions | `(oh- oh- oh- oh)` deleted, `(Welcome to the camp)` deleted | ✅ with policy guidance |
| Censoring style | `Nigga,`→`N****,` | ✅ but needs explicit user-preference setting |
| Hallucinated lines (extreme vocals) | whole-line rewrites in Saetia/Bathory | ⚠️ possible with reference + audio, lower confidence |
| Non-English | German (Söhne Mannheims), French (Naika), Spanish (Juanes) | ✅ modern models are strongly multilingual |
| Full re-sync | Playa Fly timing offset | ❌ out of scope — keep tap-to-sync |
**Context size check:** a 78-segment song + 3 reference sources ≈ 10KB compact text
≈ 3K tokens. Whole-song single-call correction is trivially cheap (cents) and fast
(one ~10–30s call) vs the old 74-sequential-calls design.
## 4. Proposed approach: opt-in "AI Suggest" in the review UI
### Product shape
- A button in the lyrics review screen (e.g. in Header or above TranscriptionView):
**"Suggest corrections (AI)"**. Nothing runs unless clicked. Zero change to the
default journey.
- On click: backend endpoint makes **one whole-song LLM call** with: compact
transcription (segments + words, ids preserved), all reference lyrics, anchor/gap
annotations, artist/title, and explicit conservative instructions (only suggest
when audio-plausible AND reference-supported; never invent).
- Response: list of proposed changes in `WordCorrection` shape (word_id-keyed,
with `reason`, `confidence`, `source`).
- **Suggestions are a pending layer** — `corrected_segments` is NOT mutated until
the user accepts. UI shows each suggestion inline (reuse the existing
`CorrectedWordWithActions` accept/revert/edit/detail affordance + correction
tooltips + `CorrectionDetailCard`), plus a summary bar: "23 suggestions —
Accept all / Reject all / step through".
- Every accept/reject lands in the existing **history stack** (undo works) and
**EditLog** (`operation: 'ai_suggestion_accept' | 'ai_suggestion_reject'`),
which doubles as labeled training/eval data accruing from day one.
### Why this fixes each historical killer
| Past killer | This design |
|---|---|
| Pipeline blocking/latency | On-demand in review UI; user watches a progress state for one call; job pipeline untouched |
| Silently introduced errors | Nothing applied without explicit accept; wrong suggestions cost one click, not invisible rework |
| Per-gap myopia | Whole-song context: chorus repetition, reference alignment, song-level consistency in one shot |
| Provider fragility | Single thin endpoint, structured output, easy to swap models; failure = "no suggestions", never a stuck job |
| No trust measurement | Accept-rate per suggestion category measured from EditLog; promotion to default someday is a data decision |
### Architecture sketch
1. **Backend** — `POST /api/review/{job_id}/auto-correct` (follows the
custom-lyrics endpoint pattern, `backend/api/routes/review.py`). Loads current
correction data (or accepts the client's current working state in the request
body so it reflects in-session edits), builds compact prompt, calls model,
validates word_ids, returns `{suggestions: WordCorrection[], model, warnings}`.
2. **Frontend** — new state in `LyricsAnalyzer`: `pendingSuggestions`. Word
rendering already supports correction highlighting; generalize the
`handler === 'AgenticCorrector'` gate in `HighlightedText.tsx` (lines ~200, ~301)
to a pending-suggestion check. Add summary/navigation bar (pattern:
`GapNavigator`).
3. **Model layer** — reuse `correction/agentic/providers/` LangChain bridge
(already supports Vertex Gemini, Anthropic, OpenAI, Ollama) or a simpler direct
client; structured output schema = list of word-id-keyed operations
(replace/delete/insert-after, new text, reason, confidence).
4. **Eval harness (build FIRST)** — script over the 30-job dataset: feed
`corrections.json`, generate suggestions, score against the human diff from
`corrections_updated.json`. Metrics: **precision** (would the human have made
this change?) and **recall** (% of human edits reproduced). Precision is the
north star — a low-recall/high-precision assistant is still a big win; the
reverse destroys trust (that's what happened before).
### Phasing
- **Phase 0:** Eval harness + prompt iteration offline against the 30-job dataset.
Compare models (Fable 5 / Opus 4.8 / Gemini) and prompt variants. Gate: precision
target agreed with Andrew (suggest ≥90% before shipping even as opt-in).
- **Phase 1:** Backend endpoint + minimal UI (button → suggestions → accept/reject
individually + accept-all). Ship to prod behind the button (it IS the flag).
- **Phase 2:** UX polish: category grouping (mishearings / deletions / formatting),
propagate-identical-fix grouping, per-suggestion audio play button (segment
playback already exists).
- **Phase 3 (experiment):** attach vocals stem audio for low-confidence gaps —
models now accept audio input; dataset already has `vocals.flac` per job to eval
this offline.
- **Someday:** auto-apply-by-default, only when prod accept-rate data earns it.
## 4b. Phase 0 results (2026-06-11): 5-model eval over all 30 jobs
Harness: `lyrics-alignment-eval-dataset/auto-correct-eval/harness.py`; results in
`auto-correct-eval/results/*.json`. One whole-song call per job; suggestions
scored against the human ground-truth diff. *Strict* = same span + same
normalized text as the human edit; *region* = touches a span the human also
edited; *gap_closed* = how much of the pre→truth distance accept-all closes.
| model | prec strict | prec region | recall strict | recall region | mean gap closed | median gap | harmful jobs | median latency |
|---|---|---|---|---|---|---|---|---|
| claude-fable-5 | **0.615** | 0.862 | **0.511** | 0.696 | **+0.505** | +0.77 | 2 | 27s |
| claude-opus-4-8 | **0.627** | **0.897** | 0.336 | 0.466 | +0.475 | +0.58 | 2 | 29s |
| gemini-3.1-pro-preview | 0.556 | 0.860 | 0.464 | 0.717 | +0.499 | +0.67 | 3 | 35s |
| gpt-5.5 | 0.442 | 0.832 | 0.357 | **0.726** | +0.502 | **+0.80** | 2 | 63s |
| claude-sonnet-4-6 | 0.209 | 0.710 | 0.174 | 0.632 | +0.091 | +0.34 | 4 | 14s |
| gpt-5.2 | 0.153 | 0.603 | 0.138 | 0.587 | **−0.796** | +0.24 | 11 | 11s |
Notes:
- GPT-5.5 (added after the first pass — it wasn't visible to the original
API key's project) lands in the top tier on outcome quality (best median
gap-closed, best region recall) but with the lowest strict precision of
the tier and ~2× the latency (median 63s). GPT-5.2 actively damages
lyrics in accept-all simulation — it would have repeated the 2025 failure.
Sonnet 4.6 is also below the bar. **Fable 5, Opus 4.8, Gemini 3.1 Pro and
GPT-5.5 are the viable tier**; the default-model decision below is
unchanged by the GPT-5.5 result (slower, less precise, new billing
surface). gpt-5.5-pro requires the OpenAI Responses API and wasn't
evaluated.
- "Harmful jobs" are almost all near-perfect transcriptions (e.g. Townes Van
Zandt: 1 human edit in 198 words) where the model proposes
reference-supported style tweaks (`all right`→`alright`, adding a leading
"And") that the human didn't bother making — mostly acceptable-or-one-click
suggestions, not hallucinations. Strict precision therefore *underestimates*
real-world accept rate; prod accept-rate from the EditLog is the metric that
matters.
- Confidence is well calibrated (style tweaks 0.55–0.6, real fixes 0.8+), so
the min-confidence knob meaningfully trades recall for precision.
- Cost ≈ $0.05–0.18/job depending on model. Latency 27–35s for the top tier.
**Decision: v1 default `AUTO_CORRECT_MODEL=gemini-3.1-pro-preview`** — within
noise of Fable 5 on gap-closed (0.499 vs 0.505), best region recall, already
served via Vertex AI in this GCP project (same path as custom-lyrics), no new
secret/billing surface. Fable 5 is the quality ceiling (best strict
recall/balance); switching is a one-env-var change and worth revisiting once
prod accept-rate data exists or if an Anthropic key is added to Secret Manager.
## 4c. Decisions captured from Andrew (2026-06-11)
1. **Models**: test Fable 5 + a cheaper Claude + latest GPT + latest Gemini Pro
— done (table above).
2. **Scope**: text-only v1 agreed. Later: simple *heuristics* (not LLM) for
timing pathologies — e.g. AudioShake leaving an unrealistically long last
word on a segment, or transcribing a 10+ second instrumental as one long
"And"/"But". Future work.
3. **Knobs**: user-facing with sensible defaults → implemented
(adlib-removal toggle, insertions toggle, confidence filter).
4. **No-reference songs**: button disabled with explanation (backend also 422s).
Future experiment (separate plan doc someday): enrich context via audio
analysis (genre/theme/key/energy), music-matching APIs and web research to
review transcriptions without references.
5. **Precision gate**: "depends how you measure" — strict precision is the
conservative floor (0.56–0.63 for the top tier), region precision 0.86–0.90.
Shipped as fully opt-in suggestions; prod accept-rate from EditLog
(`ai_suggestion_accept`/`reject` entries) becomes the real gate for any
future default-on behaviour.
## 4d. Follow-up shipped (2026-06-11, v0.178.0): Fable default + multi-model compare
Per Andrew's decisions after v0.177.0 shipped:
- **Default model switched to Claude Fable 5** (`AUTO_CORRECT_MODEL=claude-fable-5`
in the Cloud Run deploy). Anthropic provider path added to the service
(Anthropic API, structured outputs, adaptive thinking — same configuration
the eval used). Key lives in the `anthropic-api-key` secret (container
Pulumi-managed in `infrastructure/modules/secrets.py`, value added manually).
- **Multi-model compare mode** (Andrew's idea): `compare_models` setting
queries all of `AUTO_CORRECT_COMPARE_MODELS` (prod: Fable 5 + Gemini 3.1
Pro) in parallel, dedupes identical suggestions with a consensus count
(e.g. "2/2 models"), and groups conflicting overlapping suggestions —
accepting one variant rejects its siblings; accept-all picks the
highest-consensus variant per group. Partial model failures degrade to
warnings; all-fail → 502.
- **Gotcha for posterity**: the google-genai SDK mutates `response_schema`
dicts in place (injects `property_ordering`), which the Anthropic API
rejects — schemas must be deep-copied per provider call. Caught by the
real-call smoke test, now covered by a regression test.
## 5. Open questions for Andrew
1. **Model:** start with Claude Fable 5 (best reasoning, audio-capable) via the
existing Anthropic provider, or stay all-Google (Vertex Gemini 3) for billing
consolidation? Eval harness can score both — recommend deciding on data.
2. **Suggestion scope v1:** text-only (replace/delete/insert)? Timing edits are
~1% of human work and risky — recommend excluding from v1.
3. **Policy knobs:** adlib deletion and censoring are taste decisions — bake into
prompt defaults, or expose as settings like `CustomLyricsSettings` does
(allow_reword/strictness pattern)?
4. **No-reference behavior:** when no internet source matched (custom/niche songs),
suggestions are audio-only guesses — disable the button, or allow with a
warning?
5. **Precision gate:** what offline precision threshold before Phase 1 ships?
## 6. Key file references
- Correction types & pipeline: `karaoke_gen/lyrics_transcriber/types.py`
(`Word`, `LyricsSegment`, `WordCorrection`, `AnchorSequence`, `GapSequence`,
`CorrectionResult`), `correction/corrector.py`, `correction/anchor_sequence.py`
- Old agentic system (reusable provider layer): `correction/agentic/`
- Review API: `backend/api/routes/review.py` (`correction-data`, `complete`,
`custom-lyrics/generate` — the pattern to follow)
- Review UI: `frontend/components/lyrics-review/LyricsAnalyzer.tsx` (history/undo,
EditLog), `shared/HighlightedText.tsx`, `CorrectedWordWithActions.tsx`,
`CorrectionDetailCard.tsx`, `GapNavigator.tsx`,
`modals/CustomLyricsMode.tsx` (closest end-to-end LLM feature pattern)
- Frontend types: `frontend/lib/lyrics-review/types.ts`
- Eval dataset: `/Users/andrew/Projects/nomadkaraoke/lyrics-alignment-eval-dataset/`
(30 jobs; `analyze_human_edits.py` for the human-edit ground-truth diff)
- History: `docs/archive/2025-12-30-gemini3-agentic-correction-fix.md`,
`docs/archive/2025-12-31-agentic-timeout-implementation.md`,
`docs/archive/2026-01-08-performance-investigation.md`, PR #321 (disable), PR #149
(timeouts), PR #738 (custom lyrics LLM mode)
@@ -0,0 +1,160 @@
# Review-Phase Word-Timing Validation & Sanitization — Design
**Date:** 2026-06-10
**Status:** Approved (brainstorming) → ready for implementation plan
**Worktree:** `karaoke-gen-review-timing-validation` (`feat/sess-20260610-2307-review-timing-validation`)
## Background
Job `17f7c313` ("Atmosphere - Scalp") rendered two screens of lyrics overlapping. Root
cause: the segment `"A whiskey and a beer, let's forget where we are"` (segment bounds a
correct `15.18–18.04`) had its 4 leading words ("A whiskey and a") carrying invalid
timestamps `start=0.0, end=-0.005`. When the resizer split that line, the new line
inherited `start_time=0.0`, which mis-sorted the lyric screen ahead of the INTRO section
and stacked two screens.
We shipped a **render-time** safety net (`SegmentResizer._sanitize_segment_timings`,
v0.176.2, PR #804) that clamps invalid word timings into segment bounds while building the
ASS. That stops the visual overlap but does **not** fix the source: the bad data is created
and persisted during the lyrics review phase.
### Verified origin (not AudioShake)
- Base `corrections.json` (lyrics phase output) had **valid** timings for these words; 0
corrections touched them.
- The `-0.005` value is the unique fingerprint of `frontend/hooks/useManualSync.ts`
(`previousWord.end_time = currentStartTime - 0.005`, plus `currentWord.start_time =
currentTimeRef.current`).
- So the **manual-sync ("tap-to-time") tool** assigned `start=0` (words synced while the
audio playhead sat at 0) and cascaded `end = 0 - 0.005`. Manual-sync timing edits are not
recorded in the edit log (which only logs text ops), which is why the segment looked
untouched.
- Symptom the operator hit: opening that segment in the editor modal was buggy with the
0/`-0.005` values; they had to type timestamps in by hand before they could drag-adjust.
## Goal
Prevent invalid word timings from being **created** or **persisted** during review, while
keeping the editing experience flexible — specifically, the operator must still be able to
make a segment start earlier / end later easily. Render-time sanitization remains as the
last-resort net.
## Core invariant (one definition, four enforcement points)
A segment's word timings are **valid** iff, for every word:
```
segment.start_time ≤ word.start_time ≤ word.end_time ≤ segment.end_time
and words are non-decreasing in start_time across the segment
and all times are finite and ≥ 0
```
This is the same invariant the shipped render-time clamp enforces. We mirror it earlier.
### The key reconciliation: clamping is operation-specific, not global
The invariant holds **at rest** (after every save). The operator is never "trapped" by it
because the way you extend a segment is to edit a word, and **word edits expand the segment
to fit** rather than clamping the word back:
| Operation | Behavior |
|---|---|
| Drag / type a word's start earlier (or end later) in the modal | **Segment bounds auto-expand** to contain the new word time. This *is* the "make the segment start earlier / end later" control. No clamp. |
| Manual-sync tap (`useManualSync`) | Tap time is **clamped** to the segment's current audio window `[start, end]` (a tap outside is a sync glitch, the root cause). Warn if clamped. |
| Modal opens a segment containing pre-existing out-of-bounds / broken values | **Repair on open**: clamp offending words into the loaded segment bounds / fix `end<start`/negative, show a non-blocking banner. Restores a sane editing surface. |
| Backend save (`POST /corrections`) | **Sanitize** the submitted corrections to the invariant before persisting to GCS; `logger.warning` a summary. Belt-and-suspenders for any frontend gap. |
Because user edits expand the segment *before* save, legitimate extensions are within
bounds at submit time and are never clamped — only true glitches (a word at 0 in a 15 s
segment) get repaired.
UX philosophy (operator-confirmed): **clamp/repair + non-blocking warn**, never silently and
never blocking the save.
## Components
### Shared sanitizer (one canonical implementation per language)
- **Frontend:** `frontend/lib/lyrics-review/sanitizeWordTimings.ts`
- `sanitizeSegmentTimings(segment): { segment, changes: TimingChange[] }`
- Pure function. Returns the corrected segment plus a list of what changed (word id, field,
from, to) so callers can render warnings. Valid input returns `changes: []` and an
unchanged segment (referential no-op where possible).
- Also exports `expandSegmentToWords(segment)` (grow `start_time`/`end_time` to the
min/max of word times) used by the modal's edit handlers.
- **Backend:** reuse / co-locate with the existing
`SegmentResizer._sanitize_segment_timings` logic so render and submit share one definition.
Expose a thin `sanitize_corrections(corrections: dict) -> (dict, summary)` helper for the
route to call.
### Layer 1 — Manual-sync guard (`frontend/hooks/useManualSync.ts`)
- Clamp the synced `start_time` (and the derived previous-word `end_time`) into the
segment's current `[start_time, end_time]` window in both the `handleKeyDown` tap path
(~L120-155) and the `handleTap` path (~L285-316).
- Keep `end ≥ start` and non-decreasing ordering.
- If a clamp changed a value, surface a non-blocking toast (e.g. *"'A whiskey' timing was
outside the segment — snapped to 15.18s"*).
### Layer 2 — Edit-segment modal (`frontend/components/lyrics-review/modals/EditModal.tsx` + word list / `TimeInput`)
- **Sanitize-on-open:** when `editedSegment` initializes from the incoming segment, run
`sanitizeSegmentTimings`; if it changed anything, show a dismissible warning banner listing
affected words. The segment now opens with sane values so the timeline/drag editor works.
- **Segment-follows-words on edit:** word edit handlers (`handleWordChange`, drag handles,
`handleAddWord`, `splitWordWithTiming`) call `expandSegmentToWords` so editing a word's
start earlier / end later grows the segment rather than being clamped. Replace the fragile
`?? 0` fallbacks.
- **Robust inputs:** `TimeInput` and the timeline drag math tolerate `null`/`0`/inverted
values without NaN, off-canvas blocks, or unclickable handles.
### Layer 3 — Backend safety net (`backend/api/routes/jobs.py::submit_corrections`, POST `/{job_id}/corrections`)
- Before `storage.upload_json(corrections_updated.json, ...)`, run `sanitize_corrections`
over `submission.corrections['corrected_segments']`.
- Clamp words outside their segment bounds, fix `end<start`/negative, persist the cleaned
payload. `logger.warning` with job id + count + a sample. Non-blocking (the save succeeds).
- `complete-review` renders from this saved file, so this guarantees clean stored data.
## Data flow
```
Manual sync tap ─clamp→ word times (within segment) ─┐
Modal word edit ─expand segment→ word times ─────────┤→ EditModal state
Modal open (bad data) ─repair+banner→ ───────────────┘
│ POST /corrections (submission.corrections)
▼
submit_corrections ─sanitize+log→ corrections_updated.json (GCS)
│ complete-review → render worker
▼
OutputGenerator → SegmentResizer._sanitize_segment_timings (last-resort net, already shipped)
```
## Testing
- **Frontend (Jest):**
- `sanitizeWordTimings`: the exact `17f7c313` fixture ("A whiskey and a" at `0/-0.005`,
segment `15.18–18.04`) → words clamped into bounds, `end≥start`, non-decreasing; valid
input untouched (`changes: []`); `expandSegmentToWords` grows bounds for a deliberate
out-of-bounds edit.
- `useManualSync`: a tap at playhead 0 clamps to segment start and reports a change.
- `EditModal`: opening a segment with the bad fixture shows the banner and renders
sane values; dragging a word's start before `segment.start` expands the segment.
- **Backend (pytest):**
- `submit_corrections` clamps out-of-bounds words before upload and logs; a valid payload
passes through byte-for-byte; segment-expanded (legitimately extended) payloads are not
clamped.
- **Regression anchor:** the `17f7c313` shape is the shared fixture across all layers.
## Scope guardrails (YAGNI)
- No backfill of existing jobs — the render-time net already protects them.
- No change to the `complete-review` flow.
- No new "timing health" UI beyond the inline toast/banner.
- i18n: new warning strings go in `frontend/messages/en.json` and run through
`translate.py --target all` (CI enforces locale completeness).
## Out of scope / follow-ups
- Investigating *why* the manual-sync playhead can be at 0 when a tap arrives (a deeper
interaction fix) — the clamp makes it harmless regardless; revisit only if it recurs.
@@ -0,0 +1,645 @@
# Review-Phase Word-Timing Validation Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Prevent invalid word timings (the `start=0`/`end=-0.005` class that caused job `17f7c313`'s overlapping lyrics) from being created or persisted during lyrics review, while keeping segment editing flexible.
**Architecture:** One invariant — every word within its segment's `[start_time, end_time]`, `end ≥ start ≥ 0`, non-decreasing — enforced at four points: manual-sync (clamp taps, source prevention), modal-open (repair + warn), backend submit (sanitize + log), and the already-shipped render-time net. The modal already derives segment bounds from word `min/max` (`updateSegment`), so dragging a word earlier/later expands the segment naturally; that's why "word outside saved bounds" reliably means corruption, not a legit edit.
**Tech Stack:** Frontend TypeScript/React + Jest (`frontend/`); backend Python/FastAPI + pytest (`backend/`); i18n via next-intl + `translate.py`.
**Design doc:** `docs/archive/2026-06-10-review-timing-validation-design.md`
---
## File Structure
- Create `frontend/lib/lyrics-review/sanitizeWordTimings.ts` — pure sanitizer + change report (frontend canonical).
- Create `frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts` — unit tests.
- Modify `frontend/hooks/useManualSync.ts` — clamp synced times to segment bounds (Layer 1).
- Create `frontend/hooks/__tests__/useManualSync.test.ts` — sync clamp test.
- Modify `frontend/components/lyrics-review/modals/EditModal.tsx` — sanitize-on-open + warning banner (Layer 2).
- Modify `frontend/components/lyrics-review/__tests__/EditModal.test.tsx` (create if absent) — open-repair test.
- Create `backend/services/timing_sanitizer.py` — dict-level sanitizer (backend canonical).
- Create `tests/unit/services/test_timing_sanitizer.py` — unit tests.
- Modify `backend/api/routes/jobs.py` (`submit_corrections`, ~L1076-1117) — call sanitizer before GCS upload (Layer 3).
- Modify `tests/unit/api/routes/test_jobs_corrections.py` (create if absent) — submit sanitize test.
- Modify `frontend/messages/en.json` — warning strings; then `translate.py --target all`.
---
## Task 1: Frontend sanitizer (`sanitizeWordTimings.ts`)
**Files:**
- Create: `frontend/lib/lyrics-review/sanitizeWordTimings.ts`
- Test: `frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts
import { sanitizeSegmentTimings } from '../sanitizeWordTimings'
import { LyricsSegment } from '../types'
// The exact shape that broke job 17f7c313.
function scalpSegment(): LyricsSegment {
return {
id: 's1',
text: 'A whiskey and a beer, ...',
start_time: 15.18,
end_time: 18.04,
words: [
{ id: 'a', text: 'A', start_time: 0, end_time: -0.005 },
{ id: 'b', text: 'whiskey', start_time: 0, end_time: -0.005 },
{ id: 'c', text: 'and', start_time: 0, end_time: 0 },
{ id: 'd', text: 'a', start_time: 0, end_time: 0 },
{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 },
],
}
}
describe('sanitizeSegmentTimings', () => {
it('clamps out-of-bounds leading words into the segment window', () => {
const { segment, changes } = sanitizeSegmentTimings(scalpSegment())
for (const w of segment.words) {
expect(w.start_time!).toBeGreaterThanOrEqual(15.18)
expect(w.end_time!).toBeGreaterThanOrEqual(w.start_time!)
expect(w.end_time!).toBeLessThanOrEqual(18.04 + 1e-9)
}
expect(changes.length).toBeGreaterThan(0)
expect(changes.some((c) => c.wordId === 'a')).toBe(true)
})
it('leaves already-valid segments untouched and reports no changes', () => {
const seg: LyricsSegment = {
id: 's', text: 'Filling up that cup', start_time: 21.4, end_time: 22.78,
words: [
{ id: 'w0', text: 'Filling', start_time: 21.4, end_time: 21.82 },
{ id: 'w1', text: 'up', start_time: 21.86, end_time: 22.1 },
{ id: 'w2', text: 'that', start_time: 22.14, end_time: 22.42 },
{ id: 'w3', text: 'cup', start_time: 22.46, end_time: 22.78 },
],
}
const { changes } = sanitizeSegmentTimings(seg)
expect(changes).toEqual([])
})
it('handles null word timings by clamping to the segment start', () => {
const seg: LyricsSegment = {
id: 's', text: 'x y', start_time: 5, end_time: 6,
words: [
{ id: 'w0', text: 'x', start_time: null, end_time: null },
{ id: 'w1', text: 'y', start_time: 5.5, end_time: 6 },
],
}
const { segment } = sanitizeSegmentTimings(seg)
expect(segment.words[0].start_time!).toBeGreaterThanOrEqual(5)
expect(segment.words[0].end_time!).toBeGreaterThanOrEqual(segment.words[0].start_time!)
})
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd frontend && npx jest lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts`
Expected: FAIL — `Cannot find module '../sanitizeWordTimings'`.
- [ ] **Step 3: Write minimal implementation**
```typescript
// frontend/lib/lyrics-review/sanitizeWordTimings.ts
import { LyricsSegment, Word } from './types'
export interface TimingChange {
wordId: string
wordText: string
field: 'start_time' | 'end_time'
from: number | null
to: number
}
/**
* Enforce the timing invariant for one segment:
* segment.start <= word.start <= word.end <= segment.end, non-decreasing, finite, >= 0.
*
* The segment's own start/end are treated as the authoritative window. Because the
* editor derives segment bounds from word min/max on every edit (updateSegment), a word
* outside the segment window only happens via corruption (e.g. a manual-sync glitch),
* never via a legitimate extension. Returns a NEW segment plus the list of clamps applied
* so callers can warn. A clean segment returns the same word objects and changes: [].
*/
export function sanitizeSegmentTimings(segment: LyricsSegment): {
segment: LyricsSegment
changes: TimingChange[]
} {
const changes: TimingChange[] = []
const segStart = isFiniteNumber(segment.start_time) ? (segment.start_time as number) : 0
const segEndRaw = isFiniteNumber(segment.end_time) ? (segment.end_time as number) : segStart
const segEnd = Math.max(segEndRaw, segStart)
let prevEnd = segStart
const words: Word[] = segment.words.map((w) => {
const clamp = (v: number) => Math.min(Math.max(v, segStart), segEnd)
let start = isFiniteNumber(w.start_time) ? (w.start_time as number) : null
let end = isFiniteNumber(w.end_time) ? (w.end_time as number) : null
// start: must be finite, within [prevEnd-clamped-to-window, segEnd]
const wantStart = start === null ? prevEnd : start
const newStart = clamp(Math.max(wantStart, segStart))
// end: must be finite and >= start, within window
const wantEnd = end === null ? newStart : end
const newEnd = clamp(Math.max(wantEnd, newStart))
let next = w
if (newStart !== start) {
changes.push({ wordId: w.id, wordText: w.text, field: 'start_time', from: w.start_time, to: newStart })
next = { ...next, start_time: newStart }
}
if (newEnd !== end) {
changes.push({ wordId: w.id, wordText: w.text, field: 'end_time', from: w.end_time, to: newEnd })
next = { ...next, end_time: newEnd }
}
prevEnd = newEnd
return next
})
if (changes.length === 0) return { segment, changes }
return { segment: { ...segment, words }, changes }
}
function isFiniteNumber(v: number | null | undefined): boolean {
return typeof v === 'number' && Number.isFinite(v)
}
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd frontend && npx jest lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts`
Expected: PASS (3 tests).
- [ ] **Step 5: Commit**
```bash
git add frontend/lib/lyrics-review/sanitizeWordTimings.ts frontend/lib/lyrics-review/__tests__/sanitizeWordTimings.test.ts
git commit -m "feat(lyrics-review): add word-timing sanitizer with change report"
```
---
## Task 2: Manual-sync clamp (Layer 1, source prevention)
**Files:**
- Modify: `frontend/hooks/useManualSync.ts` (the `handleKeyDown` tap path ~L120-155 and `handleTap` path ~L283-316)
- Test: `frontend/hooks/__tests__/useManualSync.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// frontend/hooks/__tests__/useManualSync.test.ts
import { clampSyncTime } from '../useManualSync'
describe('clampSyncTime', () => {
it('clamps a playhead-at-0 tap up to the segment start', () => {
expect(clampSyncTime(0, 15.18, 18.04)).toBe(15.18)
})
it('clamps a tap past the segment end down to the end', () => {
expect(clampSyncTime(99, 15.18, 18.04)).toBe(18.04)
})
it('leaves an in-window tap unchanged', () => {
expect(clampSyncTime(16.0, 15.18, 18.04)).toBe(16.0)
})
it('falls back gracefully when segment bounds are null', () => {
expect(clampSyncTime(5, null, null)).toBe(5)
})
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd frontend && npx jest hooks/__tests__/useManualSync.test.ts`
Expected: FAIL — `clampSyncTime` is not exported.
- [ ] **Step 3: Add the helper and apply it in both sync paths**
Add this exported helper near the top of `frontend/hooks/useManualSync.ts` (after the constants block, ~L16):
```typescript
/**
* Clamp a manual-sync tap time into the segment's audio window. A tap should always land
* within the segment being synced; a value outside (e.g. the playhead sitting at 0) is a
* sync glitch — the source of the start=0/end=-0.005 corruption. Null bounds => no clamp.
*/
export function clampSyncTime(
time: number,
segStart: number | null,
segEnd: number | null
): number {
let t = time
if (typeof segStart === 'number' && Number.isFinite(segStart)) t = Math.max(t, segStart)
if (typeof segEnd === 'number' && Number.isFinite(segEnd)) t = Math.min(t, segEnd)
return t
}
```
In the `handleKeyDown` path, replace (~L123):
```typescript
const currentStartTime = currentTimeRef.current
```
with:
```typescript
const rawStartTime = currentTimeRef.current
const currentStartTime = clampSyncTime(
rawStartTime,
editedSegment?.start_time ?? null,
editedSegment?.end_time ?? null
)
if (currentStartTime !== rawStartTime) {
onTimingClamped?.(newWords[syncWordIndex]?.text ?? '', currentStartTime)
}
```
Apply the identical change in the `handleTap` path (~L286), reusing `clampSyncTime` and `onTimingClamped`.
Add `onTimingClamped?: (wordText: string, snappedTo: number) => void` to `UseManualSyncProps` (after `updateSegment`, ~L10) and destructure it in the hook signature (~L22). The previous-word `end_time = currentStartTime - 0.005` lines (~L144/L305) now operate on the clamped `currentStartTime`, so they can no longer produce negative values.
- [ ] **Step 4: Run test to verify it passes**
Run: `cd frontend && npx jest hooks/__tests__/useManualSync.test.ts`
Expected: PASS (4 tests).
- [ ] **Step 5: Commit**
```bash
git add frontend/hooks/useManualSync.ts frontend/hooks/__tests__/useManualSync.test.ts
git commit -m "fix(lyrics-review): clamp manual-sync taps to segment bounds (root cause of start=0)"
```
---
## Task 3: Modal sanitize-on-open + warning banner (Layer 2)
**Files:**
- Modify: `frontend/components/lyrics-review/modals/EditModal.tsx` (~L58, L67-69, render)
- Test: `frontend/components/lyrics-review/__tests__/EditModal.test.tsx` (create if absent)
- [ ] **Step 1: Write the failing test**
```tsx
// frontend/components/lyrics-review/__tests__/EditModal.test.tsx
import { render, screen } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import EditModal from '../modals/EditModal'
import en from '@/messages/en.json'
import { LyricsSegment } from '@/lib/lyrics-review/types'
const badSegment: LyricsSegment = {
id: 's1', text: 'A whiskey and a beer,', start_time: 15.18, end_time: 18.04,
words: [
{ id: 'a', text: 'A', start_time: 0, end_time: -0.005 },
{ id: 'b', text: 'whiskey', start_time: 0, end_time: -0.005 },
{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 },
],
}
function renderModal(segment: LyricsSegment) {
return render(
<NextIntlClientProvider locale="en" messages={en}>
<EditModal open segment={segment} segmentIndex={0} originalSegment={null}
onClose={() => {}} onSave={() => {}} />
</NextIntlClientProvider>
)
}
it('shows the timing-repaired banner when a segment opens with out-of-bounds words', () => {
renderModal(badSegment)
expect(screen.getByTestId('timing-sanitized-banner')).toBeInTheDocument()
})
it('shows no banner for a clean segment', () => {
renderModal({ ...badSegment, words: [{ id: 'e', text: 'beer,', start_time: 16.1, end_time: 16.42 }] })
expect(screen.queryByTestId('timing-sanitized-banner')).not.toBeInTheDocument()
})
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd frontend && npx jest components/lyrics-review/__tests__/EditModal.test.tsx`
Expected: FAIL — no `timing-sanitized-banner` test id.
- [ ] **Step 3: Sanitize on open and render the banner**
In `EditModal.tsx`, add the import (after L15):
```typescript
import { sanitizeSegmentTimings } from '@/lib/lyrics-review/sanitizeWordTimings'
```
Add banner state (after L59 `const [isPlaying, ...]`):
```typescript
const [timingFixCount, setTimingFixCount] = useState(0)
```
Replace the segment-init effect (L67-69):
```typescript
useEffect(() => {
if (!segment) {
setEditedSegment(null)
setTimingFixCount(0)
return
}
const { segment: cleaned, changes } = sanitizeSegmentTimings(segment)
setEditedSegment(cleaned)
setTimingFixCount(changes.length)
}, [segment])
```
Render the banner at the top of the modal body (inside `<DialogContent>`, before the word list). Use the namespace already loaded at L54 (`t = useTranslations('lyricsReview.modals.editAll')`):
```tsx
{timingFixCount > 0 && (
<div
data-testid="timing-sanitized-banner"
className="mb-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800"
>
{t('timingSanitized', { count: timingFixCount })}
</div>
)}
```
Pass the clamp callback to the manual-sync hook (at the `useManualSync({...})` call, ~L110-115) so sync clamps also surface a toast — add `onTimingClamped` there:
```typescript
onTimingClamped: (wordText: string, snappedTo: number) => {
toast.warning(t('timingClamped', { word: wordText, time: snappedTo.toFixed(2) }))
},
```
Add the sonner import at top (after L7): `import { toast } from 'sonner'`.
- [ ] **Step 4: Add i18n strings**
In `frontend/messages/en.json`, under `lyricsReview.modals.editAll`, add:
```json
"timingSanitized": "Fixed {count} word timing(s) that fell outside this segment.",
"timingClamped": "\"{word}\" timing was outside the segment — snapped to {time}s."
```
- [ ] **Step 5: Run test to verify it passes**
Run: `cd frontend && npx jest components/lyrics-review/__tests__/EditModal.test.tsx`
Expected: PASS (2 tests).
- [ ] **Step 6: Commit**
```bash
git add frontend/components/lyrics-review/modals/EditModal.tsx frontend/components/lyrics-review/__tests__/EditModal.test.tsx frontend/messages/en.json
git commit -m "feat(lyrics-review): repair invalid word timings on segment-edit open with a warning banner"
```
---
## Task 4: Backend sanitizer + submit integration (Layer 3)
**Files:**
- Create: `backend/services/timing_sanitizer.py`
- Test: `tests/unit/services/test_timing_sanitizer.py`
- Modify: `backend/api/routes/jobs.py` (`submit_corrections`, ~L1110-1117)
- [ ] **Step 1: Write the failing test**
```python
# tests/unit/services/test_timing_sanitizer.py
from backend.services.timing_sanitizer import sanitize_corrections
def _scalp_corrections():
return {
"corrected_segments": [
{
"id": "s1",
"text": "A whiskey and a beer,",
"start_time": 15.18,
"end_time": 18.04,
"words": [
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
],
}
]
}
def test_clamps_out_of_bounds_words():
cleaned, count = sanitize_corrections(_scalp_corrections())
words = cleaned["corrected_segments"][0]["words"]
for w in words:
assert w["start_time"] >= 15.18
assert w["end_time"] >= w["start_time"]
assert w["end_time"] <= 18.04 + 1e-9
assert count >= 4
def test_valid_corrections_unchanged():
payload = {
"corrected_segments": [
{
"id": "s", "text": "Filling up", "start_time": 21.4, "end_time": 22.1,
"words": [
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
],
}
]
}
cleaned, count = sanitize_corrections(payload)
assert count == 0
assert cleaned == payload
def test_missing_segments_key_is_noop():
cleaned, count = sanitize_corrections({"foo": "bar"})
assert count == 0
assert cleaned == {"foo": "bar"}
```
- [ ] **Step 2: Run test to verify it fails**
Run (from the repo root): `python -m pytest tests/unit/services/test_timing_sanitizer.py -q`
Expected: FAIL — `ModuleNotFoundError: backend.services.timing_sanitizer`.
- [ ] **Step 3: Write the sanitizer (dict-level, mirrors the frontend invariant and SegmentResizer._sanitize_segment_timings)**
```python
# backend/services/timing_sanitizer.py
"""Sanitize submitted review corrections so word timings stay within their segment.
Mirrors the frontend sanitizeWordTimings.ts and the render-time
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
segment window or is inverted/negative. Returns (cleaned_dict, num_clamps)."""
from __future__ import annotations
import math
from typing import Any, Dict, Tuple
def _finite(v: Any) -> bool:
return isinstance(v, (int, float)) and math.isfinite(v)
def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
segments = corrections.get("corrected_segments")
if not isinstance(segments, list):
return corrections, 0
changes = 0
for seg in segments:
if not isinstance(seg, dict):
continue
seg_start = seg.get("start_time")
seg_end = seg.get("end_time")
seg_start = seg_start if _finite(seg_start) else 0.0
seg_end = seg_end if _finite(seg_end) else seg_start
seg_end = max(seg_end, seg_start)
prev_end = seg_start
for w in seg.get("words", []):
if not isinstance(w, dict):
continue
start = w.get("start_time")
end = w.get("end_time")
want_start = start if _finite(start) else prev_end
new_start = min(max(want_start, seg_start), seg_end)
want_end = end if _finite(end) else new_start
new_end = min(max(want_end, new_start), seg_end)
if new_start != start:
w["start_time"] = new_start
changes += 1
if new_end != end:
w["end_time"] = new_end
changes += 1
prev_end = new_end
return corrections, changes
```
- [ ] **Step 4: Run test to verify it passes**
Run: `python -m pytest tests/unit/services/test_timing_sanitizer.py -q`
Expected: PASS (3 tests).
- [ ] **Step 5: Call the sanitizer in `submit_corrections`**
In `backend/api/routes/jobs.py`, inside `submit_corrections`, immediately before the GCS upload (the `corrections_gcs_path = ...` / `storage.upload_json(...)` block ~L1115), insert:
```python
# Safety net: never persist word timings that fall outside their segment.
# Frontend should already prevent this; this guarantees clean stored data
# (the render worker reads corrections_updated.json verbatim).
from backend.services.timing_sanitizer import sanitize_corrections
sanitized, clamp_count = sanitize_corrections(submission.corrections)
if clamp_count:
logger.warning(
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
f"in submitted corrections before persisting"
)
submission.corrections = sanitized
```
(`submission.corrections` is then uploaded by the existing `storage.upload_json(corrections_gcs_path, submission.corrections)` line.)
- [ ] **Step 6: Write the route-level failing test**
```python
# tests/unit/api/routes/test_jobs_corrections.py
from unittest.mock import patch, MagicMock
from backend.services.timing_sanitizer import sanitize_corrections
def test_submit_sanitizes_before_upload(monkeypatch):
"""The corrections written to GCS must have in-bounds word timings."""
captured = {}
def fake_upload_json(path, data):
captured["data"] = data
# Sanitizer is the unit under contract here; assert the integration call clamps.
bad = {
"corrected_segments": [
{"id": "s", "start_time": 15.18, "end_time": 18.04, "text": "A",
"words": [{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005}]}
]
}
cleaned, count = sanitize_corrections(bad)
assert count >= 1
assert cleaned["corrected_segments"][0]["words"][0]["start_time"] >= 15.18
```
(If the repo has FastAPI route integration harnesses under `tests/integration/`, add a fuller request-level test there following the existing pattern; the unit contract above is the minimum.)
- [ ] **Step 7: Run tests**
Run: `python -m pytest tests/unit/services/test_timing_sanitizer.py tests/unit/api/routes/test_jobs_corrections.py -q`
Expected: PASS.
- [ ] **Step 8: Commit**
```bash
git add backend/services/timing_sanitizer.py tests/unit/services/test_timing_sanitizer.py tests/unit/api/routes/test_jobs_corrections.py backend/api/routes/jobs.py
git commit -m "feat(api): sanitize out-of-bounds word timings on corrections submit"
```
---
## Task 5: Translate new strings + full suites
**Files:**
- Modify: `frontend/messages/*.json` (generated)
- [ ] **Step 1: Translate the two new keys to all locales**
Run: `cd frontend && python scripts/translate.py --messages-dir messages --target all`
Expected: `timingSanitized` / `timingClamped` added to all 33 locales (cache hits for repeats).
- [ ] **Step 2: Run the frontend suite**
Run: `cd frontend && npx jest lib/lyrics-review hooks components/lyrics-review`
Expected: PASS (all new + existing lyrics-review tests).
- [ ] **Step 3: Run the backend unit suite for touched areas**
Run: `python -m pytest tests/unit/services/test_timing_sanitizer.py tests/unit/api -q`
Expected: PASS.
- [ ] **Step 4: Version bump**
Bump `version` in `pyproject.toml` (patch, e.g. `0.176.2 -> 0.176.3`).
- [ ] **Step 5: Commit**
```bash
git add frontend/messages pyproject.toml
git commit -m "chore: translate timing-validation strings; bump version"
```
---
## Self-review notes (covered)
- **Spec coverage:** Layer 1 → Task 2; Layer 2 → Task 3; Layer 3 → Task 4; shared invariant → Tasks 1 & 4; "segment follows words" → relies on existing `EditModal.updateSegment` min/max derivation (no new code, noted in Architecture); i18n → Tasks 3 & 5; render-time net → already shipped (v0.176.2), unchanged.
- **Naming consistency:** `sanitizeSegmentTimings` (FE), `sanitize_corrections` (BE), `clampSyncTime` (sync) used identically across tasks.
- **No clamp-traps-extension:** clamping references the segment's saved bounds; legit extensions move those bounds via `updateSegment`, so they are never clamped. Only corruption (words diverged from bounds) is repaired.
@@ -0,0 +1,53 @@
# Audio Editor: Fade In / Fade Out Buttons
**Date:** 2026-06-11
**Branch:** `feat/sess-20260611-1250-audio-fade`
## Goal
Add **Fade In** and **Fade Out** action buttons to the audio editor toolbar so users
can ramp the volume of a selected region gracefully instead of a hard cut.
**Primary use case (user quote):** "when cutting off a long intro from a song, we'll
likely want it to fade in gracefully over a few seconds rather than come in really loud
at the point it was trimmed to."
## Design Decisions
- **Edge-gated display**, mirroring the existing `Trim Start` / `Trim End` buttons:
- **Fade In** appears when the selection starts near the beginning (`startSeconds < 1`).
- **Fade Out** appears when the selection ends near the end (`endSeconds > duration - 1`).
- This matches the real use case (fade the new start after trimming an intro; fade the
new end after trimming an outro) and avoids `afade`'s surprising behaviour of
silencing audio outside the fade window for mid-track selections.
- **Duration-preserving** (like `mute`) — fades only adjust volume, they don't change length.
- Implemented with FFmpeg's `afade` filter: `afade=t=in|out:st={start}:d={end-start}`.
- No new keyboard shortcut (a single key can't disambiguate in vs out cleanly).
## Changes
### Backend
1. `backend/services/audio_edit_service.py`
- Add `fade_region(input_path, start, end, direction, output_path)` — validates
`direction in {"in","out"}`, runs `afade`, returns metadata (duration preserved).
- Dispatch `fade_in` / `fade_out` in `apply_edit`.
2. `backend/api/routes/review.py`
- Add `"fade_in"`, `"fade_out"` to `valid_operations`.
### Frontend
3. `frontend/components/audio-editor/AudioEditor.tsx`
- `handleFadeIn()` / `handleFadeOut()` → `handleApply("fade_in"|"fade_out", {start_seconds, end_seconds})`.
- Edge-gated toolbar buttons with `TrendingUp` / `TrendingDown` icons.
4. i18n: add `fadeIn`, `fadeOut`, `fadeInSelection`, `fadeOutSelection` to
`frontend/messages/en.json`, then `translate.py --target all` (33 locales).
## Tests
- **Backend unit** (`test_audio_edit_service.py`): `fade_region` in/out ffmpeg args,
duration preserved, invalid direction rejected, `apply_edit` dispatch for fade_in/out.
- **Backend route** (`test_audio_edit_routes.py`): fade_in/fade_out accepted (not "Invalid operation").
- **Frontend** (`AudioEditor.test.tsx`): Fade In button renders for a start-anchored
selection and calls `applyAudioEdit` with `fade_in`.
## Out of Scope (possible future work)
- Mid-track fades (would need a `volume` envelope filter, not `afade`).
- Configurable fade curve / duration input box.
@@ -387,6 +387,11 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
style={{ height: 40 }}
/>
<h1 className="text-lg font-bold">Lyrics Transcription Review</h1>
{(job.artist || job.title) && (
<span className="text-xs md:text-sm text-muted-foreground truncate">
{[job.artist, job.title].filter(Boolean).join(" - ")}
</span>
)}
</div>
<ThemeToggle />
</div>
@@ -20,6 +20,8 @@ import {
SkipForward,
Volume2,
VolumeX,
TrendingUp,
TrendingDown,
Upload,
Check,
ChevronDown,
@@ -614,6 +616,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)
@@ -877,6 +895,19 @@ export function AudioEditor({ job }: AudioEditorProps) {
{t('trimStart')}
</Button>
)}
{selection.startSeconds < 1 && (
<Button
variant="outline"
size="sm"
disabled={isOperating}
onClick={handleFadeIn}
className="text-xs h-7"
title={t('fadeInSelection')}
>
<TrendingUp className="w-3 h-3 mr-1" />
{t('fadeIn')}
</Button>
)}
{selection.endSeconds > currentDuration - 1 && (
<Button
variant="outline"
@@ -888,6 +919,19 @@ export function AudioEditor({ job }: AudioEditorProps) {
{t('trimEnd')}
</Button>
)}
{selection.endSeconds > currentDuration - 1 && (
<Button
variant="outline"
size="sm"
disabled={isOperating}
onClick={handleFadeOut}
className="text-xs h-7"
title={t('fadeOutSelection')}
>
<TrendingDown className="w-3 h-3 mr-1" />
{t('fadeOut')}
</Button>
)}
<Button
variant="outline"
size="sm"
@@ -327,6 +327,70 @@ 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("shows playback controls", async () => {
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
render(<AudioEditor job={mockJob} />)
@@ -1,5 +1,6 @@
"use client"
import { useTranslations } from "next-intl"
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { api, ApiError, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api"
import { CommunityVersionBanner } from "@/components/job/CommunityVersionBanner"
@@ -1410,6 +1411,7 @@ function FallbackSection({
onUrlSubmit: (e: React.FormEvent) => void
onUploadSubmit: (e: React.FormEvent) => void
}) {
const t = useTranslations('jobFlow')
const isTier3WithResults = tier === 3 && hasResults
const largeButtons = !hasResults
const buttonHeight = largeButtons ? 'h-12' : 'h-9'
@@ -1435,7 +1437,7 @@ function FallbackSection({
style={{ borderColor: fallbackMode === "url" ? 'var(--brand-pink)' : 'var(--card-border)', color: 'var(--text)' }}
>
<Youtube className={`${iconSize} mr-1.5`} />
YouTube URL
{t('pasteUrlButton')}
</Button>
<Button
variant="outline"
@@ -1464,13 +1466,25 @@ function FallbackSection({
autoFocus
/>
</div>
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
{t('urlSupportedSitesHint')}{' '}
<a
href="https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md"
target="_blank"
rel="noopener noreferrer"
className="underline"
style={{ color: 'var(--brand-pink)' }}
>
{t('urlSupportedSitesLink')}
</a>
</p>
<Button
type="submit"
size="sm"
disabled={!youtubeUrl.trim() || noCredits}
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
>
Use This URL
{t('useThisUrl')}
</Button>
</form>
)}
@@ -0,0 +1,197 @@
'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 [compareModels, setCompareModels] = useState(
DEFAULT_AUTO_CORRECT_SETTINGS.compare_models,
)
const isRunning = status === 'running'
const handleRun = () => {
onRun({
suggest_adlib_removal: adlibRemoval,
allow_insertions: allowInsertions,
min_confidence: PRESET_THRESHOLDS[confidencePreset],
compare_models: compareModels,
})
}
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 htmlFor="ac-compare">{t('compareLabel')}</Label>
<p className="text-xs text-muted-foreground">
{t('compareHint')}
</p>
</div>
<Switch
id="ac-compare"
checked={compareModels}
onCheckedChange={setCompareModels}
/>
</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,294 @@
'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,
model,
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>
<Badge variant="outline" className="hidden sm:inline-flex text-xs">
{model}
</Badge>
</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.total_models > 1 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant="outline"
className={cn(
'shrink-0 text-[10px] tabular-nums',
s.consensus === s.total_models
? 'border-green-500/50 text-green-600 dark:text-green-400'
: 'border-amber-500/50 text-amber-600 dark:text-amber-400',
)}
>
{t('consensusBadge', {
consensus: s.consensus,
total: s.total_models,
})}
</Badge>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
{t('consensusTooltip', { models: s.models.join(', ') })}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{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,22 @@ 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,
})
// 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 +1321,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 +1534,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 "AI Suggest" 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: /AI Suggest/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)
})
})
+292
View File
@@ -0,0 +1,292 @@
'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
}
export function useAutoCorrect({
jobId,
data,
updateDataWithHistory,
editLog,
getAuthToken,
}: 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 [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)
setStatus('reviewing')
addEditEntry(editLog, 'ai_suggestion_run', {
details: {
model: response.model,
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()
}, [])
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,
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
+142
View File
@@ -0,0 +1,142 @@
/**
* 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,
compare_models: false,
}
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[]
}
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 ?? [],
}
}
@@ -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)
}
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "بريد إلكتروني عند الجاهزية",
"afterApproval": "بعد الموافقة، يتم عرض فيديو الكاريوكي الخاص بك وتسليمه. ~10 دقائق",
"trackProgressTenant": "تتبع التقدم في قائمة المهام الأخيرة.",
"submitAnother": "إرسال مسار آخر"
"submitAnother": "إرسال مسار آخر",
"pasteUrlButton": "لصق رابط",
"urlSupportedSitesHint": "يعمل مع YouTube و Facebook و SoundCloud و TikTok و Vimeo ومئات المواقع الأخرى.",
"urlSupportedSitesLink": "عرض جميع المواقع المدعومة",
"useThisUrl": "استخدام هذا الرابط"
},
"jobStatus": {
"settingUp": "جاري الإعداد",
@@ -772,7 +776,11 @@
"undoFailed": "فشل التراجع",
"redoFailed": "فشلت الإعادة",
"restoreFailed": "فشلت الاستعادة — قد لا يتم تطبيق بعض التعديلات",
"submitFailed": "فشل الإرسال"
"submitFailed": "فشل الإرسال",
"fadeIn": "ظهور تدريجي",
"fadeInSelection": "ظهور تدريجي في المنطقة المحددة",
"fadeOut": "تلاشي تدريجي",
"fadeOutSelection": "تلاشي تدريجي في المنطقة المحددة"
},
"audioEditRestore": {
"title": "جلسات تعديل الصوت المحفوظة",
@@ -812,7 +820,9 @@
"playback": "التشغيل",
"audioLoadError": "تعذر تحميل الصوت",
"audioStillLoading": "لا يزال الصوت قيد التحميل...",
"loadingAudio": "جاري تحميل الصوت..."
"loadingAudio": "جاري تحميل الصوت...",
"autoCorrect": "اقتراحات الذكاء الاصطناعي",
"autoCorrectDesc": "احصل على اقتراحات للتصحيح بالذكاء الاصطناعي من خلال مقارنة النص المنسوخ مع الكلمات المرجعية. لن يتم تغيير أي شيء حتى توافق على كل اقتراح."
},
"guidance": {
"showTips": "إظهار النصائح",
@@ -986,7 +996,9 @@
"loadingAll": "جاري تحميل جميع الكلمات...",
"loadingSegment": "جاري تحميل المقطع...",
"noData": "لا تتوفر بيانات للمقطع",
"unCorrect": "إلغاء التصحيح"
"unCorrect": "إلغاء التصحيح",
"timingClamped": "توقيت \"{word}\" كان خارج المقطع — تم ضبطه إلى {time} ثانية.",
"timingSanitized": "تم إصلاح توقيت {count} كلمة وقعت خارج هذا المقطع."
},
"findReplace": {
"title": "بحث واستبدال",
@@ -1268,6 +1280,50 @@
},
"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}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Correu electrònic quan estigui llest",
"afterApproval": "Després de l'aprovació, el teu vídeo de karaoke es renderitza i s'entrega. ~10 minuts",
"trackProgressTenant": "Fes un seguiment del progrés a la llista de Treballs recents.",
"submitAnother": "Envia una altra pista"
"submitAnother": "Envia una altra pista",
"pasteUrlButton": "Enganxa un enllaç",
"urlSupportedSitesHint": "Funciona amb YouTube, Facebook, SoundCloud, TikTok, Vimeo i centenars de llocs més.",
"urlSupportedSitesLink": "Consulta tots els llocs compatibles",
"useThisUrl": "Utilitza aquest URL"
},
"jobStatus": {
"settingUp": "Configurant",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sessions d'edició d'àudio desades",
@@ -812,7 +820,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": "Suggeriments de la IA",
"autoCorrectDesc": "Genera suggeriments de correcció de la IA comparant la transcripció amb la lletra de referència. No es canvia res fins que acceptis cada suggeriment."
},
"guidance": {
"showTips": "Mostra els consells",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 grau de certesa ha de tenir la IA per mostrar un suggeriment",
"confidenceLabel": "Filtre de suggeriments",
"confidence_all": "Mostra-ho tot",
"confidence_high": "Certesa alta",
"description": "La IA compara la lletra transcrita amb les fonts de referència i suggereix correccions paraula per 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çó, per la qual cosa no es poden generar suggeriments de la IA. Primer, afegeix la lletra des del tauler de referència.",
"noSuggestions": "No s'ha trobat cap problema — la IA no suggereix cap canvi.",
"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 de correcció de la IA",
"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": "Els models no coincideixen en aquestes paraules — si acceptes una variant, rebutges les altres.",
"consensusBadge": "{consensus}/{total} models",
"consensusTooltip": "Proposat per: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, až bude hotovo",
"afterApproval": "Po schválení se tvé karaoke video vyrenderuje a doručí. ~10 minut",
"trackProgressTenant": "Sleduj postup v seznamu Nedávné úlohy.",
"submitAnother": "Odeslat další stopu"
"submitAnother": "Odeslat další stopu",
"pasteUrlButton": "Vložit odkaz",
"urlSupportedSitesHint": "Funguje se službami YouTube, Facebook, SoundCloud, TikTok, Vimeo a stovkami dalších webů.",
"urlSupportedSitesLink": "Zobrazit všechny podporované weby",
"useThisUrl": "Použít tuto URL"
},
"jobStatus": {
"settingUp": "Nastavování",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Uložené relace úprav zvuku",
@@ -812,7 +820,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": "Návrhy AI",
"autoCorrectDesc": "Nech AI vygenerovat návrhy oprav porovnáním přepisu s referenčním textem. Nic se nezmění, dokud jednotlivé návrhy nepřijmeš."
},
"guidance": {
"showTips": "Zobrazit tipy",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 moc si musí být AI jistá, aby zobrazila návrh",
"confidenceLabel": "Filtr návrhů",
"confidence_all": "Zobrazit vše",
"confidence_high": "Vysoká jistota",
"description": "AI porovná přepsaný text s referenčními zdroji a navrhne opravy jednotlivých slov. Každý návrh si můžeš zkontrolovat — nic se nezmění, 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 AI. Nejprve přidej text z referenčního panelu.",
"noSuggestions": "Nebyly nalezeny žádné problémy — AI nemá žádné návrhy na změnu.",
"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 oprav AI",
"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": "Modely se na těchto slovech neshodují — přijetím jedné varianty odmítneš ostatní.",
"consensusBadge": "{consensus}/{total} modelů",
"consensusTooltip": "Navrženo: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, når den er klar",
"afterApproval": "Efter godkendelse renderes og leveres din karaokevideo. ~10 minutter",
"trackProgressTenant": "Følg fremskridt i listen over seneste job.",
"submitAnother": "Indsend et andet nummer"
"submitAnother": "Indsend et andet nummer",
"pasteUrlButton": "Indsæt et link",
"urlSupportedSitesHint": "Fungerer med YouTube, Facebook, SoundCloud, TikTok, Vimeo og hundredvis af andre sider.",
"urlSupportedSitesLink": "Se alle understøttede sider",
"useThisUrl": "Brug denne URL"
},
"jobStatus": {
"settingUp": "Sætter op",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Gemte lydredigeringssessioner",
@@ -812,7 +820,9 @@
"playback": "Afspilning",
"audioLoadError": "Kunne ikke indlæse lyd",
"audioStillLoading": "Lyden indlæses stadig...",
"loadingAudio": "Indlæser lyd..."
"loadingAudio": "Indlæser lyd...",
"autoCorrect": "AI-forslag",
"autoCorrectDesc": "Generer AI-rettelsesforslag ved at sammenligne transskriptionen med referenceteksten. Intet ændres, før du accepterer hvert forslag."
},
"guidance": {
"showTips": "Vis tips",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 sikker AI'en skal være for at vise et forslag",
"confidenceLabel": "Forslagsfilter",
"confidence_all": "Vis alle",
"confidence_high": "Høj sikkerhed",
"description": "AI'en sammenligner den transskriberede tekst med referencekilderne og foreslår rettelser på ordniveau. Du gennemgår hvert forslag — intet ændres, 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 AI-forslag. Tilføj tekster fra referencepanelet først.",
"noSuggestions": "Ingen problemer fundet — AI'en har 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": "AI-rettelsesforslag",
"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": "Modellerne er uenige om disse ord — hvis du accepterer én variant, afvises de andre.",
"consensusBadge": "{consensus}/{total} modeller",
"consensusTooltip": "Foreslået af: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-Mail, wenn fertig",
"afterApproval": "Nach der Genehmigung wird dein Karaoke-Video gerendert und geliefert. ~10 Minuten",
"trackProgressTenant": "Verfolge den Fortschritt in der Liste Aktuelle Aufträge.",
"submitAnother": "Weiteren Track einreichen"
"submitAnother": "Weiteren Track einreichen",
"pasteUrlButton": "Link einfügen",
"urlSupportedSitesHint": "Funktioniert mit YouTube, Facebook, SoundCloud, TikTok, Vimeo und Hunderten anderen Seiten.",
"urlSupportedSitesLink": "Alle unterstützten Seiten ansehen",
"useThisUrl": "Diese URL verwenden"
},
"jobStatus": {
"settingUp": "Richte ein",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Gespeicherte Audiobearbeitungs-Sitzungen",
@@ -812,7 +820,9 @@
"playback": "Wiedergabe",
"audioLoadError": "Audio konnte nicht geladen werden",
"audioStillLoading": "Audio wird noch geladen...",
"loadingAudio": "Audio wird geladen..."
"loadingAudio": "Audio wird geladen...",
"autoCorrect": "KI-Vorschläge",
"autoCorrectDesc": "Generiere KI-Korrekturvorschläge durch den Vergleich der Transkription mit dem Referenztext. Nichts wird geändert, bis du jeden Vorschlag akzeptierst."
},
"guidance": {
"showTips": "Tipps anzeigen",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 die KI sein muss, um einen Vorschlag anzuzeigen",
"confidenceLabel": "Vorschlagsfilter",
"confidence_all": "Alle anzeigen",
"confidence_high": "Hohe Sicherheit",
"description": "Die KI 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 KI-Vorschläge generiert werden. Füge zuerst Text aus dem Referenz-Panel hinzu.",
"noSuggestions": "Keine Probleme gefunden — die KI hat 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": "KI-Korrekturvorschlä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": "Die Modelle sind sich bei diesen Wörtern uneinig — wenn du eine Variante akzeptierst, werden die anderen abgelehnt.",
"consensusBadge": "{consensus}/{total} Modelle",
"consensusTooltip": "Vorgeschlagen von: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email όταν είναι έτοιμο",
"afterApproval": "Μετά την έγκριση, το karaoke video σου γίνεται render και παραδίδεται. ~10 λεπτά",
"trackProgressTenant": "Παρακολούθησε την πρόοδο στη λίστα Πρόσφατες Εργασίες.",
"submitAnother": "Υποβολή Άλλου Κομματιού"
"submitAnother": "Υποβολή Άλλου Κομματιού",
"pasteUrlButton": "Επικόλλησε έναν σύνδεσμο",
"urlSupportedSitesHint": "Λειτουργεί με YouTube, Facebook, SoundCloud, TikTok, Vimeo και εκατοντάδες άλλους ιστότοπους.",
"urlSupportedSitesLink": "Δες όλους τους υποστηριζόμενους ιστότοπους",
"useThisUrl": "Χρησιμοποίησε αυτό το URL"
},
"jobStatus": {
"settingUp": "Ρύθμιση",
@@ -772,7 +776,11 @@
"undoFailed": "Η αναίρεση απέτυχε",
"redoFailed": "Η επανάληψη απέτυχε",
"restoreFailed": "Η επαναφορά απέτυχε — κάποιες επεξεργασίες μπορεί να μην έχουν εφαρμοστεί",
"submitFailed": "Η υποβολή απέτυχε"
"submitFailed": "Η υποβολή απέτυχε",
"fadeIn": "Fade In",
"fadeInSelection": "Εφάρμοσε fade in στην επιλεγμένη περιοχή",
"fadeOut": "Fade Out",
"fadeOutSelection": "Εφάρμοσε fade out στην επιλεγμένη περιοχή"
},
"audioEditRestore": {
"title": "Αποθηκευμένες Συνεδρίες Επεξεργασίας Ήχου",
@@ -812,7 +820,9 @@
"playback": "Αναπαραγωγή",
"audioLoadError": "Δεν ήταν δυνατή η φόρτωση του ήχου",
"audioStillLoading": "Ο ήχος φορτώνει ακόμα...",
"loadingAudio": "Φόρτωση ήχου..."
"loadingAudio": "Φόρτωση ήχου...",
"autoCorrect": "Προτάσεις AI",
"autoCorrectDesc": "Δημιούργησε προτάσεις διόρθωσης AI συγκρίνοντας τη μεταγραφή με τους στίχους αναφοράς. Τίποτα δεν αλλάζει μέχρι να αποδεχτείς κάθε πρόταση."
},
"guidance": {
"showTips": "Εμφάνιση συμβουλών",
@@ -986,7 +996,9 @@
"loadingAll": "Φόρτωση όλων των λέξεων...",
"loadingSegment": "Φόρτωση τμήματος...",
"noData": "Δεν υπάρχουν διαθέσιμα δεδομένα τμήματος",
"unCorrect": "Αναίρεση Διόρθωσης"
"unCorrect": "Αναίρεση Διόρθωσης",
"timingClamped": "Ο χρονισμός του \"{word}\" ήταν εκτός του τμήματος — προσαρμόστηκε στα {time}s.",
"timingSanitized": "Διορθώθηκαν {count} χρονισμοί λέξεων που έπεφταν εκτός αυτού του τμήματος."
},
"findReplace": {
"title": "Εύρεση και Αντικατάσταση",
@@ -1268,6 +1280,50 @@
},
"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": "Πόσο σίγουρο πρέπει να είναι το AI για να εμφανίσει μια πρόταση",
"confidenceLabel": "Φίλτρο προτάσεων",
"confidence_all": "Εμφάνιση όλων",
"confidence_high": "Υψηλή βεβαιότητα",
"description": "Το AI συγκρίνει τους μεταγραμμένους στίχους με τις πηγές αναφοράς και προτείνει διορθώσεις σε επίπεδο λέξης. Εσύ ελέγχεις κάθε πρόταση — τίποτα δεν εφαρμόζεται μέχρι να το αποδεχτείς.",
"dismiss": "Αγνόηση προτάσεων",
"expand": "Ανάπτυξη προτάσεων",
"insertMarker": "εισαγωγή:",
"insertionsHint": "Επίτρεψε προτάσεις που εισάγουν λέξεις που παραλείφθηκαν κατά τη μεταγραφή",
"insertionsLabel": "Πρόταση λέξεων που λείπουν",
"noReferences": "Δεν υπάρχουν διαθέσιμοι στίχοι αναφοράς για αυτό το τραγούδι, επομένως δεν μπορούν να δημιουργηθούν προτάσεις AI. Πρόσθεσε στίχους από το πάνελ αναφοράς πρώτα.",
"noSuggestions": "Δεν βρέθηκαν προβλήματα — το AI δεν έχει προτεινόμενες αλλαγές.",
"reject": "Απόρριψη πρότασης",
"rejectAll": "Απόρριψη όλων",
"rejected": "Απορρίφθηκε",
"runButton": "Λήψη προτάσεων",
"running": "Ανάλυση στίχων… αυτό συνήθως διαρκεί 15–60 δευτερόλεπτα.",
"staleHint": "Αυτές οι λέξεις επεξεργάστηκαν μετά τη δημιουργία των προτάσεων, επομένως αυτή η πρόταση δεν ισχύει πλέον.",
"summary": "{total} προτάσεις · {pending} σε εκκρεμότητα · {accepted} αποδεκτές",
"title": "Προτάσεις διόρθωσης AI",
"undo": "Αναίρεση αυτής της πρότασης",
"cancel": "Ακύρωση",
"close": "Κλείσιμο",
"confidence_balanced": "Ισορροπημένη",
"compareHint": "Πιο αργό και κοστίζει περισσότερο, αλλά δείχνει σε ποιες προτάσεις συμφωνούν πολλαπλά μοντέλα",
"compareLabel": "Σύγκρινε πολλαπλά μοντέλα AI",
"conflictBadge": "παραλλαγή",
"conflictTooltip": "Τα μοντέλα διαφωνούν για αυτές τις λέξεις — αν αποδεχτείς μια παραλλαγή, απορρίπτεις τις υπόλοιπες.",
"consensusBadge": "{consensus}/{total} μοντέλα",
"consensusTooltip": "Προτάθηκε από: {models}"
}
},
"instrumentalReview": {
+58 -2
View File
@@ -473,6 +473,10 @@
"weFindBestAudio": "We find the best audio",
"uploadAFile": "upload a file",
"youtubeUrl": "YouTube URL",
"pasteUrlButton": "Paste a link",
"useThisUrl": "Use This URL",
"urlSupportedSitesHint": "Works with YouTube, Facebook, SoundCloud, TikTok, Vimeo and hundreds of other sites.",
"urlSupportedSitesLink": "See all supported sites",
"onNextPage": "(on next page)",
"artist": "Artist",
"artistPlaceholder": "e.g. Queen",
@@ -749,6 +753,10 @@
"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",
"undo": "Undo (Ctrl+Z)",
"redo": "Redo (Ctrl+Shift+Z)",
"playPause": "Play/Pause (Space)",
@@ -812,7 +820,9 @@
"playback": "Playback",
"loadingAudio": "Loading audio...",
"audioStillLoading": "Audio is still loading...",
"audioLoadError": "Couldn't load audio"
"audioLoadError": "Couldn't load audio",
"autoCorrect": "AI Suggest",
"autoCorrectDesc": "Generate AI correction suggestions by comparing the transcription against the reference lyrics. Nothing is changed until you accept each suggestion."
},
"guidance": {
"showTips": "Show tips",
@@ -989,7 +999,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",
@@ -1268,6 +1280,50 @@
"legendSinger": "Singer:",
"keyboardHintSegment": "With a segment focused, press 1 / 2 / B",
"resetOverridesTooltip": "Reset word overrides in this segment"
},
"autoCorrect": {
"title": "AI correction suggestions",
"description": "The AI 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 AI 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 the AI must be to show a suggestion",
"confidence_all": "Show all",
"confidence_balanced": "Balanced",
"confidence_high": "High confidence",
"cancel": "Cancel",
"close": "Close",
"runButton": "Get suggestions",
"noSuggestions": "No issues found — the AI has 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": "Models disagree about these words — accepting one variant rejects the others."
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Correo cuando esté listo",
"afterApproval": "Después de la aprobación, tu video de karaoke se renderiza y se entrega. ~10 minutos",
"trackProgressTenant": "Sigue el progreso en la lista de Trabajos recientes.",
"submitAnother": "Enviar otra pista"
"submitAnother": "Enviar otra pista",
"pasteUrlButton": "Pega un enlace",
"urlSupportedSitesHint": "Funciona con YouTube, Facebook, SoundCloud, TikTok, Vimeo y cientos de sitios más.",
"urlSupportedSitesLink": "Ver todos los sitios compatibles",
"useThisUrl": "Usar esta URL"
},
"jobStatus": {
"settingUp": "Configurando",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sesiones de edición de audio guardadas",
@@ -812,7 +820,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": "Sugerencia de IA",
"autoCorrectDesc": "Genera sugerencias de corrección de IA comparando la transcripción con las letras de referencia. No se cambia nada hasta que aceptes cada sugerencia."
},
"guidance": {
"showTips": "Mostrar consejos",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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é tan segura debe estar la IA para mostrar una sugerencia",
"confidenceLabel": "Filtro de sugerencias",
"confidence_all": "Mostrar todas",
"confidence_high": "Alta confianza",
"description": "La IA compara las letras transcritas con las fuentes de referencia y sugiere correcciones a nivel de palabra. Tú revisas cada sugerencia — no se aplica nada hasta que la aceptes.",
"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 de IA. Agrega letras desde el panel de referencia primero.",
"noSuggestions": "No se encontraron problemas — la IA no tiene 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 corrección de IA",
"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": "Los modelos no coinciden en estas palabras; al aceptar una variante, se rechazan las demás.",
"consensusBadge": "{consensus}/{total} modelos",
"consensusTooltip": "Propuesto por: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Sähköposti kun valmis",
"afterApproval": "Hyväksymisen jälkeen karaokevideosi renderöidään ja toimitetaan. ~10 minuuttia",
"trackProgressTenant": "Seuraa edistymistä Viimeisimmät työt -luettelossa.",
"submitAnother": "Lähetä toinen raita"
"submitAnother": "Lähetä toinen raita",
"pasteUrlButton": "Liitä linkki",
"urlSupportedSitesHint": "Toimii YouTuben, Facebookin, SoundCloudin, TikTokin, Vimeon ja satojen muiden sivustojen kanssa.",
"urlSupportedSitesLink": "Katso kaikki tuetut sivustot",
"useThisUrl": "Käytä tätä osoitetta"
},
"jobStatus": {
"settingUp": "Asetetaan",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Tallennetut äänimuokkausistunnot",
@@ -812,7 +820,9 @@
"playback": "Toisto",
"audioLoadError": "Ääntä ei voitu ladata",
"audioStillLoading": "Ääni latautuu yhä...",
"loadingAudio": "Ladataan ääntä..."
"loadingAudio": "Ladataan ääntä...",
"autoCorrect": "Tekoälyn ehdotukset",
"autoCorrectDesc": "Luo tekoälyn korjausehdotuksia vertaamalla transkriptiota viitesanoituksiin. Mitään ei muuteta ennen kuin hyväksyt jokaisen ehdotuksen."
},
"guidance": {
"showTips": "Näytä vinkit",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 tekoälyn on oltava näyttääkseen ehdotuksen",
"confidenceLabel": "Ehdotusten suodatin",
"confidence_all": "Näytä kaikki",
"confidence_high": "Korkea varmuus",
"description": "Tekoäly vertaa transkriptoituja sanoituksia viitelähteisiin ja ehdottaa sanakohtaisia korjauksia. Tarkistat jokaisen ehdotuksen — mitään ei muuteta 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 viitesanoituksia, joten tekoälyehdotuksia ei voida luoda. Lisää sanoitukset ensin viitepaneelista.",
"noSuggestions": "Ongelmia ei löytynyt — tekoäly ei ehdota 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": "Tekoälyn korjausehdotukset",
"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": "Mallit ovat eri mieltä näistä sanoista — yhden vaihtoehdon hyväksyminen hylkää muut.",
"consensusBadge": "{consensus}/{total} mallia",
"consensusTooltip": "Ehdottanut: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail quand c'est prêt",
"afterApproval": "Après approbation, ta vidéo karaoké est rendue et livrée. ~10 minutes",
"trackProgressTenant": "Suis la progression dans la liste des Projets récents.",
"submitAnother": "Soumettre une autre piste"
"submitAnother": "Soumettre une autre piste",
"pasteUrlButton": "Coller un lien",
"urlSupportedSitesHint": "Fonctionne avec YouTube, Facebook, SoundCloud, TikTok, Vimeo et des centaines d'autres sites.",
"urlSupportedSitesLink": "Voir tous les sites compatibles",
"useThisUrl": "Utiliser cette URL"
},
"jobStatus": {
"settingUp": "Configuration",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sessions d'édition audio sauvegardées",
@@ -812,7 +820,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": "Suggestions de l'IA",
"autoCorrectDesc": "Génère des suggestions de correction de l'IA en comparant la transcription aux paroles de référence. Rien n'est modifié tant que tu n'acceptes pas chaque suggestion."
},
"guidance": {
"showTips": "Afficher les conseils",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 par l'IA pour afficher une suggestion",
"confidenceLabel": "Filtre de suggestions",
"confidence_all": "Tout afficher",
"confidence_high": "Certitude élevée",
"description": "L'IA 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 pour cette chanson, les suggestions de l'IA 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é — l'IA n'a aucune modification à suggérer.",
"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 de l'IA",
"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": "Les modèles ne sont pas d'accord sur ces mots — accepter une variante rejette les autres.",
"consensusBadge": "{consensus}/{total} modèles",
"consensusTooltip": "Proposé par : {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "אימייל כשמוכן",
"afterApproval": "לאחר האישור, וידאו הקריוקי שלך מרונדר ומסופק. ~10 דקות",
"trackProgressTenant": "עקוב אחר ההתקדמות ברשימת העבודות האחרונות.",
"submitAnother": "שלח רצועה נוספת"
"submitAnother": "שלח רצועה נוספת",
"pasteUrlButton": "הדבקת קישור",
"urlSupportedSitesHint": "עובד עם YouTube, Facebook, SoundCloud, TikTok, Vimeo ומאות אתרים נוספים.",
"urlSupportedSitesLink": "לצפייה בכל האתרים הנתמכים",
"useThisUrl": "שימוש בכתובת זו"
},
"jobStatus": {
"settingUp": "מגדיר",
@@ -772,7 +776,11 @@
"undoFailed": "ביטול נכשל",
"redoFailed": "ביצוע שוב נכשל",
"restoreFailed": "שחזור נכשל — ייתכן שחלק מהעריכות לא הוחלו",
"submitFailed": "שליחה נכשלה"
"submitFailed": "שליחה נכשלה",
"fadeIn": "פייד אין",
"fadeInSelection": "החלת פייד אין על האזור הנבחר",
"fadeOut": "פייד אאוט",
"fadeOutSelection": "החלת פייד אאוט על האזור הנבחר"
},
"audioEditRestore": {
"title": "הפעלות עריכת אודיו שמורות",
@@ -812,7 +820,9 @@
"playback": "השמעה",
"audioLoadError": "לא הצלחנו לטעון את האודיו",
"audioStillLoading": "האודיו עדיין נטען...",
"loadingAudio": "טוען אודיו..."
"loadingAudio": "טוען אודיו...",
"autoCorrect": "הצעות AI",
"autoCorrectDesc": "יצירת הצעות תיקון של AI על ידי השוואת התמלול למילות המקור. שום דבר לא ישתנה עד לאישור של כל הצעה."
},
"guidance": {
"showTips": "הצג טיפים",
@@ -986,7 +996,9 @@
"loadingAll": "טוען את כל המילים...",
"loadingSegment": "טוען מקטע...",
"noData": "אין נתוני מקטע זמינים",
"unCorrect": "בטל תיקון"
"unCorrect": "בטל תיקון",
"timingClamped": "התזמון של \"{word}\" היה מחוץ למקטע — הוצמד ל-{time} שניות.",
"timingSanitized": "תוקנו {count} תזמוני מילים שחרגו מהמקטע הזה."
},
"findReplace": {
"title": "חפש והחלף",
@@ -1268,6 +1280,50 @@
},
"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": "רמת הביטחון הנדרשת מה-AI כדי להציג הצעה",
"confidenceLabel": "מסנן הצעות",
"confidence_all": "הצג הכל",
"confidence_high": "ביטחון גבוה",
"description": "ה-AI משווה את המילים שתומללו למקורות ומציע תיקונים ברמת המילה. באפשרותך לעבור על כל הצעה — שום שינוי לא יבוצע עד לאישור.",
"dismiss": "הסתר הצעות",
"expand": "הרחב הצעות",
"insertMarker": "הוסף:",
"insertionsHint": "אפשר הצעות שמוסיפות מילים שהתפספסו בתמלול",
"insertionsLabel": "הצע מילים חסרות",
"noReferences": "אין מילות מקור זמינות לשיר זה, ולכן לא ניתן ליצור הצעות AI. יש להוסיף מילים מחלונית המקורות תחילה.",
"noSuggestions": "לא נמצאו בעיות — ל-AI אין שינויים להציע.",
"reject": "דחה הצעה",
"rejectAll": "דחה הכל",
"rejected": "נדחה",
"runButton": "קבל הצעות",
"running": "מנתח מילים… פעולה זו אורכת בדרך כלל 15–60 שניות.",
"staleHint": "מילים אלו נערכו מאז שההצעות נוצרו, ולכן הצעה זו כבר אינה רלוונטית.",
"summary": "{total} הצעות · {pending} ממתינות · {accepted} התקבלו",
"title": "הצעות תיקון של AI",
"undo": "בטל הצעה זו",
"cancel": "ביטול",
"close": "סגירה",
"confidence_balanced": "מאוזנת",
"compareHint": "איטי ויקר יותר, אבל מראה על אילו הצעות מספר מודלים מסכימים",
"compareLabel": "השוואה בין מספר מודלי AI",
"conflictBadge": "גרסה",
"conflictTooltip": "המודלים לא מסכימים לגבי המילים האלו — אישור גרסה אחת ידחה את האחרות.",
"consensusBadge": "{consensus}/{total} מודלים",
"consensusTooltip": "הוצע על ידי: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "तैयार होने पर ईमेल",
"afterApproval": "अप्रूवल के बाद, तुम्हारा कराओके वीडियो रेंडर और डिलीवर किया जाता है। ~10 मिनट",
"trackProgressTenant": "हाल के जॉब्स लिस्ट में प्रोग्रेस ट्रैक करो।",
"submitAnother": "एक और ट्रैक सबमिट करो"
"submitAnother": "एक और ट्रैक सबमिट करो",
"pasteUrlButton": "एक लिंक पेस्ट करो",
"urlSupportedSitesHint": "यह YouTube, Facebook, SoundCloud, TikTok, Vimeo और सैकड़ों अन्य साइटों के साथ काम करता है।",
"urlSupportedSitesLink": "सभी समर्थित साइटें देखो",
"useThisUrl": "इस URL का इस्तेमाल करो"
},
"jobStatus": {
"settingUp": "सेटअप हो रहा है",
@@ -772,7 +776,11 @@
"undoFailed": "अनडू विफल रहा",
"redoFailed": "रीडू विफल रहा",
"restoreFailed": "रिस्टोर विफल रहा — कुछ एडिट्स लागू नहीं हुए होंगे",
"submitFailed": "सबमिट विफल रहा"
"submitFailed": "सबमिट विफल रहा",
"fadeIn": "फ़ेड इन",
"fadeInSelection": "चुने गए हिस्से पर फ़ेड इन करो",
"fadeOut": "फ़ेड आउट",
"fadeOutSelection": "चुने गए हिस्से पर फ़ेड आउट करो"
},
"audioEditRestore": {
"title": "सेव किए गए ऑडियो एडिट सेशंस",
@@ -812,7 +820,9 @@
"playback": "प्लेबैक",
"audioLoadError": "ऑडियो लोड नहीं हो सका",
"audioStillLoading": "ऑडियो अभी भी लोड हो रहा है...",
"loadingAudio": "ऑडियो लोड हो रहा है..."
"loadingAudio": "ऑडियो लोड हो रहा है...",
"autoCorrect": "AI सुझाव",
"autoCorrectDesc": "ट्रांसक्रिप्शन की तुलना रेफरेंस लिरिक्स से करके AI सुधार के सुझाव पाओ। जब तक तुम हर सुझाव को स्वीकार नहीं करते, तब तक कुछ भी नहीं बदलता।"
},
"guidance": {
"showTips": "टिप्स दिखाओ",
@@ -986,7 +996,9 @@
"loadingAll": "सभी शब्द लोड हो रहे हैं...",
"loadingSegment": "सेगमेंट लोड हो रहा है...",
"noData": "कोई सेगमेंट डेटा उपलब्ध नहीं है",
"unCorrect": "अन-करेक्ट करो"
"unCorrect": "अन-करेक्ट करो",
"timingClamped": "\"{word}\" की टाइमिंग सेगमेंट के बाहर थी — इसे {time}s पर सेट कर दिया गया है।",
"timingSanitized": "इस सेगमेंट के बाहर आने वाली {count} शब्द की टाइमिंग को ठीक किया गया।"
},
"findReplace": {
"title": "ढूंढो और बदलो",
@@ -1268,6 +1280,50 @@
},
"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": "सुझाव दिखाने के लिए AI को कितना आश्वस्त होना चाहिए",
"confidenceLabel": "सुझाव फ़िल्टर",
"confidence_all": "सभी दिखाओ",
"confidence_high": "ज़्यादा आश्वस्त",
"description": "AI ट्रांसक्राइब किए गए लिरिक्स की तुलना रेफरेंस से करता है और शब्दों में सुधार के सुझाव देता है। तुम हर सुझाव की समीक्षा कर सकते हो — जब तक तुम उसे स्वीकार नहीं करते, तब तक कुछ भी लागू नहीं होता।",
"dismiss": "सुझाव हटाओ",
"expand": "सुझाव पूरे दिखाओ",
"insertMarker": "जोड़ो:",
"insertionsHint": "उन सुझावों को अनुमति दो जो ट्रांसक्रिप्शन में छूटे हुए शब्दों को जोड़ते हैं",
"insertionsLabel": "छूटे हुए शब्दों का सुझाव दो",
"noReferences": "इस गाने के लिए कोई रेफरेंस लिरिक्स उपलब्ध नहीं हैं, इसलिए AI सुझाव नहीं दे सकता। पहले रेफरेंस पैनल से लिरिक्स जोड़ो।",
"noSuggestions": "कोई समस्या नहीं मिली — AI के पास बदलाव के लिए कोई सुझाव नहीं है।",
"reject": "सुझाव अस्वीकार करो",
"rejectAll": "सभी अस्वीकार करो",
"rejected": "अस्वीकार किया गया",
"runButton": "सुझाव प्राप्त करो",
"running": "लिरिक्स का विश्लेषण हो रहा है… इसमें आमतौर पर 15–60 सेकंड लगते हैं।",
"staleHint": "सुझाव आने के बाद इन शब्दों को एडिट किया गया था, इसलिए यह सुझाव अब लागू नहीं होता।",
"summary": "{total} सुझाव · {pending} लंबित · {accepted} स्वीकार किए गए",
"title": "AI सुधार सुझाव",
"undo": "इस सुझाव को पूर्ववत करो",
"cancel": "कैंसल",
"close": "बंद करो",
"confidence_balanced": "संतुलित",
"compareHint": "यह धीमा है और इसमें ज़्यादा खर्च आता है, लेकिन यह दिखाता है कि किन सुझावों पर कई मॉडल सहमत हैं",
"compareLabel": "कई AI मॉडलों की तुलना करो",
"conflictBadge": "विकल्प",
"conflictTooltip": "इन शब्दों पर मॉडल असहमत हैं — एक विकल्प को स्वीकार करने से बाकी अस्वीकार हो जाते हैं।",
"consensusBadge": "{consensus}/{total} मॉडल",
"consensusTooltip": "इनके द्वारा प्रस्तावित: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail kada bude spremno",
"afterApproval": "Nakon odobrenja, tvoj karaoke video se renderira i isporučuje. ~10 minuta",
"trackProgressTenant": "Prati napredak na popisu Nedavni poslovi.",
"submitAnother": "Pošalji još jednu pjesmu"
"submitAnother": "Pošalji još jednu pjesmu",
"pasteUrlButton": "Zalijepi poveznicu",
"urlSupportedSitesHint": "Radi s platformama YouTube, Facebook, SoundCloud, TikTok, Vimeo i stotinama drugih stranica.",
"urlSupportedSitesLink": "Pogledaj sve podržane stranice",
"useThisUrl": "Upotrijebi ovaj URL"
},
"jobStatus": {
"settingUp": "Postavljanje",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Spremljene sesije uređivanja zvuka",
@@ -812,7 +820,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": "AI prijedlog",
"autoCorrectDesc": "Generiraj AI prijedloge za ispravak uspoređujući transkripciju s referentnim tekstom. Ništa se ne mijenja dok ne prihvatiš svaki prijedlog."
},
"guidance": {
"showTips": "Prikaži savjete",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 AI mora biti siguran da bi prikazao prijedlog",
"confidenceLabel": "Filtar prijedloga",
"confidence_all": "Prikaži sve",
"confidence_high": "Visoka pouzdanost",
"description": "AI 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 referentnog teksta, pa se AI prijedlozi ne mogu generirati. Prvo dodaj tekst iz referentnog panela.",
"noSuggestions": "Nisu pronađeni problemi — AI 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": "AI prijedlozi za ispravak",
"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": "Modeli se ne slažu oko ovih riječi — prihvaćanje jedne varijante odbacuje ostale.",
"consensusBadge": "{consensus}/{total} modela",
"consensusTooltip": "Predložili: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, ha kész",
"afterApproval": "A jóváhagyás után a karaoke videód renderelésre és kézbesítésre kerül. ~10 perc",
"trackProgressTenant": "Kövesd a folyamatot a Legutóbbi projektek listában.",
"submitAnother": "Másik dal beküldése"
"submitAnother": "Másik dal beküldése",
"pasteUrlButton": "Illessz be egy linket",
"urlSupportedSitesHint": "Működik a YouTube, Facebook, SoundCloud, TikTok, Vimeo és több száz más oldallal.",
"urlSupportedSitesLink": "Nézd meg az összes támogatott oldalt",
"useThisUrl": "Használd ezt az URL-t"
},
"jobStatus": {
"settingUp": "Beállítás",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Mentett hangszerkesztési munkamenetek",
@@ -812,7 +820,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": "MI-javaslat",
"autoCorrectDesc": "Generálj MI-javítási javaslatokat az átírás és a referenciadalszöveg összehasonlításával. Semmi sem változik, amíg el nem fogadod az egyes javaslatokat."
},
"guidance": {
"showTips": "Tippek mutatása",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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": "Milyen biztosnak kell lennie az MI-nek ahhoz, hogy megjelenítsen egy javaslatot",
"confidenceLabel": "Javaslatszűrő",
"confidence_all": "Összes megjelenítése",
"confidence_high": "Nagy bizonyosság",
"description": "Az MI összehasonlítja az átírt dalszöveget a referenciaforrásokkal, és szószintű 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 nem érhető el referenciadalszöveg, így az MI nem tud javaslatokat tenni. Először adj hozzá dalszöveget a referenciapanelen.",
"noSuggestions": "Nem találtunk problémát — az MI-nek nincsenek módosítási javaslatai.",
"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": "MI-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": "A modellek nem értenek egyet ezeknél a szavaknál — egy változat elfogadásával elutasítod a többit.",
"consensusBadge": "{consensus}/{total} modell",
"consensusTooltip": "Javasolta: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email saat siap",
"afterApproval": "Setelah persetujuan, video karaoke Anda dirender dan dikirim. ~10 menit",
"trackProgressTenant": "Lacak kemajuan di daftar Proyek Terbaru.",
"submitAnother": "Kirim Track Lain"
"submitAnother": "Kirim Track Lain",
"pasteUrlButton": "Tempel tautan",
"urlSupportedSitesHint": "Berfungsi dengan YouTube, Facebook, SoundCloud, TikTok, Vimeo, dan ratusan situs lainnya.",
"urlSupportedSitesLink": "Lihat semua situs yang didukung",
"useThisUrl": "Gunakan URL Ini"
},
"jobStatus": {
"settingUp": "Menyiapkan",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sesi Edit Audio Tersimpan",
@@ -812,7 +820,9 @@
"playback": "Pemutaran",
"audioLoadError": "Gagal memuat audio",
"audioStillLoading": "Audio masih dimuat...",
"loadingAudio": "Memuat audio..."
"loadingAudio": "Memuat audio...",
"autoCorrect": "Saran AI",
"autoCorrectDesc": "Buat saran koreksi AI dengan membandingkan transkripsi dengan lirik referensi. Tidak ada perubahan yang diterapkan sampai Anda menerima setiap saran."
},
"guidance": {
"showTips": "Tampilkan tips",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 AI yang diperlukan untuk menampilkan saran",
"confidenceLabel": "Filter saran",
"confidence_all": "Tampilkan semua",
"confidence_high": "Keyakinan tinggi",
"description": "AI membandingkan lirik hasil transkripsi dengan sumber referensi dan menyarankan perbaikan per kata. Anda dapat meninjau setiap saran — tidak ada perubahan yang diterapkan sampai Anda menerimanya.",
"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 AI tidak dapat dibuat. Tambahkan lirik dari panel referensi terlebih dahulu.",
"noSuggestions": "Tidak ada masalah yang ditemukan — AI tidak memiliki saran perubahan.",
"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 AI",
"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": "Model memberikan hasil berbeda untuk kata-kata ini — menerima satu varian akan menolak varian lainnya.",
"consensusBadge": "{consensus}/{total} model",
"consensusTooltip": "Diusulkan oleh: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email quando pronto",
"afterApproval": "Dopo l'approvazione, il tuo video karaoke viene renderizzato e consegnato. ~10 minuti",
"trackProgressTenant": "Segui i progressi nell'elenco Lavori recenti.",
"submitAnother": "Invia un'altra traccia"
"submitAnother": "Invia un'altra traccia",
"pasteUrlButton": "Incolla un link",
"urlSupportedSitesHint": "Funziona con YouTube, Facebook, SoundCloud, TikTok, Vimeo e centinaia di altri siti.",
"urlSupportedSitesLink": "Vedi tutti i siti supportati",
"useThisUrl": "Usa questo URL"
},
"jobStatus": {
"settingUp": "Configurazione",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sessioni di modifica audio salvate",
@@ -812,7 +820,9 @@
"playback": "Riproduzione",
"audioLoadError": "Impossibile caricare l'audio",
"audioStillLoading": "L'audio è ancora in caricamento...",
"loadingAudio": "Caricamento audio..."
"loadingAudio": "Caricamento audio...",
"autoCorrect": "Suggerimenti IA",
"autoCorrectDesc": "Genera suggerimenti di correzione dell'IA confrontando la trascrizione con il testo di riferimento. Non verrà modificato nulla finché non accetterai i singoli suggerimenti."
},
"guidance": {
"showTips": "Mostra suggerimenti",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 sicura l'IA prima di mostrare un suggerimento",
"confidenceLabel": "Filtro suggerimenti",
"confidence_all": "Mostra tutti",
"confidence_high": "Alta sicurezza",
"description": "L'IA confronta il testo trascritto con le fonti di riferimento e suggerisce correzioni parola per parola. Sei tu a controllare 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 sono disponibili testi di riferimento per questa canzone, quindi non è possibile generare i suggerimenti dell'IA. Aggiungi prima un testo dal pannello dei riferimenti.",
"noSuggestions": "Nessun problema trovato: l'IA non ha modifiche da suggerire.",
"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 dell'IA",
"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": "I modelli non concordano su queste parole — accettare una variante esclude le altre.",
"consensusBadge": "{consensus}/{total} modelli",
"consensusTooltip": "Proposto da: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "準備完了時にメールでお知らせ",
"afterApproval": "承認後、カラオケ動画がレンダリングされ納品されます。約10分",
"trackProgressTenant": "最近のジョブリストで進捗を追跡します。",
"submitAnother": "別のトラックを送信"
"submitAnother": "別のトラックを送信",
"pasteUrlButton": "リンクを貼り付ける",
"urlSupportedSitesHint": "YouTube、Facebook、SoundCloud、TikTok、Vimeoなど、数百ものサイトに対応しています。",
"urlSupportedSitesLink": "対応サイト一覧を見る",
"useThisUrl": "このURLを使用する"
},
"jobStatus": {
"settingUp": "セットアップ中",
@@ -772,7 +776,11 @@
"undoFailed": "元に戻す操作に失敗しました",
"redoFailed": "やり直し操作に失敗しました",
"restoreFailed": "復元に失敗しました — 一部の編集が適用されていない可能性があります",
"submitFailed": "送信に失敗しました"
"submitFailed": "送信に失敗しました",
"fadeIn": "フェードイン",
"fadeInSelection": "選択した範囲をフェードイン",
"fadeOut": "フェードアウト",
"fadeOutSelection": "選択した範囲をフェードアウト"
},
"audioEditRestore": {
"title": "保存されたオーディオ編集セッション",
@@ -812,7 +820,9 @@
"playback": "再生",
"audioLoadError": "音声を読み込めませんでした",
"audioStillLoading": "音声はまだ読み込み中です...",
"loadingAudio": "音声を読み込み中..."
"loadingAudio": "音声を読み込み中...",
"autoCorrect": "AI提案",
"autoCorrectDesc": "文字起こしとリファレンス歌詞を比較して、AIが修正案を生成します。各提案を採用するまで、実際の歌詞が変更されることはありません。"
},
"guidance": {
"showTips": "ヒントを表示",
@@ -986,7 +996,9 @@
"loadingAll": "すべての単語を読み込み中...",
"loadingSegment": "セグメントを読み込み中...",
"noData": "利用可能なセグメントデータがありません",
"unCorrect": "修正を取り消す"
"unCorrect": "修正を取り消す",
"timingClamped": "\"{word}\" のタイミングがセグメント外だったため、{time}秒に調整されました。",
"timingSanitized": "このセグメント外にあった {count} 個の単語のタイミングを修正しました。"
},
"findReplace": {
"title": "検索と置換",
@@ -1268,6 +1280,50 @@
},
"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": "AIがどの程度の確信度で提案を表示するかの基準です。",
"confidenceLabel": "提案フィルター",
"confidence_all": "すべて表示",
"confidence_high": "高い確信度",
"description": "AIが文字起こしされた歌詞とリファレンスを比較し、単語レベルで修正を提案します。すべての提案はご自身で確認でき、採用するまで実際の歌詞には反映されません。",
"dismiss": "提案を非表示にする",
"expand": "提案を展開する",
"insertMarker": "挿入:",
"insertionsHint": "文字起こしで抜けている単語を追加する提案を表示します。",
"insertionsLabel": "不足している単語の追加を提案",
"noReferences": "この曲にはリファレンス歌詞がないため、AIの提案を生成できません。まずリファレンスパネルから歌詞を追加してください。",
"noSuggestions": "問題は見つかりませんでした。AIからの修正提案はありません。",
"reject": "提案を却下する",
"rejectAll": "すべて却下する",
"rejected": "却下済み",
"runButton": "提案を取得する",
"running": "歌詞を分析しています… 通常15〜60秒かかります。",
"staleHint": "提案の生成後に歌詞が編集されたため、この提案は無効になりました。",
"summary": "{total}件の提案 · 保留中 {pending}件 · 採用済み {accepted}件",
"title": "AI修正提案",
"undo": "この提案を元に戻す",
"cancel": "キャンセル",
"close": "閉じる",
"confidence_balanced": "バランス",
"compareHint": "時間とコストはかかりますが、複数のモデルで一致した提案を確認できます。",
"compareLabel": "複数のAIモデルを比較する",
"conflictBadge": "別案",
"conflictTooltip": "モデル間でこれらの単語の認識が異なります。1つの案を採用すると、他の案は破棄されます。",
"consensusBadge": "{consensus}/{total} モデル",
"consensusTooltip": "提案元: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "준비 시 이메일 알림",
"afterApproval": "승인 후 노래방 비디오가 렌더링되어 전달됩니다. 약 10분 소요",
"trackProgressTenant": "최근 작업 목록에서 진행 상황을 추적하세요.",
"submitAnother": "다른 트랙 제출"
"submitAnother": "다른 트랙 제출",
"pasteUrlButton": "링크 붙여넣기",
"urlSupportedSitesHint": "YouTube, Facebook, SoundCloud, TikTok, Vimeo 등 수백 개의 사이트에서 사용할 수 있습니다.",
"urlSupportedSitesLink": "지원되는 모든 사이트 보기",
"useThisUrl": "이 URL 사용하기"
},
"jobStatus": {
"settingUp": "설정 중",
@@ -772,7 +776,11 @@
"undoFailed": "실행 취소 실패",
"redoFailed": "다시 실행 실패",
"restoreFailed": "복원 실패 — 일부 편집 내용이 적용되지 않았을 수 있습니다",
"submitFailed": "제출 실패"
"submitFailed": "제출 실패",
"fadeIn": "페이드 인",
"fadeInSelection": "선택한 영역에 페이드 인 적용",
"fadeOut": "페이드 아웃",
"fadeOutSelection": "선택한 영역에 페이드 아웃 적용"
},
"audioEditRestore": {
"title": "저장된 오디오 편집 세션",
@@ -812,7 +820,9 @@
"playback": "재생",
"audioLoadError": "오디오를 불러올 수 없습니다",
"audioStillLoading": "아직 오디오를 불러오는 중입니다...",
"loadingAudio": "오디오를 불러오는 중입니다..."
"loadingAudio": "오디오를 불러오는 중입니다...",
"autoCorrect": "AI 제안",
"autoCorrectDesc": "변환된 가사를 참조 가사와 비교하여 AI 수정 제안을 생성합니다. 각 제안을 수락하기 전까지는 아무것도 변경되지 않습니다."
},
"guidance": {
"showTips": "팁 표시",
@@ -986,7 +996,9 @@
"loadingAll": "모든 단어 불러오는 중...",
"loadingSegment": "세그먼트 불러오는 중...",
"noData": "세그먼트 데이터가 없습니다",
"unCorrect": "수정 취소"
"unCorrect": "수정 취소",
"timingClamped": "\"{word}\" 타이밍이 구간을 벗어나 {time}초로 조정되었습니다.",
"timingSanitized": "이 구간을 벗어난 단어 타이밍 {count}개를 수정했습니다."
},
"findReplace": {
"title": "찾기 및 바꾸기",
@@ -1268,6 +1280,50 @@
},
"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": "제안을 표시하기 위한 AI의 확신도 기준",
"confidenceLabel": "제안 필터",
"confidence_all": "모두 보기",
"confidence_high": "높은 확신도",
"description": "AI가 변환된 가사를 참조 소스와 비교하여 단어 수준의 수정을 제안합니다. 모든 제안을 검토할 수 있으며, 수락하기 전까지는 아무것도 적용되지 않습니다.",
"dismiss": "제안 무시",
"expand": "제안 펼치기",
"insertMarker": "삽입:",
"insertionsHint": "변환 과정에서 누락된 단어를 삽입하는 제안 허용",
"insertionsLabel": "누락된 단어 제안",
"noReferences": "이 노래에 사용할 수 있는 참조 가사가 없어 AI 제안을 생성할 수 없습니다. 먼저 참조 패널에서 가사를 추가해 주세요.",
"noSuggestions": "발견된 문제 없음 — AI가 제안할 변경 사항이 없습니다.",
"reject": "제안 거부",
"rejectAll": "모두 거부",
"rejected": "거부됨",
"runButton": "제안 받기",
"running": "가사 분석 중… 보통 15~60초 정도 걸립니다.",
"staleHint": "제안이 생성된 후 해당 단어가 수정되어 이 제안은 더 이상 유효하지 않습니다.",
"summary": "{total}개 제안 · {pending}개 대기 중 · {accepted}개 수락됨",
"title": "AI 수정 제안",
"undo": "이 제안 실행 취소",
"cancel": "취소",
"close": "닫기",
"confidence_balanced": "균형",
"compareHint": "시간과 비용이 더 들지만, 여러 모델이 공통으로 제안하는 내용을 확인할 수 있어요.",
"compareLabel": "여러 AI 모델 비교하기",
"conflictBadge": "다른 버전",
"conflictTooltip": "이 단어들에 대해 모델마다 제안이 달라요. 하나의 버전을 수락하면 나머지는 반영되지 않아요.",
"consensusBadge": "{consensus}/{total}개 모델",
"consensusTooltip": "제안한 모델: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mel apabila sedia",
"afterApproval": "Selepas kelulusan, video karaoke anda dirender dan dihantar. ~10 minit",
"trackProgressTenant": "Jejaki kemajuan dalam senarai Kerja Terkini.",
"submitAnother": "Hantar Trek Lain"
"submitAnother": "Hantar Trek Lain",
"pasteUrlButton": "Tampal pautan",
"urlSupportedSitesHint": "Berfungsi dengan YouTube, Facebook, SoundCloud, TikTok, Vimeo dan beratus-ratus laman web lain.",
"urlSupportedSitesLink": "Lihat semua laman web yang disokong",
"useThisUrl": "Gunakan URL Ini"
},
"jobStatus": {
"settingUp": "Menyediakan",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sesi Suntingan Audio Disimpan",
@@ -812,7 +820,9 @@
"playback": "Main Balik",
"audioLoadError": "Tidak dapat memuatkan audio",
"audioStillLoading": "Audio masih dimuatkan...",
"loadingAudio": "Memuatkan audio..."
"loadingAudio": "Memuatkan audio...",
"autoCorrect": "Cadangan AI",
"autoCorrectDesc": "Jana cadangan pembetulan AI dengan membandingkan transkripsi dengan lirik rujukan. Tiada perubahan akan dibuat sehingga anda menerima setiap cadangan."
},
"guidance": {
"showTips": "Tunjukkan petua",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 AI yang diperlukan untuk menunjukkan cadangan",
"confidenceLabel": "Penapis cadangan",
"confidence_all": "Tunjukkan semua",
"confidence_high": "Keyakinan tinggi",
"description": "AI membandingkan lirik yang ditranskripsi dengan sumber rujukan dan mencadangkan pembetulan pada peringkat perkataan. Anda 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 AI tidak dapat dijana. Tambahkan lirik dari panel rujukan terlebih dahulu.",
"noSuggestions": "Tiada isu ditemui — AI tiada cadangan perubahan.",
"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 AI",
"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": "Model tidak bersetuju tentang perkataan ini — menerima satu varian akan menolak varian yang lain.",
"consensusBadge": "{consensus}/{total} model",
"consensusTooltip": "Dicadangkan oleh: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-post når klar",
"afterApproval": "Etter godkjenning blir karaokevideoen din gjengitt og levert. ~10 minutter",
"trackProgressTenant": "Følg fremdriften i listen over nylige jobber.",
"submitAnother": "Send inn et nytt spor"
"submitAnother": "Send inn et nytt spor",
"pasteUrlButton": "Lim inn en lenke",
"urlSupportedSitesHint": "Fungerer med YouTube, Facebook, SoundCloud, TikTok, Vimeo og hundrevis av andre nettsteder.",
"urlSupportedSitesLink": "Se alle støttede nettsteder",
"useThisUrl": "Bruk denne URL-en"
},
"jobStatus": {
"settingUp": "Setter opp",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Lagrede lydredigeringsøkter",
@@ -812,7 +820,9 @@
"playback": "Avspilling",
"audioLoadError": "Kunne ikke laste inn lyd",
"audioStillLoading": "Lyden laster fortsatt inn...",
"loadingAudio": "Laster inn lyd..."
"loadingAudio": "Laster inn lyd...",
"autoCorrect": "AI-forslag",
"autoCorrectDesc": "Generer AI-korrigeringsforslag ved å sammenligne transkripsjonen med referanseteksten. Ingenting endres før du godtar hvert forslag."
},
"guidance": {
"showTips": "Vis tips",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 sikker AI-en må være for å vise et forslag",
"confidenceLabel": "Forslagsfilter",
"confidence_all": "Vis alle",
"confidence_high": "Høy sikkerhet",
"description": "AI-en sammenligner den transkriberte teksten med referansekildene og foreslår rettelser på ordnivå. Du går gjennom hvert forslag — ingenting blir endret 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 referansetekster er tilgjengelige for denne sangen, så AI-forslag kan ikke genereres. Legg til tekst fra referansepanelet først.",
"noSuggestions": "Ingen problemer funnet — AI-en har 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": "AI-korrigeringsforslag",
"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": "Modellene er uenige om disse ordene — hvis du godtar én variant, avvises de andre.",
"consensusBadge": "{consensus}/{total} modeller",
"consensusTooltip": "Foreslått av: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail wanneer klaar",
"afterApproval": "Na goedkeuring wordt je karaokevideo gerenderd en geleverd. ~10 minuten",
"trackProgressTenant": "Volg de voortgang in de Recente Taken lijst.",
"submitAnother": "Nog een track indienen"
"submitAnother": "Nog een track indienen",
"pasteUrlButton": "Plak een link",
"urlSupportedSitesHint": "Werkt met YouTube, Facebook, SoundCloud, TikTok, Vimeo en honderden andere sites.",
"urlSupportedSitesLink": "Bekijk alle ondersteunde sites",
"useThisUrl": "Gebruik deze URL"
},
"jobStatus": {
"settingUp": "Instellen",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Opgeslagen Audio Bewerkingssessies",
@@ -812,7 +820,9 @@
"playback": "Afspelen",
"audioLoadError": "Kon audio niet laden",
"audioStillLoading": "Audio is nog aan het laden...",
"loadingAudio": "Audio laden..."
"loadingAudio": "Audio laden...",
"autoCorrect": "AI-suggesties",
"autoCorrectDesc": "Genereer AI-correctiesuggesties door de transcriptie te vergelijken met de referentiesongtekst. Er wordt niets gewijzigd totdat je elke suggestie accepteert."
},
"guidance": {
"showTips": "Toon tips",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 de AI moet zijn om een suggestie te tonen",
"confidenceLabel": "Suggestiefilter",
"confidence_all": "Toon alles",
"confidence_high": "Hoge zekerheid",
"description": "De AI 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 AI-suggesties worden gegenereerd. Voeg eerst een songtekst toe via het referentiepaneel.",
"noSuggestions": "Geen problemen gevonden — de AI heeft geen wijzigingen voorgesteld.",
"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": "AI-correctiesuggesties",
"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": "De modellen zijn het niet eens over deze woorden — als je één variant accepteert, wijs je de andere af.",
"consensusBadge": "{consensus}/{total} modellen",
"consensusTooltip": "Voorgesteld door: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, gdy gotowe",
"afterApproval": "Po zatwierdzeniu twoje wideo karaoke jest renderowane i dostarczane. ~10 minut",
"trackProgressTenant": "Śledź postępy na liście Ostatnich zadań.",
"submitAnother": "Prześlij kolejny utwór"
"submitAnother": "Prześlij kolejny utwór",
"pasteUrlButton": "Wklej link",
"urlSupportedSitesHint": "Działa z YouTube, Facebookiem, SoundCloud, TikTokiem, Vimeo i setkami innych stron.",
"urlSupportedSitesLink": "Zobacz wszystkie obsługiwane strony",
"useThisUrl": "Użyj tego adresu URL"
},
"jobStatus": {
"settingUp": "Konfigurowanie",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Zapisane sesje edycji dźwięku",
@@ -812,7 +820,9 @@
"playback": "Odtwarzanie",
"audioLoadError": "Nie udało się załadować audio",
"audioStillLoading": "Audio wciąż się ładuje...",
"loadingAudio": "Ładowanie audio..."
"loadingAudio": "Ładowanie audio...",
"autoCorrect": "Sugestie AI",
"autoCorrectDesc": "Generuj sugestie poprawek AI, porównując transkrypcję z tekstem referencyjnym. Nic nie zostanie zmienione, dopóki nie zaakceptujesz każdej sugestii."
},
"guidance": {
"showTips": "Pokaż wskazówki",
@@ -986,7 +996,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ń",
@@ -1268,6 +1280,50 @@
},
"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": "Jak pewne musi być AI, aby pokazać sugestię",
"confidenceLabel": "Filtr sugestii",
"confidence_all": "Pokaż wszystkie",
"confidence_high": "Wysoka pewność",
"description": "AI porównuje transkrybowany tekst ze źródłami referencyjnymi i sugeruje poprawki na poziomie słów. Przeglądasz każdą sugestię — nic nie zostanie zmienione, 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 tej piosenki nie ma dostępnego tekstu referencyjnego, więc nie można wygenerować sugestii AI. Najpierw dodaj tekst w panelu referencyjnym.",
"noSuggestions": "Nie znaleziono problemów — AI nie ma 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 poprawek AI",
"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": "Modele nie są zgodne co do tych słów — zaakceptowanie jednego wariantu odrzuca pozostałe.",
"consensusBadge": "{consensus}/{total} modeli",
"consensusTooltip": "Zaproponowane przez: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail quando pronto",
"afterApproval": "Após a aprovação, seu vídeo de karaokê é renderizado e entregue. ~10 minutos",
"trackProgressTenant": "Acompanhe o progresso na lista de Trabalhos Recentes.",
"submitAnother": "Enviar Outra Faixa"
"submitAnother": "Enviar Outra Faixa",
"pasteUrlButton": "Cole um link",
"urlSupportedSitesHint": "Funciona com YouTube, Facebook, SoundCloud, TikTok, Vimeo e centenas de outros sites.",
"urlSupportedSitesLink": "Ver todos os sites compatíveis",
"useThisUrl": "Usar esta URL"
},
"jobStatus": {
"settingUp": "Configurando",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sessões de Edição de Áudio Salvas",
@@ -812,7 +820,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": "Sugestões da IA",
"autoCorrectDesc": "Gere sugestões de correção da IA comparando a transcrição com a letra de referência. Nada é alterado até que você aceite cada sugestão."
},
"guidance": {
"showTips": "Mostrar dicas",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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": "O nível de confiança que a IA deve ter para mostrar uma sugestão",
"confidenceLabel": "Filtro de sugestões",
"confidence_all": "Mostrar todas",
"confidence_high": "Alta confiança",
"description": "A IA 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, portanto, não é possível gerar sugestões da IA. Adicione a letra no painel de referência primeiro.",
"noSuggestions": "Nenhum problema encontrado — a IA não tem 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 correção da IA",
"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": "Os modelos discordam sobre estas palavras — aceitar uma variante rejeita as outras.",
"consensusBadge": "{consensus}/{total} modelos",
"consensusTooltip": "Proposto por: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email când este gata",
"afterApproval": "După aprobare, videoclipul tău de karaoke este randat și livrat. ~10 minute",
"trackProgressTenant": "Urmărește progresul în lista de Joburi recente.",
"submitAnother": "Trimite altă piesă"
"submitAnother": "Trimite altă piesă",
"pasteUrlButton": "Lipește un link",
"urlSupportedSitesHint": "Funcționează cu YouTube, Facebook, SoundCloud, TikTok, Vimeo și sute de alte site-uri.",
"urlSupportedSitesLink": "Vezi toate site-urile acceptate",
"useThisUrl": "Folosește acest URL"
},
"jobStatus": {
"settingUp": "Se configurează",
@@ -772,7 +776,11 @@
"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ă"
},
"audioEditRestore": {
"title": "Sesiuni de editare audio salvate",
@@ -812,7 +820,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": "Sugestii AI",
"autoCorrectDesc": "Generează sugestii de corectare AI comparând transcrierea cu versurile de referință. Nimic nu se modifică până nu accepți fiecare sugestie."
},
"guidance": {
"showTips": "Arată sfaturi",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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 AI-ul pentru a afișa o sugestie",
"confidenceLabel": "Filtru de sugestii",
"confidence_all": "Afișează toate",
"confidence_high": "Încredere ridicată",
"description": "AI-ul compară versurile transcrise cu sursele de referință și sugerează corecturi la nivel de cuvânt. Tu revizuiești fiecare sugestie — nimic nu se aplică 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 sunt disponibile versuri de referință pentru această melodie, așa că sugestiile AI nu pot fi generate. Adaugă mai întâi versuri din panoul de referință.",
"noSuggestions": "Nu s-au găsit probleme — AI-ul nu are 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 corectare AI",
"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": "Modelele au variante diferite pentru aceste cuvinte — dacă accepți o variantă, le respingi pe celelalte.",
"consensusBadge": "{consensus}/{total} modele",
"consensusTooltip": "Propus de: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email, когда будет готово",
"afterApproval": "После утверждения твое караоке-видео рендерится и доставляется. ~10 минут",
"trackProgressTenant": "Отслеживай прогресс в списке Недавних задач.",
"submitAnother": "Отправить еще один трек"
"submitAnother": "Отправить еще один трек",
"pasteUrlButton": "Вставить ссылку",
"urlSupportedSitesHint": "Работает с YouTube, Facebook, SoundCloud, TikTok, Vimeo и сотнями других сайтов.",
"urlSupportedSitesLink": "Посмотреть все поддерживаемые сайты",
"useThisUrl": "Использовать эту ссылку"
},
"jobStatus": {
"settingUp": "Настройка",
@@ -772,7 +776,11 @@
"undoFailed": "Ошибка отмены",
"redoFailed": "Ошибка повтора",
"restoreFailed": "Ошибка восстановления — некоторые правки могли быть не применены",
"submitFailed": "Ошибка отправки"
"submitFailed": "Ошибка отправки",
"fadeIn": "Плавное нарастание",
"fadeInSelection": "Плавное нарастание в выделенной области",
"fadeOut": "Плавное затухание",
"fadeOutSelection": "Плавное затухание в выделенной области"
},
"audioEditRestore": {
"title": "Сохраненные сессии редактирования аудио",
@@ -812,7 +820,9 @@
"playback": "Воспроизведение",
"audioLoadError": "Не удалось загрузить аудио",
"audioStillLoading": "Аудио всё ещё загружается...",
"loadingAudio": "Загрузка аудио..."
"loadingAudio": "Загрузка аудио...",
"autoCorrect": "Правки от ИИ",
"autoCorrectDesc": "Получи от ИИ предложенные правки на основе сравнения распознанного текста с эталонным. Ничего не изменится, пока ты не примешь каждую из них."
},
"guidance": {
"showTips": "Показать советы",
@@ -986,7 +996,9 @@
"loadingAll": "Загрузка всех слов...",
"loadingSegment": "Загрузка сегмента...",
"noData": "Нет данных сегмента",
"unCorrect": "Отменить исправление"
"unCorrect": "Отменить исправление",
"timingClamped": "Тайминг \"{word}\" выходил за пределы сегмента — установлен на {time} с.",
"timingSanitized": "Исправлено {count} таймингов слов, выходивших за пределы этого сегмента."
},
"findReplace": {
"title": "Найти и заменить",
@@ -1268,6 +1280,50 @@
},
"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}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "E-mail, keď bude hotovo",
"afterApproval": "Po schválení sa tvoje karaoke video vyrenderuje a doručí. ~10 minút",
"trackProgressTenant": "Sleduj pokrok v zozname Nedávne úlohy.",
"submitAnother": "Odoslať ďalšiu skladbu"
"submitAnother": "Odoslať ďalšiu skladbu",
"pasteUrlButton": "Vlož odkaz",
"urlSupportedSitesHint": "Funguje s YouTube, Facebook, SoundCloud, TikTok, Vimeo a stovkami ďalších stránok.",
"urlSupportedSitesLink": "Pozri si všetky podporované stránky",
"useThisUrl": "Použi túto URL"
},
"jobStatus": {
"settingUp": "Nastavuje sa",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Uložené relácie úprav zvuku",
@@ -812,7 +820,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": "Návrhy AI",
"autoCorrectDesc": "Vygeneruj si návrhy opráv od AI porovnaním prepisu s referenčným textom. Nič sa nezmení, kým jednotlivé návrhy neprijmeš."
},
"guidance": {
"showTips": "Zobraziť tipy",
@@ -986,7 +996,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ť",
@@ -1268,6 +1280,50 @@
},
"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": "Nakoľko si musí byť AI istá, aby zobrazila návrh",
"confidenceLabel": "Filter návrhov",
"confidence_all": "Zobraziť všetko",
"confidence_high": "Vysoká istota",
"description": "AI porovná prepísaný text s referenčnými zdrojmi a navrhne opravy na úrovni jednotlivých slov. Každý návrh si môžeš skontrolovať — nič sa nezmení, kým ho neprijmeš.",
"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 sú k dispozícii žiadne referenčné texty, takže nie je možné vygenerovať návrhy AI. Najprv pridaj text z referenčného panela.",
"noSuggestions": "Nenašli sa žiadne problémy — AI nenavrhuje žiadne 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 opráv AI",
"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": "Modely sa nezhodujú na týchto slovách — prijatím jedného variantu odmietneš ostatné.",
"consensusBadge": "{consensus}/{total} modelov",
"consensusTooltip": "Navrhli: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Mejla när det är klart",
"afterApproval": "Efter godkännande renderas och levereras din karaokevideo. ~10 minuter",
"trackProgressTenant": "Följ framstegen i listan över senaste jobb.",
"submitAnother": "Skicka in ett till spår"
"submitAnother": "Skicka in ett till spår",
"pasteUrlButton": "Klistra in en länk",
"urlSupportedSitesHint": "Fungerar med YouTube, Facebook, SoundCloud, TikTok, Vimeo och hundratals andra webbplatser.",
"urlSupportedSitesLink": "Se alla webbplatser som stöds",
"useThisUrl": "Använd den här URL:en"
},
"jobStatus": {
"settingUp": "Ställer in",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Sparade ljudredigeringssessioner",
@@ -812,7 +820,9 @@
"playback": "Uppspelning",
"audioLoadError": "Kunde inte ladda ljudet",
"audioStillLoading": "Ljudet laddas fortfarande...",
"loadingAudio": "Laddar ljud..."
"loadingAudio": "Laddar ljud...",
"autoCorrect": "AI-förslag",
"autoCorrectDesc": "Generera AI-korrigeringsförslag genom att jämföra transkriberingen med referenstexten. Inget ändras förrän du accepterar varje förslag."
},
"guidance": {
"showTips": "Visa tips",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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äker AI:n måste vara för att visa ett förslag",
"confidenceLabel": "Förslagsfilter",
"confidence_all": "Visa alla",
"confidence_high": "Hög säkerhet",
"description": "AI:n jämför den transkriberade låttexten med referenskällorna och föreslår korrigeringar på ordnivå. Du granskar varje förslag — inget 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": "Inga referenstexter är tillgängliga för den här låten, så AI-förslag kan inte genereras. Lägg till låttext från referenspanelen först.",
"noSuggestions": "Inga problem hittades — AI:n har 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": "AI-korrigeringsfö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": "Modellerna är oense om dessa ord — om du accepterar en variant väljs de andra bort.",
"consensusBadge": "{consensus}/{total} modeller",
"consensusTooltip": "Föreslaget av: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "ส่งอีเมลเมื่อพร้อม",
"afterApproval": "หลังจากอนุมัติ วิดีโอคาราโอเกะของคุณจะถูกเรนเดอร์และจัดส่ง ~10 นาที",
"trackProgressTenant": "ติดตามความคืบหน้าในรายการงานล่าสุด",
"submitAnother": "ส่งแทร็กอื่น"
"submitAnother": "ส่งแทร็กอื่น",
"pasteUrlButton": "วางลิงก์",
"urlSupportedSitesHint": "รองรับการใช้งานกับ YouTube, Facebook, SoundCloud, TikTok, Vimeo และเว็บไซต์อื่นๆ อีกหลายร้อยแห่ง",
"urlSupportedSitesLink": "ดูเว็บไซต์ที่รองรับทั้งหมด",
"useThisUrl": "ใช้ URL นี้"
},
"jobStatus": {
"settingUp": "กำลังตั้งค่า",
@@ -772,7 +776,11 @@
"undoFailed": "การเลิกทำล้มเหลว",
"redoFailed": "การทำซ้ำล้มเหลว",
"restoreFailed": "การกู้คืนล้มเหลว — การแก้ไขบางอย่างอาจไม่ถูกนำไปใช้",
"submitFailed": "การส่งล้มเหลว"
"submitFailed": "การส่งล้มเหลว",
"fadeIn": "เฟดอิน",
"fadeInSelection": "เฟดอินในส่วนที่เลือก",
"fadeOut": "เฟดเอาต์",
"fadeOutSelection": "เฟดเอาต์ในส่วนที่เลือก"
},
"audioEditRestore": {
"title": "เซสชันการแก้ไขเสียงที่บันทึกไว้",
@@ -812,7 +820,9 @@
"playback": "การเล่น",
"audioLoadError": "ไม่สามารถโหลดเสียงได้",
"audioStillLoading": "ไฟล์เสียงยังโหลดอยู่...",
"loadingAudio": "กำลังโหลดไฟล์เสียง..."
"loadingAudio": "กำลังโหลดไฟล์เสียง...",
"autoCorrect": "AI แนะนำ",
"autoCorrectDesc": "สร้างคำแนะนำการแก้ไขจาก AI โดยเปรียบเทียบการถอดความกับเนื้อเพลงอ้างอิง จะไม่มีการเปลี่ยนแปลงใดๆ จนกว่าคุณจะยอมรับแต่ละคำแนะนำ"
},
"guidance": {
"showTips": "แสดงเคล็ดลับ",
@@ -986,7 +996,9 @@
"loadingAll": "กำลังโหลดคำทั้งหมด...",
"loadingSegment": "กำลังโหลดส่วน...",
"noData": "ไม่มีข้อมูลส่วน",
"unCorrect": "ยกเลิกการแก้ไข"
"unCorrect": "ยกเลิกการแก้ไข",
"timingClamped": "เวลาของ \"{word}\" อยู่นอกช่วง — ปรับไปที่ {time} วินาที",
"timingSanitized": "แก้ไขเวลาของคำจำนวน {count} คำที่อยู่นอกช่วงนี้"
},
"findReplace": {
"title": "ค้นหาและแทนที่",
@@ -1268,6 +1280,50 @@
},
"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": "ระดับความมั่นใจของ AI ในการแสดงคำแนะนำ",
"confidenceLabel": "ตัวกรองคำแนะนำ",
"confidence_all": "แสดงทั้งหมด",
"confidence_high": "ความมั่นใจสูง",
"description": "AI จะเปรียบเทียบเนื้อเพลงที่ถอดความกับแหล่งอ้างอิงและแนะนำการแก้ไขในระดับคำ คุณสามารถตรวจสอบทุกคำแนะนำได้ — จะไม่มีการเปลี่ยนแปลงใดๆ จนกว่าคุณจะกดยอมรับ",
"dismiss": "ปิดคำแนะนำ",
"expand": "ขยายคำแนะนำ",
"insertMarker": "แทรก:",
"insertionsHint": "อนุญาตให้แนะนำการแทรกคำที่ตกหล่นจากการถอดความ",
"insertionsLabel": "แนะนำคำที่หายไป",
"noReferences": "ไม่มีเนื้อเพลงอ้างอิงสำหรับเพลงนี้ จึงไม่สามารถสร้างคำแนะนำจาก AI ได้ กรุณาเพิ่มเนื้อเพลงจากแผงอ้างอิงก่อน",
"noSuggestions": "ไม่พบปัญหา — AI ไม่มีคำแนะนำในการแก้ไข",
"reject": "ปฏิเสธคำแนะนำ",
"rejectAll": "ปฏิเสธทั้งหมด",
"rejected": "ปฏิเสธแล้ว",
"runButton": "รับคำแนะนำ",
"running": "กำลังวิเคราะห์เนื้อเพลง… โดยปกติจะใช้เวลา 15–60 วินาที",
"staleHint": "คำเหล่านี้ถูกแก้ไขหลังจากที่สร้างคำแนะนำแล้ว คำแนะนำนี้จึงไม่สามารถใช้ได้อีกต่อไป",
"summary": "{total} คำแนะนำ · รอดำเนินการ {pending} รายการ · ยอมรับแล้ว {accepted} รายการ",
"title": "คำแนะนำการแก้ไขจาก AI",
"undo": "เลิกทำคำแนะนำนี้",
"cancel": "ยกเลิก",
"close": "ปิด",
"confidence_balanced": "สมดุล",
"compareHint": "ช้ากว่าและมีค่าใช้จ่ายสูงกว่า แต่จะแสดงคำแนะนำที่โมเดลหลายตัวเห็นตรงกัน",
"compareLabel": "เปรียบเทียบโมเดล AI หลายตัว",
"conflictBadge": "ตัวเลือก",
"conflictTooltip": "โมเดลให้ผลลัพธ์คำเหล่านี้ไม่ตรงกัน — การเลือกตัวเลือกหนึ่งจะเป็นการปฏิเสธตัวเลือกอื่นๆ",
"consensusBadge": "{consensus}/{total} โมเดล",
"consensusTooltip": "เสนอโดย: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Mag-email kapag handa na",
"afterApproval": "Pagkatapos aprubahan, ire-render at idedeliver ang iyong karaoke video. ~10 minuto",
"trackProgressTenant": "Subaybayan ang progreso sa listahan ng Mga Kamakailang Job.",
"submitAnother": "Mag-submit ng Ibang Track"
"submitAnother": "Mag-submit ng Ibang Track",
"pasteUrlButton": "Mag-paste ng link",
"urlSupportedSitesHint": "Gumagana sa YouTube, Facebook, SoundCloud, TikTok, Vimeo at daan-daang iba pang mga site.",
"urlSupportedSitesLink": "Tingnan ang lahat ng suportadong site",
"useThisUrl": "Gamitin ang URL na Ito"
},
"jobStatus": {
"settingUp": "Sine-set up",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Mga Naka-save na Audio Edit Session",
@@ -812,7 +820,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": "AI Suggest",
"autoCorrectDesc": "Bumuo ng mga mungkahi sa pagwawasto ng AI sa pamamagitan ng pagkukumpara ng transcription sa reference lyrics. Walang mababago hangga't hindi mo tinatanggap ang bawat mungkahi."
},
"guidance": {
"showTips": "Ipakita ang mga tip",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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": "Gaano dapat kasigurado ang AI para magpakita ng mungkahi",
"confidenceLabel": "Filter ng mungkahi",
"confidence_all": "Ipakita lahat",
"confidence_high": "Mataas na kasiguraduhan",
"description": "Ikinukumpara ng AI 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 mababago 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 makakagawa ng mga AI suggestion. Magdagdag muna ng lyrics mula sa reference panel.",
"noSuggestions": "Walang nakitang isyu — walang iminumungkahing pagbabago ang AI.",
"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 sa pagwawasto ng AI",
"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": "Hindi magkakatugma ang mga modelo sa mga salitang ito — kapag tinanggap ang isang variant, tatanggihan ang iba.",
"consensusBadge": "{consensus}/{total} modelo",
"consensusTooltip": "Iminungkahi ng: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Hazır olduğunda e-posta",
"afterApproval": "Onaydan sonra karaoke videon oluşturulur ve teslim edilir. ~10 dakika",
"trackProgressTenant": "İlerlemeyi Son İşler listesinden takip et.",
"submitAnother": "Başka Bir Parça Gönder"
"submitAnother": "Başka Bir Parça Gönder",
"pasteUrlButton": "Bir bağlantı yapıştır",
"urlSupportedSitesHint": "YouTube, Facebook, SoundCloud, TikTok, Vimeo ve yüzlerce başka siteyle çalışır.",
"urlSupportedSitesLink": "Desteklenen tüm siteleri gör",
"useThisUrl": "Bu URL'yi Kullan"
},
"jobStatus": {
"settingUp": "Ayarlanıyor",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Kaydedilmiş Ses Düzenleme Oturumları",
@@ -812,7 +820,9 @@
"playback": "Oynatma",
"audioLoadError": "Ses yüklenemedi",
"audioStillLoading": "Ses hâlâ yükleniyor...",
"loadingAudio": "Ses yükleniyor..."
"loadingAudio": "Ses yükleniyor...",
"autoCorrect": "Yapay Zeka Önerisi",
"autoCorrectDesc": "Deşifreyi referans şarkı sözleriyle karşılaştırarak yapay zeka düzeltme önerileri oluştur. Sen her bir öneriyi kabul edene kadar hiçbir şey değiştirilmez."
},
"guidance": {
"showTips": "İpuçlarını göster",
@@ -986,7 +996,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",
@@ -1268,6 +1280,50 @@
},
"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": "Yapay zekanın bir öneri göstermesi için ne kadar emin olması gerektiği",
"confidenceLabel": "Öneri filtresi",
"confidence_all": "Tümünü göster",
"confidence_high": "Yüksek güven",
"description": "Yapay zeka, deşifre edilen şarkı sözlerini referans kaynaklarla karşılaştırır ve kelime düzeyinde düzeltmeler önerir. Her öneriyi sen incelersin — sen kabul edene kadar hiçbir şey 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özü bulunmuyor, bu yüzden yapay zeka önerileri oluşturulamıyor. Önce referans panelinden şarkı sözlerini ekle.",
"noSuggestions": "Hiçbir sorun bulunamadı — yapay zekanın önerdiği 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": "Yapay zeka 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": "Modeller bu kelimeler konusunda uyuşmuyor — bir varyantı kabul ettiğinde diğerlerini reddetmiş olursun.",
"consensusBadge": "{consensus}/{total} model",
"consensusTooltip": "Öneren: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Email, коли готово",
"afterApproval": "Після затвердження твоє караоке-відео рендериться та доставляється. ~10 хвилин",
"trackProgressTenant": "Відстежуй прогрес у списку Останні завдання.",
"submitAnother": "Надіслати ще один трек"
"submitAnother": "Надіслати ще один трек",
"pasteUrlButton": "Вставити посилання",
"urlSupportedSitesHint": "Працює з YouTube, Facebook, SoundCloud, TikTok, Vimeo та сотнями інших сайтів.",
"urlSupportedSitesLink": "Переглянути всі підтримувані сайти",
"useThisUrl": "Використати це посилання"
},
"jobStatus": {
"settingUp": "Налаштування",
@@ -772,7 +776,11 @@
"undoFailed": "Помилка скасування",
"redoFailed": "Помилка повторення",
"restoreFailed": "Помилка відновлення — деякі редагування могли не застосуватися",
"submitFailed": "Помилка надсилання"
"submitFailed": "Помилка надсилання",
"fadeIn": "Плавне наростання",
"fadeInSelection": "Плавне наростання у виділеному фрагменті",
"fadeOut": "Плавне згасання",
"fadeOutSelection": "Плавне згасання у виділеному фрагменті"
},
"audioEditRestore": {
"title": "Збережені сеанси редагування аудіо",
@@ -812,7 +820,9 @@
"playback": "Відтворення",
"audioLoadError": "Не вдалося завантажити аудіо",
"audioStillLoading": "Аудіо ще завантажується...",
"loadingAudio": "Завантаження аудіо..."
"loadingAudio": "Завантаження аудіо...",
"autoCorrect": "Пропозиції ШІ",
"autoCorrectDesc": "Генеруй пропозиції виправлень від ШІ, порівнюючи транскрипцію з еталонним текстом. Нічого не зміниться, поки ти не приймеш кожну пропозицію."
},
"guidance": {
"showTips": "Показати підказки",
@@ -986,7 +996,9 @@
"loadingAll": "Завантаження всіх слів...",
"loadingSegment": "Завантаження сегмента...",
"noData": "Дані сегмента недоступні",
"unCorrect": "Скасувати виправлення"
"unCorrect": "Скасувати виправлення",
"timingClamped": "Таймінг \"{word}\" виходив за межі сегмента — прив'язано до {time} с.",
"timingSanitized": "Виправлено {count} таймінг(ів) слів, що виходили за межі цього сегмента."
},
"findReplace": {
"title": "Знайти та замінити",
@@ -1268,6 +1280,50 @@
},
"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}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "Gửi email khi sẵn sàng",
"afterApproval": "Sau khi phê duyệt, video karaoke của bạn sẽ được xuất và phân phối. ~10 phút",
"trackProgressTenant": "Theo dõi tiến trình trong danh sách Công việc gần đây.",
"submitAnother": "Gửi bài hát khác"
"submitAnother": "Gửi bài hát khác",
"pasteUrlButton": "Dán liên kết",
"urlSupportedSitesHint": "Hỗ trợ YouTube, Facebook, SoundCloud, TikTok, Vimeo và hàng trăm trang web khác.",
"urlSupportedSitesLink": "Xem tất cả các trang web được hỗ trợ",
"useThisUrl": "Sử dụng URL này"
},
"jobStatus": {
"settingUp": "Đang thiết lập",
@@ -772,7 +776,11 @@
"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"
},
"audioEditRestore": {
"title": "Các phiên chỉnh sửa âm thanh đã lưu",
@@ -812,7 +820,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": "Đề xuất từ AI",
"autoCorrectDesc": "Tạo các đề xuất sửa lỗi từ AI 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",
@@ -986,7 +996,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ế",
@@ -1268,6 +1280,50 @@
},
"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 độ chắc chắn của AI để 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": "AI 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": "Bài hát này chưa có lời tham khảo nên AI không thể tạo đề xuất. Bạn hãy thêm lời bài hát từ bảng tham khảo trước nhé.",
"noSuggestions": "Không tìm thấy vấn đề nào — AI không có đề xuất thay đổi nào.",
"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 sửa lỗi của AI",
"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ác mô hình không đồng nhất về những từ này — chấp nhận một biến thể sẽ loại bỏ các biến thể khác.",
"consensusBadge": "{consensus}/{total} mô hình",
"consensusTooltip": "Đề xuất bởi: {models}"
}
},
"instrumentalReview": {
+60 -4
View File
@@ -529,7 +529,11 @@
"emailWhenReady": "准备好时发送电子邮件",
"afterApproval": "批准后,您的卡拉OK视频将被渲染并交付。约 10 分钟",
"trackProgressTenant": "在“最近任务”列表中跟踪进度。",
"submitAnother": "提交另一首曲目"
"submitAnother": "提交另一首曲目",
"pasteUrlButton": "粘贴链接",
"urlSupportedSitesHint": "支持 YouTube、Facebook、SoundCloud、TikTok、Vimeo 以及数百个其他网站。",
"urlSupportedSitesLink": "查看所有支持的网站",
"useThisUrl": "使用此链接"
},
"jobStatus": {
"settingUp": "设置中",
@@ -772,7 +776,11 @@
"undoFailed": "撤销失败",
"redoFailed": "重做失败",
"restoreFailed": "恢复失败——某些编辑可能未应用",
"submitFailed": "提交失败"
"submitFailed": "提交失败",
"fadeIn": "淡入",
"fadeInSelection": "在选定区域淡入",
"fadeOut": "淡出",
"fadeOutSelection": "在选定区域淡出"
},
"audioEditRestore": {
"title": "已保存的音频编辑会话",
@@ -812,7 +820,9 @@
"playback": "播放",
"audioLoadError": "无法加载音频",
"audioStillLoading": "音频仍在加载中...",
"loadingAudio": "正在加载音频..."
"loadingAudio": "正在加载音频...",
"autoCorrect": "AI 建议",
"autoCorrectDesc": "通过将转录歌词与参考歌词进行对比来生成 AI 纠错建议。在您接受每条建议之前,不会更改任何内容。"
},
"guidance": {
"showTips": "显示提示",
@@ -986,7 +996,9 @@
"loadingAll": "正在加载所有单词...",
"loadingSegment": "正在加载片段...",
"noData": "无可用片段数据",
"unCorrect": "取消校对"
"unCorrect": "取消校对",
"timingClamped": "\"{word}\" 的时间点超出了片段范围 — 已调整至 {time} 秒。",
"timingSanitized": "已修复 {count} 个超出此片段范围的单词时间点。"
},
"findReplace": {
"title": "查找和替换",
@@ -1268,6 +1280,50 @@
},
"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": "AI 显示建议所需的置信度",
"confidenceLabel": "建议筛选器",
"confidence_all": "显示全部",
"confidence_high": "高置信度",
"description": "AI 会将转录的歌词与参考来源进行对比,并提供词级别的修改建议。您可以逐一审核所有建议——在您接受之前,不会应用任何更改。",
"dismiss": "忽略建议",
"expand": "展开建议",
"insertMarker": "插入:",
"insertionsHint": "允许建议插入转录漏掉的词",
"insertionsLabel": "建议补充漏词",
"noReferences": "这首歌没有可用的参考歌词,因此无法生成 AI 建议。请先从参考面板添加歌词。",
"noSuggestions": "未发现问题——AI 没有修改建议。",
"reject": "拒绝建议",
"rejectAll": "全部拒绝",
"rejected": "已拒绝",
"runButton": "获取建议",
"running": "正在分析歌词……这通常需要 15–60 秒。",
"staleHint": "这些词在生成建议后已被编辑,因此该建议不再适用。",
"summary": "{total} 条建议 · {pending} 条待处理 · {accepted} 条已接受",
"title": "AI 纠错建议",
"undo": "撤销此建议",
"cancel": "取消",
"close": "关闭",
"confidence_balanced": "平衡",
"compareHint": "速度较慢且成本较高,但会显示多个模型一致认可的建议",
"compareLabel": "比较多个 AI 模型",
"conflictBadge": "选项",
"conflictTooltip": "各模型对这些词存在分歧 —— 接受其中一个选项将放弃其他选项。",
"consensusBadge": "{consensus}/{total} 个模型",
"consensusTooltip": "推荐模型:{models}"
}
},
"instrumentalReview": {
+3
View File
@@ -33,6 +33,9 @@ def create_secrets() -> dict[str, secretmanager.Secret]:
"langfuse-secret-key",
"langfuse-host",
# AI auto-correct suggestions (Claude models via Anthropic API)
"anthropic-api-key",
# Service authentication
"flacfetch-api-key",
"flacfetch-api-url",
@@ -63,6 +63,14 @@ class SegmentResizer:
List of resized LyricsSegment objects
"""
self._log_input_segments(segments)
# Guarantee valid, in-bounds word timing before doing anything else.
# Transcription occasionally emits words with missing/zero/negative
# timestamps; when a segment is later split, the derived sub-segment
# inherits words[0].start_time, so a bogus value (e.g. 0.0) becomes the
# sub-segment's start_time and corrupts downstream screen ordering.
segments = [self._sanitize_segment_timings(segment) for segment in segments]
resized_segments: List[LyricsSegment] = []
for segment_idx, segment in enumerate(segments):
@@ -124,6 +132,70 @@ class SegmentResizer:
singer=word.singer,
)
def _sanitize_segment_timings(self, segment: LyricsSegment) -> LyricsSegment:
"""Return a copy of ``segment`` whose word timings are valid and in-bounds.
A word is considered invalid if its ``start_time`` falls outside the
segment's ``[start_time, end_time]`` window, or if its ``end_time`` is
missing/before its ``start_time``/after the segment end. Only invalid
timings are corrected — already-valid words are left untouched — so the
karaoke highlight sweep is preserved wherever the source data is good.
A corrected start clamps to the later of the segment start and the
previous word's end (keeping words non-decreasing); a corrected end
clamps to ``[start, segment_end]``.
"""
seg_start = segment.start_time
seg_end = segment.end_time if segment.end_time >= seg_start else seg_start
sanitized_words: List[Word] = []
prev_end = seg_start
changed = False
for word in segment.words:
start, end = word.start_time, word.end_time
if start is None or start < seg_start or start > seg_end:
start = min(max(prev_end, seg_start), seg_end)
changed = True
if end is None or end < start or end > seg_end:
end = min(max(start, end if end is not None else start), seg_end)
if end < start:
end = start
changed = True
if start != word.start_time or end != word.end_time:
self.logger.debug(
f"Sanitized word '{word.text}' timing {word.start_time}-{word.end_time} "
f"-> {start}-{end} (segment {seg_start:.2f}-{seg_end:.2f})"
)
sanitized_words.append(
Word(
id=word.id,
text=word.text,
start_time=start,
end_time=end,
confidence=word.confidence if hasattr(word, "confidence") else None,
created_during_correction=getattr(word, "created_during_correction", False),
singer=word.singer,
)
)
else:
sanitized_words.append(word)
prev_end = end
if not changed:
return segment
return LyricsSegment(
id=segment.id,
text=segment.text,
words=sanitized_words,
start_time=segment.start_time,
end_time=segment.end_time,
singer=segment.singer,
)
def _split_oversized_segment(self, segment_idx: int, segment: LyricsSegment) -> List[LyricsSegment]:
"""Split an oversized segment into multiple segments at natural break points.
Generated
+8 -5
View File
@@ -221,14 +221,14 @@ files = [
[[package]]
name = "anthropic"
version = "0.75.0"
version = "0.109.1"
description = "The official Python library for the anthropic API"
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "anthropic-0.75.0-py3-none-any.whl", hash = "sha256:ea8317271b6c15d80225a9f3c670152746e88805a7a61e14d4a374577164965b"},
{file = "anthropic-0.75.0.tar.gz", hash = "sha256:e8607422f4ab616db2ea5baacc215dd5f028da99ce2f022e33c7c535b29f3dfb"},
{file = "anthropic-0.109.1-py3-none-any.whl", hash = "sha256:ce7d94a7657f2aa29338cca448945eac621b4f62c1794cf461cb32847223e9b8"},
{file = "anthropic-0.109.1.tar.gz", hash = "sha256:83e06b3d9d40ff5898f588020e0cc4e42187de954549a3b5fbe6e2685a09c785"},
]
[package.dependencies]
@@ -239,12 +239,15 @@ httpx = ">=0.25.0,<1"
jiter = ">=0.4.0,<1"
pydantic = ">=1.9.0,<3"
sniffio = "*"
typing-extensions = ">=4.10,<5"
typing-extensions = ">=4.14,<5"
[package.extras]
aiohttp = ["aiohttp", "httpx-aiohttp (>=0.1.9)"]
aws = ["boto3 (>=1.28.57)", "botocore (>=1.31.57)"]
bedrock = ["boto3 (>=1.28.57)", "botocore (>=1.31.57)"]
mcp = ["mcp (>=1.0) ; python_version >= \"3.10\""]
vertex = ["google-auth[requests] (>=2,<3)"]
webhooks = ["standardwebhooks (>=1.0.1,<2)"]
[[package]]
name = "anyio"
@@ -10716,4 +10719,4 @@ local-whisper = ["whisper-timestamped"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.14"
content-hash = "12d73833198d94b95f682e0e424485d6a82698021e1a05b33a27e91cd53bdc90"
content-hash = "e1d4b08e501aa1b41d6b2668dc1fbf5a4afd2b05d07c539711eadd652712a3df"
+2 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.175.1"
version = "0.179.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
@@ -64,6 +64,7 @@ langchain = ">=0.3.0"
langchain-core = ">=0.3.0"
langchain-openai = ">=0.2.0"
langchain-anthropic = ">=0.2.0"
anthropic = ">=0.109.0" # direct dep: auto-correct structured outputs (output_config)
langchain-ollama = ">=0.2.0"
langchain-google-genai = ">=2.0.0"
langfuse = ">=3.0.0"
@@ -0,0 +1,98 @@
"""Regression tests: a resized (split) segment must never inherit a word
timestamp that falls outside its parent segment's [start_time, end_time].
Bug (job 17f7c313, "Atmosphere - Scalp"): the transcription emitted the segment
A whiskey and a beer, let's forget where we are (start=15.18, end=18.04)
but the four leading words ("A", "whiskey", "and", "a") had invalid timestamps
(start_time=0.0, end_time=-0.005) — only "beer," onward carried real timing.
``_create_segment_from_words`` sets a split line's ``start_time`` to
``words[0].start_time``, so the line "A whiskey and a beer," inherited
start_time=0.0.
That zero start_time corrupts screen ordering downstream: a LyricsScreen sorts by
``min(line.segment.start_time)``, so the screen jumped ahead of the INTRO section
screen. The INTRO then wiped the active-line bookkeeping and the next screen
faded in (post-instrumental) over the still-displayed previous screen — two full
screens of lyrics rendered on top of each other for 7-12 seconds.
The resizer must guarantee valid, in-bounds word timing so a split segment can
never start before its parent segment does.
"""
import logging
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
from karaoke_gen.lyrics_transcriber.types import LyricsSegment, Word
def _scalp_segment() -> LyricsSegment:
"""The exact shape of the offending segment from job 17f7c313."""
words = [
Word(id="w0", text="A", start_time=0.0, end_time=-0.005),
Word(id="w1", text="whiskey", start_time=0.0, end_time=-0.005),
Word(id="w2", text="and", start_time=0.0, end_time=0.0),
Word(id="w3", text="a", start_time=0.0, end_time=0.0),
Word(id="w4", text="beer,", start_time=16.10, end_time=16.42),
Word(id="w5", text="let's", start_time=16.46, end_time=16.64),
Word(id="w6", text="forget", start_time=16.68, end_time=17.14),
Word(id="w7", text="where", start_time=17.20, end_time=17.44),
Word(id="w8", text="we", start_time=17.46, end_time=17.62),
Word(id="w9", text="are", start_time=17.66, end_time=18.04),
]
return LyricsSegment(
id="s",
text="A whiskey and a beer, let's forget where we are",
words=words,
start_time=15.18,
end_time=18.04,
)
def test_split_segment_start_time_not_before_parent():
"""A split sub-segment must not start before its parent segment's start_time."""
resizer = SegmentResizer(max_line_length=36, logger=logging.getLogger("test"))
result = resizer.resize_segments([_scalp_segment()])
# The segment is over 36 chars, so it splits into multiple lines.
assert len(result) > 1, "expected the segment to be split"
for s in result:
assert s.start_time >= 15.18, f"sub-segment '{s.text}' starts at {s.start_time}, before parent 15.18"
def test_resized_words_stay_within_parent_bounds():
"""Every word in the output must have valid, in-bounds, non-inverted timing."""
resizer = SegmentResizer(max_line_length=36, logger=logging.getLogger("test"))
result = resizer.resize_segments([_scalp_segment()])
for s in result:
for w in s.words:
assert w.start_time >= 15.18, f"word '{w.text}' start {w.start_time} < parent start 15.18"
assert w.end_time >= w.start_time, f"word '{w.text}' end {w.end_time} < start {w.start_time}"
assert w.end_time <= 18.04 + 1e-6, f"word '{w.text}' end {w.end_time} > parent end 18.04"
def test_valid_timings_are_left_untouched():
"""Sanitation must not perturb already-valid word timings."""
resizer = SegmentResizer(max_line_length=36, logger=logging.getLogger("test"))
words = [
Word(id="w0", text="Filling", start_time=21.40, end_time=21.82),
Word(id="w1", text="up", start_time=21.86, end_time=22.10),
Word(id="w2", text="that", start_time=22.14, end_time=22.42),
Word(id="w3", text="cup", start_time=22.46, end_time=22.78),
]
seg = LyricsSegment(id="s", text="Filling up that cup", words=words, start_time=21.40, end_time=22.78)
result = resizer.resize_segments([seg])
assert len(result) == 1
out = result[0]
assert out.start_time == 21.40
assert [(w.start_time, w.end_time) for w in out.words] == [
(21.40, 21.82),
(21.86, 22.10),
(22.14, 22.42),
(22.46, 22.78),
]